Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions .claude/rules/event-contracts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
paths:
- "**/*.asyncapi.yaml"
- "**/*.asyncapi.yml"
- "**/*.asyncapi.json"
- "**/events/**"
- "**/schemas/**"
- "**/*.avsc"
- "**/*.proto"
- "**/kafka/**"
- "**/*.graphql"
- "**/*.graphqls"
---

# Distributed Systems & Event Contracts

### Sagas, Not Distributed Transactions
Multi-service workflows use the saga pattern with compensating actions for rollback. Each step publishes an event on success; each step has a defined compensation if a downstream step fails. There is no distributed transaction coordinator. If you are implementing a saga:
- Each step must be independently completable and compensatable.
- Compensating actions must be idempotent (they may execute more than once).
- Use Kafka topics for saga events. Do not use synchronous callback chains disguised as a saga.
- The saga must be resilient to out-of-order delivery and duplicate events.
- Document the saga flow, including the compensation path, in an ADR.

### Kafka Usage Patterns
- Use CloudEvents envelope format for event metadata.
- Partition keys must ensure ordering for the same entity (typically entity ID or tenant + entity ID).
- Consumers must be idempotent. Assume at-least-once delivery.
- Use consumer groups appropriately for scaling. Understand that repartitioning affects ordering guarantees.
- Dead letter topics for messages that fail processing after retries.
- Do not use Kafka as a request-reply mechanism. That is synchronous communication disguised as async.

### Stateful Stream Processing
Use Kafka Streams with a RocksDB state store for consumer state — deduplication, windowing, aggregation, joins. Do not use external datastores (Caffeine, Redis, MongoDB, PostgreSQL) for Kafka consumer state: state belongs co-located with partition assignment and made fault-tolerant via changelog topics. For the dedup-durability rule specifically, see `standards/events.md#std-events-idempotency`.

### Schema Evolution
Additive changes only unless there is an explicit exception with a migration plan approved by EA. Do not remove fields, rename fields, or change field types on existing events.

### Contract Co-Location
If you add or modify an event, update the AsyncAPI specification (or the canonical contract definition) as part of the same change. Do not ship event changes without updating the contract.

### Schema and Client Resilience
Assume clients may receive unknown enum values and new fields at any time. Design for forward compatibility. Do not write exhaustive enum switches without a default/unknown handler. Do not fail on unrecognized fields. GraphQL schema evolution and event schema evolution must be additive - new fields and enum values must not break existing consumers.

For new event schemas, also see the `kafka-event-design` skill.
102 changes: 102 additions & 0 deletions .claude/rules/ooad-solid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
paths:
- "**/*.py"
- "**/*.ts"
- "**/*.tsx"
- "**/*.java"
- "**/*.kt"
- "**/*.go"
---

# Object-Oriented Analysis and Design

### Composition Over Inheritance
Build behavior by composing small, focused objects. Do not build deep class hierarchies. If you are extending a base class, evaluate whether delegation or composition would be cleaner. Keep inheritance to a maximum of two levels. If you are going deeper, refactor to composition.

### Program to Interfaces, Not Implementations
Define behavior through protocols (Python), interfaces (TypeScript/Java), or abstract base classes. Consumers depend on the abstraction, never the concrete class. Use structural typing (Python Protocol, TypeScript interfaces) to define contracts. Favor protocols over subclassing.

### Vendor Integrations Behind Abstractions
When integrating a vendor or third-party service, define an interface for the *capability* the vendor provides, not the vendor itself. The vendor is an implementation detail behind an adapter. If the vendor changes tomorrow, the blast radius should be one adapter, not every file that touches that capability.

Bad: `ValidicDeviceDataService`, `ValidicClient`, `ValidicTransformer` spread across the codebase.
Good: `DeviceDataProvider` interface with a `ValidicDeviceDataAdapter` as the concrete implementation.

### Encapsulate What Varies
Identify what changes and isolate it behind an interface. Use the Strategy pattern when behavior varies based on context - inject a strategy rather than adding conditionals or subclass overrides. Use the Template Method pattern when the overall algorithm is fixed but individual steps vary.

### No God Objects
If a class has more than one axis of change or knows about too many concerns, decompose it. Single Responsibility applies at the class level, not just the method level.

### Value Objects for Domain Concepts
Use immutable value types for concepts like identifiers, measurements, date ranges, and money. Equality by value, not identity. Use frozen dataclasses (Python), readonly types (TypeScript), or records (Java).

