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: As solution architect, deliver a complete, evidence-backed, user-validated architecture decision report covering ALL concerns (backend, frontend, design patterns, library ecosystem, testing, CI/CD, deployment, monitoring, code quality, dependency management) — every concern researched with 3+ options, every recommendation carrying confidence % + cited evidence, every decision user-confirmed — so implementation proceeds on sound, owned architectural choices.
Summary:
- Decide mode FIRST (Step 1): greenfield researches every concern from scratch; brownfield reads reference docs + accepted ADRs, constrains research to existing stack — NEVER re-litigate a settled ADR-recorded decision without superseding-ADR rationale.
- Rank every decision by REVERSIBILITY first (Step 2): one-way door (data model, tenancy, consistency model, service boundaries, public contracts, sync-vs-async) → ADR + user validation MANDATORY; two-way door → decide and move. — why: architecture IS the set of decisions expensive to reverse; treating a one-way door as reversible is the costliest error this skill can make.
- Drive style choice with NUMBERS, not adjectives: quantify Step-2 quality-attribute scenarios (latency p95/p99, throughput, SLO, RPO/RTO, data growth, concurrency); pick ≤3 DRIVING attributes and name which ones you SACRIFICE; any unknown target becomes explicit
Unresolved question, never a silent guess.
- Profile the workload before selecting a scaling technique: read/write ratio · sustained/peak RPS · query shapes · data size/growth · burstiness/hot keys · consistency/staleness · user geography. Escalate through the smallest reversible rung: measure/tune → choose vertical and/or stateless horizontal scale from headroom + availability needs → read/write-specific tactics → partition/shard LAST. — why: a scalable product is a sequence of evidenced bottleneck removals, not a shopping list of distributed components.
- Simplicity is the default; complexity must be BOUGHT with a measured requirement — modulith-first, distribute only against a named + measured extraction trigger (Step 3A). Reason FROM
.claude/docs/architecture-knowledge.md (laws, coupling taxonomy, style triggers, trade-off + anti-pattern catalogs) — never from familiarity or fashion.
- Every concern needs 3+ researched options with cited evidence (stars, last release, downloads, CVE scan) + confidence % — familiarity alone never sufficient grounds for a recommendation.
- Interrogate before deciding, DESIGN IT TWICE, then self-audit: run the 15-question pre-decision script (§20.1) on every one-way door (Step 2-2) · produce ≥2 MATERIALLY different candidates per one-way door before choosing (Step 3A) · run the 11 thinking red flags (§20.3) against your own draft before emitting. Prescribe the TACTIC (§2), never the product. — why: a first-idea design with no rejected alternative and no named falsifier is a belief, not a decision.
- Produce the two binding downstream contracts or the chain breaks: emit an ADR per hard-to-reverse decision (
architecture-review Cat 9 enforces) and the Scaffold Handoff tool-choices table (scaffold/harness-setup consume), then run the MANDATORY Step-12 user-validation interview before confirming.
- Main steps/tasks (run in order, track each): 1 Load Context (+pick greenfield/brownfield mode) → 2 Derive Architecture Requirements (+workload profile/scaling ladder, reversibility ranking, ≤3 driving attributes, 6-part quality-attribute scenarios, 2-2 pre-decision interrogation, user-validate) → 3A Backend Styles (selection procedure incl. DESIGN IT TWICE + extraction triggers) → 3B Backend Design Patterns → 3C Data & Consistency Architecture (store/substrate per access pattern, replication/failover, cache contract, consistency + staleness, transaction boundary, tenancy, partitioning, migrations, retention) → 3D Integration & API Architecture (sync-vs-async + acceptance state, API/edge cache style, versioning, contract tests, outbox, idempotency, event granularity) → 4 Frontend Architecture (styles + patterns) → 4B UI System Architecture (styling/tokens/components/responsive, user-validate; skip if backend-only) → 5 Library Ecosystem Research (3 options/concern) → 6 Testing Architecture → 7 CI/CD & Deployment (+expand–contract migrations, backward AND forward compat) → 8 Observability & Monitoring (signal roles + sampling/cardinality) → 9 Code Quality + Scaffold Handoff table → 10 Dependency Risk Assessment → 11 Generate Report + emit ADRs → 12 User Validation Interview (8-12 questions, mark
confirmed) → Next Steps + always-offer council escalation. — why: AI keeps forgetting the skill's own steps; this is the recovery anchor.
Workflow (12 steps):
- Load Context — Read domain model, tech stack, business evaluation, refined PBI
- Derive Architecture Requirements — Profile workload + ordered scaling ladder, rank reversibility, pick ≤3 driving attributes, quantify 6-part scenarios, run 2-2 pre-decision interrogation on every one-way door
- Backend Architecture — 3A styles (selection procedure) · 3B design patterns · 3C data & consistency · 3D integration & APIs
- Frontend Architecture — Research top 3 frontend architecture styles + design patterns
- Library Ecosystem Research — Best-practice libraries per concern (validation, caching, logging, utils, etc.)
- Testing Architecture — Unit, integration, E2E, performance testing frameworks + strategy
- CI/CD & Deployment — Pipeline design, containerization, orchestration, IaC
- Observability & Monitoring — Logging, metrics, tracing, alerting stack
- Code Quality & Clean Code — Linters, analyzers, formatters, enforcement tooling
- Dependency Risk Assessment — Package health, obsolescence risk, maintenance cost
- Generate Report — Full architecture decision report with all recommendations
- User Validation — Present findings, ask 8-12 questions, confirm all decisions
Key Rules:
- MANDATORY IMPORTANT MUST ATTENTION research minimum 3 options per architecture concern with web evidence
- MANDATORY IMPORTANT MUST ATTENTION include confidence % with evidence for every recommendation
- MANDATORY IMPORTANT MUST ATTENTION run user validation interview at end (never skip)
- Delegate to
solution-architect agent for complex architecture decisions
- All claims must cite sources (URL, benchmark, case study, or codebase evidence)
- Base every recommendation on evidence, never on familiarity alone
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
Inputs & Handoffs (consume vs produce)
Skill sits mid-workflow — consumes settled upstream decisions, produces artifacts downstream steps build on. Do NOT re-derive what upstream step already owns; do NOT leave downstream consumer without its needed artifact. — why: re-deriving settled decisions wastes effort and risks divergence from the recorded choice.
| Consumes (read, don't re-derive) |
From |
Produces (named deliverable) |
Consumed by |
| Bounded contexts, aggregates, domain events, ERD |
domain-analysis |
Architecture decision report ({plan-dir}/research/...) |
plan, plan-execute |
| Confirmed languages/frameworks/databases |
tech-stack-research |
Confirmed decisions ({plan-dir}/phase-02b-architecture.md) |
plan, scaffold |
| Expected scale, compliance, budget constraints |
business-evaluation |
Scaffold Handoff table (tooling + fitness rules) |
scaffold, harness-setup |
| Existing stack/patterns/ADRs (brownfield) |
reference docs, docs/adr/** |
ADRs for hard-to-reverse decisions (docs/adr/) |
architecture-review (conformance) |
If upstream artifact missing, capture minimum needed here and note gap — NEVER silently re-run full upstream analysis. — why: a silent re-run hides the missing-input gap that the owning step should resolve.
Step 1: Load Context
Mode (decide first): Greenfield (new project, e.g. via workflow-greenfield-init) → research every concern from scratch, full 3-options-per-concern. Brownfield (large feature in existing codebase, e.g. workflow-big-feature) → FIRST read project reference docs + accepted ADRs, constrain research to existing stack/patterns, propose changes only where new requirement genuinely outgrows them — NEVER re-litigate settled ADR-recorded decision without superseding-ADR rationale. — why: re-deciding a recorded choice churns the codebase and breaks downstream conformance checks.
Read artifacts from prior workflow steps (search plans/ and team-artifacts/):
- Domain model / ERD (complexity, bounded contexts, aggregate count)
- Tech stack decisions (confirmed languages, frameworks, databases)
- Business evaluation (scale, constraints, compliance)
- Refined PBI (scope, acceptance criteria)
- Discovery interview (team skills, experience level)
Extract, summarize:
| Signal |
Value |
Source |
| Bounded contexts |
... |
domain model |
| Aggregate count |
... |
domain model |
| Cross-context events |
... |
domain model |
| Confirmed tech stack |
... |
tech stack phase |
| Expected scale |
... |
business eval |
| Team architecture exp. |
... |
discovery |
| Compliance requirements |
... |
business eval |
| Real-time needs |
Yes/No |
refined PBI |
| Integration complexity |
Low/Med/High |
domain model |
| Deployment target |
... |
business eval |
Step 2: Derive Architecture Requirements
Reason FROM the knowledge body, not from memory. .claude/docs/architecture-knowledge.md is AUTHORITATIVE for architecture laws (CAP/PACELC, Conway, Amdahl, USL, Little, Gall, Hyrum, Parnas), the coupling taxonomy + four coupling dimensions, style-selection triggers, the trade-off cheat sheet, and the ~100-entry anti-pattern catalog. Read the sections relevant to this design before recommending. Honor the catalog's provenance markers in §3/§8/§9/§10 — a row (or section banner) marked — VERIFY is an UNVERIFIED assertion, so cite it as a hypothesis to check against the named source where one is named (a [model-knowledge] row names none — check the project's own docs or a primary source instead), NEVER as settled fact in a recommendation. The project's own reference docs and accepted ADRs OUTRANK that catalog on any conflict — the catalog supplies universal reasoning, the project supplies binding convention. — why: universal names hardcoded as project rules rot against real repos.
2-0: Rank every decision by REVERSIBILITY (do this FIRST)
Architecture = the set of decisions expensive to reverse; everything cheap to reverse is design — leave it to implementers. Classify each decision BEFORE researching it, because the classification sets how much rigour it earns.
| Class |
Meaning |
Required treatment |
| One-way door |
Reversal costs a migration, a rewrite, or a breaking change to consumers |
ADR (Step 11) + user validation (Step 12) MANDATORY — research 3+ options, name the rejected alternative AND the measurable revisit trigger |
| Two-way door |
Reversal is a refactor inside one module |
Decide, record one line, move on — NEVER burn a validation question on it |
One-way doors (assume MANDATORY ADR unless proven otherwise): data model + primary-key strategy · tenancy model · consistency model per read path · sync-vs-async at a boundary · public API/event contract · service boundary lines · cloud-primitive lock-in · auth/identity model · data residency + retention.
MANDATORY IMPORTANT MUST ATTENTION never treat a one-way door as a two-way door to save a step — why: an unreviewed irreversible decision is the single most expensive failure mode of this skill, and it surfaces months later as a migration.
Map signals to architecture constraints:
| Signal |
Architecture Requirement |
Priority |
| Many bounded contexts |
Clear module boundaries, context isolation |
Must |
| High scale |
Horizontal scaling, stateless services, caching strategy |
Must |
| Complex domain |
Rich domain model, separation of domain from infra |
Must |
| Cross-context events |
Event-driven communication, eventual consistency |
Must |
| Small team |
Low ceremony, fewer layers, convention over configuration |
Should |
| Compliance |
Audit trail, immutable events, access control layers |
Must |
| Real-time |
Event sourcing or pub/sub, WebSocket/SSE support |
Should |
| High integration complexity |
Anti-corruption layers, adapter pattern, API gateway |
Should |
Quality-Attribute Scenarios (quantify — these drive the style choice)
Qualitative "Must/Should" cannot decide, e.g., modular monolith vs microservices. Capture measurable targets; ask user for any unknown by asking the user directly (guess acceptable only when labelled an assumption with confidence %). These targets become ADR-recorded budgets architecture-review Category 9 later checks changes against. — why: a style chosen without numbers is a guess, not an enforceable decision.
| Quality attribute |
Scenario (stimulus → measurable response) |
Target (fill in) |
| Latency |
p95 / p99 response time for the hottest read and write paths |
e.g. p99 < 300ms |
| Throughput |
Sustained req/s and peak burst the system must absorb |
e.g. 500 rps peak |
| Availability / SLO |
Target uptime and error budget |
e.g. 99.9% |
| Data durability (RPO) |
Max acceptable data loss on failure |
e.g. ≤ 5 min |
| Recovery (RTO) |
Max acceptable time to restore service |
e.g. ≤ 30 min |
| Data-volume growth |
Row/document/event growth → storage, index, partition strategy |
e.g. 10M rows/yr |
| Concurrency |
Concurrent users/sessions and contention hot spots |
e.g. 2k concurrent |
| Compliance/retention |
Regulated data, retention window, residency, audit |
e.g. GDPR, 7yr |
| Cost unit economics |
$/request, $/tenant, $/MAU — and whether unit cost RISES with scale |
e.g. <$0.002/req |
Scenario template — all SIX parts, none optional: [SOURCE: who/what triggers] [STIMULUS: the event] on [ARTIFACT: which component] under [ENVIRONMENT: the conditions] SHALL produce [RESPONSE] within [MEASURE: threshold + instrument]. "Must be scalable" decides nothing; "5,000 concurrent checkout sessions at 400 rps SHALL complete p99 < 800 ms, ≤0.1% errors, verified by the CI k6 profile" selects a structure.
MUST ATTENTION a scenario missing SOURCE or ARTIFACT is untestable — you cannot write a fitness function for "the system" under "load", so name the actor and the component. — why: an unattributed scenario gets no owner, no test and no budget, so it is never verified and silently degrades.
Rule: any target left unknown is explicit Unresolved question (Step 11), NEVER a silent omission — an architecture chosen without scale numbers is a guess, not a decision.
Workload Profile + Scaling Ladder (MANDATORY before technique selection)
Record read:write ratio · sustained/peak RPS or events/s · dominant query/write shapes · dataset size + growth · payload size · burst duration · hot-key/tenant skew · user regions · latency percentile targets · consistency/staleness tolerance. For every proposed scaling component, name the measured bottleneck it removes and the next bottleneck it creates.
| Order |
Use when evidence shows |
First tactic |
Purchase price |
| 1. Measure + tune |
Baseline unknown or slow path unprofiled |
Query/plan analysis, indexes, batching, pooling, compression |
Engineering time; lowest reversibility cost |
| 2A. Vertical scale |
One node remains simplest and headroom exists |
More CPU/RAM/IOPS; tune runtime/database |
Hardware ceiling; remaining SPOF without redundancy |
| 2B. Horizontal app scale |
Availability or aggregate compute requires replicas and the path can be stateless |
Replicas + redundant load balancing + health checks |
Coordination, externalized state, deployment complexity |
| 4. Read-path scale |
High read ratio or global read latency |
Cache/CDN/read replicas/read models |
Invalidation, lag, read-your-writes, cache-key correctness |
| 5. Write-path scale |
Bursty ingest or heavy work need not finish inline |
Batching, durable queue + workers; LSM store for sustained write-heavy known-query workloads |
Accepted ≠ completed, retries/idempotency/backpressure; compaction/read amplification |
| 6. Partition/shard |
Earlier rungs proven insufficient by capacity measurements |
Query-aligned partition key + reshard plan |
Cross-shard queries/transactions, hotspots, hard reversal |
MANDATORY IMPORTANT MUST ATTENTION NEVER jump to sharding, multi-region writes, or an extra datastore without evidence that earlier rungs cannot meet the quantified target — why: these are hard-to-reverse operational systems, not generic performance upgrades.
Move each attribute with a TACTIC, not a product. Once a target is unmet or at risk, select the mechanism from the tactics inventory in .claude/docs/architecture-knowledge.md §2 (availability · performance · modifiability · security · testability · usability) — "bulkhead a pool per dependency" is a design decision; "add Kubernetes" is a shopping list. — why: the tactic is portable across stacks and makes the trade-off legible, the product imports costs nobody asked for.
2-1: Pick ≤3 DRIVING attributes — and name what you SACRIFICE
Quality attributes CONFLICT, and that conflict IS the architecture: consistency↔availability · latency↔durability · flexibility↔simplicity · security↔usability · cost↔redundancy · performance↔modifiability.
MANDATORY IMPORTANT MUST ATTENTION name at most 3 DRIVING attributes and explicitly record which attributes are being SACRIFICED to buy them — a design claiming to maximize everything has decided nothing — why: unnamed sacrifices resurface as production surprises nobody agreed to.
| Field |
Record |
| Driving attributes (≤3) |
... + the quantified target for each (from the table above) |
| Explicitly sacrificed |
... + the acceptable degradation, e.g. "search may lag ≤5 s" |
| Trade-off purchased |
Use the "buy this / pay with this" table in .claude/docs/architecture-knowledge.md §19 — state cost, never just benefit |
Availability arithmetic (compute it, never assert it): dependencies in a request path MULTIPLY — five 99.9% deps ⇒ ~99.5% (≈43 h/yr down). Redundancy in PARALLEL adds 9s only when failure modes are genuinely independent; shared config, control plane, DNS and the deploy pipeline are the usual hidden serial term. Ladder: 99% = 3.65 d/yr · 99.9% = 8.77 h · 99.95% = 4.38 h · 99.99% = 52.6 min · 99.999% = 5.26 min.
Cost is a quality attribute, not a later phase. Model unit economics now — an architecture whose UNIT cost RISES with scale fails eventually regardless of elegance. Biggest web-system drivers: egress + cross-AZ/cross-region traffic · idle over-provisioned compute · unbounded log/metric/trace retention and cardinality · per-request managed-service pricing at steady high volume · always-on non-prod. Serverless vs always-on inverts with utilization — model it, don't assume it.
MANDATORY IMPORTANT MUST ATTENTION validate derived requirements with user by asking the user directly before proceeding.
2-2: Pre-Decision Interrogation (MANDATORY for every one-way door from 2-0)
Answer the 15-question pre-decision script in .claude/docs/architecture-knowledge.md §20.1 for each one-way door BEFORE researching options. Record answers in the Step 11 report; any question answered "unknown" becomes an Unresolved question, never a silent gap.
The five that most often expose a wrong decision — never skip these:
| # |
Question |
Why it changes the answer |
| 3 |
Is this a one-way or two-way door, and what makes it so? |
Sets how much rigour the decision earns; misclassification is this skill's most expensive failure |
| 5-6 |
Expected load NOW and at 10× — and what breaks FIRST? |
Names the actual bottleneck instead of the imagined one; 10×, never 1000× |
| 8 |
What is the consistency requirement PER read path, and what staleness is acceptable? |
Consistency is decided per path, never once globally |
| 14 |
What existing thing could be used instead of building? |
Generic subdomains (auth, billing, notifications, search) are the top source of wasted architecture budget |
| 15 |
What would have to be TRUE for this to be the WRONG choice — and how would I detect it? |
Becomes the ADR's measurable revisit trigger |
MANDATORY IMPORTANT MUST ATTENTION a one-way door with no answer to question 15 is a BELIEF, not a decision — NEVER emit its ADR without a named falsifier and a measurable revisit trigger. — why: with no trigger nobody ever revisits it, so the decision outlives the constraints that justified it.
Architecture & Scalability Scorecard Inputs (feeds architecture-scalability-review)
Record these decisions now so the init-time architecture-scalability-review scorecard (mode=init) can grade them later against enforceable mechanisms, not intent. Each row is a design decision, not a finding — capture the choice AND where it is enforced. Leave any unknown as explicit Unresolved question (Step 11), never a silent omission. — why: a scorecard can only grade decisions actually recorded with an enforcement home.
| Scorecard input |
Design prompt (decide + record where enforced) |
Enforcement handoff |
| Build & CI scalability |
As the codebase grows, how are build/CI times kept bounded? Decide incremental builds, changed/affected-only detection, local + remote cache strategy, and CI test/build parallelism. Name the build-system fit (single-package vs monorepo tool such as Nx / Turborepo / Bazel) as an evaluated option, not a default. |
Step 7 (CI/CD provider parallelism + caching) |
| Horizontal scaling budgets |
From the Step 2 scale targets, decide stateless app nodes, load balancing, caching tiers, async/queue + back-pressure, DB scale plan (sharding/partitioning/replication), connection pooling, rate limits, and a SPOF scan of every single-instance dependency. |
ADR + Step 8 observability SLOs |
| Strategic DRY |
Decide the strategic DRY / shared-knowledge strategy: monorepo, shared domain lib, custom platform / util lib — AND explicitly when NOT to share. Keep domain concepts OUT of generic/shared/infra layers (a shared layer coupled to one consumer's domain is no longer reusable). |
Step 9 arch-rules + scaffold foundation |
| Dependency-boundary enforcement |
Decide explicit dependency directions between modules/contexts and the mechanism that enforces them (no circular deps). |
Step 9 "Arch rules / fitness" handoff → linter-setup |
These inputs are graded at init/audit by architecture-scalability-review; per-change regressions are caught by architecture-review. Do NOT turn this step into an auditor — record decisions here and route grading to those skills.
Step 3: Backend Architecture
3A: Architecture Styles
WebSearch top 3 backend architecture styles. Candidates:
| Style |
Best For |
Research Focus |
| Clean Architecture |
Complex domains, long-lived projects |
Dependency rule, testability, flexibility |
| Hexagonal (Ports+Adapt) |
Integration-heavy, multiple I/O adapters |
Port contracts, adapter isolation |
| Vertical Slice |
Feature-focused teams, rapid delivery |
Slice isolation, code locality |
| Modular Monolith |
Starting simple, eventual decomposition |
Module boundaries, migration path |
| Microservices |
Large teams, independent deployment |
Service boundaries, operational overhead |
| CQRS + Event Sourcing |
Audit-heavy, complex queries |
Read/write separation, event store |
| Layered (N-Tier) |
Simple CRUD, small teams |
Layer responsibilities, coupling risk |
Full 16-style matrix with per-style buys / costs / choose-when / avoid-when → .claude/docs/architecture-knowledge.md §5.
Style selection procedure (MANDATORY order — never shortcut)
- Take the ≤3 quantified driving attributes from Step 2-1.
- ELIMINATE every style that cannot meet them (state which attribute eliminated it).
- DESIGN IT TWICE — produce ≥2 MATERIALLY different surviving candidate designs (not two spellings of one idea) and write what each SACRIFICES. — why: committing to the first idea that occurred to you is the most common architecture failure and the one nobody records; a second real candidate is what makes the first one a choice.
- Among survivors take the SIMPLEST — not the most capable.
- Emit an ADR (Step 11) naming the rejected alternative AND the measurable trigger that would revisit the choice.
MANDATORY IMPORTANT MUST ATTENTION design-it-twice applies to EVERY one-way door from 2-0, not only the style choice — data model, tenancy model, consistency model per read path, sync-vs-async at a boundary. NEVER emit a one-way-door ADR whose "Alternatives considered" section was written to justify a decision already made. — why: a retrofitted alternative is advocacy, not evaluation, and it hides the sacrifice the reviewer needs to see.
Styles COMPOSE — modular monolith + event-driven integration + 2-3 extracted services is the most common good real answer. Recommending a single pure style is usually a sign step 2 was skipped.
MANDATORY IMPORTANT MUST ATTENTION — modulith-first default. Default to a modular monolith with CI-ENFORCED module boundaries (architecture tests, Step 9) and extract services ONLY against a named, measured trigger from the table below. Microservices are a destination reached under pressure, NEVER a starting point — the 2025-2026 industry correction is documented: many organizations re-consolidated after debugging complexity, ops overhead and network latency outweighed autonomy gains. — why: distribution bought speculatively pays every distributed cost immediately and collects the benefit never.
| Legitimate extraction trigger (record BEFORE building) |
NOT a trigger (reject these) |
| Independent scaling profile ≥10x divergent |
"The codebase feels big" |
| Different compliance / data-residency boundary |
"Microservices are best practice" |
| Different availability requirement |
A resume, a conference talk, or framework support |
| A team boundary PROVABLY blocked by shared deploys |
One slow endpoint (fix the endpoint) |
| Genuinely different runtime need (GPU, language, memory profile) |
A new team was hired |
| Fault isolation for a KNOWN-unreliable dependency |
The domain has many entities |
MUST ATTENTION verify platform maturity before recommending microservices: CI/CD, IaC, distributed tracing, on-call, and a platform team. Microservices without them is the most reliable predictor of a failed migration — recommend the modulith and say so explicitly.
MUST ATTENTION draw boundaries around capabilities/behaviors (Checkout, Fulfilment, Pricing), NEVER around nouns/data (UserService, ProductService). Entity-per-service guarantees every real use case must synchronously traverse many services — a distributed monolith produced by design. The unit of extraction is the bounded context, not the entity.
3B: Backend Design Patterns
Evaluate applicability per layer:
| Pattern |
Layer |
When to Apply |
| Repository |
Data Access |
Abstract data store, enable testing |
| CQRS |
Application |
Separate read/write models, complex queries |
| Mediator |
Application |
Decouple handlers from controllers |
| Strategy |
Domain/App |
Multiple interchangeable algorithms |
| Observer/Events |
Domain |
Cross-aggregate side effects |
| Factory |
Domain |
Complex object creation with invariants |
| Decorator |
Cross-cutting |
Add behavior without modifying (logging, caching) |
| Adapter |
Infrastructure |
Isolate external dependencies |
| Specification |
Domain |
Composable business rules, complex filtering |
| Unit of Work |
Data Access |
Transaction management across repositories |
| Saga/Orchestr. |
Cross-service |
Distributed transactions, compensating actions |
| Outbox |
Messaging |
Reliable event publishing with DB transactions |
| Circuit Breaker |
Infrastructure |
External service resilience |
Per recommended pattern document: Apply to, Why, Example, Risk if skipped.
MUST ATTENTION patterns are a VOCABULARY for a solution you already need, never a menu to shop from — applying patterns to demonstrate knowledge produces the gas factory anti-pattern. The right number of patterns is the SMALLEST number that removes a DEMONSTRATED pain. Watch the chronically over-applied ones: Singleton (global mutable state → prefer one DI registration), Service Locator (hides dependencies from compiler and tests), CQRS on simple CRUD, event sourcing used as an audit log (an audit table is the right answer).
Step 3C: Data & Consistency Architecture
Skip if: the change touches no persistence, no consistency boundary, and no tenant-scoped data. Otherwise MANDATORY.
Data outlives every service, framework and team — this is the MOST irreversible step in this skill. Treat every row below as a one-way door (Step 2-0) until proven otherwise: each needs an ADR and a Step-12 validation question.
| Decision | Decide + record
…(truncated)
1---2name: architecture-design3description: [Architecture] Use when designing solution architecture across backend, frontend, data & consistency, integration & APIs, deployment, monitoring, testing, and code quality. Architecture laws, style-selection triggers, coupling taxonomy, trade-off tables and the anti-pattern catalog live in `.claude/docs/architecture-knowledge.md`.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:** As solution architect, deliver a complete, evidence-backed, user-validated architecture decision report covering ALL concerns (backend, frontend, design patterns, library ecosystem, testing, CI/CD, deployment, monitoring, code quality, dependency management) — every concern researched with 3+ options, every recommendation carrying confidence % + cited evidence, every decision user-confirmed — so implementation proceeds on sound, owned architectural choices.6162**Summary:**6364- Decide mode FIRST (Step 1): greenfield researches every concern from scratch; brownfield reads reference docs + accepted ADRs, constrains research to existing stack — NEVER re-litigate a settled ADR-recorded decision without superseding-ADR rationale.65- **Rank every decision by REVERSIBILITY first (Step 2): one-way door (data model, tenancy, consistency model, service boundaries, public contracts, sync-vs-async) → ADR + user validation MANDATORY; two-way door → decide and move.** — why: architecture IS the set of decisions expensive to reverse; treating a one-way door as reversible is the costliest error this skill can make.66- Drive style choice with NUMBERS, not adjectives: quantify Step-2 quality-attribute scenarios (latency p95/p99, throughput, SLO, RPO/RTO, data growth, concurrency); pick **≤3 DRIVING attributes and name which ones you SACRIFICE**; any unknown target becomes explicit `Unresolved question`, never a silent guess.67- **Profile the workload before selecting a scaling technique:** read/write ratio · sustained/peak RPS · query shapes · data size/growth · burstiness/hot keys · consistency/staleness · user geography. Escalate through the smallest reversible rung: measure/tune → choose vertical and/or stateless horizontal scale from headroom + availability needs → read/write-specific tactics → partition/shard LAST. — why: a scalable product is a sequence of evidenced bottleneck removals, not a shopping list of distributed components.68- **Simplicity is the default; complexity must be BOUGHT with a measured requirement — modulith-first, distribute only against a named + measured extraction trigger (Step 3A).** Reason FROM `.claude/docs/architecture-knowledge.md` (laws, coupling taxonomy, style triggers, trade-off + anti-pattern catalogs) — never from familiarity or fashion.69- Every concern needs 3+ researched options with cited evidence (stars, last release, downloads, CVE scan) + confidence % — familiarity alone never sufficient grounds for a recommendation.70- **Interrogate before deciding, DESIGN IT TWICE, then self-audit:** run the 15-question pre-decision script (§20.1) on every one-way door (Step 2-2) · produce ≥2 MATERIALLY different candidates per one-way door before choosing (Step 3A) · run the 11 thinking red flags (§20.3) against your own draft before emitting. Prescribe the **TACTIC** (§2), never the product. — why: a first-idea design with no rejected alternative and no named falsifier is a belief, not a decision.71- Produce the two binding downstream contracts or the chain breaks: emit an ADR per hard-to-reverse decision (`architecture-review` Cat 9 enforces) and the Scaffold Handoff tool-choices table (`scaffold`/`harness-setup` consume), then run the MANDATORY Step-12 user-validation interview before confirming.72- **Main steps/tasks (run in order, track each):** 1 Load Context (+pick greenfield/brownfield mode) → 2 Derive Architecture Requirements (+workload profile/scaling ladder, reversibility ranking, ≤3 driving attributes, 6-part quality-attribute scenarios, 2-2 pre-decision interrogation, user-validate) → 3A Backend Styles (selection procedure incl. DESIGN IT TWICE + extraction triggers) → 3B Backend Design Patterns → **3C Data & Consistency Architecture** (store/substrate per access pattern, replication/failover, cache contract, consistency + staleness, transaction boundary, tenancy, partitioning, migrations, retention) → **3D Integration & API Architecture** (sync-vs-async + acceptance state, API/edge cache style, versioning, contract tests, outbox, idempotency, event granularity) → 4 Frontend Architecture (styles + patterns) → 4B UI System Architecture (styling/tokens/components/responsive, user-validate; skip if backend-only) → 5 Library Ecosystem Research (3 options/concern) → 6 Testing Architecture → 7 CI/CD & Deployment (+expand–contract migrations, backward AND forward compat) → 8 Observability & Monitoring (signal roles + sampling/cardinality) → 9 Code Quality + Scaffold Handoff table → 10 Dependency Risk Assessment → 11 Generate Report + emit ADRs → 12 User Validation Interview (8-12 questions, mark `confirmed`) → Next Steps + always-offer council escalation. — why: AI keeps forgetting the skill's own steps; this is the recovery anchor.7374**Workflow (12 steps):**75761. **Load Context** — Read domain model, tech stack, business evaluation, refined PBI772. **Derive Architecture Requirements** — Profile workload + ordered scaling ladder, rank reversibility, pick ≤3 driving attributes, quantify 6-part scenarios, run 2-2 pre-decision interrogation on every one-way door783. **Backend Architecture** — 3A styles (selection procedure) · 3B design patterns · **3C data & consistency** · **3D integration & APIs**794. **Frontend Architecture** — Research top 3 frontend architecture styles + design patterns805. **Library Ecosystem Research** — Best-practice libraries per concern (validation, caching, logging, utils, etc.)816. **Testing Architecture** — Unit, integration, E2E, performance testing frameworks + strategy827. **CI/CD & Deployment** — Pipeline design, containerization, orchestration, IaC838. **Observability & Monitoring** — Logging, metrics, tracing, alerting stack849. **Code Quality & Clean Code** — Linters, analyzers, formatters, enforcement tooling8510. **Dependency Risk Assessment** — Package health, obsolescence risk, maintenance cost8611. **Generate Report** — Full architecture decision report with all recommendations8712. **User Validation** — Present findings, ask 8-12 questions, confirm all decisions8889**Key Rules:**9091- **MANDATORY IMPORTANT MUST ATTENTION** research minimum 3 options per architecture concern with web evidence92- **MANDATORY IMPORTANT MUST ATTENTION** include confidence % with evidence for every recommendation93- **MANDATORY IMPORTANT MUST ATTENTION** run user validation interview at end (never skip)94- Delegate to `solution-architect` agent for complex architecture decisions95- All claims must cite sources (URL, benchmark, case study, or codebase evidence)96- Base every recommendation on evidence, never on familiarity alone9798**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**99100---101102## Inputs & Handoffs (consume vs produce)103104Skill sits mid-workflow — consumes settled upstream decisions, produces artifacts downstream steps build on. Do NOT re-derive what upstream step already owns; do NOT leave downstream consumer without its needed artifact. — why: re-deriving settled decisions wastes effort and risks divergence from the recorded choice.105106| Consumes (read, don't re-derive) | From | Produces (named deliverable) | Consumed by |107| ------------------------------------------------ | ----------------------------- | ------------------------------------------------------------ | ----------------------------------- |108| Bounded contexts, aggregates, domain events, ERD | `domain-analysis` | Architecture decision report (`{plan-dir}/research/...`) | `plan`, `plan-execute` |109| Confirmed languages/frameworks/databases | `tech-stack-research` | Confirmed decisions (`{plan-dir}/phase-02b-architecture.md`) | `plan`, `scaffold` |110| Expected scale, compliance, budget constraints | `business-evaluation` | Scaffold Handoff table (tooling + fitness rules) | `scaffold`, `harness-setup` |111| Existing stack/patterns/ADRs (brownfield) | reference docs, `docs/adr/**` | ADRs for hard-to-reverse decisions (`docs/adr/`) | `architecture-review` (conformance) |112113If upstream artifact missing, capture minimum needed here and note gap — NEVER silently re-run full upstream analysis. — why: a silent re-run hides the missing-input gap that the owning step should resolve.114115---116117## Step 1: Load Context118119> **Mode (decide first):** **Greenfield** (new project, e.g. via `workflow-greenfield-init`) → research every concern from scratch, full 3-options-per-concern. **Brownfield** (large feature in existing codebase, e.g. `workflow-big-feature`) → FIRST read project reference docs + accepted ADRs, constrain research to existing stack/patterns, propose changes only where new requirement genuinely outgrows them — NEVER re-litigate settled ADR-recorded decision without superseding-ADR rationale. — why: re-deciding a recorded choice churns the codebase and breaks downstream conformance checks.120121Read artifacts from prior workflow steps (search `plans/` and `team-artifacts/`):122123- Domain model / ERD (complexity, bounded contexts, aggregate count)124- Tech stack decisions (confirmed languages, frameworks, databases)125- Business evaluation (scale, constraints, compliance)126- Refined PBI (scope, acceptance criteria)127- Discovery interview (team skills, experience level)128129Extract, summarize:130131| Signal | Value | Source |132| ----------------------- | ------------ | ---------------- |133| Bounded contexts | ... | domain model |134| Aggregate count | ... | domain model |135| Cross-context events | ... | domain model |136| Confirmed tech stack | ... | tech stack phase |137| Expected scale | ... | business eval |138| Team architecture exp. | ... | discovery |139| Compliance requirements | ... | business eval |140| Real-time needs | Yes/No | refined PBI |141| Integration complexity | Low/Med/High | domain model |142| Deployment target | ... | business eval |143144---145146## Step 2: Derive Architecture Requirements147148> **Reason FROM the knowledge body, not from memory.** `.claude/docs/architecture-knowledge.md` is AUTHORITATIVE for architecture laws (CAP/PACELC, Conway, Amdahl, USL, Little, Gall, Hyrum, Parnas), the coupling taxonomy + four coupling dimensions, style-selection triggers, the trade-off cheat sheet, and the ~100-entry anti-pattern catalog. Read the sections relevant to this design before recommending. **Honor the catalog's provenance markers in §3/§8/§9/§10** — a row (or section banner) marked `— VERIFY` is an UNVERIFIED assertion, so cite it as a hypothesis to check against the named source **where one is named** (a `[model-knowledge]` row names none — check the project's own docs or a primary source instead), NEVER as settled fact in a recommendation. **The project's own reference docs and accepted ADRs OUTRANK that catalog on any conflict** — the catalog supplies universal reasoning, the project supplies binding convention. — why: universal names hardcoded as project rules rot against real repos.149150### 2-0: Rank every decision by REVERSIBILITY (do this FIRST)151152Architecture = the set of decisions **expensive to reverse**; everything cheap to reverse is design — leave it to implementers. Classify each decision BEFORE researching it, because the classification sets how much rigour it earns.153154| Class | Meaning | Required treatment |155| ---------------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |156| **One-way door** | Reversal costs a migration, a rewrite, or a breaking change to consumers | **ADR (Step 11) + user validation (Step 12) MANDATORY** — research 3+ options, name the rejected alternative AND the measurable revisit trigger |157| **Two-way door** | Reversal is a refactor inside one module | Decide, record one line, move on — NEVER burn a validation question on it |158159**One-way doors (assume MANDATORY ADR unless proven otherwise):** data model + primary-key strategy · tenancy model · consistency model per read path · sync-vs-async at a boundary · public API/event contract · service boundary lines · cloud-primitive lock-in · auth/identity model · data residency + retention.160161**MANDATORY IMPORTANT MUST ATTENTION** never treat a one-way door as a two-way door to save a step — why: an unreviewed irreversible decision is the single most expensive failure mode of this skill, and it surfaces months later as a migration.162163Map signals to architecture constraints:164165| Signal | Architecture Requirement | Priority |166| --------------------------- | --------------------------------------------------------- | -------- |167| Many bounded contexts | Clear module boundaries, context isolation | Must |168| High scale | Horizontal scaling, stateless services, caching strategy | Must |169| Complex domain | Rich domain model, separation of domain from infra | Must |170| Cross-context events | Event-driven communication, eventual consistency | Must |171| Small team | Low ceremony, fewer layers, convention over configuration | Should |172| Compliance | Audit trail, immutable events, access control layers | Must |173| Real-time | Event sourcing or pub/sub, WebSocket/SSE support | Should |174| High integration complexity | Anti-corruption layers, adapter pattern, API gateway | Should |175176### Quality-Attribute Scenarios (quantify — these drive the style choice)177178Qualitative "Must/Should" cannot decide, e.g., modular monolith vs microservices. Capture **measurable** targets; ask user for any unknown by asking the user directly (guess acceptable only when labelled an assumption with confidence %). These targets become ADR-recorded budgets `architecture-review` Category 9 later checks changes against. — why: a style chosen without numbers is a guess, not an enforceable decision.179180| Quality attribute | Scenario (stimulus → measurable response) | Target (fill in) |181| --------------------- | ------------------------------------------------------------------------- | ------------------ |182| Latency | p95 / p99 response time for the hottest read and write paths | e.g. p99 < 300ms |183| Throughput | Sustained req/s and peak burst the system must absorb | e.g. 500 rps peak |184| Availability / SLO | Target uptime and error budget | e.g. 99.9% |185| Data durability (RPO) | Max acceptable data loss on failure | e.g. ≤ 5 min |186| Recovery (RTO) | Max acceptable time to restore service | e.g. ≤ 30 min |187| Data-volume growth | Row/document/event growth → storage, index, partition strategy | e.g. 10M rows/yr |188| Concurrency | Concurrent users/sessions and contention hot spots | e.g. 2k concurrent |189| Compliance/retention | Regulated data, retention window, residency, audit | e.g. GDPR, 7yr |190| Cost unit economics | `$/request`, `$/tenant`, `$/MAU` — and whether unit cost RISES with scale | e.g. <$0.002/req |191192Scenario template — **all SIX parts, none optional**: `[SOURCE: who/what triggers] [STIMULUS: the event] on [ARTIFACT: which component] under [ENVIRONMENT: the conditions] SHALL produce [RESPONSE] within [MEASURE: threshold + instrument]`. "Must be scalable" decides nothing; "5,000 concurrent checkout sessions at 400 rps SHALL complete p99 < 800 ms, ≤0.1% errors, verified by the CI k6 profile" selects a structure.193194**MUST ATTENTION** a scenario missing SOURCE or ARTIFACT is untestable — you cannot write a fitness function for "the system" under "load", so name the actor and the component. — why: an unattributed scenario gets no owner, no test and no budget, so it is never verified and silently degrades.195196**Rule:** any target left unknown is explicit `Unresolved question` (Step 11), NEVER a silent omission — an architecture chosen without scale numbers is a guess, not a decision.197198### Workload Profile + Scaling Ladder (MANDATORY before technique selection)199200Record `read:write ratio` · sustained/peak RPS or events/s · dominant query/write shapes · dataset size + growth · payload size · burst duration · hot-key/tenant skew · user regions · latency percentile targets · consistency/staleness tolerance. For every proposed scaling component, name the measured bottleneck it removes and the next bottleneck it creates.201202| Order | Use when evidence shows | First tactic | Purchase price |203| ------------------------ | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |204| 1. Measure + tune | Baseline unknown or slow path unprofiled | Query/plan analysis, indexes, batching, pooling, compression | Engineering time; lowest reversibility cost |205| 2A. Vertical scale | One node remains simplest and headroom exists | More CPU/RAM/IOPS; tune runtime/database | Hardware ceiling; remaining SPOF without redundancy |206| 2B. Horizontal app scale | Availability or aggregate compute requires replicas and the path can be stateless | Replicas + redundant load balancing + health checks | Coordination, externalized state, deployment complexity |207| 4. Read-path scale | High read ratio or global read latency | Cache/CDN/read replicas/read models | Invalidation, lag, read-your-writes, cache-key correctness |208| 5. Write-path scale | Bursty ingest or heavy work need not finish inline | Batching, durable queue + workers; LSM store for sustained write-heavy known-query workloads | Accepted ≠ completed, retries/idempotency/backpressure; compaction/read amplification |209| 6. Partition/shard | Earlier rungs proven insufficient by capacity measurements | Query-aligned partition key + reshard plan | Cross-shard queries/transactions, hotspots, hard reversal |210211**MANDATORY IMPORTANT MUST ATTENTION** NEVER jump to sharding, multi-region writes, or an extra datastore without evidence that earlier rungs cannot meet the quantified target — why: these are hard-to-reverse operational systems, not generic performance upgrades.212213**Move each attribute with a TACTIC, not a product.** Once a target is unmet or at risk, select the mechanism from the tactics inventory in `.claude/docs/architecture-knowledge.md` §2 (availability · performance · modifiability · security · testability · usability) — "bulkhead a pool per dependency" is a design decision; "add Kubernetes" is a shopping list. — why: the tactic is portable across stacks and makes the trade-off legible, the product imports costs nobody asked for.214215### 2-1: Pick ≤3 DRIVING attributes — and name what you SACRIFICE216217Quality attributes CONFLICT, and that conflict IS the architecture: consistency↔availability · latency↔durability · flexibility↔simplicity · security↔usability · cost↔redundancy · performance↔modifiability.218219**MANDATORY IMPORTANT MUST ATTENTION** name at most 3 DRIVING attributes and explicitly record which attributes are being SACRIFICED to buy them — a design claiming to maximize everything has decided nothing — why: unnamed sacrifices resurface as production surprises nobody agreed to.220221| Field | Record |222| ----------------------- | ------------------------------------------------------------------------------------------------------------------------- |223| Driving attributes (≤3) | ... + the quantified target for each (from the table above) |224| Explicitly sacrificed | ... + the acceptable degradation, e.g. "search may lag ≤5 s" |225| Trade-off purchased | Use the "buy this / pay with this" table in `.claude/docs/architecture-knowledge.md` §19 — state cost, never just benefit |226227**Availability arithmetic (compute it, never assert it):** dependencies in a request path MULTIPLY — five 99.9% deps ⇒ ~99.5% (≈43 h/yr down). Redundancy in PARALLEL adds 9s **only when failure modes are genuinely independent**; shared config, control plane, DNS and the deploy pipeline are the usual hidden serial term. Ladder: 99% = 3.65 d/yr · 99.9% = 8.77 h · 99.95% = 4.38 h · 99.99% = 52.6 min · 99.999% = 5.26 min.228229**Cost is a quality attribute, not a later phase.** Model unit economics now — an architecture whose UNIT cost RISES with scale fails eventually regardless of elegance. Biggest web-system drivers: egress + cross-AZ/cross-region traffic · idle over-provisioned compute · unbounded log/metric/trace retention and cardinality · per-request managed-service pricing at steady high volume · always-on non-prod. Serverless vs always-on **inverts with utilization** — model it, don't assume it.230231**MANDATORY IMPORTANT MUST ATTENTION** validate derived requirements with user by asking the user directly before proceeding.232233### 2-2: Pre-Decision Interrogation (MANDATORY for every one-way door from 2-0)234235Answer the 15-question pre-decision script in `.claude/docs/architecture-knowledge.md` §20.1 for each one-way door BEFORE researching options. Record answers in the Step 11 report; any question answered "unknown" becomes an `Unresolved question`, never a silent gap.236237The five that most often expose a wrong decision — never skip these:238239| # | Question | Why it changes the answer |240| --- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |241| 3 | Is this a one-way or two-way door, and what makes it so? | Sets how much rigour the decision earns; misclassification is this skill's most expensive failure |242| 5-6 | Expected load NOW and at 10× — and **what breaks FIRST**? | Names the actual bottleneck instead of the imagined one; 10×, never 1000× |243| 8 | What is the consistency requirement PER read path, and what staleness is acceptable? | Consistency is decided per path, never once globally |244| 14 | What existing thing could be used instead of building? | Generic subdomains (auth, billing, notifications, search) are the top source of wasted architecture budget |245| 15 | **What would have to be TRUE for this to be the WRONG choice — and how would I detect it?** | Becomes the ADR's measurable revisit trigger |246247**MANDATORY IMPORTANT MUST ATTENTION** a one-way door with no answer to question 15 is a BELIEF, not a decision — NEVER emit its ADR without a named falsifier and a measurable revisit trigger. — why: with no trigger nobody ever revisits it, so the decision outlives the constraints that justified it.248249### Architecture & Scalability Scorecard Inputs (feeds `architecture-scalability-review`)250251Record these decisions now so the init-time `architecture-scalability-review` scorecard (`mode=init`) can grade them later against **enforceable mechanisms, not intent**. Each row is a **design decision**, not a finding — capture the choice AND where it is enforced. Leave any unknown as explicit `Unresolved question` (Step 11), never a silent omission. — why: a scorecard can only grade decisions actually recorded with an enforcement home.252253| Scorecard input | Design prompt (decide + record where enforced) | Enforcement handoff |254| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |255| Build & CI scalability | As the codebase grows, how are build/CI times kept bounded? Decide **incremental** builds, changed/**affected**-only detection, local + **remote cache** strategy, and CI test/build parallelism. Name the build-system fit (single-package vs monorepo tool such as Nx / Turborepo / Bazel) **as an evaluated option**, not a default. | Step 7 (CI/CD provider parallelism + caching) |256| Horizontal scaling budgets | From the Step 2 scale targets, decide **stateless** app nodes, load balancing, caching tiers, async/queue + back-pressure, DB scale plan (sharding/partitioning/replication), connection pooling, rate limits, and a **SPOF** scan of every single-instance dependency. | ADR + Step 8 observability SLOs |257| Strategic DRY | Decide the **strategic DRY** / shared-knowledge strategy: monorepo, shared domain lib, custom platform / util lib — AND explicitly when NOT to share. Keep domain concepts OUT of generic/shared/infra layers (a shared layer coupled to one consumer's domain is no longer reusable). | Step 9 arch-rules + `scaffold` foundation |258| Dependency-boundary enforcement | Decide explicit dependency directions between modules/contexts and the mechanism that enforces them (no circular deps). | Step 9 "Arch rules / fitness" handoff → `linter-setup` |259260These inputs are graded at init/audit by `architecture-scalability-review`; per-change regressions are caught by `architecture-review`. Do NOT turn this step into an auditor — record decisions here and route grading to those skills.261262---263264## Step 3: Backend Architecture265266### 3A: Architecture Styles267268WebSearch top 3 backend architecture styles. Candidates:269270| Style | Best For | Research Focus |271| --------------------------- | ---------------------------------------- | ----------------------------------------- |272| **Clean Architecture** | Complex domains, long-lived projects | Dependency rule, testability, flexibility |273| **Hexagonal (Ports+Adapt)** | Integration-heavy, multiple I/O adapters | Port contracts, adapter isolation |274| **Vertical Slice** | Feature-focused teams, rapid delivery | Slice isolation, code locality |275| **Modular Monolith** | Starting simple, eventual decomposition | Module boundaries, migration path |276| **Microservices** | Large teams, independent deployment | Service boundaries, operational overhead |277| **CQRS + Event Sourcing** | Audit-heavy, complex queries | Read/write separation, event store |278| **Layered (N-Tier)** | Simple CRUD, small teams | Layer responsibilities, coupling risk |279280Full 16-style matrix with per-style _buys / costs / choose-when / avoid-when_ → `.claude/docs/architecture-knowledge.md` §5.281282#### Style selection procedure (MANDATORY order — never shortcut)2832841. Take the ≤3 quantified driving attributes from Step 2-1.2852. **ELIMINATE** every style that cannot meet them (state which attribute eliminated it).2863. **DESIGN IT TWICE** — produce ≥2 MATERIALLY different surviving candidate designs (not two spellings of one idea) and write what each SACRIFICES. — why: committing to the first idea that occurred to you is the most common architecture failure and the one nobody records; a second real candidate is what makes the first one a choice.2874. Among survivors take the **SIMPLEST** — not the most capable.2885. Emit an ADR (Step 11) naming the rejected alternative AND the **measurable trigger** that would revisit the choice.289290**MANDATORY IMPORTANT MUST ATTENTION** design-it-twice applies to EVERY one-way door from 2-0, not only the style choice — data model, tenancy model, consistency model per read path, sync-vs-async at a boundary. NEVER emit a one-way-door ADR whose "Alternatives considered" section was written to justify a decision already made. — why: a retrofitted alternative is advocacy, not evaluation, and it hides the sacrifice the reviewer needs to see.291292Styles COMPOSE — modular monolith + event-driven integration + 2-3 extracted services is the most common good real answer. Recommending a single pure style is usually a sign step 2 was skipped.293294**MANDATORY IMPORTANT MUST ATTENTION — modulith-first default.** Default to a **modular monolith with CI-ENFORCED module boundaries** (architecture tests, Step 9) and extract services ONLY against a named, measured trigger from the table below. **Microservices are a destination reached under pressure, NEVER a starting point** — the 2025-2026 industry correction is documented: many organizations re-consolidated after debugging complexity, ops overhead and network latency outweighed autonomy gains. — why: distribution bought speculatively pays every distributed cost immediately and collects the benefit never.295296| Legitimate extraction trigger (record BEFORE building) | NOT a trigger (reject these) |297| ---------------------------------------------------------------- | ------------------------------------------------- |298| Independent scaling profile ≥10x divergent | "The codebase feels big" |299| Different compliance / data-residency boundary | "Microservices are best practice" |300| Different availability requirement | A resume, a conference talk, or framework support |301| A team boundary PROVABLY blocked by shared deploys | One slow endpoint (fix the endpoint) |302| Genuinely different runtime need (GPU, language, memory profile) | A new team was hired |303| Fault isolation for a KNOWN-unreliable dependency | The domain has many entities |304305**MUST ATTENTION** verify platform maturity before recommending microservices: CI/CD, IaC, distributed tracing, on-call, and a platform team. Microservices without them is the most reliable predictor of a failed migration — recommend the modulith and say so explicitly.306307**MUST ATTENTION** draw boundaries around **capabilities/behaviors** (`Checkout`, `Fulfilment`, `Pricing`), NEVER around **nouns/data** (`UserService`, `ProductService`). Entity-per-service guarantees every real use case must synchronously traverse many services — a distributed monolith produced by design. The unit of extraction is the **bounded context**, not the entity.308309### 3B: Backend Design Patterns310311Evaluate applicability per layer:312313| Pattern | Layer | When to Apply |314| ------------------- | -------------- | ------------------------------------------------- |315| **Repository** | Data Access | Abstract data store, enable testing |316| **CQRS** | Application | Separate read/write models, complex queries |317| **Mediator** | Application | Decouple handlers from controllers |318| **Strategy** | Domain/App | Multiple interchangeable algorithms |319| **Observer/Events** | Domain | Cross-aggregate side effects |320| **Factory** | Domain | Complex object creation with invariants |321| **Decorator** | Cross-cutting | Add behavior without modifying (logging, caching) |322| **Adapter** | Infrastructure | Isolate external dependencies |323| **Specification** | Domain | Composable business rules, complex filtering |324| **Unit of Work** | Data Access | Transaction management across repositories |325| **Saga/Orchestr.** | Cross-service | Distributed transactions, compensating actions |326| **Outbox** | Messaging | Reliable event publishing with DB transactions |327| **Circuit Breaker** | Infrastructure | External service resilience |328329Per recommended pattern document: **Apply to**, **Why**, **Example**, **Risk if skipped**.330331**MUST ATTENTION** patterns are a VOCABULARY for a solution you already need, never a menu to shop from — applying patterns to demonstrate knowledge produces the _gas factory_ anti-pattern. The right number of patterns is the SMALLEST number that removes a DEMONSTRATED pain. Watch the chronically over-applied ones: Singleton (global mutable state → prefer one DI registration), Service Locator (hides dependencies from compiler and tests), CQRS on simple CRUD, event sourcing used as an audit log (an audit table is the right answer).332333---334335## Step 3C: Data & Consistency Architecture336337> **Skip if:** the change touches no persistence, no consistency boundary, and no tenant-scoped data. Otherwise MANDATORY.338339**Data outlives every service, framework and team — this is the MOST irreversible step in this skill.** Treat every row below as a one-way door (Step 2-0) until proven otherwise: each needs an ADR and a Step-12 validation question.340341| Decision | Decide + record 342343…(truncated)