diff --git a/.claude/rules/event-contracts.md b/.claude/rules/event-contracts.md new file mode 100644 index 0000000..c52f6b0 --- /dev/null +++ b/.claude/rules/event-contracts.md @@ -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. \ No newline at end of file diff --git a/.claude/rules/ooad-solid.md b/.claude/rules/ooad-solid.md new file mode 100644 index 0000000..b3481b9 --- /dev/null +++ b/.claude/rules/ooad-solid.md @@ -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. \ No newline at end of file diff --git a/.claude/rules/operational.md b/.claude/rules/operational.md new file mode 100644 index 0000000..3947cfc --- /dev/null +++ b/.claude/rules/operational.md @@ -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. \ No newline at end of file diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md new file mode 100644 index 0000000..f5426a8 --- /dev/null +++ b/.claude/rules/testing.md @@ -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. \ No newline at end of file diff --git a/.github/workflows/check-commit-message.yml b/.github/workflows/check-commit-message.yml new file mode 100644 index 0000000..bd00755 --- /dev/null +++ b/.github/workflows/check-commit-message.yml @@ -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 + with: + pattern: '^(Bump|Merge|Revert|Reapply|fix\(security\):|\[Aikido\]|build\(deps(-dev)?\): bump|([A-Z]+-[0-9]+))\s+.+' + flags: 'gm' + error: 'Commit message must begin with a JIRA Issue Key: e.g. HP-123 ' + + - 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 })); + } else if (context.payload.commits) { + messages = context.payload.commits.map(c => ({ ref: c.id.slice(0, 7), text: c.message })); + } + } + + 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.` + ); + } diff --git a/.github/workflows/pr-architecture-review.yml b/.github/workflows/pr-architecture-review.yml new file mode 100644 index 0000000..09a2e4e --- /dev/null +++ b/.github/workflows/pr-architecture-review.yml @@ -0,0 +1,22 @@ +name: PR Architecture Review + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +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 }} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..05df854 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,113 @@ +# icanbwell - AI Agent Instructions + +> **Scope:** Organization-wide baseline. Applies to all repositories in the icanbwell GitHub organization. +> **Owner:** Enterprise Architecture (@icanbwell/enterprise-architecture) +> **Precedence:** This file sets the floor. Repo-level instruction files (copilot-instructions.md, CLAUDE.md) may add stricter requirements or repo-specific context but must not weaken or contradict these directives. If there is a conflict, this baseline wins. Repo-level overrides may only tighten rules, never loosen them. Any true exception requires EA approval with documented rationale, scope, owner, JIRA ticket, and expiry date. +> +> **Context-budget note:** This file loads in full on every session, in every repo. Keep it to hard, always-applicable constraints. File-type-specific detail (OOAD/SOLID, testing, event contracts, operational patterns) lives in `.claude/rules/*.md` and loads only when Claude touches a matching file. Vendor/pattern-specific guidance lives in `.claude/skills/*` and loads only when invoked. Don't re-add prose here that a rule or skill already covers. + +--- + +## Platform Identity + +b.well is a cloud-native, multi-tenant, microservice-based, event-driven healthcare data platform under HIPAA, FHIR-native, exposed via a federated GraphQL gateway. Services are independently deployable, communicate asynchronously by default, and own their private datastores. The FHIR server is the system-of-record, accessed only via approved APIs and contracts. Cross-service workflows use sagas and event choreography, never distributed transactions or synchronous orchestration chains. + +Code that violates tenant isolation, leaks PHI, bypasses the gateway, introduces unapproved technology, or creates tight coupling between services is incorrect regardless of whether it compiles and passes tests. + +--- + +## Design-Time Quality Kit & Knowledge Substrate + +The worst failures happen at **design time**, before code review can catch them. b.well maintains a tool-neutral **knowledge substrate** โ€” the single source of truth for rules, patterns, and gradeable review rubrics โ€” and a design-time kit that uses it. Reach for these instead of re-deriving (or reinventing) an approach: + +- **Authoring a design?** Use the **`tech-design`** skill โ€” it walks you through the rubric so the design passes EA review the first time. +- **Reviewing a design?** Use **`/tech-design-review`** โ€” it grades a TDD/FDR against the rubric and returns concrete, cited gaps. +- **Rubrics** (`rubrics/`) โ€” what "good" means, gradeably: `tech-design-rubric.md`, `fhir-feasibility-rubric.md` (conformance + IG conformance + resource-explosion feasibility), `api-design-rubric.md`. +- **Patterns** (`patterns/`) โ€” named, blessed shapes to appeal to by name, not reinvent: `orchestrated-long-running-work`, `temporal-coalescing`, `event-key-and-partition-design`. +- **Decision guides** (`decision-guides/`) โ€” e.g. `datastore-selection.md` (including *do not put run/FSM state on a FHIR `Task`*). +- **Standards** (`standards/`) โ€” canonical rules, e.g. `events.md` (Kafka/event conventions; supersedes the inline `patient.updated`-style examples elsewhere in this file). +- **Reference architectures** (`reference-architectures/`) โ€” annotated real exemplars (the DEQM orchestrator; a good API/SDK). + +Overview + the stable-anchor citation convention: `docs/knowledge-substrate.md`. Cite substrate content by anchor (e.g. `standards/events.md#std-events-partition-key`), never by line number. + +--- + +## Hard Non-Negotiables + +- **Event-driven first.** Default to async via Kafka + CloudEvents. A sync service-to-service call needs a documented reason (immediate response required, data can't be pre-materialized). See the `sync-to-async` skill. +- **Choreography over orchestration.** Services react to events; no cross-domain god orchestrator, no request-reply chains disguised as async. Saga detail (compensation, idempotency, ordering): `.claude/rules/event-contracts.md`. +- **Service data ownership.** Never read from or write to another service's private datastore. Consume owned data via events or the owning service's public API. +- **Tenant isolation.** Mandatory on every persistence model and query path โ€” correctness, not best-effort. If you can't confirm tenant filtering on a new data access path, flag it. +- **FHIR-native modeling.** Use standard FHIR resources before inventing schemas. New resource usage or structural changes need an FDR. Extensions are a last resort requiring review. See the `fhir-design` skill. +- **Federated gateway only.** Client-facing capabilities go through the federated graph โ€” no point-to-point service APIs bypassing it. Public API/schema changes are additive-only and need a Tech Design Review. See the `api-design-guardian` skill. +- **No unapproved technology.** Check `policies/approved-tech.yaml` before adding any datastore, cache, queue, search engine, observability sink, vendor, or significant library. Not listed โ†’ Tech Design Review. Infra changes go through Terraform PRs, never manual console steps. +- **Eventually consistent by default.** Don't design cross-service reads/UX assuming immediate consistency. Strong consistency belongs inside a single bounded context. + +Detailed Kafka usage patterns, schema evolution rules, and forward-compatibility requirements: `.claude/rules/event-contracts.md`. + +--- + +## Code & Design Conventions + +OOAD, SOLID, hexagonal-boundary, DRY/idempotency/minimal-diff, and modern-idiom (Java/Python/TypeScript) conventions apply to source files and load automatically via `.claude/rules/ooad-solid.md`. + +Testing discipline (parameterized tests, AAA, mock-only-at-boundaries, contract tests, tenant-isolation-in-integration-tests) loads automatically for test files via `.claude/rules/testing.md`. + +Timeouts/retries, circuit breakers, N+1/full-scan awareness, and observability requirements load automatically for service source files via `.claude/rules/operational.md`. + +Follow whatever linter/formatter/static-analysis config exists in the repo โ€” these rules cover architectural judgment linters can't catch, not style. + +--- + +## Security + +**PHI/PII:** Never in logs, test fixtures, example payloads, comments, commit messages, PR descriptions, or screenshots. Use synthetic/redacted data. + +**Auth:** OAuth/OIDC only. No custom auth schemes, no hardcoded credentials, tokens, or secrets anywhere. + +--- + +## Governing Processes + +- **New technology, vendor, or pattern; public API changes; cross-team impact:** Tech Design Review with EA (JIRA ticket, type "Tech Design Review", linked design doc). +- **FHIR data modeling decisions:** FDR process โ€” FDR Confluence page + FHIR SME approval. +- **Non-trivial repo-local implementation decisions** (library choice, caching strategy, new pattern in the repo): ADR in the repo's `adrs/` directory, MADR format (https://adr.github.io/madr/). Show the options considered, not just the conclusion. + +Unsure if a change needs review? "Is it NEW?" โ€” new technology, new vendor, or a pattern not previously used in this codebase โ†’ needs EA review. + +--- + +## Agent Behavior + +- **Plan before acting.** Before non-trivial changes, restate which constraints apply (tenancy, PHI, contracts, dependencies) and flag if it touches tenant isolation, PHI, public contracts, event schemas, or a new dependency. +- **Diagnose before escalating.** Read logs and check the obvious (right token/var, remote configured, did it actually fail vs. warn) before concluding something needs org-admin intervention or new infrastructure. +- **Respect system constraints.** If branch protection blocks a merge, CI is failing, or a process needs approval, don't repeatedly offer workarounds. If told an action is blocked, don't re-propose it with different wording. +- **Don't guess commands.** Use the repo's actual build/test/lint commands (Makefile, package.json, build.gradle, Pipfile). Say so if unclear. +- **Don't introduce dependencies casually.** Check `approved-tech.yaml` first; popularity isn't approval. +- **Reference governing artifacts.** Cite the Tech Design Doc/FDR/ADR/AsyncAPI spec in the PR when a change touches a public API, event contract, or cross-service behavior. +- **Flag what looks wrong.** Missing tenant filtering, PHI in fixtures, a vendor name baked into business logic, a sync call where an event belongs โ€” flag it, don't silently work around it. +- **Code ownership.** No "Co-Authored-By", "Generated by", or other AI attribution in commits, PRs, or comments. The author on the commit is the owner. + +--- + +## Branch Naming + +Format: `XX-PROJ-123` (initials-JIRA project-ticket number), e.g. `WF-EA-2136`. No `feature/`, `fix/`, `bugfix/`, `hotfix/` prefixes โ€” the JIRA key carries the context. + +## Commit Messages + +Every commit starts with a JIRA issue key, no conventional-commit prefixes: `EA-789 add FHIR resource validation`. Exceptions: automated dependency bumps (`Bump version`, `build(deps): ...`) and git operations (`Merge`, `Revert`, `Reapply`). Commits are validated automatically. No ticket for your work? Create one before committing. + +--- + +## icanbwell Infrastructure + +Atlassian: https://icanbwell.atlassian.net/ ยท Slack workspace: icanbwell ยท Common JIRA projects: EA, HP, PAY, RNGR. + +Use the `atlassian:*` skills (ticket creation/triage, status reports, Confluence search) and `slack:*` skills (search, digests, announcements) for these operations rather than calling MCP tools ad hoc โ€” they already encode the correct cloudId lookup, project conventions, and troubleshooting steps. + +--- + +## Code Style + +Follow whatever linter, formatter, and static analysis configuration exists in the repo. Don't duplicate what automated tooling already enforces โ€” these instructions are for architectural and design decisions linters can't catch. \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..be66473 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,3 @@ +# Architecture instruction files owned by Enterprise Architecture +/AGENTS.md @icanbwell/enterprise-architecture +/CLAUDE.md @icanbwell/enterprise-architecture diff --git a/copilot-instructions.md b/copilot-instructions.md new file mode 100644 index 0000000..1c2ea05 --- /dev/null +++ b/copilot-instructions.md @@ -0,0 +1,28 @@ +# icanbwell - Copilot Instructions + +You are working in a cloud-native, multi-tenant, HIPAA-compliant healthcare platform. The platform is FHIR-native, event-driven (Kafka + CloudEvents), and exposes capabilities through a federated GraphQL gateway. + +## Hard Constraints +- Tenant isolation is mandatory on every data access path. Not optional. +- No PHI/PII in logs, test fixtures, example data, comments, or PR descriptions. +- No new technology, vendors, or patterns without checking approved-tech.yaml and EA review. +- Public API changes require a Tech Design Review. +- Event-driven first. Default to async via Kafka. Justify sync. +- Client-facing access goes through the federated GraphQL gateway. No bypass. + +## Design Defaults +- Program to interfaces, not implementations. Vendor integrations behind capability abstractions. +- Composition over inheritance. Strategy pattern over growing conditionals. +- Dependency injection at boundaries. No hidden global state. +- Idempotent consumers. Assume at-least-once delivery. +- Parameterized tests for functions with more than two input variations. +- Mock only at external boundaries. + +## Before Coding +- Find and use the repo's canonical build/test/lint commands. Do not guess. +- Propose a plan for non-trivial changes. Call out tenancy, PHI, contract, and dependency risks. +- Check approved-tech.yaml before introducing any dependency. +- If your change touches public API, events, or cross-service behavior, reference the governing artifact (TDD, FDR, ADR, AsyncAPI). + +## Repo-Specific Instructions +Check .github/copilot-instructions.md in the specific repository for repo-level context, commands, and additional guidelines that extend these org-wide instructions. diff --git a/policies/approved-tech.yaml b/policies/approved-tech.yaml new file mode 100644 index 0000000..9964add --- /dev/null +++ b/policies/approved-tech.yaml @@ -0,0 +1,386 @@ +# Approved Technology Stack - icanbwell +# Owner: Enterprise Architecture +# Last Updated: 2026-09-21 +# Version: 1.1.0 +# +# Purpose: Centralized registry of approved technologies, frameworks, and tools. +# Any addition requires Tech Design Review with EA approval. +# +# Enforcement: +# - severity: "warn" = Flag for review, does not block +# - severity: "error" = Blocks PR merge, requires exception approval +# - Phase 2 enforcement starts at "warn" for all categories + +--- +version: "1.1.0" +updated: "2026-09-21" +enforcement: + defaultSeverity: "warn" + exceptionProcess: "Tech Design Review with EA (JIRA ticket in EA project)" + +categories: + # ============================================================================ + # Languages + # ============================================================================ + languages: + severity: "warn" + approved: + - name: "TypeScript" + versions: ["5.x"] + notes: "Preferred for new Node.js services" + + - name: "JavaScript" + versions: ["ES2022+"] + notes: "Approved for Node.js services alongside TypeScript" + + - name: "Python" + versions: ["3.11", "3.12"] + notes: "Preferred for data pipelines, AI/ML services" + + - name: "Java" + versions: ["17", "21"] + notes: "Spring Boot services, FHIR processing" + + - name: "Kotlin" + versions: ["1.9+"] + notes: "Mobile SDKs, Android native" + + - name: "Swift" + versions: ["5.9+"] + notes: "iOS SDK only" + + - name: "HCL" + versions: ["Terraform 1.5+"] + notes: "Infrastructure as Code only" + + # ============================================================================ + # Frameworks & Libraries + # ============================================================================ + frameworks: + severity: "warn" + approved: + # Backend Frameworks + - name: "NestJS" + category: "backend" + versions: ["10.x"] + notes: "Preferred Node.js backend framework" + + - name: "FastAPI" + category: "backend" + versions: ["0.109+"] + notes: "Preferred Python backend framework" + + - name: "Flask" + category: "backend" + versions: ["3.x"] + notes: "LEGACY ONLY - Do not use for new services. Migrate to FastAPI." + legacy: true + + - name: "Django" + category: "backend" + versions: ["4.x", "5.x"] + notes: "Legacy bwell-platform only. Do not use for new services." + legacy: true + + - name: "Spring Boot" + category: "backend" + versions: ["3.x"] + notes: "Java microservices standard" + + # Frontend Frameworks + - name: "React" + category: "frontend" + versions: ["18.x"] + notes: "Web UI standard" + + - name: "React Native" + category: "mobile" + versions: ["0.73+"] + notes: "Mobile app standard" + + # AI/ML Frameworks + - name: "LangChain" + category: "ai-ml" + versions: ["0.1.x"] + notes: "LLM orchestration, agent frameworks" + + - name: "LangGraph" + category: "ai-ml" + versions: ["0.0.x"] + notes: "Stateful agent workflows" + + # ============================================================================ + # Data Storage + # ============================================================================ + datastores: + severity: "warn" + approved: + - name: "FHIR Server" + type: "document" + implementation: "MongoDB" + notes: "Platform system-of-record; access via FHIR APIs only" + + - name: "MongoDB" + type: "document" + versions: ["7.x"] + notes: "Service-private datastores; tenant isolation mandatory" + + - name: "PostgreSQL" + type: "relational" + versions: ["15.x", "16.x"] + notes: "First-class approved relational store, incl. operational run/FSM state with JPA + Flyway migrations (the clinical-reasoning-orchestrator uses PostgreSQL). Choose relational (PostgreSQL) vs document (MongoDB) by workload, not by default โ€” see decision-guides/datastore-selection.md. A new-service datastore still requires a Tech Design Review; tenant isolation mandatory." + + - name: "Elasticsearch" + type: "search" + versions: ["8.x"] + notes: "Search and analytics; requires Tech Design Review for new use cases" + + - name: "Neo4j" + type: "graph" + versions: ["5.x"] + notes: "Graph database for data operations; requires Tech Design Review for new use cases" + + - name: "ClickHouse" + type: "analytics" + versions: ["23.x", "24.x"] + notes: "OLAP database for analytics and time-series data. Also an active EA-approved track (EA-2126) as a hybrid FHIR storage backend for resources that exceed MongoDB's 16MB BSON limit (e.g. Group at 1M+ members) โ€” see reference-architectures/fhir-server-group-scaling.md. That is a reviewed, in-flight direction for the specific fhir-server use case, not a blanket approval to use ClickHouse as a general operational datastore; a new use case still requires a Tech Design Review." + + - name: "Databricks" + type: "analytics-platform" + versions: ["Runtime 13.x+"] + notes: "Data lakehouse platform for big data analytics and ML pipelines" + + # ============================================================================ + # Messaging & Events + # ============================================================================ + messaging: + severity: "warn" + approved: + - name: "Kafka" + versions: ["3.x"] + notes: "Primary async communication; CloudEvents envelope required" + patterns: + - "CloudEvents format mandatory" + - "Idempotent consumers required" + - "Partition keys must ensure entity ordering" + + - name: "Kafka Streams" + versions: ["3.x"] + notes: "Stateful stream processing for Kafka consumers. Use for deduplication, windowing, aggregation, joins. RocksDB state store provides fault-tolerant state via changelog topics. Do NOT use external caches/databases (Caffeine, Redis, MongoDB, PostgreSQL) for Kafka consumer state." + patterns: + - "State co-located with Kafka partition assignment" + - "RocksDB state store backed by changelog topics" + - "Tenant isolation in state keys (tenantId prefix)" + + # ============================================================================ + # Caching + # ============================================================================ + caching: + severity: "warn" + approved: + - name: "Redis" + versions: ["7.x"] + notes: "Distributed cache standard; tenant keys required; cache introduction requires ADR" + + - name: "In-Process Caching" + examples: ["Caffeine (Java)", "node-cache (Node.js)", "cachetools (Python)"] + notes: "Service-local caching; requires ADR documenting strategy, size limits, TTL, eviction policy" + + # ============================================================================ + # Observability + # ============================================================================ + observability: + severity: "warn" + approved: + - name: "OpenTelemetry" + versions: ["1.x"] + notes: "Tracing, metrics, logs; trace context propagation mandatory" + required: true + + - name: "Groundcover" + versions: ["Current"] + notes: "K8s observability platform" + + - name: "Sentry" + versions: ["Current"] + notes: "Error tracking and exception aggregation. 25+ live production projects predating this registry entry -- see EA-2671. Configuration is governed by the EA standard requiring send_default_pii=false explicitly. A separate RFC to consolidate backend observability onto Groundcover (moving backend services off Sentry) is in draft and not settled; this entry records current approved practice and does not pre-empt that RFC's outcome." + + # ============================================================================ + # BI & Reporting + # ============================================================================ + reporting: + severity: "warn" + approved: + - name: "Sigma" + versions: ["Current"] + notes: "BI/dashboarding tool, reads from Databricks/Delta Lake. In production use (client-hub dashboard-mfe, data-integration-service's Kafka -> Delta Lake -> Sigma pipeline for CMS network metrics, bwell-databricks sigma_write schema, Helix) prior to being added to this registry -- see EA-2653. A new dashboard on data not already flowing to Sigma (e.g. a new PHI-adjacent data class) still requires its own Tech Design Review for the data-handling posture, even though the tool itself is approved." + + # ============================================================================ + # Infrastructure & DevOps + # ============================================================================ + infrastructure: + severity: "warn" + approved: + - name: "Terraform" + versions: ["1.5+"] + notes: "IaC standard; all infra changes via Terraform PRs" + required: true + + - name: "Docker" + versions: ["24+"] + notes: "Containerization standard" + required: true + + - name: "Kubernetes" + versions: ["1.28+"] + provider: "AWS EKS" + notes: "Orchestration standard" + + - name: "Helm" + versions: ["3.x"] + notes: "K8s package management; .helm/ structure standard" + + - name: "GitHub Actions" + versions: ["Current"] + notes: "CI/CD standard" + + # ============================================================================ + # Testing Frameworks + # ============================================================================ + testing: + severity: "warn" + approved: + - name: "Jest" + language: "TypeScript/JavaScript" + versions: ["29.x"] + notes: "TypeScript/Node.js testing standard" + + - name: "pytest" + language: "Python" + versions: ["8.x"] + notes: "Python testing standard; pytest-cov for coverage" + + - name: "JUnit 5" + language: "Java" + versions: ["5.10+"] + notes: "Java testing standard; Jacoco for coverage" + + - name: "Playwright" + category: "e2e" + versions: ["1.x"] + notes: "Browser testing for web UIs" + + - name: "Detox" + category: "mobile-e2e" + versions: ["20.x"] + notes: "React Native E2E testing" + + - name: "Karate" + category: "api" + versions: ["1.4+"] + notes: "API contract testing" + + # ============================================================================ + # Linting & Formatting + # ============================================================================ + linting: + severity: "warn" + approved: + - name: "ESLint" + language: "TypeScript/JavaScript" + versions: ["9.x"] + notes: "Flat config (eslint.config.js) preferred; migrate from .eslintrc" + + - name: "Ruff" + language: "Python" + versions: ["0.3+"] + notes: "Python linter; replaces Flake8; combines linting + formatting" + + - name: "Prettier" + language: "TypeScript/JavaScript" + versions: ["3.x"] + notes: "Code formatting; consistent config org-wide" + + # ============================================================================ + # Security Scanning + # ============================================================================ + security: + severity: "warn" + approved: + - name: "Aikido" + category: "SAST/SCA" + versions: ["Current"] + notes: "SAST and dependency scanning; managed by Security team" + + - name: "CodeQL" + category: "SAST" + versions: ["Current"] + notes: "GitHub native SAST; language-specific queries" + +# ============================================================================ +# Migration Notes +# ============================================================================ +migrations: + - from: "Flake8" + to: "Ruff" + status: "Mandatory" + notes: "All repos must migrate to Ruff. Flake8 is deprecated." + + - from: "Black" + to: "Ruff Formatter" + status: "Mandatory" + notes: "Ruff combines linting + formatting; simplifies toolchain. Black is deprecated." + + - from: "Flask" + to: "FastAPI" + status: "Recommended" + notes: "Migrate Flask services to FastAPI for new features; full migration not required immediately" + + - from: ".eslintrc.json" + to: "eslint.config.js" + status: "Recommended" + notes: "ESLint 9+ flat config; improved composability" + +# ============================================================================ +# Restricted Technologies +# ============================================================================ +restricted: + - name: "Go" + reason: "On hold pending language strategy review. Existing Go services (provider-directory, document-processing-handlers) are grandfathered." + exception: "Requires Tech Design Review with EA approval for new services." + severity: "error" + + - name: "SQS" + reason: "Prefer Kafka for cross-service async communication. SQS creates AWS lock-in and lacks CloudEvents support." + exception: "Requires Tech Design Review with EA approval. Must document why Kafka is insufficient." + severity: "warn" + + - name: "New Cache Introduction" + reason: "All cache introductions (Redis, Caffeine, in-memory) require ADR or Tech Design Review" + requiresADR: true + exception: "Document cache strategy, size limits, TTL, eviction policy, tenant isolation approach" + + - name: "New NoSQL Databases" + reason: "Datastores require Tech Design Review; prefer MongoDB/PostgreSQL" + exception: "EA-approved use cases only" + + - name: "Service Meshes" + reason: "Complexity vs. benefit trade-off under evaluation" + exception: "EA-approved pilots only" + + - name: "Client-Side State Management (Redux, MobX, etc.)" + reason: "React Context + hooks preferred for new code" + exception: "Legacy codebases maintain existing patterns" + +# ============================================================================ +# Review Process +# ============================================================================ +reviewProcess: + trigger: "Introduction of technology not listed in this file" + steps: + - "Create JIRA ticket in EA project (type: Tech Design Review)" + - "Submit Technical Design Document with rationale" + - "EA review and approval/rejection" + - "If approved, update this file via PR to icanbwell/.github" + sla: "5 business days for EA review" + appeals: "Escalate to VP Engineering if rejected"