### Law of Demeter
Do not chain through objects. If you are writing `a.b.c.doThing()`, something is leaking its internals. Ask, don't reach.

---

## SOLID Principles

### Single Responsibility
One reason to change per class or module. If a function does transformation AND persistence, split it. If a service handles both business logic and infrastructure concerns, separate them.

### Open/Closed
Extend behavior through new classes, not by modifying existing ones. No growing conditional chains - use strategy pattern or composition for extensibility.

### Liskov Substitution
Any implementation of an interface must be fully swappable without breaking callers. Do not override methods to throw NotImplementedError or silently change expected behavior.

### Interface Segregation
Keep interfaces small and focused. If a consumer only needs read access, do not force it to depend on an interface that also includes write methods. Split large interfaces into focused ones.

### Dependency Inversion
Depend on abstractions at module and service boundaries. Inject dependencies through constructors. Never instantiate infrastructure inside business logic. Never use service locators when constructor injection is available.

---

## Architectural Boundaries

### Separate Domain from Infrastructure
Keep business logic independent of frameworks, databases, and external services. Domain logic should not import infrastructure concerns. Infrastructure adapts to domain interfaces, not the other way around.

In repos using ports and adapters (hexagonal architecture), respect the layering:
- **Domain layer**: Business logic, domain models, port interfaces. No infrastructure imports.
- **Application layer**: Use case orchestration, service interfaces. Coordinates domain and ports.
- **Infrastructure layer**: Adapters implementing ports (database, HTTP clients, message brokers, vendor integrations).

If the repo does not use explicit hexagonal structure, follow the principle spiritually: domain code exposes interfaces, infrastructure code implements them. Do not let database schemas, REST frameworks, or vendor SDKs leak into business logic.

---

## General Design Principles

### DRY, Pragmatically
Prefer duplication over the wrong abstraction. Extract shared logic only when the pattern is stable and repeats across multiple call sites, or when there is clear semantic reuse. Premature abstraction creates coupling that is harder to undo than duplicated code. If you are unsure whether to extract, leave it duplicated until the pattern is clear.

### Explicit Over Clever
Readable code over compact code. Name things for what they do, not how they are implemented. Prefer explicit types and contracts at boundaries over inference.

### Fail Fast
Validate inputs at the boundary and reject early. Do not let bad data propagate through layers. Typed and structured errors at boundaries, not stringly-typed error messages or raw exception forwarding.

### No Hidden Global State
All dependencies must be explicit and injectable. No module-level singletons that hold state. No implicit service locators.

### Idempotency by Default
Any consumer that processes events or handles retries must be idempotent. This is not optional in a distributed system with at-least-once delivery. Duplicate processing must produce the same result. Use idempotency keys, deduplication checks, or upsert semantics. Design every Kafka consumer, webhook handler, and retry-capable operation with the assumption that it will be called more than once with the same input.

### Minimal Diff
Make the smallest change that satisfies the requirement. Do not rename, reformat, or reorganize unrelated code in the same PR. Do not refactor modules you were not asked to change. Scope the change to what was requested.

---

## Modern, Idiomatic Code

Use current language idioms for the repo's language version. Do not write legacy-style code.

**Java:** Use records for data carriers, not POJOs with boilerplate getters/setters. Use sealed interfaces for closed type hierarchies. Use pattern matching where available. Use `var` for local variables when the type is obvious from the right side. Use streams and Optional appropriately, not for every operation.

**Python:** Use dataclasses or Pydantic models, not manual dict manipulation. Use type hints everywhere. Use structural pattern matching (3.10+) where it improves clarity. Use `Protocol` for structural typing. Use `async`/`await` for IO-bound operations in async services.

**TypeScript:** Use discriminated unions for variant types, not type casting chains. Use strict mode. Use `readonly` and `as const` where appropriate. Use modern `satisfies` operator for type-safe object literals. Use optional chaining and nullish coalescing instead of manual null checks.
25 changes: 25 additions & 0 deletions .claude/rules/operational.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
paths:
- "**/*.py"
- "**/*.ts"
- "**/*.tsx"
- "**/*.java"
- "**/*.kt"
- "**/*.go"
---

# Operational Realism

Services run in a distributed environment, fail independently, and must handle partial failures gracefully.

### Timeouts and Retries
Every external call must have an explicit timeout. Retries must use exponential backoff with jitter. Do not use unbounded retries. Implement DLQ (dead letter queue) patterns for messages that fail after retry exhaustion.

