Codex compatibility note:
- Invoke repository skills with
$skill-name in Codex; this mirrored copy rewrites legacy Claude /skill-name references.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required
spawn_agent subagent(s) for that task.
- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs.
When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json (project-specific paths, commands, modules, and workflow/test settings)
docs/project-reference/docs-index-reference.md (routes to the full docs/project-reference/* catalog)
docs/project-reference/lessons.md (always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra):
project-structure-reference.md
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md, domain-entities-reference.md
- Frontend/UI/styling/design-system:
frontend-patterns-reference.md, scss-styling-guide.md, design-system/README.md
- Spec authoring,
docs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.md
- Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.md plus the spec docs above
- Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.md and source Feature Specs under docs/specs/
- Integration test implementation/review:
integration-test-reference.md
- E2E test implementation/review:
e2e-test-reference.md
- Code review/audit work:
code-review-rules.md plus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking: set in_progress when step starts, set completed when step ends.
[BLOCKING] Every completed/skipped step MUST include brief evidence or explicit skip reason.
[BLOCKING] If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
Quick Summary
Goal: Ensure changes preserve architecture boundaries, ownership, message flow, and generated artifact integrity before handoff — validating changed code against layers, service boundaries, message flow, CQRS, repositories, entity events, frontend architecture, generated artifacts, recorded architecture decisions (ADRs), and quality tooling.
Summary:
- Purpose: validate a changeset against architecture rules the project records in its OWN reference docs; classify every finding PASS/WARN/BLOCKED with
file:line proof; self-validate before handoff — one reviewer in the workflow-review-changes pipeline.
- Main phases — run in order: Phase 0 load architecture rules → Phase 1 determine scope → Phase 2 blast radius (if
graph.db) → Phase 3 architecture review (13 categories) → Phase 4 finalize compliance report → Phase 5 $why-review self-validation gate → Next Steps ask the user directly.
- The 13 Phase-3 categories — review EVERY applicable one, serially: 0 quality-tooling baseline · 1 clean-architecture layers · 2 message-bus patterns · 3 CQRS compliance · 4 repository patterns · 5 service-pattern era (legacy vs modern) · 6 entity event handlers · 7 service boundaries · 8 frontend architecture (frontend files only) · 9 ADR / recorded-decision conformance · 10 spec-loop discipline (property-TC + dual-feedback) · 11 scalability & coupling regression (diff-scoped; BLOCKED/WARN) · 12 data, consistency & tenancy boundaries (dual-write, idempotency, isolation level + write skew, unfenced lock, breaking migration, tenant isolation, dataset writer ownership; BLOCKED/WARN). Per category:
Think: derivation → doc rule → source evidence → file:line proof + grep 3+ counterexamples → verdict. NEVER scan categories in parallel; codebase convention wins over a suspected violation. — why: skipping a category silently drops the violation class it uniquely covers.
- Workload-first scalability gate: before judging a scale technique, prove read/write ratio · sustained/peak load · query shapes · data growth · burst/hot-key skew · geography · latency/consistency budgets; then check the reversible ladder (measure/tune → vertical and/or stateless horizontal from headroom + availability → read/write tactics → partition/shard LAST). Missing evidence means INFO/route, never a scale violation. — why: architecture review must catch regressions without penalizing a lean system for scale it does not have.
- Phase 0 is non-negotiable and first: load the project architecture docs (
backend-patterns-reference.md, project-structure-reference.md, frontend-patterns-reference.md, code-review-rules.md) — every rule and base-class/symbol name comes from those docs, NEVER general knowledge; the framework names in Categories 2–8 are illustrative only.
- Universal reasoning comes from
.claude/docs/architecture-knowledge.md (coupling taxonomy + four coupling dimensions, distributed-monolith signature, module-design principles §4, isolation levels + coordination primitives §8-§9, ~100-entry anti-pattern catalog, symptom→root-cause triage, judgment checklists §20) — use it to RECOGNIZE a defect class, then prove it with file:line. The project's own reference docs and accepted ADRs OUTRANK that catalog on every conflict — NEVER flag a deviation from the catalog as a project violation. An anti-pattern match is a HYPOTHESIS until evidence plus the damaged quality attribute are both named. — why: pattern-shape matching without project grounding is exactly the guess-as-fact failure this skill exists to prevent.
- Stay in lane: deep-review only what this skill OWNS (layers, messaging/CQRS/repos/service boundaries, entity events, frontend architecture, quality tooling, generated artifacts, ADRs); record a one-line
→ route to {sibling} pointer for security/performance/DDD/UI/test findings instead of expanding them. — why: duplicated findings across reviewers inflate severity counts and bury issues each reviewer uniquely owns.
- Read-only until validated: self-audit every draft finding against the 11 thinking red flags (
architecture-knowledge.md §20.3) FIRST — a finding whose sacrifice/trade-off you cannot name, or that rests on "best practice", is demoted or deleted, never reworded — then run the Phase 5 $why-review self-validation gate before handoff; fixes happen only in the validated fix loop, and every fix restarts a full review from Phase 0. Write findings to plans/reports/arch-review-{date}-{slug}.md.
Default scope: All uncommitted changes (staged + unstaged). Override: specify files, directories, services, or full codebase.
MANDATORY MUST ATTENTION Plan tasks to READ architecture docs BEFORE reviewing:
docs/project-reference/backend-patterns-reference.md — CQRS, messaging, repos, validation, entity events, layer rules (READ FIRST — primary rules source)
docs/project-reference/project-structure-reference.md — service map, layer structure, DB ownership
docs/project-reference/frontend-patterns-reference.md — component hierarchy, store, API patterns (frontend files only)
docs/project-reference/code-review-rules.md — anti-patterns, conventions
Not found → search: "architecture documentation", "service patterns", "messaging patterns". Rules come from docs — NOT general knowledge.
Workflow:
- Phase 0: Load Architecture Rules — Read project architecture docs (rules come from docs, NEVER general knowledge)
- Phase 1: Determine Scope — Changed files (default) or user-specified scope
- Phase 2: Blast Radius — Run
$graph-blast-radius if graph.db exists
- Phase 3: Architecture Review — Check each file serially against all 13 applicable categories (0 tooling → 12 data, consistency & tenancy)
- Phase 4: Finalize — Generate compliance report with PASS/BLOCKED/WARN verdicts
- Phase 5: Why-Review Self-Validation Gate — Adversarially validate own findings via
$why-review before handoff (MANDATORY when any finding exists)
- Next Steps — ask the user directly:
$code-simplifier / $code-review / skip
Key Rules (top 3 critical first):
- MUST ATTENTION read project architecture docs in Phase 0 BEFORE reviewing — rules come from docs, NEVER general knowledge.
- Every violation needs
file:line proof + grep 3+ counterexamples before flagging — NEVER speculate.
- MUST ATTENTION review one category at a time: doc rule → source evidence → verdict — NEVER scan categories simultaneously.
- Write findings to
plans/reports/arch-review-{date}-{slug}.md.
- BLOCKED = must fix before merge | WARN = review and decide | PASS = compliant.
- Review is read-only until
$why-review --validate-findings confirms findings; fixes happen only in the validated fix loop or downstream plan/feature-implement, and every fix restarts a full architecture review from Phase 0 with a fresh task breakdown.
Your Mission
First Principle — Easy to Change
Success metric: future change cost. DRY, SRP, abstraction, patterns, naming, layering, tests exist to make next change cheaper.
Before applying any rule, ask: does this lower or raise future change cost?
- Reject "best practices" raising cost: premature abstraction, speculative generality, leaky indirection, ceremony without payoff. — why: cost added now with no payoff is debt, not quality.
- Name real enemies: coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early.
- Prefer simple reversible design over sophisticated rigid design. — why: reversible decisions cost less to undo when wrong.
- If downstream rule raises change cost, this principle wins.
Quality Tooling Principle — Tech-Stack Adaptive
Architecture review includes automated quality guardrails. Without stack-appropriate linting, formatting, type checks, static analysis, dependency/security-review scanning, CI enforcement, defects depend on reviewer memory.
Evaluate detected stacks, not fixed tool list:
- Detect stacks from project-reference docs, manifests, lock files, build files, CI before recommending tools.
- Per production stack, verify formatter/style config, linter/code analyzer, compiler/type-check strictness, dependency/vulnerability scanning, tests/coverage, CI/pre-commit enforcement.
- Prefer official or ecosystem-standard tooling; local docs absent/stale → check current official docs before recommending setup.
- MUST ATTENTION recommend enforceable best practice only: installed but unwired tool = WARN; production source with no relevant automated quality gate = BLOCKED.
- Identify missing capability first; map to local equivalent before prescribing new tooling. — why: prescribing a tool that duplicates an existing gate adds noise, not coverage.
Review Mindset (NON-NEGOTIABLE)
Skeptical. Every claim needs traced proof, confidence >80%.
- NEVER flag violations without reading actual code + tracing dependency — READ the code, trace the import chain, then flag.
- Every finding MUST include
file:line evidence.
- Before flagging pattern violation: grep 3+ existing examples — codebase convention wins.
- Question: "Actually a violation, or an established exception?"
Ownership & Handoff (own vs delegate)
This skill = one reviewer in a multi-reviewer pipeline — workflow-review-changes runs it beside the siblings below. Review ONLY what this skill owns; route the rest so findings are not double-reported across reviewers.
| This skill OWNS (deep-review here) |
Delegate to sibling (one-line pointer only — do NOT deep-review) |
| Layer boundaries, dependency direction, business-logic placement |
— |
| Messaging patterns, CQRS structure, repository patterns, service-pattern era, entity event handlers, service boundaries |
— |
| Frontend ARCHITECTURE (base classes, store/effect, API-service base, subscription teardown, CSS-class presence) |
Visual/SCSS/responsive/z-index quality → ui-review |
| Quality-tooling baseline, generated-artifact integrity, ADR / recorded-decision conformance |
— |
| Architecture-level auth PLACEMENT (a gate exists at the boundary) |
OWASP, secrets, dependency/supply-chain, authz-matrix depth → security-review |
| Structural soundness of a hot path (no obvious N+1 introduced by the diff) |
Query plans, indexing depth, latency/throughput budgets → performance-review |
| — |
Domain entity / value-object DDD design quality → domain-entities-review |
| — |
Integration-test assertion quality, coverage, traceability → integration-test-review |
| — |
Runtime production-readiness of service/API changes (observability wiring, rollback) → production-readiness-review |
When a finding clearly belongs to a sibling, record one-line → route to {skill} pointer and move on — NEVER expand it. — why: duplicated findings across reviewers inflate severity counts and bury issues each reviewer uniquely owns.
Phase 0: Load Architecture Rules (MANDATORY FIRST)
MUST ATTENTION: Read project docs BEFORE reviewing. Rules come from docs, NEVER general knowledge.
- read
docs/project-reference/backend-patterns-reference.md — extract messaging naming, layer rules, CQRS patterns, repo rules, entity event handler patterns, validation patterns
- read
docs/project-reference/project-structure-reference.md — extract service map, layer structure, DB ownership
- frontend files in scope → read
docs/project-reference/frontend-patterns-reference.md
- read
docs/project-reference/code-review-rules.md — extract anti-patterns + review rules directly
Universal reasoning layer (secondary, never authoritative): consult .claude/docs/architecture-knowledge.md for the coupling taxonomy + four coupling dimensions, the distributed-monolith detection signature, the ~100-entry anti-pattern catalog, and the symptom→root-cause triage matrix. Use it to RECOGNIZE a defect class the project docs do not name explicitly. Honor its provenance markers in §3/§8/§9/§10: a row or section banner marked — VERIFY is an UNVERIFIED assertion — it may seed a hypothesis, but NEVER quote it as the authority for a finding; confirm against the named source (or the project's own docs) first.
MUST ATTENTION — precedence is absolute. Project reference docs and accepted ADRs > the knowledge catalog > general knowledge. NEVER report a deviation from the catalog as a project violation, and NEVER let a catalog entry override an established, grepped codebase convention. Every catalog-derived observation is a HYPOTHESIS until you have BOTH file:line/config/topology evidence AND the named quality attribute it damages — otherwise record it as INFO or drop it. — why: universal patterns applied as project rules generate confident false positives, the most expensive output this skill can produce.
Phase 1: Determine Scope
Default (no override): Review all uncommitted changes.
git status # List changed files
git diff # Staged + unstaged changes
git diff --cached # Staged only
- Collect file list to review.
- Categorize: backend (.cs), frontend (.ts/.html), config, docs, other.
- Filter to architecture-relevant files (skip pure docs, configs, tests unless architecture-relevant).
Phase 2: Blast Radius (if graph.db exists)
.code-graph/graph.db exists → call $graph-blast-radius skill.
- Record: impacted file count, cross-service impact, risk level.
- Prioritize review by highest-impact files first.
- Graph unavailable → note "Graph not available — skipping blast radius" and proceed.
Per changed file with downstream impact:
python .claude/scripts/code_graph trace <changed-file> --direction downstream --json
Flag MESSAGE_BUS consumers or event handlers impacted by changes.
Phase 3: Architecture Review
Create report: plans/reports/arch-review-{date}-{slug}.md
Per file in scope, evaluate against ALL applicable categories. Skip categories not applicable to file type.
MUST ATTENTION review serially. Per applicable category: read docs/source evidence → derive risk with Think: → grep 3+ examples/counterexamples → record PASS/WARN/BLOCKED. NEVER scan categories simultaneously — why: parallel scanning collapses per-category evidence into one undifferentiated pass and drops findings.
Portability note (MUST ATTENTION): Framework symbols, base-class names, directory conventions in Categories 2–8 below are illustrative examples — authoritative form comes from Phase 0 reference docs (backend-patterns-reference.md, frontend-patterns-reference.md, project-structure-reference.md); verify code against those docs. On any stack, map each example to project's equivalent as named in its own reference docs, flag deviations from project's actual convention — NEVER from these literal names. Same discipline as Category 5: read project docs at review time; NEVER treat a hardcoded name as universal.
Category 0: Quality Tooling Baseline — Severity: BLOCKED/WARN
Think: Can project automatically catch style, type, complexity, security, dependency, boundary regressions for detected stacks?
- Detect production stacks via
docs/project-config.json, relevant docs, manifests, lock files, build files, CI.
- Inventory gates: formatter, linter, code/static analyzer, compiler/type checker, dependency audit/SCA/SBOM, SAST, test/coverage, architecture/dependency-boundary checks, pre-commit, CI/build.
- Verify stack-appropriate coverage:
.editorconfig/language analyzers, JavaScript/TypeScript linting, UI template linting when supported, formatter config, dependency vulnerability scans, semantic security analysis.
- BLOCKED when production stack lacks runnable lint/static-analysis/type-check command and equivalent enforced gate, or CI/build references missing/broken quality command.
- WARN when tooling local-only, not wired into CI/build/pre-commit, partial for active production code, broadly/unexplainedly suppressed, unclear on generated-code exclusions, or stale for stack.
- Scope to the change (MUST ATTENTION): On normal change-level review, pre-existing tooling gap unrelated to diff is WARN with single note — NEVER BLOCK whole review on standing, change-unrelated condition. Reserve BLOCKED for: new stack/service introduced by this change with no gate, change itself removing/breaking existing gate, or explicit full-codebase/greenfield audit scope. — why: change review that BLOCKs on unrelated standing gap produces noise that buries regression the diff actually introduced.
- Before recommending tools, find current official/ecosystem setup and cite it; recommend capabilities first, tools second.
Fitness-function enforcement (architectural rules must be EXECUTABLE): an architectural rule not automatically verified is a SUGGESTION and will be violated within a quarter. Check whether the project's own recorded architectural rules have a machine check — and whether THIS change adds a rule with no check:
| Rule the project records |
Fitness function expected (any equivalent counts) |
| Layer / dependency direction |
Architecture test in CI (ArchUnit / NetArchTest / dependency-cruiser / import-linter / lint boundary rules) |
| No module cycles |
Cycle detection failing the build |
| Domain purity |
Assertion that the domain package imports no framework/ORM/HTTP namespace |
| API / event schema compatibility |
OpenAPI-or-protobuf diff gate · schema-registry backward-compat check · consumer contract tests |
| Multi-tenant isolation |
Test asserting a cross-tenant query returns zero rows (see Category 12) |
| Resilience |
"Every outbound call has a timeout" lint or test |
| Performance / bundle budget |
Latency-or-size assertion in the pipeline |
- WARN when a recorded architectural rule has NO machine check and relies on review discipline alone. BLOCKED when this change REMOVES or disables an existing architecture/boundary check, or introduces a new enforced-by-prose-only boundary while the project already has a fitness-function mechanism available.
- Existing violation backlog is fine if it is a RATCHET (new violations blocked, count only decrements) — a "cleanup later" comment with no gate is WARN.
Violation format:
BLOCKED: {stack} has no enforced lint/static-analysis/type-check quality gate ({evidenceFile}:{line})
WARN: recorded architecture rule "{rule}" has no fitness function — enforced by review discipline only ({docFile}:{line})
Category 1: Clean Architecture Layers — Severity: BLOCKED
Think: What layer is this file in? What layers can it legally import from? Does any import break inward-only flow (Service/API → Application → Domain ← Persistence)?
- Read
docs/project-config.json → architectureRules.layerBoundaries for project-specific rules.
- Determine layer from file path: Domain/, Application/, Persistence/, Service/.
- Scan configured language's import/include statements — flag imports from forbidden layers.
- MUST ATTENTION verify business logic in correct layer: Entity/Domain > Service/Application > Controller/Component.
- NEVER allow direct infrastructure access from Domain — keep repo interfaces in Domain, implementations in Persistence. — why: Domain depending on infrastructure inverts the dependency rule and couples core logic to a swappable detail.
- NEVER allow business logic in API/Controller layer — push it down to Entity/Domain or Application.
- Module cycles (BLOCKED): a cycle in the module/package dependency graph means the two modules ARE one deployable unit whatever the folder structure says. Detect with the graph (
trace --direction both) or the project's dependency tool; flag any NEW cycle the diff introduces. — why: an unbroken cycle makes independent testing, release and extraction impossible, and it never gets easier to cut later.
- Domain purity (BLOCKED): the domain layer MUST NOT import ORM attributes, HTTP types, SQL, serialization or framework namespaces. Grep the changed domain files for the infrastructure namespaces named in
backend-patterns-reference.md.
- Shared/infra layer domain leak (BLOCKED): a generic/shared/infrastructure layer MUST reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. This leak compiles, runs, and passes functional tests while silently coupling the "reusable" layer to one consumer. Fix by keeping the shared type domain-free and pushing domain fields down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable, and every later consumer inherits the wrong abstraction.
- Cohesion / dumping ground (WARN): a new or growing
Utils/Common/Shared/Helpers/Managers module that everything imports is coincidental cohesion — it becomes the coupling hub and the cycle source. Test: "how many DIFFERENT reasons would make me edit this file?" More than one actor ⇒ split.
- Pass-through layer (WARN): a layer that only forwards calls unchanged (sinkhole) adds cost with no responsibility — collapse it or give it a real job.
- Shallow module / pass-through method (WARN): a new type whose public interface is nearly as large as its implementation, or a method that only forwards to the next layer with no added responsibility, earns nothing — it is interface cost with no hidden complexity. Judge module VALUE as functionality hidden ÷ interface surface: many tiny one-method classes ("classitis") raise total complexity while looking modular. Prefer pulling the complexity DOWNWARD into one deep module over spreading it across N call sites. — why: reviewers count classes and read it as modularity, so this defect is the one that survives review and then makes every future change touch five files.
- DIP placement (WARN, BLOCKED when the project's docs require it): dependency inversion is only real when the interface lives in the domain/policy package and the adapter package depends inward. An interface declared beside its single implementation in the infrastructure package is a naming convention, not inversion — grep where the changed port/interface is DECLARED, not merely where it is used. — why: an interface in the infra package leaves the dependency arrow pointing the wrong way while the code reads as clean architecture.
- Wrong-abstraction extraction (WARN): a diff that MERGES two code paths that look alike but change for DIFFERENT reasons creates a shared module with two actors. Duplication is cheaper than the wrong abstraction — require three real occurrences sharing the same reason to change (rule of three) before extracting. Verify against the project's own strategic-DRY decision before flagging. — why: a premature abstraction is defended by everyone who depends on it, so its cost compounds while duplication's cost stays linear.
Violation format:
BLOCKED: {layer} layer file {filePath}:{line} imports from {forbiddenLayer} layer ({importStatement})
BLOCKED: {filePath}:{line} introduces module cycle {A} → {B} → {A}
BLOCKED: shared/infra {filePath}:{line} references consumer domain concept {concept} — shared layer must stay domain-free
Category 2: Message Bus Patterns — Severity: BLOCKED/WARN
Think: Does this message correctly name its type (event vs request)? Does it extend the right base class? Is producer/consumer relationship correctly oriented — does the leader service own the event?
Naming (BLOCKED):
- Event messages + request messages MUST follow project's bus-message naming convention — encode owning service + feature + action, with distinct suffix distinguishing event-kind from request-kind messages. Resolve exact convention + suffixes from
backend-patterns-reference.md.
- Grep existing examples in source for current stack's message-naming pattern before flagging — codebase convention wins.
Base classes (BLOCKED): Verify against bus base types named in backend-patterns-reference.md (Phase 0); concrete names are illustrative examples.
- Bus messages MUST extend project's trackable/payload bus-message base — see
backend-patterns-reference.md.
- Consumers MUST extend project's message-bus consumer base — see
backend-patterns-reference.md.
- Producers MUST extend project's event-bus-message producer base — see
backend-patterns-reference.md.
Upstream/Downstream (BLOCKED):
- Leader service owns entity data → defines event message for it.
- Follower services consume events — NEVER produce events about data they don't own. — why: producing events about non-owned data forks the source of truth across services.
- NO circular listening: A→B + B→A for same data = boundary violation.
- Consumers MUST implement project's cross-message dependency-wait primitive for cross-message data dependencies — see
backend-patterns-reference.md.
Ordered delivery (WARN):
- Messages requiring ordered processing MUST set project's ordered-delivery / sub-queue partition key to meaningful value (resolve concrete API from
backend-patterns-reference.md).
- Unordered messages leave it unset / null.
Reliable publication — dual write (BLOCKED):
- NEVER write the database and publish a message as two independent operations. Any changed flow that commits state AND publishes MUST go through the project's inbox/outbox mechanism or CDC (verify the project's inbox/outbox enablement config — see
backend-patterns-reference.md). — why: dual write fails silently in both directions — DB commits + publish fails ⇒ downstream never learns and diverges forever; publish succeeds + DB rolls back ⇒ phantom downstream data referencing a row that does not exist. Neither failure appears in tests or logs.
- Consumer idempotency (BLOCKED): exactly-once DELIVERY is impossible, so at-least-once is what the bus gives you. Every changed consumer MUST be idempotent — dedup on message ID with a TTL, a version/sequence check that discards backward transitions, or a naturally idempotent write (
SET status = 'paid', never balance += x). Grep the handler for the project's dedup primitive. — why: a non-idempotent consumer produces duplicate side effects — double charge, double email, double shipment — only under redelivery, which is exactly when nobody is watching.
- Poison message + queue bounds (WARN): capped retries with exponential backoff and jitter, then DLQ; DLQ depth monitored. Flag unbounded queues, uncapped/infinite retry, and unjittered retry (synchronizes into a thundering herd). A DLQ nobody watches is data loss with extra steps.
- Command-in-event-costume (WARN): an "event" with exactly ONE permitted consumer that MUST handle it, whose failure means the business flow failed, is a command misnamed as an event — you pay async debugging difficulty AND keep the sync coupling. Flag the naming, route the redesign to
domain-analysis.
- Raw-row events (WARN): publishing internal DB rows/columns as the event contract (CDC with no mapping layer) freezes your schema as a public contract by Hyrum's Law — consumers then depend on columns you can never rename.
- Durability acknowledgement weakened (BLOCKED when a diff lowers it, WARN when newly introduced): a change to producer ack mode, replication factor, or min-in-sync-replicas that accepts data loss on leader failure.
acks=1 loses the message when the leader dies before replication; acks=all waits for every replica CURRENTLY in the ISR, so min.insync.replicas is the FLOOR that decides whether a shrunken ISR rejects the write or accepts it with no error — with min.insync=1 a healthy 3-replica ISR still waits for 3, but durability DEGRADES to acks=1 the moment the ISR shrinks to the leader alone. Check BOTH values together, never one alone, and flag the degradation path rather than asserting an unconditional equivalence. — why: the config reads as durable while the guarantee is not, and the loss appears only during the failover nobody rehearsed.
- Ordering/replay assumption unmet (WARN): a changed consumer that assumes global ordering when the broker gives ordering only per partition key, or that assumes replay is available on a consume-and-gone queue. Verify the required ordering scope (global / per-entity / none) and replay window against the project's broker config. Queue-vs-log semantics →
.claude/docs/architecture-knowledge.md §10.
Also verify:
- NEVER direct cross-service DB access — MUST use message bus. — why: direct DB reach couples services and bypasses ownership boundaries.
- last-sync-timestamp field on message used for conflict resolution in consumers (resolve concrete field from
backend-patterns-reference.md).
- Event schema changes are backward-compatible (a rolling deploy runs old and new consumers simultaneously) — a breaking schema change with no versioning or compatibility gate is BLOCKED.
Violation format:
BLOCKED: {filePath}:{line} writes DB then publishes without outbox/CDC — dual write, silent divergence on partial failure
BLOCKED: {filePath}:{line} consumer is not idempotent — no dedup/version check under at-least-once delivery
Category 3: CQRS Compliance — Severity: BLOCKED/WARN
Think: Is Command+Result+Handler in one file? Is validation using fluent API (not exceptions)? Does DTO own mapping, not the handler? Are side effects in event handlers, not command handlers?
File organization (BLOCKED):
- Command + Result + Handler MUST be in ONE file under the command folder for the feature (resolve concrete folder from project's structure reference /
docs/project-config.json; e.g. {command-folder}/{Feature}/)
- Query + Result + Handler MUST be in ONE file under the query folder for the feature (resolve concrete folder from project's structure reference /
docs/project-config.json; e.g. {query-folder}/{Feature}/)
Validation (BLOCKED):
- MUST use project's validation-result fluent API — NEVER throw exceptions for validation; return validation result instead — verify exact type + method names in
backend-patterns-reference.md. — why: exceptions for expected-invalid input conflate control flow with errors and skip the validation pipeline.
- Sync validation in command's validate hook, async in request-validation hook — see
backend-patterns-reference.md for hook names.
DTO mapping (BLOCKED):
- DTOs MUST own entity mapping via project's DTO base mapping methods — NEVER map in command handlers; map in the DTO instead — see
backend-patterns-reference.md for method names.
Side effects (BLOCKED):
- NEVER put side effects (notifications, sync, cascade updates) in command handlers — place them in Entity Event Handlers instead. — why: side effects in the handler couple the command to downstream concerns and cascade failures.
- Side effects go in Entity Event Handlers under project's event-handler folder (resolve from project's structure reference /
docs/project-config.json; e.g. {event-handler-folder}/)
- Each handler = one independent concern (failures don't cascade).
Category 4: Repository Patterns — Severity: BLOCKED
Think: Is this using a service-specific repo interface, not the generic one? Are complex queries extracted to RepositoryExtensions?
- MUST use project's service-specific repository abstraction — NEVER the generic root-repository base directly; per-service naming scheme defined in
backend-patterns-reference.md. — why: the generic base leaks unbounded query surface and erases per-service boundaries.
- Complex queries MUST use project's repository-extension pattern with static expressions (e.g.
RepositoryExtensions)
- All query filter/FK/sort columns MUST have database indexes.
Violation format:
BLOCKED: {filePath}:{line} uses the generic root-repository base instead of the service-specific repository — see backend-patterns-reference.md for the required naming
Category 5: Service Pattern Era (Legacy vs Modern Split) — Severity: BLOCKED (new services) / WARN (existing)
Think: When project distinguishes legacy vs modern service patterns (e.g., auth scheme, telemetry stack, permission model, language-version syntax), is this a new service (must follow modern) or an existing legacy service (expect legacy patterns)? Is the modern pattern partially mixed into a legacy service without full migration?
New services — BLOCKED if any legacy-only pattern used. Identify project's modern-pattern checklist from injected reference docs (e.g., project-structure-reference.md, ADRs, scaffolding templates) and verify every item.
Existing legacy services — WARN if modern patterns partially mixed without full migration. Flag legacy patterns only when partial mixing creates inconsistency; in their own consistent context they are expected, NOT violations.
Determining era: Read project's reference docs at review time — service-pattern era assignments are project-specific and listed authoritatively there. NEVER hardcode service names in this skill. — why: hardcoded service names rot the moment the project renames or adds a service, and break portability to other repos.
Category 6: Entity Event Handlers — Severity: BLOCKED/WARN
Think: Are side effects defined inline in command handlers (wrong) or in project's event-handler folder (correct)? Does each handler have a single concern?
Location (BLOCKED):
- Entity event handlers MUST be in project's event-handler folder (resolve from project's structure reference /
docs/project-config.json; e.g. {event-handler-folder}/)
- NEVER inline side effects in command handlers — move them to a dedicated entity event handler. — why: inline side effects couple the command to downstream concerns and cascade failures.
Implementation (BLOCKED):
- MUST extend project's entity-event application-handler base — see
backend-patterns-reference.md.
- MUST implement CRUD-action filter hook — see `backend-patterns-reference
…(truncated)
1---2name: architecture-review3description: "[Code Quality] Use when reviewing architecture compliance for layers, messaging, service boundaries, CQRS, repos, entity events, and data/consistency/tenancy boundaries. Universal architecture laws, coupling taxonomy and the anti-pattern catalog live in `.claude/docs/architecture-knowledge.md` (project docs always outrank it)."4---56> Codex compatibility note:7>8> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.9> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.10> - User-question prompts mean to ask the user directly in Codex.11> - Ignore Claude-specific mode-switch instructions when they appear.12> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.13> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.14> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.15> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.16> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.1718<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->1920## Codex Project-Reference Loading (No Hooks)2122Codex uses static project-reference loading instead of runtime-injected project docs.23When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.2425**Always read:**2627- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)28- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)29- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)3031**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.3233**Situation-based docs:**3435- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`36- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`37- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`38- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`39- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above40- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`41- Integration test implementation/review: `integration-test-reference.md`42- E2E test implementation/review: `e2e-test-reference.md`43- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files4445Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.4647<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->4849<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->5051> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.52> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.53> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.54> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.5556<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->5758## Quick Summary5960**Goal:** Ensure changes preserve architecture boundaries, ownership, message flow, and generated artifact integrity before handoff — validating changed code against layers, service boundaries, message flow, CQRS, repositories, entity events, frontend architecture, generated artifacts, recorded architecture decisions (ADRs), and quality tooling.6162**Summary:**6364- **Purpose:** validate a changeset against architecture rules the project records in its OWN reference docs; classify every finding PASS/WARN/BLOCKED with `file:line` proof; self-validate before handoff — one reviewer in the `workflow-review-changes` pipeline.65- **Main phases — run in order:** Phase 0 load architecture rules → Phase 1 determine scope → Phase 2 blast radius (if `graph.db`) → Phase 3 architecture review (13 categories) → Phase 4 finalize compliance report → Phase 5 `$why-review` self-validation gate → Next Steps ask the user directly.66- **The 13 Phase-3 categories — review EVERY applicable one, serially:** 0 quality-tooling baseline · 1 clean-architecture layers · 2 message-bus patterns · 3 CQRS compliance · 4 repository patterns · 5 service-pattern era (legacy vs modern) · 6 entity event handlers · 7 service boundaries · 8 frontend architecture (frontend files only) · 9 ADR / recorded-decision conformance · 10 spec-loop discipline (property-TC + dual-feedback) · 11 scalability & coupling regression (diff-scoped; BLOCKED/WARN) · **12 data, consistency & tenancy boundaries (dual-write, idempotency, isolation level + write skew, unfenced lock, breaking migration, tenant isolation, dataset writer ownership; BLOCKED/WARN)**. Per category: `Think:` derivation → doc rule → source evidence → `file:line` proof + grep 3+ counterexamples → verdict. NEVER scan categories in parallel; codebase convention wins over a suspected violation. — why: skipping a category silently drops the violation class it uniquely covers.67- **Workload-first scalability gate:** before judging a scale technique, prove read/write ratio · sustained/peak load · query shapes · data growth · burst/hot-key skew · geography · latency/consistency budgets; then check the reversible ladder (measure/tune → vertical and/or stateless horizontal from headroom + availability → read/write tactics → partition/shard LAST). Missing evidence means INFO/route, never a scale violation. — why: architecture review must catch regressions without penalizing a lean system for scale it does not have.68- Phase 0 is non-negotiable and first: load the project architecture docs (`backend-patterns-reference.md`, `project-structure-reference.md`, `frontend-patterns-reference.md`, `code-review-rules.md`) — every rule and base-class/symbol name comes from those docs, NEVER general knowledge; the framework names in Categories 2–8 are illustrative only.69- **Universal reasoning comes from `.claude/docs/architecture-knowledge.md`** (coupling taxonomy + four coupling dimensions, distributed-monolith signature, module-design principles §4, isolation levels + coordination primitives §8-§9, ~100-entry anti-pattern catalog, symptom→root-cause triage, judgment checklists §20) — use it to RECOGNIZE a defect class, then prove it with `file:line`. **The project's own reference docs and accepted ADRs OUTRANK that catalog on every conflict — NEVER flag a deviation from the catalog as a project violation.** An anti-pattern match is a HYPOTHESIS until evidence plus the damaged quality attribute are both named. — why: pattern-shape matching without project grounding is exactly the guess-as-fact failure this skill exists to prevent.70- Stay in lane: deep-review only what this skill OWNS (layers, messaging/CQRS/repos/service boundaries, entity events, frontend architecture, quality tooling, generated artifacts, ADRs); record a one-line `→ route to {sibling}` pointer for security/performance/DDD/UI/test findings instead of expanding them. — why: duplicated findings across reviewers inflate severity counts and bury issues each reviewer uniquely owns.71- Read-only until validated: **self-audit every draft finding against the 11 thinking red flags (`architecture-knowledge.md` §20.3) FIRST** — a finding whose sacrifice/trade-off you cannot name, or that rests on "best practice", is demoted or deleted, never reworded — then run the Phase 5 `$why-review` self-validation gate before handoff; fixes happen only in the validated fix loop, and every fix restarts a full review from Phase 0. Write findings to `plans/reports/arch-review-{date}-{slug}.md`.7273**Default scope:** All uncommitted changes (staged + unstaged). Override: specify files, directories, services, or full codebase.7475> **MANDATORY MUST ATTENTION** Plan tasks to READ architecture docs BEFORE reviewing:76>77> 1. `docs/project-reference/backend-patterns-reference.md` — CQRS, messaging, repos, validation, entity events, layer rules **(READ FIRST — primary rules source)**78> 2. `docs/project-reference/project-structure-reference.md` — service map, layer structure, DB ownership79> 3. `docs/project-reference/frontend-patterns-reference.md` — component hierarchy, store, API patterns **(frontend files only)**80> 4. `docs/project-reference/code-review-rules.md` — anti-patterns, conventions81>82> Not found → search: "architecture documentation", "service patterns", "messaging patterns". Rules come from docs — NOT general knowledge.8384**Workflow:**85861. **Phase 0: Load Architecture Rules** — Read project architecture docs (rules come from docs, NEVER general knowledge)872. **Phase 1: Determine Scope** — Changed files (default) or user-specified scope883. **Phase 2: Blast Radius** — Run `$graph-blast-radius` if `graph.db` exists894. **Phase 3: Architecture Review** — Check each file serially against all 13 applicable categories (0 tooling → 12 data, consistency & tenancy)905. **Phase 4: Finalize** — Generate compliance report with PASS/BLOCKED/WARN verdicts916. **Phase 5: Why-Review Self-Validation Gate** — Adversarially validate own findings via `$why-review` before handoff (MANDATORY when any finding exists)927. **Next Steps** — ask the user directly: `$code-simplifier` / `$code-review` / skip9394**Key Rules (top 3 critical first):**9596- MUST ATTENTION read project architecture docs in Phase 0 BEFORE reviewing — rules come from docs, NEVER general knowledge.97- Every violation needs `file:line` proof + grep 3+ counterexamples before flagging — NEVER speculate.98- MUST ATTENTION review one category at a time: doc rule → source evidence → verdict — NEVER scan categories simultaneously.99- Write findings to `plans/reports/arch-review-{date}-{slug}.md`.100- BLOCKED = must fix before merge | WARN = review and decide | PASS = compliant.101- Review is read-only until `$why-review --validate-findings` confirms findings; fixes happen only in the validated fix loop or downstream plan/feature-implement, and every fix restarts a full architecture review from Phase 0 with a fresh task breakdown.102103## Your Mission104105<task>106$ARGUMENTS107</task>108109## First Principle — Easy to Change110111> **Success metric: future change cost.** DRY, SRP, abstraction, patterns, naming, layering, tests exist to make next change cheaper.112113Before applying any rule, ask: **does this lower or raise future change cost?**114115- Reject "best practices" raising cost: premature abstraction, speculative generality, leaky indirection, ceremony without payoff. — why: cost added now with no payoff is debt, not quality.116- Name real enemies: **coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early**.117- Prefer simple reversible design over sophisticated rigid design. — why: reversible decisions cost less to undo when wrong.118- If downstream rule raises change cost, this principle wins.119120---121122## Quality Tooling Principle — Tech-Stack Adaptive123124> Architecture review includes automated quality guardrails. Without stack-appropriate linting, formatting, type checks, static analysis, dependency/security-review scanning, CI enforcement, defects depend on reviewer memory.125126Evaluate detected stacks, not fixed tool list:127128- Detect stacks from project-reference docs, manifests, lock files, build files, CI before recommending tools.129- Per production stack, verify formatter/style config, linter/code analyzer, compiler/type-check strictness, dependency/vulnerability scanning, tests/coverage, CI/pre-commit enforcement.130- Prefer official or ecosystem-standard tooling; local docs absent/stale → check current official docs before recommending setup.131- MUST ATTENTION recommend enforceable best practice only: installed but unwired tool = WARN; production source with no relevant automated quality gate = BLOCKED.132- Identify missing capability first; map to local equivalent before prescribing new tooling. — why: prescribing a tool that duplicates an existing gate adds noise, not coverage.133134---135136## Review Mindset (NON-NEGOTIABLE)137138Skeptical. Every claim needs traced proof, confidence >80%.139140- NEVER flag violations without reading actual code + tracing dependency — READ the code, trace the import chain, then flag.141- Every finding MUST include `file:line` evidence.142- Before flagging pattern violation: grep 3+ existing examples — codebase convention wins.143- Question: "Actually a violation, or an established exception?"144145## Ownership & Handoff (own vs delegate)146147This skill = one reviewer in a multi-reviewer pipeline — `workflow-review-changes` runs it beside the siblings below. Review ONLY what this skill owns; route the rest so findings are not double-reported across reviewers.148149| This skill OWNS (deep-review here) | Delegate to sibling (one-line pointer only — do NOT deep-review) |150| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |151| Layer boundaries, dependency direction, business-logic placement | — |152| Messaging patterns, CQRS structure, repository patterns, service-pattern era, entity event handlers, service boundaries | — |153| Frontend ARCHITECTURE (base classes, store/effect, API-service base, subscription teardown, CSS-class presence) | Visual/SCSS/responsive/z-index quality → `ui-review` |154| Quality-tooling baseline, generated-artifact integrity, ADR / recorded-decision conformance | — |155| Architecture-level auth PLACEMENT (a gate exists at the boundary) | OWASP, secrets, dependency/supply-chain, authz-matrix depth → `security-review` |156| Structural soundness of a hot path (no obvious N+1 introduced by the diff) | Query plans, indexing depth, latency/throughput budgets → `performance-review` |157| — | Domain entity / value-object DDD design quality → `domain-entities-review` |158| — | Integration-test assertion quality, coverage, traceability → `integration-test-review` |159| — | Runtime production-readiness of service/API changes (observability wiring, rollback) → `production-readiness-review` |160161When a finding clearly belongs to a sibling, record one-line `→ route to {skill}` pointer and move on — NEVER expand it. — why: duplicated findings across reviewers inflate severity counts and bury issues each reviewer uniquely owns.162163## Phase 0: Load Architecture Rules (MANDATORY FIRST)164165> **MUST ATTENTION:** Read project docs BEFORE reviewing. Rules come from docs, NEVER general knowledge.166167- read `docs/project-reference/backend-patterns-reference.md` — extract messaging naming, layer rules, CQRS patterns, repo rules, entity event handler patterns, validation patterns168- read `docs/project-reference/project-structure-reference.md` — extract service map, layer structure, DB ownership169- frontend files in scope → read `docs/project-reference/frontend-patterns-reference.md`170- read `docs/project-reference/code-review-rules.md` — extract anti-patterns + review rules directly171172**Universal reasoning layer (secondary, never authoritative):** consult `.claude/docs/architecture-knowledge.md` for the coupling taxonomy + four coupling dimensions, the distributed-monolith detection signature, the ~100-entry anti-pattern catalog, and the symptom→root-cause triage matrix. Use it to RECOGNIZE a defect class the project docs do not name explicitly. **Honor its provenance markers in §3/§8/§9/§10:** a row or section banner marked `— VERIFY` is an UNVERIFIED assertion — it may seed a hypothesis, but NEVER quote it as the authority for a finding; confirm against the named source (or the project's own docs) first.173174> **MUST ATTENTION — precedence is absolute.** Project reference docs and accepted ADRs > the knowledge catalog > general knowledge. **NEVER report a deviation from the catalog as a project violation**, and NEVER let a catalog entry override an established, grepped codebase convention. Every catalog-derived observation is a HYPOTHESIS until you have BOTH `file:line`/config/topology evidence AND the named quality attribute it damages — otherwise record it as INFO or drop it. — why: universal patterns applied as project rules generate confident false positives, the most expensive output this skill can produce.175176## Phase 1: Determine Scope177178**Default (no override):** Review all uncommitted changes.179180```bash181git status # List changed files182git diff # Staged + unstaged changes183git diff --cached # Staged only184```185186- Collect file list to review.187- Categorize: backend (.cs), frontend (.ts/.html), config, docs, other.188- Filter to architecture-relevant files (skip pure docs, configs, tests unless architecture-relevant).189190## Phase 2: Blast Radius (if graph.db exists)191192- `.code-graph/graph.db` exists → call `$graph-blast-radius` skill.193- Record: impacted file count, cross-service impact, risk level.194- Prioritize review by highest-impact files first.195- Graph unavailable → note "Graph not available — skipping blast radius" and proceed.196197Per changed file with downstream impact:198199```bash200python .claude/scripts/code_graph trace <changed-file> --direction downstream --json201```202203Flag MESSAGE_BUS consumers or event handlers impacted by changes.204205## Phase 3: Architecture Review206207Create report: `plans/reports/arch-review-{date}-{slug}.md`208209Per file in scope, evaluate against ALL applicable categories. Skip categories not applicable to file type.210211MUST ATTENTION review serially. Per applicable category: read docs/source evidence → derive risk with `Think:` → grep 3+ examples/counterexamples → record PASS/WARN/BLOCKED. NEVER scan categories simultaneously — why: parallel scanning collapses per-category evidence into one undifferentiated pass and drops findings.212213> **Portability note (MUST ATTENTION):** Framework symbols, base-class names, directory conventions in Categories 2–8 below are **illustrative examples** — authoritative form comes from Phase 0 reference docs (`backend-patterns-reference.md`, `frontend-patterns-reference.md`, `project-structure-reference.md`); verify code against those docs. On any stack, map each example to project's equivalent as named in its own reference docs, flag deviations from project's **actual** convention — NEVER from these literal names. Same discipline as Category 5: read project docs at review time; NEVER treat a hardcoded name as universal.214215---216217### Category 0: Quality Tooling Baseline — Severity: BLOCKED/WARN218219**Think:** Can project automatically catch style, type, complexity, security, dependency, boundary regressions for detected stacks?220221- Detect production stacks via `docs/project-config.json`, relevant docs, manifests, lock files, build files, CI.222- Inventory gates: formatter, linter, code/static analyzer, compiler/type checker, dependency audit/SCA/SBOM, SAST, test/coverage, architecture/dependency-boundary checks, pre-commit, CI/build.223- Verify stack-appropriate coverage: `.editorconfig`/language analyzers, JavaScript/TypeScript linting, UI template linting when supported, formatter config, dependency vulnerability scans, semantic security analysis.224- BLOCKED when production stack lacks runnable lint/static-analysis/type-check command and equivalent enforced gate, or CI/build references missing/broken quality command.225- WARN when tooling local-only, not wired into CI/build/pre-commit, partial for active production code, broadly/unexplainedly suppressed, unclear on generated-code exclusions, or stale for stack.226- **Scope to the change (MUST ATTENTION):** On normal change-level review, _pre-existing_ tooling gap unrelated to diff is WARN with single note — NEVER BLOCK whole review on standing, change-unrelated condition. Reserve BLOCKED for: new stack/service introduced by this change with no gate, change itself removing/breaking existing gate, or explicit full-codebase/greenfield audit scope. — why: change review that BLOCKs on unrelated standing gap produces noise that buries regression the diff actually introduced.227- Before recommending tools, find current official/ecosystem setup and cite it; recommend capabilities first, tools second.228229**Fitness-function enforcement (architectural rules must be EXECUTABLE):** an architectural rule not automatically verified is a SUGGESTION and will be violated within a quarter. Check whether the project's own recorded architectural rules have a machine check — and whether THIS change adds a rule with no check:230231| Rule the project records | Fitness function expected (any equivalent counts) |232| -------------------------------- | ----------------------------------------------------------------------------------------------------------- |233| Layer / dependency direction | Architecture test in CI (ArchUnit / NetArchTest / dependency-cruiser / import-linter / lint boundary rules) |234| No module cycles | Cycle detection failing the build |235| Domain purity | Assertion that the domain package imports no framework/ORM/HTTP namespace |236| API / event schema compatibility | OpenAPI-or-protobuf diff gate · schema-registry backward-compat check · consumer contract tests |237| Multi-tenant isolation | Test asserting a cross-tenant query returns zero rows (see Category 12) |238| Resilience | "Every outbound call has a timeout" lint or test |239| Performance / bundle budget | Latency-or-size assertion in the pipeline |240241- **WARN** when a recorded architectural rule has NO machine check and relies on review discipline alone. **BLOCKED** when this change REMOVES or disables an existing architecture/boundary check, or introduces a new enforced-by-prose-only boundary while the project already has a fitness-function mechanism available.242- Existing violation backlog is fine if it is a RATCHET (new violations blocked, count only decrements) — a "cleanup later" comment with no gate is WARN.243244**Violation format:**245246```247BLOCKED: {stack} has no enforced lint/static-analysis/type-check quality gate ({evidenceFile}:{line})248WARN: recorded architecture rule "{rule}" has no fitness function — enforced by review discipline only ({docFile}:{line})249```250251---252253### Category 1: Clean Architecture Layers — Severity: BLOCKED254255**Think:** What layer is this file in? What layers can it legally import from? Does any import break inward-only flow (Service/API → Application → Domain ← Persistence)?256257- Read `docs/project-config.json` → `architectureRules.layerBoundaries` for project-specific rules.258- Determine layer from file path: Domain/, Application/, Persistence/, Service/.259- Scan configured language's import/include statements — flag imports from forbidden layers.260- MUST ATTENTION verify business logic in correct layer: Entity/Domain > Service/Application > Controller/Component.261- NEVER allow direct infrastructure access from Domain — keep repo interfaces in Domain, implementations in Persistence. — why: Domain depending on infrastructure inverts the dependency rule and couples core logic to a swappable detail.262- NEVER allow business logic in API/Controller layer — push it down to Entity/Domain or Application.263- **Module cycles (BLOCKED):** a cycle in the module/package dependency graph means the two modules ARE one deployable unit whatever the folder structure says. Detect with the graph (`trace --direction both`) or the project's dependency tool; flag any NEW cycle the diff introduces. — why: an unbroken cycle makes independent testing, release and extraction impossible, and it never gets easier to cut later.264- **Domain purity (BLOCKED):** the domain layer MUST NOT import ORM attributes, HTTP types, SQL, serialization or framework namespaces. Grep the changed domain files for the infrastructure namespaces named in `backend-patterns-reference.md`.265- **Shared/infra layer domain leak (BLOCKED):** a generic/shared/infrastructure layer MUST reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. **This leak compiles, runs, and passes functional tests while silently coupling the "reusable" layer to one consumer.** Fix by keeping the shared type domain-free and pushing domain fields down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable, and every later consumer inherits the wrong abstraction.266- **Cohesion / dumping ground (WARN):** a new or growing `Utils`/`Common`/`Shared`/`Helpers`/`Managers` module that everything imports is coincidental cohesion — it becomes the coupling hub and the cycle source. Test: "how many DIFFERENT reasons would make me edit this file?" More than one actor ⇒ split.267- **Pass-through layer (WARN):** a layer that only forwards calls unchanged (sinkhole) adds cost with no responsibility — collapse it or give it a real job.268- **Shallow module / pass-through method (WARN):** a new type whose public interface is nearly as large as its implementation, or a method that only forwards to the next layer with no added responsibility, earns nothing — it is interface cost with no hidden complexity. Judge module VALUE as _functionality hidden ÷ interface surface_: many tiny one-method classes ("classitis") raise total complexity while looking modular. Prefer pulling the complexity DOWNWARD into one deep module over spreading it across N call sites. — why: reviewers count classes and read it as modularity, so this defect is the one that survives review and then makes every future change touch five files.269- **DIP placement (WARN, BLOCKED when the project's docs require it):** dependency inversion is only real when the **interface lives in the domain/policy package** and the adapter package depends inward. An interface declared beside its single implementation in the infrastructure package is a naming convention, not inversion — grep where the changed port/interface is DECLARED, not merely where it is used. — why: an interface in the infra package leaves the dependency arrow pointing the wrong way while the code reads as clean architecture.270- **Wrong-abstraction extraction (WARN):** a diff that MERGES two code paths that look alike but change for DIFFERENT reasons creates a shared module with two actors. Duplication is cheaper than the wrong abstraction — require three real occurrences sharing the same reason to change (**rule of three**) before extracting. Verify against the project's own strategic-DRY decision before flagging. — why: a premature abstraction is defended by everyone who depends on it, so its cost compounds while duplication's cost stays linear.271272**Violation format:**273274```275BLOCKED: {layer} layer file {filePath}:{line} imports from {forbiddenLayer} layer ({importStatement})276BLOCKED: {filePath}:{line} introduces module cycle {A} → {B} → {A}277BLOCKED: shared/infra {filePath}:{line} references consumer domain concept {concept} — shared layer must stay domain-free278```279280---281282### Category 2: Message Bus Patterns — Severity: BLOCKED/WARN283284**Think:** Does this message correctly name its type (event vs request)? Does it extend the right base class? Is producer/consumer relationship correctly oriented — does the leader service own the event?285286**Naming (BLOCKED):**287288- Event messages + request messages MUST follow project's bus-message naming convention — encode owning service + feature + action, with distinct suffix distinguishing event-kind from request-kind messages. Resolve exact convention + suffixes from `backend-patterns-reference.md`.289- Grep existing examples in source for current stack's message-naming pattern before flagging — codebase convention wins.290291**Base classes (BLOCKED):** Verify against bus base types named in `backend-patterns-reference.md` (Phase 0); concrete names are illustrative examples.292293- Bus messages MUST extend project's trackable/payload bus-message base — see `backend-patterns-reference.md`.294- Consumers MUST extend project's message-bus consumer base — see `backend-patterns-reference.md`.295- Producers MUST extend project's event-bus-message producer base — see `backend-patterns-reference.md`.296297**Upstream/Downstream (BLOCKED):**298299- Leader service owns entity data → defines event message for it.300- Follower services consume events — NEVER produce events about data they don't own. — why: producing events about non-owned data forks the source of truth across services.301- NO circular listening: A→B + B→A for same data = boundary violation.302- Consumers MUST implement project's cross-message dependency-wait primitive for cross-message data dependencies — see `backend-patterns-reference.md`.303304**Ordered delivery (WARN):**305306- Messages requiring ordered processing MUST set project's ordered-delivery / sub-queue partition key to meaningful value (resolve concrete API from `backend-patterns-reference.md`).307- Unordered messages leave it unset / null.308309**Reliable publication — dual write (BLOCKED):**310311- **NEVER write the database and publish a message as two independent operations.** Any changed flow that commits state AND publishes MUST go through the project's inbox/outbox mechanism or CDC (verify the project's inbox/outbox enablement config — see `backend-patterns-reference.md`). — why: **dual write fails silently in both directions** — DB commits + publish fails ⇒ downstream never learns and diverges forever; publish succeeds + DB rolls back ⇒ phantom downstream data referencing a row that does not exist. Neither failure appears in tests or logs.312- **Consumer idempotency (BLOCKED):** exactly-once DELIVERY is impossible, so at-least-once is what the bus gives you. Every changed consumer MUST be idempotent — dedup on message ID with a TTL, a version/sequence check that discards backward transitions, or a naturally idempotent write (`SET status = 'paid'`, never `balance += x`). Grep the handler for the project's dedup primitive. — why: a non-idempotent consumer produces duplicate side effects — double charge, double email, double shipment — only under redelivery, which is exactly when nobody is watching.313- **Poison message + queue bounds (WARN):** capped retries with exponential backoff **and jitter**, then DLQ; DLQ depth monitored. Flag unbounded queues, uncapped/infinite retry, and unjittered retry (synchronizes into a thundering herd). A DLQ nobody watches is data loss with extra steps.314- **Command-in-event-costume (WARN):** an "event" with exactly ONE permitted consumer that MUST handle it, whose failure means the business flow failed, is a command misnamed as an event — you pay async debugging difficulty AND keep the sync coupling. Flag the naming, route the redesign to `domain-analysis`.315- **Raw-row events (WARN):** publishing internal DB rows/columns as the event contract (CDC with no mapping layer) freezes your schema as a public contract by Hyrum's Law — consumers then depend on columns you can never rename.316- **Durability acknowledgement weakened (BLOCKED when a diff lowers it, WARN when newly introduced):** a change to producer ack mode, replication factor, or min-in-sync-replicas that accepts data loss on leader failure. `acks=1` loses the message when the leader dies before replication; **`acks=all` waits for every replica CURRENTLY in the ISR, so `min.insync.replicas` is the FLOOR that decides whether a shrunken ISR rejects the write or accepts it with no error** — with `min.insync=1` a healthy 3-replica ISR still waits for 3, but durability DEGRADES to `acks=1` the moment the ISR shrinks to the leader alone. Check BOTH values together, never one alone, and flag the degradation path rather than asserting an unconditional equivalence. — why: the config reads as durable while the guarantee is not, and the loss appears only during the failover nobody rehearsed.317- **Ordering/replay assumption unmet (WARN):** a changed consumer that assumes global ordering when the broker gives ordering only per partition key, or that assumes replay is available on a consume-and-gone queue. Verify the required ordering scope (global / per-entity / none) and replay window against the project's broker config. Queue-vs-log semantics → `.claude/docs/architecture-knowledge.md` §10.318319**Also verify:**320321- NEVER direct cross-service DB access — MUST use message bus. — why: direct DB reach couples services and bypasses ownership boundaries.322- last-sync-timestamp field on message used for conflict resolution in consumers (resolve concrete field from `backend-patterns-reference.md`).323- Event schema changes are backward-compatible (a rolling deploy runs old and new consumers simultaneously) — a breaking schema change with no versioning or compatibility gate is BLOCKED.324325**Violation format:**326327```328BLOCKED: {filePath}:{line} writes DB then publishes without outbox/CDC — dual write, silent divergence on partial failure329BLOCKED: {filePath}:{line} consumer is not idempotent — no dedup/version check under at-least-once delivery330```331332---333334### Category 3: CQRS Compliance — Severity: BLOCKED/WARN335336**Think:** Is Command+Result+Handler in one file? Is validation using fluent API (not exceptions)? Does DTO own mapping, not the handler? Are side effects in event handlers, not command handlers?337338**File organization (BLOCKED):**339340- Command + Result + Handler MUST be in ONE file under the command folder for the feature _(resolve concrete folder from project's structure reference / `docs/project-config.json`; e.g. `{command-folder}/{Feature}/`)_341- Query + Result + Handler MUST be in ONE file under the query folder for the feature _(resolve concrete folder from project's structure reference / `docs/project-config.json`; e.g. `{query-folder}/{Feature}/`)_342343**Validation (BLOCKED):**344345- MUST use project's validation-result fluent API — NEVER throw exceptions for validation; return validation result instead — verify exact type + method names in `backend-patterns-reference.md`. — why: exceptions for expected-invalid input conflate control flow with errors and skip the validation pipeline.346- Sync validation in command's validate hook, async in request-validation hook — see `backend-patterns-reference.md` for hook names.347348**DTO mapping (BLOCKED):**349350- DTOs MUST own entity mapping via project's DTO base mapping methods — NEVER map in command handlers; map in the DTO instead — see `backend-patterns-reference.md` for method names.351352**Side effects (BLOCKED):**353354- NEVER put side effects (notifications, sync, cascade updates) in command handlers — place them in Entity Event Handlers instead. — why: side effects in the handler couple the command to downstream concerns and cascade failures.355- Side effects go in Entity Event Handlers under project's event-handler folder _(resolve from project's structure reference / `docs/project-config.json`; e.g. `{event-handler-folder}/`)_356- Each handler = one independent concern (failures don't cascade).357358---359360### Category 4: Repository Patterns — Severity: BLOCKED361362**Think:** Is this using a service-specific repo interface, not the generic one? Are complex queries extracted to RepositoryExtensions?363364- MUST use project's service-specific repository abstraction — NEVER the generic root-repository base directly; per-service naming scheme defined in `backend-patterns-reference.md`. — why: the generic base leaks unbounded query surface and erases per-service boundaries.365- Complex queries MUST use project's repository-extension pattern with static expressions _(e.g. `RepositoryExtensions`)_366- All query filter/FK/sort columns MUST have database indexes.367368**Violation format:**369370```371BLOCKED: {filePath}:{line} uses the generic root-repository base instead of the service-specific repository — see backend-patterns-reference.md for the required naming372```373374---375376### Category 5: Service Pattern Era (Legacy vs Modern Split) — Severity: BLOCKED (new services) / WARN (existing)377378**Think:** When project distinguishes legacy vs modern service patterns (e.g., auth scheme, telemetry stack, permission model, language-version syntax), is this a new service (must follow modern) or an existing legacy service (expect legacy patterns)? Is the modern pattern partially mixed into a legacy service without full migration?379380**New services — BLOCKED if any legacy-only pattern used.** Identify project's modern-pattern checklist from injected reference docs (e.g., `project-structure-reference.md`, ADRs, scaffolding templates) and verify every item.381382**Existing legacy services — WARN if modern patterns partially mixed without full migration.** Flag legacy patterns only when partial mixing creates inconsistency; in their own consistent context they are expected, NOT violations.383384**Determining era:** Read project's reference docs at review time — service-pattern era assignments are project-specific and listed authoritatively there. NEVER hardcode service names in this skill. — why: hardcoded service names rot the moment the project renames or adds a service, and break portability to other repos.385386---387388### Category 6: Entity Event Handlers — Severity: BLOCKED/WARN389390**Think:** Are side effects defined inline in command handlers (wrong) or in project's event-handler folder (correct)? Does each handler have a single concern?391392**Location (BLOCKED):**393394- Entity event handlers MUST be in project's event-handler folder _(resolve from project's structure reference / `docs/project-config.json`; e.g. `{event-handler-folder}/`)_395- NEVER inline side effects in command handlers — move them to a dedicated entity event handler. — why: inline side effects couple the command to downstream concerns and cascade failures.396397**Implementation (BLOCKED):**398399- MUST extend project's entity-event application-handler base — see `backend-patterns-reference.md`.400- MUST implement CRUD-action filter hook — see `backend-patterns-reference401402…(truncated)