[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 AskUserQuestion.
- 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 —
AskUserQuestion: /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.md for hook name.
- One handler = one independent concern.
Naming (WARN):
- Convention:
{Action}On{Trigger}EntityEventHandler
- Grep existing examples before flagging.
Producer patterns (BLOCKED):
- Bus message producers MUST extend project's event-bus-message producer base — see
backend-patterns-reference.md.
- MUST implement message-build + action-filter hooks — see
backend-patterns-reference.md for hook names.
Category 7: Service Boundaries — Severity: BLOCKED
Think: Does any code reach directly into another service's database or project reference? All cross-service data flow MUST go through the message bus.
- NEVER direct DB access to another service's database — route through the message bus. — why: direct DB reach couples services and bypasses ownership boundaries.
- NEVER
using reference to another service's domain/persistence project — depend on shared message contracts instead.
- Cross-service communication via message bus only (event bus or request bus).
- Shared data through shared message projects, NOT direct references.
- Verify service-to-DB mapping from
project-structure-reference.md.
- One writer per dataset (BLOCKED): every dataset has exactly ONE owning service/module that writes it. Many READERS are fine — via API, replica, or published event stream. Flag any change that adds a second writer to a dataset owned elsewhere. — why: shared write access is shared coupling with NO contract; the data then diverges and no layer owns correctness.
- Shared domain library (WARN): a change making many services depend on one shared domain library forces lockstep deploys — that is deployment + semantic coupling, not reuse. Small duplicated DTOs are cheaper; share only genuinely generic technical utilities. Verify against the project's own strategic-DRY decision before flagging.
- Entity-shaped boundaries (WARN): a new service/module named for a NOUN (
UserService, ProductService) doing CRUD signals boundaries drawn around data instead of capabilities — it guarantees real use cases must synchronously traverse many services. Flag the smell; route the re-modeling to domain-analysis.
Violation format:
BLOCKED: {filePath}:{line} references {otherService} domain/persistence directly — must use message bus
BLOCKED: {filePath}:{line} writes {dataset} owned by {otherService} — second writer, no contract
Category 8: Frontend Architecture (if frontend files in scope) — Severity: BLOCKED/WARN
Think: Are components extending the right base class? Is state going through the store? Are subscriptions properly cleaned up?
Verify against frontend-patterns-reference.md (Phase 0, frontend files); concrete names are illustrative examples.
- Components MUST extend project's component base classes (BLOCKED) — see
frontend-patterns-reference.md.
- State MUST use project's view-model store + reactive-effect pattern — NEVER manual signals or direct HTTP client (BLOCKED); route state through the store — see
frontend-patterns-reference.md.
- API services MUST extend project's API-service base (BLOCKED) — see
frontend-patterns-reference.md.
- All subscriptions MUST use project's auto-teardown operator — NEVER manual unsubscribe (BLOCKED). — why: manual unsubscribe is forgotten o
…(truncated)
1---2name: architecture-review-23description: "[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<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->78> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.9> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.10> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.11> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.1213<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->1415## Quick Summary1617**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.1819**Summary:**2021- **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.22- **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 `AskUserQuestion`.23- **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.24- **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.25- 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.26- **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.27- 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.28- 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`.2930**Default scope:** All uncommitted changes (staged + unstaged). Override: specify files, directories, services, or full codebase.3132> **MANDATORY MUST ATTENTION** Plan tasks to READ architecture docs BEFORE reviewing:33>34> 1. `docs/project-reference/backend-patterns-reference.md` — CQRS, messaging, repos, validation, entity events, layer rules **(READ FIRST — primary rules source)**35> 2. `docs/project-reference/project-structure-reference.md` — service map, layer structure, DB ownership36> 3. `docs/project-reference/frontend-patterns-reference.md` — component hierarchy, store, API patterns **(frontend files only)**37> 4. `docs/project-reference/code-review-rules.md` — anti-patterns, conventions38>39> Not found → search: "architecture documentation", "service patterns", "messaging patterns". Rules come from docs — NOT general knowledge.4041**Workflow:**42431. **Phase 0: Load Architecture Rules** — Read project architecture docs (rules come from docs, NEVER general knowledge)442. **Phase 1: Determine Scope** — Changed files (default) or user-specified scope453. **Phase 2: Blast Radius** — Run `/graph-blast-radius` if `graph.db` exists464. **Phase 3: Architecture Review** — Check each file serially against all 13 applicable categories (0 tooling → 12 data, consistency & tenancy)475. **Phase 4: Finalize** — Generate compliance report with PASS/BLOCKED/WARN verdicts486. **Phase 5: Why-Review Self-Validation Gate** — Adversarially validate own findings via `/why-review` before handoff (MANDATORY when any finding exists)497. **Next Steps** — `AskUserQuestion`: `/code-simplifier` / `/code-review` / skip5051**Key Rules (top 3 critical first):**5253- MUST ATTENTION read project architecture docs in Phase 0 BEFORE reviewing — rules come from docs, NEVER general knowledge.54- Every violation needs `file:line` proof + grep 3+ counterexamples before flagging — NEVER speculate.55- MUST ATTENTION review one category at a time: doc rule → source evidence → verdict — NEVER scan categories simultaneously.56- Write findings to `plans/reports/arch-review-{date}-{slug}.md`.57- BLOCKED = must fix before merge | WARN = review and decide | PASS = compliant.58- 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.5960## Your Mission6162<task>63$ARGUMENTS64</task>6566## First Principle — Easy to Change6768> **Success metric: future change cost.** DRY, SRP, abstraction, patterns, naming, layering, tests exist to make next change cheaper.6970Before applying any rule, ask: **does this lower or raise future change cost?**7172- 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.73- Name real enemies: **coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early**.74- Prefer simple reversible design over sophisticated rigid design. — why: reversible decisions cost less to undo when wrong.75- If downstream rule raises change cost, this principle wins.7677---7879## Quality Tooling Principle — Tech-Stack Adaptive8081> 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.8283Evaluate detected stacks, not fixed tool list:8485- Detect stacks from project-reference docs, manifests, lock files, build files, CI before recommending tools.86- Per production stack, verify formatter/style config, linter/code analyzer, compiler/type-check strictness, dependency/vulnerability scanning, tests/coverage, CI/pre-commit enforcement.87- Prefer official or ecosystem-standard tooling; local docs absent/stale → check current official docs before recommending setup.88- MUST ATTENTION recommend enforceable best practice only: installed but unwired tool = WARN; production source with no relevant automated quality gate = BLOCKED.89- 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.9091---9293## Review Mindset (NON-NEGOTIABLE)9495Skeptical. Every claim needs traced proof, confidence >80%.9697- NEVER flag violations without reading actual code + tracing dependency — READ the code, trace the import chain, then flag.98- Every finding MUST include `file:line` evidence.99- Before flagging pattern violation: grep 3+ existing examples — codebase convention wins.100- Question: "Actually a violation, or an established exception?"101102## Ownership & Handoff (own vs delegate)103104This 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.105106| This skill OWNS (deep-review here) | Delegate to sibling (one-line pointer only — do NOT deep-review) |107| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |108| Layer boundaries, dependency direction, business-logic placement | — |109| Messaging patterns, CQRS structure, repository patterns, service-pattern era, entity event handlers, service boundaries | — |110| Frontend ARCHITECTURE (base classes, store/effect, API-service base, subscription teardown, CSS-class presence) | Visual/SCSS/responsive/z-index quality → `ui-review` |111| Quality-tooling baseline, generated-artifact integrity, ADR / recorded-decision conformance | — |112| Architecture-level auth PLACEMENT (a gate exists at the boundary) | OWASP, secrets, dependency/supply-chain, authz-matrix depth → `security-review` |113| Structural soundness of a hot path (no obvious N+1 introduced by the diff) | Query plans, indexing depth, latency/throughput budgets → `performance-review` |114| — | Domain entity / value-object DDD design quality → `domain-entities-review` |115| — | Integration-test assertion quality, coverage, traceability → `integration-test-review` |116| — | Runtime production-readiness of service/API changes (observability wiring, rollback) → `production-readiness-review` |117118When 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.119120## Phase 0: Load Architecture Rules (MANDATORY FIRST)121122> **MUST ATTENTION:** Read project docs BEFORE reviewing. Rules come from docs, NEVER general knowledge.123124- read `docs/project-reference/backend-patterns-reference.md` — extract messaging naming, layer rules, CQRS patterns, repo rules, entity event handler patterns, validation patterns125- read `docs/project-reference/project-structure-reference.md` — extract service map, layer structure, DB ownership126- frontend files in scope → read `docs/project-reference/frontend-patterns-reference.md`127- read `docs/project-reference/code-review-rules.md` — extract anti-patterns + review rules directly128129**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.130131> **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.132133## Phase 1: Determine Scope134135**Default (no override):** Review all uncommitted changes.136137```bash138git status # List changed files139git diff # Staged + unstaged changes140git diff --cached # Staged only141```142143- Collect file list to review.144- Categorize: backend (.cs), frontend (.ts/.html), config, docs, other.145- Filter to architecture-relevant files (skip pure docs, configs, tests unless architecture-relevant).146147## Phase 2: Blast Radius (if graph.db exists)148149- `.code-graph/graph.db` exists → call `/graph-blast-radius` skill.150- Record: impacted file count, cross-service impact, risk level.151- Prioritize review by highest-impact files first.152- Graph unavailable → note "Graph not available — skipping blast radius" and proceed.153154Per changed file with downstream impact:155156```bash157python .claude/scripts/code_graph trace <changed-file> --direction downstream --json158```159160Flag MESSAGE_BUS consumers or event handlers impacted by changes.161162## Phase 3: Architecture Review163164Create report: `plans/reports/arch-review-{date}-{slug}.md`165166Per file in scope, evaluate against ALL applicable categories. Skip categories not applicable to file type.167168MUST 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.169170> **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.171172---173174### Category 0: Quality Tooling Baseline — Severity: BLOCKED/WARN175176**Think:** Can project automatically catch style, type, complexity, security, dependency, boundary regressions for detected stacks?177178- Detect production stacks via `docs/project-config.json`, relevant docs, manifests, lock files, build files, CI.179- 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.180- Verify stack-appropriate coverage: `.editorconfig`/language analyzers, JavaScript/TypeScript linting, UI template linting when supported, formatter config, dependency vulnerability scans, semantic security analysis.181- BLOCKED when production stack lacks runnable lint/static-analysis/type-check command and equivalent enforced gate, or CI/build references missing/broken quality command.182- 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.183- **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.184- Before recommending tools, find current official/ecosystem setup and cite it; recommend capabilities first, tools second.185186**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:187188| Rule the project records | Fitness function expected (any equivalent counts) |189| -------------------------------- | ----------------------------------------------------------------------------------------------------------- |190| Layer / dependency direction | Architecture test in CI (ArchUnit / NetArchTest / dependency-cruiser / import-linter / lint boundary rules) |191| No module cycles | Cycle detection failing the build |192| Domain purity | Assertion that the domain package imports no framework/ORM/HTTP namespace |193| API / event schema compatibility | OpenAPI-or-protobuf diff gate · schema-registry backward-compat check · consumer contract tests |194| Multi-tenant isolation | Test asserting a cross-tenant query returns zero rows (see Category 12) |195| Resilience | "Every outbound call has a timeout" lint or test |196| Performance / bundle budget | Latency-or-size assertion in the pipeline |197198- **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.199- 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.200201**Violation format:**202203```204BLOCKED: {stack} has no enforced lint/static-analysis/type-check quality gate ({evidenceFile}:{line})205WARN: recorded architecture rule "{rule}" has no fitness function — enforced by review discipline only ({docFile}:{line})206```207208---209210### Category 1: Clean Architecture Layers — Severity: BLOCKED211212**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)?213214- Read `docs/project-config.json` → `architectureRules.layerBoundaries` for project-specific rules.215- Determine layer from file path: Domain/, Application/, Persistence/, Service/.216- Scan configured language's import/include statements — flag imports from forbidden layers.217- MUST ATTENTION verify business logic in correct layer: Entity/Domain > Service/Application > Controller/Component.218- 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.219- NEVER allow business logic in API/Controller layer — push it down to Entity/Domain or Application.220- **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.221- **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`.222- **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.223- **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.224- **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.225- **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.226- **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.227- **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.228229**Violation format:**230231```232BLOCKED: {layer} layer file {filePath}:{line} imports from {forbiddenLayer} layer ({importStatement})233BLOCKED: {filePath}:{line} introduces module cycle {A} → {B} → {A}234BLOCKED: shared/infra {filePath}:{line} references consumer domain concept {concept} — shared layer must stay domain-free235```236237---238239### Category 2: Message Bus Patterns — Severity: BLOCKED/WARN240241**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?242243**Naming (BLOCKED):**244245- 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`.246- Grep existing examples in source for current stack's message-naming pattern before flagging — codebase convention wins.247248**Base classes (BLOCKED):** Verify against bus base types named in `backend-patterns-reference.md` (Phase 0); concrete names are illustrative examples.249250- Bus messages MUST extend project's trackable/payload bus-message base — see `backend-patterns-reference.md`.251- Consumers MUST extend project's message-bus consumer base — see `backend-patterns-reference.md`.252- Producers MUST extend project's event-bus-message producer base — see `backend-patterns-reference.md`.253254**Upstream/Downstream (BLOCKED):**255256- Leader service owns entity data → defines event message for it.257- 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.258- NO circular listening: A→B + B→A for same data = boundary violation.259- Consumers MUST implement project's cross-message dependency-wait primitive for cross-message data dependencies — see `backend-patterns-reference.md`.260261**Ordered delivery (WARN):**262263- 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`).264- Unordered messages leave it unset / null.265266**Reliable publication — dual write (BLOCKED):**267268- **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.269- **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.270- **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.271- **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`.272- **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.273- **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.274- **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.275276**Also verify:**277278- NEVER direct cross-service DB access — MUST use message bus. — why: direct DB reach couples services and bypasses ownership boundaries.279- last-sync-timestamp field on message used for conflict resolution in consumers (resolve concrete field from `backend-patterns-reference.md`).280- 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.281282**Violation format:**283284```285BLOCKED: {filePath}:{line} writes DB then publishes without outbox/CDC — dual write, silent divergence on partial failure286BLOCKED: {filePath}:{line} consumer is not idempotent — no dedup/version check under at-least-once delivery287```288289---290291### Category 3: CQRS Compliance — Severity: BLOCKED/WARN292293**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?294295**File organization (BLOCKED):**296297- 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}/`)_298- 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}/`)_299300**Validation (BLOCKED):**301302- 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.303- Sync validation in command's validate hook, async in request-validation hook — see `backend-patterns-reference.md` for hook names.304305**DTO mapping (BLOCKED):**306307- 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.308309**Side effects (BLOCKED):**310311- 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.312- 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}/`)_313- Each handler = one independent concern (failures don't cascade).314315---316317### Category 4: Repository Patterns — Severity: BLOCKED318319**Think:** Is this using a service-specific repo interface, not the generic one? Are complex queries extracted to RepositoryExtensions?320321- 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.322- Complex queries MUST use project's repository-extension pattern with static expressions _(e.g. `RepositoryExtensions`)_323- All query filter/FK/sort columns MUST have database indexes.324325**Violation format:**326327```328BLOCKED: {filePath}:{line} uses the generic root-repository base instead of the service-specific repository — see backend-patterns-reference.md for the required naming329```330331---332333### Category 5: Service Pattern Era (Legacy vs Modern Split) — Severity: BLOCKED (new services) / WARN (existing)334335**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?336337**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.338339**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.340341**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.342343---344345### Category 6: Entity Event Handlers — Severity: BLOCKED/WARN346347**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?348349**Location (BLOCKED):**350351- 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}/`)_352- 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.353354**Implementation (BLOCKED):**355356- MUST extend project's entity-event application-handler base — see `backend-patterns-reference.md`.357- MUST implement CRUD-action filter hook — see `backend-patterns-reference.md` for hook name.358- One handler = one independent concern.359360**Naming (WARN):**361362- Convention: `{Action}On{Trigger}EntityEventHandler`363- Grep existing examples before flagging.364365**Producer patterns (BLOCKED):**366367- Bus message producers MUST extend project's event-bus-message producer base — see `backend-patterns-reference.md`.368- MUST implement message-build + action-filter hooks — see `backend-patterns-reference.md` for hook names.369370---371372### Category 7: Service Boundaries — Severity: BLOCKED373374**Think:** Does any code reach directly into another service's database or project reference? All cross-service data flow MUST go through the message bus.375376- NEVER direct DB access to another service's database — route through the message bus. — why: direct DB reach couples services and bypasses ownership boundaries.377- NEVER `using` reference to another service's domain/persistence project — depend on shared message contracts instead.378- Cross-service communication via message bus only (event bus or request bus).379- Shared data through shared message projects, NOT direct references.380- Verify service-to-DB mapping from `project-structure-reference.md`.381- **One writer per dataset (BLOCKED):** every dataset has exactly ONE owning service/module that writes it. Many READERS are fine — via API, replica, or published event stream. Flag any change that adds a second writer to a dataset owned elsewhere. — why: shared write access is shared coupling with NO contract; the data then diverges and no layer owns correctness.382- **Shared domain library (WARN):** a change making many services depend on one shared _domain_ library forces lockstep deploys — that is deployment + semantic coupling, not reuse. Small duplicated DTOs are cheaper; share only genuinely generic technical utilities. Verify against the project's own strategic-DRY decision before flagging.383- **Entity-shaped boundaries (WARN):** a new service/module named for a NOUN (`UserService`, `ProductService`) doing CRUD signals boundaries drawn around data instead of capabilities — it guarantees real use cases must synchronously traverse many services. Flag the smell; route the re-modeling to `domain-analysis`.384385**Violation format:**386387```388BLOCKED: {filePath}:{line} references {otherService} domain/persistence directly — must use message bus389BLOCKED: {filePath}:{line} writes {dataset} owned by {otherService} — second writer, no contract390```391392---393394### Category 8: Frontend Architecture (if frontend files in scope) — Severity: BLOCKED/WARN395396**Think:** Are components extending the right base class? Is state going through the store? Are subscriptions properly cleaned up?397398Verify against `frontend-patterns-reference.md` (Phase 0, frontend files); concrete names are illustrative examples.399400- Components MUST extend project's component base classes (BLOCKED) — see `frontend-patterns-reference.md`.401- State MUST use project's view-model store + reactive-effect pattern — NEVER manual signals or direct HTTP client (BLOCKED); route state through the store — see `frontend-patterns-reference.md`.402- API services MUST extend project's API-service base (BLOCKED) — see `frontend-patterns-reference.md`.403- All subscriptions MUST use project's auto-teardown operator — NEVER manual unsubscribe (BLOCKED). — why: manual unsubscribe is forgotten o404405…(truncated)