### Circuit Breakers
Use circuit breaker patterns for synchronous calls to external services. When a dependency is failing, fail fast rather than accumulating blocked threads and cascading the failure upstream.

### Performance Awareness
Do not introduce "fetch the entire record" behavior unless it is an explicit, reviewed decision. Be aware of N+1 query patterns, unbounded list fetches, and full-collection scans. Healthcare records can be large - assume they are. In a microservice architecture, a single slow query can cascade through downstream consumers via backpressure.

### Observability Is a Deliverable
OpenTelemetry tracing propagation must be maintained across service boundaries. Trace context must flow through Kafka headers, HTTP headers, and any other transport. Logs must be structured (JSON) with correlation IDs. Metrics must be meaningful, not just counters. If you add a new service interaction or failure mode, add the corresponding observability. In a distributed system, observability is how you debug production - it is not optional.
39 changes: 39 additions & 0 deletions .claude/rules/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
paths:
- "**/*test*.py"
- "**/test_*.py"
- "**/*_test.py"
- "**/*.test.ts"
- "**/*.test.tsx"
- "**/*.spec.ts"
- "**/*Test.java"
- "**/tests/**"
- "**/test/**"
- "**/__tests__/**"
---

# Testing

### Testing Is Part of the Change
Every behavioral change ships with tests. Tests are not a follow-up task.

### Parameterized Tests
Use parameterized tests (Jest `test.each`, pytest `@pytest.mark.parametrize`, JUnit `@ParameterizedTest`) for any function with more than two input variations. Data-driven test cases, not copy-pasted test methods with one value changed.

### Arrange-Act-Assert
Structure every test with clear setup, execution, and verification phases. One behavior per test. Multiple asserts are fine when they verify that single behavior.

### Mock Only at External Boundaries
Mock external services, databases, and third-party APIs. Do not mock internal implementation details. If you need extensive mocking to test a unit, the design is too coupled - fix the design, not the test.

### Test Error Paths
Test failure modes, error handling, retries, and edge cases explicitly. Do not test only the happy path.

### Contract Tests at Boundaries
API request/response shapes, event schemas, and external integration contracts must have contract tests. When you change a public API or event schema, update the contract test in the same PR.

### Tenant Isolation in Integration Tests
Integration tests must verify that tenant boundaries are enforced. Cross-tenant data leakage is a correctness bug, not a nice-to-have test case.

### Test Behavior, Not Implementation
Assert on what happened, not how it happened internally. Tests should survive refactoring of internals without breaking.
79 changes: 79 additions & 0 deletions .github/workflows/check-commit-message.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
name: 'Commit Message Check'
on:
pull_request:
types: [opened, edited, reopened, synchronize]
push:
branches: [main, 'releases/*']

jobs:
check-commit-message:
name: Check Commit Message
runs-on: ubuntu-latest
steps:
- name: Check For Issue Key
uses: gsactions/commit-message-checker@v2

@aikido-pr-checks aikido-pr-checks Bot Sep 22, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3rd party Github Actions should be pinned - high severity
A third-party GitHub Action was imported, and is not pinned via a hash. This leaves your CI/CD at risk for potential supply chain attacks, if the affected GitHub Action is compromised.

Suggested change
uses: gsactions/commit-message-checker@v2
uses: gsactions/commit-message-checker@16fa2d5de096ae0d35626443bcd24f1e756cafee # v2.0.0

Reply @AikidoSec ignore: [REASON] to ignore this issue.
More info

with:
pattern: '^(Bump|Merge|Revert|Reapply|fix\(security\):|\[Aikido\]|build\(deps(-dev)?\): bump|([A-Z]+-[0-9]+))\s+.+'
flags: 'gm'
Comment on lines +15 to +17

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Commit-message enforcement is weaker than AGENTS.md's 'every commit starts with a JIRA issue key' rule: the checker's flags 'gm' (line 17) make the pattern's ^ anchor match the start of any line, not just the subject. A commit whose first line lacks a JIRA key can still pass CI if a later body line happens to start with a matching token, since gsactions/commit-message-checker's regex test returns true on any match anywhere in the message. Fix: drop the 'm' flag (or explicitly test only the first line) so the prefix rule is enforced on the subject, not anywhere in the body.

Why this was flagged

check-commit-message.yml lines 15-18 (new file) configure gsactions/commit-message-checker@ v2 with pattern '^(Bump|Merge|Revert|Reapply|fix(security):|[Aikido]|build(deps(-dev)?): bump|([A-Z]+-[0-9]+))\s+.+' and flags 'gm'. The 'm' flag makes '^' match the start of every line in a multi-line commit message, so the underlying regex test succeeds if any line anywhere matches, not only the first line. AGENTS.md's 'Commit Messages' section states every commit starts with a JIRA key; this check enforces 'contains a matching line somewhere' instead of 'starts with', so a badly-prefixed commit can slip through CI undetected. This is a newly introduced check, so the gap is new, not pre-existing.

Verification: nit. check-commit-message.yml (new file) sets pattern '^(Bump|Merge|Revert|Reapply|fix(security):|[Aikido]|build(deps(-dev)?): bump|([A-Z]+-[0-9]+))\s+.+' with flags 'gm' (lines 16-17). The 'm' flag makes '^' match the start of every line, and gsactions/commit-message-checker@ v2 passes when RegExp.test() matches anywhere in the multi-line message. So a commit with a non-JIRA…

error: 'Commit message must begin with a JIRA Issue Key: e.g. HP-123 <message>'

- name: Reject AI attribution in commits/PR description
uses: actions/github-script@v7
with:
script: |
// AGENTS.md "Code ownership": no Co-Authored-By/Generated-by/AI attribution
// in commits, PRs, or comments — the author on the commit is the owner.
// Tool name list, not just "claude" — the rule bans AI attribution generically.
const AI_TOOL = '(?:claude|chatgpt|gpt-\\d|copilot|codex|gemini|cursor|windsurf|devin|cody|tabnine|bard|anthropic|openai)';
const BAD_PATTERN = new RegExp(
`co-authored-by:[^\\n]*${AI_TOOL}` +
`|generated\\s+(with|by)\\s*\\[?${AI_TOOL}` +
`|🤖\\s*generated\\s+with`,
'i'
);
const violations = [];

let messages = [];
if (context.eventName === 'pull_request') {
// github.paginate, not a single per_page:100 call — PRs can exceed 100 commits.
const commits = await github.paginate(github.rest.pulls.listCommits, {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.payload.pull_request.number,
per_page: 100,
});
messages = commits.map(c => ({ ref: c.sha.slice(0, 7), text: c.commit.message }));
if (context.payload.pull_request.body && BAD_PATTERN.test(context.payload.pull_request.body)) {
violations.push('PR description');
}
} else if (context.eventName === 'push') {
// The push webhook payload's `commits` array is capped at 20 entries by GitHub,
// regardless of how many commits were actually pushed — resolve the full range
// via the compare API instead, keyed off before/after SHAs.
const before = context.payload.before;
const after = context.payload.after;
if (before && after && !/^0+$/.test(before)) {
const { data: comparison } = await github.rest.repos.compareCommitsWithBasehead({
owner: context.repo.owner,
repo: context.repo.repo,
basehead: `${before}...${after}`,
});
messages = comparison.commits.map(c => ({ ref: c.sha.slice(0, 7), text: c.commit.message }));
Comment on lines +49 to +61

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Maintainers pushing a large batch of commits (branch import, long-lived release rebase) get silent gaps in JIRA-key enforcement that direct pushes to main/releases/* now rely on. The push-event branch (lines 49-65) calls compareCommitsWithBasehead once and maps comparison.commits (line 61) without pagination or checking comparison.total_commits, but GitHub's compare API caps the returned commits list (documented ~250 entries) — commits beyond that cap are never checked, though the comment at lines 50-52 claims this resolves 'the full range'. Fix: page through the compare results (or fall back to the List Commits API keyed off before/after) when total_commits exceeds commits.length, matching the github.paginate approach already used for the pull_request branch at line 39.

Why this was flagged

Trigger: a push to main or releases/* (line 6) whose before..after range spans more than the compare API's commit cap (~250), e.g. importing history into a new release branch or force-pushing a rebased long-lived branch. At line 56-61 the code does a single compareCommitsWithBasehead call and maps comparison.commits directly, with no github.paginate and no check of comparison.total_commits vs commits.length. On the base branch this whole compare path did not exist; the old push handling used context.payload.commits, capped at 20 (per the comment at line 50), so the gap existed but was already flagged there. Here the comment at lines 50-52 claims to 'resolve the full range', giving a false sense that pushes are now fully checked, when commits beyond the API's cap are silently never matched against the JIRA-key pattern and the workflow reports success. The pull_request branch avoids this by using github.paginate (line 39) with an explicit comment noting PRs can exceed 100 commits; the push branch has no equivalent safeguard.

Verification: nit. The mechanism is real: at lines 56-61 the push path does a single github.rest.repos.compareCommitsWithBasehead({ basehead: ${before}...${after} }) call and maps comparison.commits directly (line 61) with no github.paginate and no check of comparison.total_commits against comparison.commits.length. GitHub's compare API caps the returned commits array at 250 entries (documented…

} else if (context.payload.commits) {
messages = context.payload.commits.map(c => ({ ref: c.id.slice(0, 7), text: c.message }));
}
Comment on lines +49 to +64

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Maintainers get incomplete JIRA-key/AI-attribution enforcement on new branch pushes: when before is all-zero (e.g. cutting a new releases/* branch), the code falls back to context.payload.commits, which the comment at lines 50-52 itself says GitHub caps at 20 entries — the very cap this compare-API workaround exists to avoid. Any commits beyond the first 20 on that push skip validation entirely. Fix: for the all-zero-before case, resolve the full commit range via another API (e.g. list commits ahead of the merge-base, or compare against the branch's parent ref) instead of the capped webhook payload, so branch-creation pushes get the same complete coverage as normal pushes.

Why this was flagged

Trigger: a push event to main or releases/* (workflow trigger at lines 5-6) where context.payload.before is all zeros — i.e. branch creation, common when cutting a releases/* branch from main with more than 20 commits. At line 55 the before && !/^0+$/.test(before) check is false, so the compare-API path (lines 56-61) is skipped and code falls to line 62-63, using context.payload.commits, which the adjacent comment (lines 50-52) documents as capped at 20 by GitHub. Result: only the last 20 commits get checked for JIRA-key/AI-attribution violations; earlier commits on the new branch are silently unvalidated, unlike the normal-push path this same diff added to fix exactly that cap.

Verification: nit. The gap is factually real and reachable. Line 55 guards the compare-API path with before && after && !/^0+$/.test(before); on a branch-creation push (before all zeros — e.g. cutting a releases/* branch, which matches the trigger at lines 5-6) this is false, so lines 56-61 are skipped and control reaches line 62-63, which uses context.payload.commits. The adjacent comment (lines…

}

for (const m of messages) {
if (BAD_PATTERN.test(m.text)) {
violations.push(`commit ${m.ref}`);
}
}

if (violations.length) {
core.setFailed(
'No "Co-Authored-By", "Generated by/with Claude", or other AI attribution allowed in commits, ' +
'PRs, or comments (AGENTS.md "Code ownership" — the author on the commit is the owner). ' +
`Found in: ${violations.join(', ')}. Remove it (amend/rebase the commit, or edit the PR description) and push again.`
);
}
22 changes: 22 additions & 0 deletions .github/workflows/pr-architecture-review.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: PR Architecture Review

on:
pull_request_target:
types: [opened, synchronize, reopened]
Comment on lines +4 to +5

@aikido-pr-checks aikido-pr-checks Bot Sep 22, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using unsafe GitHub Actions trigger may allow privilege escalation via CI/CD - medium severity
Using pull_request_target or workflow_run as a trigger is not recommended, as it may allow an attacker to elevate its privileges via the CI/CD pipeline by exfiltrating secrets (e.g. by reading out the caches of the GitHub Actions pipeline or listing loaded secrets in the environment). If the affected repository is open source, the attacker doesn't have to be an insider but could be any GitHub user.

Suggested change
pull_request_target:
types: [opened, synchronize, reopened]
pull_request:
types: [opened, synchronize, reopened]

Reply @AikidoSec ignore: [REASON] to ignore this issue.
More info


permissions:
contents: read
pull-requests: write

jobs:
call-review:
uses: icanbwell/.github/.github/workflows/pr-architecture-review-reusable.yml@main
with:
pr_number: ${{ github.event.pull_request.number }}
pr_author: ${{ github.event.pull_request.user.login }}
base_ref: ${{ github.event.pull_request.base.ref }}
head_ref: ${{ github.event.pull_request.head.ref }}
head_sha: ${{ github.event.pull_request.head.sha }}
secrets:
gh_token: ${{ secrets.GITHUB_TOKEN }}
bwell_dev_pat: ${{ secrets.BWELL_DEV_PAT }}
Loading
Loading