azcodr 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.agents/hooks.json.example +42 -0
  2. package/.agents/mcp_config.json.example +24 -0
  3. package/.agents/scripts/safety_guard.sh +16 -0
  4. package/.agents/scripts/verify_completion.sh +13 -0
  5. package/.agents/skills/agentic-architect/SKILL.md +15 -8
  6. package/.agents/skills/agentic-architect/references/agents_md_template.md +6 -3
  7. package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +1 -1
  8. package/.agents/skills/agentic-architect/references/skill_template.md +2 -1
  9. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +189 -6
  10. package/.agents/skills/clean-code-refactor/SKILL.md +6 -6
  11. package/.agents/skills/compliance-audit/SKILL.md +1 -1
  12. package/.agents/skills/lets-build/SKILL.md +22 -7
  13. package/.agents/skills/lets-build/references/architecture_interview_matrix.md +8 -2
  14. package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +53 -6
  15. package/.agents/skills/lets-build/references/project_readme_template.md +4 -4
  16. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +181 -36
  17. package/.agents/skills/product-analyst/SKILL.md +13 -2
  18. package/.agents/skills/relentless-questioner/SKILL.md +13 -5
  19. package/.agents/skills/relentless-questioner/references/adaptive_question_trees.md +18 -0
  20. package/.gitignore +2 -0
  21. package/AGENTS.md +25 -40
  22. package/README.md +27 -40
  23. package/bin/azcodr.js +9 -4
  24. package/docs/rules/agentic_configuration.md +123 -32
  25. package/docs/rules/api_architecture.md +179 -0
  26. package/docs/rules/caching.md +30 -13
  27. package/docs/rules/cloud_native.md +10 -12
  28. package/docs/rules/cqrs.md +203 -0
  29. package/docs/rules/database_design.md +125 -0
  30. package/docs/rules/database_operations.md +56 -14
  31. package/docs/rules/design_patterns.md +18 -11
  32. package/docs/rules/devops_ci_cd.md +76 -0
  33. package/docs/rules/domain_driven_design.md +17 -13
  34. package/docs/rules/feature_flags.md +21 -4
  35. package/docs/rules/frontend_architecture.md +157 -0
  36. package/docs/rules/multitenancy_architecture.md +98 -0
  37. package/docs/rules/product_ownership.md +22 -27
  38. package/docs/rules/relentless_questioning.md +4 -0
  39. package/docs/rules/requirements_engineering.md +16 -14
  40. package/docs/rules/security_compliance.md +53 -0
  41. package/docs/rules/server_driven_ui.md +20 -3
  42. package/docs/rules/test_driven_development.md +119 -62
  43. package/docs/rules/type_safety.md +65 -0
  44. package/docs/rules/ui_ux_architecture.md +33 -30
  45. package/docs/rules/workflow_state_machines.md +20 -3
  46. package/lib/scaffold.js +117 -5
  47. package/memory.md +12 -131
  48. package/package.json +2 -2
  49. package/docs/rules/accessibility.md +0 -31
  50. package/docs/rules/advanced_api_patterns.md +0 -104
  51. package/docs/rules/api_versioning.md +0 -113
  52. package/docs/rules/application_security.md +0 -23
  53. package/docs/rules/architecture_decision_records.md +0 -42
  54. package/docs/rules/compliance.md +0 -25
  55. package/docs/rules/container_infrastructure.md +0 -32
  56. package/docs/rules/continuous_deployment.md +0 -24
  57. package/docs/rules/continuous_integration.md +0 -20
  58. package/docs/rules/continuous_learning.md +0 -29
  59. package/docs/rules/database_integrity.md +0 -80
  60. package/docs/rules/database_migrations.md +0 -41
  61. package/docs/rules/database_performance.md +0 -44
  62. package/docs/rules/database_transactions.md +0 -81
  63. package/docs/rules/devsecops.md +0 -33
  64. package/docs/rules/multitenancy_isolation.md +0 -88
  65. package/docs/rules/react.md +0 -78
  66. package/docs/rules/rest_api_conventions.md +0 -46
  67. package/docs/rules/tenant_dynamic_schemas.md +0 -88
  68. package/docs/rules/tenant_pluggable_logic.md +0 -59
  69. package/docs/rules/test_isolation.md +0 -26
  70. package/docs/rules/typescript.md +0 -55
  71. package/docs/rules/ui_navigation.md +0 -20
  72. package/docs/rules/workspace_isolation.md +0 -25
package/README.md CHANGED
@@ -38,10 +38,13 @@
38
38
  ├── docs/
39
39
  │ ├── knowledge/ # Institutional knowledge & domain contracts
40
40
  │ │ └── ubiquitous_language.md # Living Ubiquitous Language glossary template
41
- │ └── rules/ # 44 atomic single-responsibility domain rules
41
+ │ └── rules/ # 28 cohesive single-responsibility domain rules
42
42
  ├── AGENTS.md # Lean root agentic configuration (< 120 lines)
43
- ├── CLAUDE.md -> AGENTS.md # Filesystem symlink for harness parity
44
- ├── agents.md -> AGENTS.md # Filesystem symlink for harness parity
43
+ ├── CLAUDE.md -> AGENTS.md # Filesystem symlink for harness parity (Claude Code)
44
+ ├── agents.md -> AGENTS.md # Filesystem symlink for harness parity (Codex / Standard)
45
+ ├── GEMINI.md -> AGENTS.md # Filesystem symlink for harness parity (Antigravity / Gemini)
46
+ ├── .cursorrules -> AGENTS.md # Filesystem symlink for harness parity (Cursor)
47
+ ├── .windsurfrules -> AGENTS.md # Filesystem symlink for harness parity (Windsurf)
45
48
  ├── memory.md # Master memory hub & Lightweight ADR ledger
46
49
  └── README.md # Project documentation
47
50
  ```
@@ -50,54 +53,38 @@
50
53
 
51
54
  ## 📋 Progressive Disclosure Rules Catalog (`docs/rules/`)
52
55
 
53
- The architecture enforces 44 atomic, single-responsibility domain rules. Read on demand to prevent prompt context bloat:
56
+ The architecture enforces 28 cohesive, single-responsibility domain rules. Read on demand to prevent prompt context bloat:
54
57
 
55
58
  | Domain | Rule Reference File | Key Focus & Invariants |
56
59
  |---|---|---|
57
- | **TDD Double Loop** | [`test_driven_development.md`](./docs/rules/test_driven_development.md) | Uncle Bob's 3 Laws, nano-cycles, Ping-Pong pairing, outside-in double loop. |
58
- | **Test Coverage & Isolation** | [`test_isolation.md`](./docs/rules/test_isolation.md) | 100.00% full-stack coverage, status codes, transactional DB rollback. |
59
- | **Clean Code** | [`clean_code.md`](./docs/rules/clean_code.md) | 5 evolutionary tipping points, Refactor-Before-Add, CQS, SLAP, DRY, fitness functions. |
60
- | **Design Patterns** | [`design_patterns.md`](./docs/rules/design_patterns.md) | Adapter, Factory, Strategy, Result `<T, E>`, and complete 23 GoF catalog. |
61
- | **Type Safety** | [`typescript.md`](./docs/rules/typescript.md) | Compiler strictness, branded nominal types, type safety, static sound invariants. |
62
- | **ADRs** | [`architecture_decision_records.md`](./docs/rules/architecture_decision_records.md) | Authoring Lightweight Architectural Decision Records in `memory.md`. |
60
+ | **TDD & Isolation** | [`test_driven_development.md`](./docs/rules/test_driven_development.md) | Outside-In TDD, Uncle Bob's 3 Laws, 100% coverage, test isolation & DB rollback. |
61
+ | **Clean Code** | [`clean_code.md`](./docs/rules/clean_code.md) | Naming, small functions, CQS, SLAP, DRY, DbC, zero side-effects. |
62
+ | **Design Patterns** | [`design_patterns.md`](./docs/rules/design_patterns.md) | Adapter, Factory, Strategy, Result `<T, E>`, and GoF pattern catalog. |
63
+ | **Type Safety** | [`type_safety.md`](./docs/rules/type_safety.md) | Compiler strictness, branded nominal types, type discriminators across polyglot languages. |
63
64
  | **Authentication** | [`authentication.md`](./docs/rules/authentication.md) | In-memory access tokens, refresh token rotation (RTR), WebAuthn passkeys. |
64
65
  | **Authorization** | [`authorization.md`](./docs/rules/authorization.md) | CASL, OPA Rego policy engines, OpenFGA ReBAC, server guards. |
65
- | **Multi-Tenancy Isolation** | [`multitenancy_isolation.md`](./docs/rules/multitenancy_isolation.md) | Tenant context resolution, 4 universal data isolation models, RLS/interceptor safety. |
66
- | **REST API Conventions** | [`rest_api_conventions.md`](./docs/rules/rest_api_conventions.md) | Standard HTTP status codes, enumeration masking, subresource endpoints. |
67
- | **Advanced API Patterns** | [`advanced_api_patterns.md`](./docs/rules/advanced_api_patterns.md) | Allowed Actions (`_actions`), Idempotency keys, cursor pagination, OCC. |
68
- | **API Versioning** | [`api_versioning.md`](./docs/rules/api_versioning.md) | URI versioning (`/v1/`), RFC 8594 Sunset/Deprecation headers, 90-day window. |
69
- | **Tenant Dynamic Schemas** | [`tenant_dynamic_schemas.md`](./docs/rules/tenant_dynamic_schemas.md) | Hybrid core + JSON/document storage, JSON Schema Draft 2020-12, meta-schemas. |
70
- | **Tenant Pluggable Logic** | [`tenant_pluggable_logic.md`](./docs/rules/tenant_pluggable_logic.md) | Common Expression Language (CEL), Wasm sandboxing, durable workflows (Temporal/BPMN). |
71
- | **Server-Driven UI** | [`server_driven_ui.md`](./docs/rules/server_driven_ui.md) | Client-agnostic layout schemas, multi-renderer component registries, DTCG tokens. |
72
- | **Database Transactions** | [`database_transactions.md`](./docs/rules/database_transactions.md) | ACID atomicity, isolation levels, defensive timeouts, transactional outbox. |
73
- | **Database Migrations** | [`database_migrations.md`](./docs/rules/database_migrations.md) | Declarative/versioned migrations (Atlas/Flyway), zero-downtime expand-contract. |
74
- | **Database Integrity** | [`database_integrity.md`](./docs/rules/database_integrity.md) | Foreign keys, domain CHECK constraints, interval EXCLUDE, soft-delete indexes. |
75
- | **Database Operations** | [`database_operations.md`](./docs/rules/database_operations.md) | Continuous PITR, autovacuum/defrag tuning, connection pooling, role separation. |
76
- | **Database Performance** | [`database_performance.md`](./docs/rules/database_performance.md) | Eliminating N+1 queries, DataLoader batching, composite tenant indexes. |
77
- | **Caching** | [`caching.md`](./docs/rules/caching.md) | Cache Port semantics, Cache-Aside, jittered TTLs, XFetch stampede defense. |
78
- | **Application Security** | [`application_security.md`](./docs/rules/application_security.md) | OWASP Top 10 defenses, cryptographic rigor, token bucket rate limiting. |
79
- | **Regulatory Compliance** | [`compliance.md`](./docs/rules/compliance.md) | SOC 2 Type II controls, ISO/IEC 27001 ISMS, GDPR data erasure rights. |
80
- | **DevSecOps** | [`devsecops.md`](./docs/rules/devsecops.md) | Secretlint pre-commit gating, CycloneDX SBOM generation, Trivy/Grype scanning. |
66
+ | **Multi-Tenancy** | [`multitenancy_architecture.md`](./docs/rules/multitenancy_architecture.md) | Tenant context, 4 isolation models, RLS, dynamic schemas, pluggable logic & YAGNI gates. |
67
+ | **API Architecture** | [`api_architecture.md`](./docs/rules/api_architecture.md) | HTTP status codes, sync vs async (202), `_actions`, idempotency keys, cursor pagination, OCC, versioning. |
68
+ | **Server-Driven UI** | [`server_driven_ui.md`](./docs/rules/server_driven_ui.md) | Backend-driven layout schemas, multi-renderer component registries, DTCG tokens & YAGNI gate. |
69
+ | **Database Design** | [`database_design.md`](./docs/rules/database_design.md) | Relational integrity, FKs, CHECK constraints, Canonical 6 audit fields, ACID transactions, Outbox CDC. |
70
+ | **Database Operations** | [`database_operations.md`](./docs/rules/database_operations.md) | Zero-downtime expand-contract migrations, N+1 elimination, DataLoader, indexing, pooling, PITR. |
71
+ | **Caching** | [`caching.md`](./docs/rules/caching.md) | Cache Port semantics, Cache-Aside, jittered TTLs, XFetch stampede defense & YAGNI gate. |
72
+ | **Security & Compliance** | [`security_compliance.md`](./docs/rules/security_compliance.md) | OWASP Top 10 defenses, rate limiting, crypto, SOC 2 Type II, ISO 27001, GDPR data erasure. |
73
+ | **DevOps & CI/CD** | [`devops_ci_cd.md`](./docs/rules/devops_ci_cd.md) | Shift-left trunk-based CI, OCI distroless containers, Secretlint/Trivy DevSecOps, zero-downtime CD. |
74
+ | **Cloud-Native 12-Factor** | [`cloud_native.md`](./docs/rules/cloud_native.md) | 12-Factor (2026 Edition), OpenTelemetry (OTel), stateless isolates. |
81
75
  | **Error Architecture** | [`error_handling.md`](./docs/rules/error_handling.md) | Fail-fast schema validation, structured OTel/Pino tracing, RFC 7807 envelopes. |
82
- | **Feature Flags** | [`feature_flags.md`](./docs/rules/feature_flags.md) | OpenFeature standard, Flipt/Unleash backends, targeting, kill switches. |
83
- | **Continuous Integration** | [`continuous_integration.md`](./docs/rules/continuous_integration.md) | Shift-left automated pipelines, trunk-based development, build caching. |
84
- | **Continuous Deployment** | [`continuous_deployment.md`](./docs/rules/continuous_deployment.md) | Zero-downtime rollouts, Cosign container signing, container minimization. |
85
- | **Container Infrastructure** | [`container_infrastructure.md`](./docs/rules/container_infrastructure.md) | Unified gateway, minimal OCI distroless/scratch containers, non-root user security. |
76
+ | **Feature Flags** | [`feature_flags.md`](./docs/rules/feature_flags.md) | OpenFeature standard, Flipt/Unleash backends, targeting, kill switches & YAGNI gate. |
86
77
  | **Transactional Email** | [`transactional_email.md`](./docs/rules/transactional_email.md) | Declarative templates (MJML/JSON), safe interpolation, SMTP integration testing. |
87
- | **Accessibility** | [`accessibility.md`](./docs/rules/accessibility.md) | WCAG 2.2 AA compliance, accessible primitives, focus trapping, ARIA live regions. |
88
- | **UI Navigation** | [`ui_navigation.md`](./docs/rules/ui_navigation.md) | Bidirectional URL state synchronization, deep linking, search params. |
89
- | **UI/UX Architecture** | [`ui_ux_architecture.md`](./docs/rules/ui_ux_architecture.md) | Design triage, persistent app shell, collapsible sidebar, dual-experience portals. |
90
- | **React & Frontend** | [`react.md`](./docs/rules/react.md) | Modern React, shadcn/ui, TanStack Query, React Hook Form, and Zod validation. |
78
+ | **UI/UX Architecture** | [`ui_ux_architecture.md`](./docs/rules/ui_ux_architecture.md) | Design triage gate, persistent app shell, collapsible sidebar, dual-experience portals, dev persona. |
79
+ | **Frontend Architecture** | [`frontend_architecture.md`](./docs/rules/frontend_architecture.md) | Accessible headless primitives, WCAG 2.2 AA, server cache sync, form validation, 5-tier state, URL navigation. |
91
80
  | **Requirements Engineering** | [`requirements_engineering.md`](./docs/rules/requirements_engineering.md) | User stories vs requirements, 3 C's, INVEST vertical cake slicing, Gherkin. |
92
81
  | **Product Ownership** | [`product_ownership.md`](./docs/rules/product_ownership.md) | Product Backlog Management, OKRs, Kano/MoSCoW/RICE, Product Value, empiricism. |
93
- | **Domain-Driven Design** | [`domain_driven_design.md`](./docs/rules/domain_driven_design.md) | Problem vs Solution Space, Ubiquitous Language, Aggregates, Capability Mapping. |
94
- | **Workflow State Machines** | [`workflow_state_machines.md`](./docs/rules/workflow_state_machines.md) | Configurable workflows, in-aggregate invariant FSMs, transition guards & audit logs. |
95
- | **Cloud-Native 12-Factor** | [`cloud_native.md`](./docs/rules/cloud_native.md) | 12-Factor (2026 Edition), OpenTelemetry (OTel), stateless isolates. |
96
- | **Agentic Config & Skills** | [`agentic_configuration.md`](./docs/rules/agentic_configuration.md) | Progressive disclosure architecture, skill inquiry branches, refinement loop. |
97
82
  | **Project Management** | [`project_management.md`](./docs/rules/project_management.md) | Work-In-Progress limits (WIP = 1), SMART developer tasks, Definition of Done. |
83
+ | **Domain-Driven Design** | [`domain_driven_design.md`](./docs/rules/domain_driven_design.md) | Ubiquitous Language, Bounded Contexts, Aggregates, Capability Mapping. |
84
+ | **CQRS & Projections** | [`cqrs.md`](./docs/rules/cqrs.md) | Evolutionary CQRS spectrum, YAGNI defense, read projections, outbox CDC. |
85
+ | **Workflow State Machines** | [`workflow_state_machines.md`](./docs/rules/workflow_state_machines.md) | Configurable workflows, in-aggregate invariant FSMs, transition guards & audit logs & YAGNI gate. |
86
+ | **Agentic Governance** | [`agentic_configuration.md`](./docs/rules/agentic_configuration.md) | Progressive disclosure, ADR ledger, workspace sovereignty, continuous learning, YAGNI gate triad. |
98
87
  | **Relentless Questioning** | [`relentless_questioning.md`](./docs/rules/relentless_questioning.md) | Dynamic context-aware interrogation loops, adaptive decision trees. |
99
- | **Workspace Isolation** | [`workspace_isolation.md`](./docs/rules/workspace_isolation.md) | Strict workspace sovereignty, zero global contamination, local ground truth. |
100
- | **Continuous Learning** | [`continuous_learning.md`](./docs/rules/continuous_learning.md) | Direct 4-step rule ingestion, root-cause analysis, dynamic invariant updates. |
101
88
 
102
89
  ---
103
90
 
package/bin/azcodr.js CHANGED
@@ -97,6 +97,9 @@ async function runCli(rawArgs = process.argv.slice(2), io = {}) {
97
97
  return exit(1);
98
98
  } else if (!targetDir) {
99
99
  targetDir = arg;
100
+ } else {
101
+ err(`❌ Error: Unexpected argument '${arg}'. Run 'npx azcodr --help' for available options.`);
102
+ return exit(1);
100
103
  }
101
104
  }
102
105
 
@@ -181,18 +184,20 @@ async function runCli(rawArgs = process.argv.slice(2), io = {}) {
181
184
  out(' ✅ Workspace knowledge hub and ADR ledger copied (docs/knowledge/, memory.md)');
182
185
  out(' ✅ Specialized agentic skills copied (.agents/skills/)');
183
186
  out(' ✅ Editor formatting standards initialized (.editorconfig)');
184
- out(' ✅ Agent directives and harness symlinks established (AGENTS.md, CLAUDE.md, agents.md)');
187
+ out(' ✅ Agent directives and harness symlinks established (AGENTS.md, CLAUDE.md, agents.md, GEMINI.md, .cursorrules, .windsurfrules, .github/copilot-instructions.md)');
188
+ out(' ✅ Project configuration initialized (package.json)');
185
189
  if (result.gitInitialized) {
186
190
  out(' ✅ Git repository initialized');
187
191
  }
188
192
 
189
193
  out('\n🎉 azcodr initialized successfully!\n');
190
194
  out('Next steps:');
195
+ let step = 1;
191
196
  if (targetDir !== '.' && targetDir !== './') {
192
- out(` 1. cd ${targetDir}`);
197
+ out(` ${step++}. cd ${targetDir}`);
193
198
  }
194
- out(' 2. Open the project in your AI coding assistant (Antigravity, Claude Code, Cursor, OpenHands)');
195
- out(' 3. Run /lets-build to start the architectural interview and scaffold your application stack!\n');
199
+ out(` ${step++}. Open the project in your AI coding assistant (Antigravity, Claude Code, Cursor, OpenHands)`);
200
+ out(` ${step++}. Run /lets-build to start the architectural interview and scaffold your application stack!\n`);
196
201
  }
197
202
  return exit(0);
198
203
  } catch (error) {
@@ -1,6 +1,6 @@
1
- # Agentic Configuration, Skills & Harness Standards
1
+ # Agentic Configuration, Governance & Harness Standards
2
2
 
3
- > **Core Mandate:** Maintain lean agent entrypoints via progressive disclosure, modular documentation, strict skill front matter standards, harness symlink parity, and relentless questioning during skill architecture.
3
+ > **Core Mandate:** Enforce progressive disclosure across agent entrypoints, strict skill front matter standards, workspace sovereignty, continuous learning via the direct rule ingestion loop, and immutable Architectural Decision Records (ADRs).
4
4
 
5
5
  ---
6
6
 
@@ -37,14 +37,28 @@ Different AI agents and IDE harnesses look for different configuration filenames
37
37
  - Standard: `AGENTS.md`
38
38
  - Lowercase: `agents.md`
39
39
  - Anthropic Claude Code: `CLAUDE.md`
40
+ - Google Antigravity & Gemini CLI: `GEMINI.md`
41
+ - Cursor: `.cursorrules`
42
+ - Windsurf: `.windsurfrules`
43
+ - GitHub Copilot: `.github/copilot-instructions.md`
40
44
 
41
45
  **Standard:** Maintain identical configuration across all harnesses by establishing filesystem symbolic links:
42
46
  ```bash
43
47
  ln -sf AGENTS.md agents.md
44
48
  ln -sf AGENTS.md CLAUDE.md
49
+ ln -sf AGENTS.md GEMINI.md
50
+ ln -sf AGENTS.md .cursorrules
51
+ ln -sf AGENTS.md .windsurfrules
52
+ mkdir -p .github && ln -sf ../AGENTS.md .github/copilot-instructions.md
45
53
  ```
46
54
  Never duplicate content into separate files.
47
55
 
56
+ ### Context Budget & Token Economy Directives
57
+ To prevent LLM context exhaustion, attention dilution, and model degradation:
58
+ - **Per-File Rule Size Cap (24 KB / 24,000 bytes):** Every rule file in `docs/rules/` must strictly stay under 24,000 bytes. Files exceeding this ceiling risk truncation across agent runtimes.
59
+ - **Aggregate Rules Token Budget (20,000 tokens):** Continuous and directory-scoped rules share an aggregate budget. Over-budget rules are demoted to file-pointer references. Always use concise, actionable directives rather than prose tutorials.
60
+ - **Progressive Offloading:** Offload deep specifications, schemas, or large lookup matrices to dedicated reference files loaded on demand.
61
+
48
62
  ---
49
63
 
50
64
  ## 4. Skills Architecture (`.agents/skills/<skill-name>/`)
@@ -71,9 +85,34 @@ description: <Imperative trigger description under 1024 characters. MUST start w
71
85
  - Include structured response templates and self-validation checklists for deterministic output.
72
86
 
73
87
  ### Progressive Disclosure Subdirectories
74
- - `references/`: Detailed sub-domain markdown files loaded on demand by the skill.
88
+ Adhere strictly to the standard agent skills folder taxonomy:
75
89
  - `scripts/`: Deterministic executable scripts (bash, node, python) for tasks where LLMs produce non-deterministic drift.
76
- - `assets/`: Static data, lookup tables, schemas, or boilerplate templates.
90
+ - `references/`: Detailed sub-domain markdown manuals loaded on demand by the skill.
91
+ - `resources/`: Static templates, lookup tables, JSON schemas, or mock artifacts.
92
+ - `examples/`: Reference implementations and concrete code patterns.
93
+
94
+ ### Deterministic Lifecycle Hooks (`.agents/hooks.json`)
95
+ To enforce non-negotiable safety guardrails and automated verification without stochastic agent failure:
96
+ - **`PreToolUse`**: Intercept destructive or dangerous CLI commands (`rm -rf`, DROP DATABASE, git push --force) and force explicit confirmation (`decision: ask`).
97
+ - **`PostToolUse`**: Automatically trigger fast linters (`npm run lint`), formatters, or unit test verification after tool runs.
98
+ - **`Stop`**: Intercept premature agent termination when background tasks are running or tests remain failing (`decision: continue`).
99
+
100
+ ### Model Context Protocol (MCP) Integration (`.agents/mcp_config.json`)
101
+ When external tool capabilities are required (database introspectors, cloud telemetry, documentation search):
102
+ - Standardize on vendor-neutral **Model Context Protocol (MCP)** specifications.
103
+ - Declare local or containerized MCP tool servers in `.agents/mcp_config.json`.
104
+ - Treat MCP tools as secondary adapter driving ports, keeping domain logic decoupled from proprietary platform APIs.
105
+
106
+ ### Explicit Prohibition: The "Library-as-a-Skill" Anti-Pattern
107
+ Never author or dynamically generate skills for commodity open-source packages or libraries (e.g. `react`, `tanstack`, `shadcn`, `zustand`, `testing-library`, `vitest`):
108
+ - **Prompt Bloat & Re-Explanation Tax:** Skill descriptions are continuously loaded into the agent's `<skills>` context. Proliferating skills for every library in a stack floods the prompt with thousands of redundant tokens and degrades model reasoning.
109
+ - **Parametric Redundancy:** Frontier LLMs already possess extensive parametric knowledge of open-source library APIs. Re-explaining basic imports and function signatures in a skill wastes context and creates documentation rot.
110
+ - **Trigger Collision & Agent Paralysis:** When a prompt touches UI, form validation, and data fetching, having 5 library skills triggers semantic collision, causing the agent to waste execution turns resolving which sub-skill to run.
111
+ - **The 4-Layer Resolution Standard:** Always resolve library stack knowledge through the **4-Layer Resolution Model**:
112
+ 1. *Layer 1 (Manifest Ground Truth):* Read `package.json`, `components.json`, or `tsconfig.json`.
113
+ 2. *Layer 2 (Stack Contract in `AGENTS.md`):* 3–5 line declaration in project entrypoint stamped by `/lets-build`.
114
+ 3. *Layer 3 (Universal Domain Rules):* Enforce architectural invariants (`frontend_architecture.md`, `test_driven_development.md`) rather than library syntax.
115
+ 4. *Layer 4 (Tool & CLI Execution):* Direct execution of official CLIs (`npx shadcn@latest add ...`) or local component inspection.
77
116
 
78
117
  ---
79
118
 
@@ -111,38 +150,40 @@ Coding tasks and agentic skills exhibit an explicit **Many-to-Many ($M:N$) Relat
111
150
  - **Zero Cross-Contamination:** No skill may write code or modify files outside its declared functional boundary.
112
151
  - **Pure Function Semantics:** Analysis skills must remain read-only and side-effect free.
113
152
 
153
+ ## 6. The Mandatory YAGNI Gate Triad (Rules & Skills)
154
+
155
+ LLM coding agents have a natural statistical bias toward **Instruction Creep** and **Eager Pattern Application**: when provided with a rule explaining an advanced pattern, agents reflexively apply it everywhere, causing severe architectural bloat.
156
+
157
+ To prevent premature abstraction, every architectural pattern rule and skill must enforce the **YAGNI Gate Triad**:
158
+
159
+ 1. **The Simple Baseline (Day 1 Default):**
160
+ - The zero-overhead, default implementation that solves the immediate requirement without indirection (e.g. single database model before CQRS, relational indexes before Redis, standard React components before Server-Driven UI).
161
+ 2. **The Anti-Triggers (Strictly Forbidden Scenarios):**
162
+ - Explicit, negative conditions where applying the pattern or skill is forbidden as premature over-engineering (e.g. no caching for low-throughput queries, no state machines for 2-state boolean flags, no skills for routine typo fixes).
163
+ 3. **The Empirical Tipping Point (Graduation Threshold):**
164
+ - Measurable, verified criteria that MUST be breached before graduating to the pattern (e.g. p99 latency > 200ms after indexing, 3+ non-linear lifecycle states with transition guards, untrusted third-party user scripts).
165
+
166
+ ### Foundational Leverage vs. Speculative Over-Engineering
167
+ A common misunderstanding is that YAGNI forbids using external libraries. **This is completely false**:
168
+ - **YAGNI Attacks:** Speculative custom code, home-grown frameworks, custom wheel reinvention, and premature multi-tier distributed architectures.
169
+ - **YAGNI Mandates:** Adopting battle-tested, open-source building blocks (`shadcn/ui`, `Tailwind CSS`, `Zod`, `TanStack Query`, `Lombok`) to solve concrete, present requirements with the minimum amount of custom code (preventing Not-Invented-Here / NIH syndrome).
170
+
114
171
  ---
115
172
 
116
- ## 6. The Relentless Skill Architecture Inquiry
173
+ ## 7. The Relentless Skill Architecture Inquiry
117
174
 
118
175
  Never architect or modify a skill based on assumptions. Before authoring any `SKILL.md`, run the **7 Core Skill Inquiry Branches**:
119
176
 
120
- ```
121
- [New Skill / Rule Request]
122
- │
123
- ▼
124
- [Branch 1: Placement] ────────── Should this be AGENTS.md, a Rule, or a Skill?
125
- │
126
- ▼
127
- [Branch 2: Trigger Boundaries] ── Exact 'Use when...' and explicit 'Do NOT use for...'?
128
- │
129
- ▼
130
- [Branch 3: Domain Ground Truth] ─ Have generic textbook tutorials been purged?
131
- │
132
- ▼
133
- [Branch 4: Gotchas & Anti-Patterns] What specific AI mistakes MUST be forbidden?
134
- │
135
- ▼
136
- [Branch 5: Determinism vs LLM] ── Should deterministic steps be scripts in scripts/?
137
- │
138
- ▼
139
- [Branch 6: Progressive Bloat] ─── Is SKILL.md < 500 lines with sub-docs in references/?
140
- │
141
- ▼
142
- [Branch 7: Verification Loop] ─── Are there output templates and self-checklists?
143
- │
144
- ▼
145
- [Ready to Author / Update Skill]
177
+ ```mermaid
178
+ flowchart TD
179
+ Req["New Skill / Rule Request"] --> B1["Branch 1: Placement<br/>AGENTS.md, Rule, or Skill?"]
180
+ B1 --> B2["Branch 2: Trigger Boundaries<br/>Exact 'Use when...' & 'Do NOT use for...'?"]
181
+ B2 --> B3["Branch 3: Domain Ground Truth<br/>Generic textbook tutorials purged?"]
182
+ B3 --> B4["Branch 4: Gotchas & Anti-Patterns<br/>What AI mistakes MUST be forbidden?"]
183
+ B4 --> B5["Branch 5: Determinism vs LLM<br/>Deterministic steps scripted in scripts/?"]
184
+ B5 --> B6["Branch 6: Progressive Bloat<br/>SKILL.md < 500 lines with sub-docs in references/?"]
185
+ B6 --> B7["Branch 7: Verification Loop<br/>Output templates & self-checklists present?"]
186
+ B7 --> Ready["Ready to Author / Update Skill"]
146
187
  ```
147
188
 
148
189
  ### The 7 Core Inquiry Branches
@@ -159,10 +200,60 @@ Never architect or modify a skill based on assumptions. Before authoring any `SK
159
200
 
160
201
  ---
161
202
 
162
- ## 7. The Continuous Refinement Loop
203
+ ## 8. The Continuous Refinement Loop
163
204
 
164
205
  When an AI produces suboptimal code or documentation:
165
206
  1. Preserve the original AI output draft.
166
207
  2. Make manual corrections to produce the desired gold-standard output.
167
208
  3. Diff the original draft against the corrected version to identify specific gaps.
168
209
  4. Update the relevant skill's "What NOT to do" or guideline section to prevent repeating that mistake.
210
+
211
+ ---
212
+
213
+ ## 9. Workspace Sovereignty & Zero Global Interference
214
+
215
+ Enforce strict workspace containment within the workspace root (`./`):
216
+ - **Ground Truth Boundary**: Only files, dependencies, configuration files (`package.json`, `tsconfig.json`, `docker-compose.yml`), and verified command executions within the local workspace (`./`) constitute project truth.
217
+ - **Zero Global Contamination**: Never import, execute, or assume tools, environment variables, or conventions from global system directories (e.g. `~/.config`, `/tmp`, `~/.gemini/antigravity-cli`, or parent directories) unless explicitly defined within local workspace configuration.
218
+ - **Sibling Project Isolation**: Strictly ignore external or legacy projects. Do not read from or write to directories outside the local repository (`./`).
219
+ - **Subagent Context Sandboxing**: When spawning subagents or executing commands, ensure working directories are anchored strictly to `./`.
220
+
221
+ ---
222
+
223
+ ## 10. Continuous Learning & The Direct Rule Ingestion Loop
224
+
225
+ Whenever an error, test failure, build friction, or architectural anti-pattern occurs during development, immediately execute the 4-step loop:
226
+
227
+ ```
228
+ 1. Capture Defect ──► 2. Root Cause Analysis ──► 3. Synthesize Invariant ──► 4. Update Rule / Skill
229
+ ```
230
+
231
+ 1. **Capture Defect**: Record the failure symptoms, stack trace, and failing test case.
232
+ 2. **Root Cause Analysis**: Identify the fundamental architectural or operational gap (not just the surface symptom).
233
+ 3. **Synthesize Invariant**: Formulate a concrete, positive architectural invariant and code example showing the correct implementation.
234
+ 4. **Update Rule / Skill**:
235
+ - Update the governing domain rule in `docs/rules/<domain>.md` or specialized skill in `.agents/skills/` directly.
236
+ - If the lesson introduces an architectural trade-off or paradigm shift, record a lightweight ADR in [`memory.md`](../../memory.md).
237
+ - Run verification (`npm test && npm run validate`) to ensure 100% integrity.
238
+
239
+ ---
240
+
241
+ ## 11. Architectural Decision Records (ADR) Standards
242
+
243
+ Significant architectural, technical stack, or invariant decisions must be captured in [`memory.md`](../../memory.md):
244
+
245
+ ### Required ADR Envelope:
246
+ ```markdown
247
+ #### ADR-XXX: <Imperative Action-Oriented Title>
248
+ - **Date:** YYYY-MM-DD | **Status:** PROPOSED | ACCEPTED | SUPERSEDED | DEPRECATED
249
+ - **Context:** The specific operational or technical problem, constraint, or trade-off requiring a decision.
250
+ - **Decision:** Concrete, unambiguous architecture choice and positive invariants.
251
+ - **Consequences:** Direct benefits and deliberate operational trade-offs accepted.
252
+ - **Enforced In:** Links to specific rule files in `docs/rules/` or code paths.
253
+ ```
254
+
255
+ ### Numbering & Immutability:
256
+ - ADR numbers are monotonically increasing (`ADR-001`, `ADR-002`, ...).
257
+ - ADR entries are **immutable history**. Never edit past accepted ADRs to represent new decisions; author a new ADR that explicitly supersedes the former.
258
+ - **Fresh Project Baseline (ADR Clean Slate):** When starting or bootstrapping a new project from this starter template, the memory ledger in [`memory.md`](../../memory.md) must be a clean slate with zero prior decisions recorded. The initial technical foundation derived during `/lets-build` must always be recorded as **`ADR-001`**. Template development history from `azcodr` must never bleed into downstream project memory ledgers.
259
+
@@ -0,0 +1,179 @@
1
+ # API Architecture, Protocols & Communication Standards
2
+
3
+ > **Core Mandate:** Enforce standard HTTP semantics, synchronous vs. asynchronous processing (`202 Accepted`), capability metadata (`_actions`), safe mutations via idempotency keys, keyset cursor pagination, optimistic concurrency control (OCC), and RFC 8594 lifecycle versioning.
4
+
5
+ ---
6
+
7
+ ## 1. Standard HTTP Semantics & Status Codes
8
+
9
+ APIs must adhere strictly to standard HTTP semantics. Never return `200 OK` for error envelopes:
10
+
11
+ | Status Code | Semantic Purpose | When to Return |
12
+ |---|---|---|
13
+ | **`200 OK`** | Successful read or synchronous update | Standard `GET`, `PATCH`, `PUT` queries that return payloads. |
14
+ | **`201 Created`** | Successful resource creation | Synchronous `POST` with `Location: /api/v1/resources/:id` header. |
15
+ | **`202 Accepted`** | Asynchronous task accepted | Tasks exceeding latency budgets (> 1.5s) delegated to background queues. |
16
+ | **`204 No Content`** | Successful action with zero payload | Standard `DELETE` or empty mutation responses. |
17
+ | **`400 Bad Request`** | Malformed syntax or protocol violation | Unparseable JSON, invalid query parameters. |
18
+ | **`401 Unauthorized`** | Missing or invalid authentication | Missing, expired, or tampered JWT / API token. |
19
+ | **`403 Forbidden`** | Authenticated but insufficient permission | Role, tenant boundary, or policy guard denial. |
20
+ | **`404 Not Found`** | Resource does not exist | Unknown entity identifier (or masked tenant resource). |
21
+ | **`409 Conflict`** | State conflict or race condition | Concurrency mismatch (`If-Match`), unique constraint, or in-flight idempotency. |
22
+ | **`422 Unprocessable`** | Semantic validation failure | Schema constraint violation (RFC 7807 problem details). |
23
+ | **`500 Internal Error`** | Unhandled server exception | Unexpected server failure; never leak internal stack traces. |
24
+
25
+ ### Subresource URL Conventions
26
+ - Express relational hierarchy cleanly: `/api/v1/organizations/:orgId/projects/:projectId/members`.
27
+ - Limit URL nesting to a maximum of 2 subresource levels; for deeper resources, access directly via canonical ID (`/api/v1/tasks/:taskId`).
28
+
29
+ ### Enumeration Masking
30
+ - Authentication and recovery endpoints must never reveal user existence (e.g. return `"If an account exists, a recovery link has been sent"` with identical timing).
31
+
32
+ ---
33
+
34
+ ## 2. Synchronous vs. Asynchronous Processing (`202 Accepted`)
35
+
36
+ Operations with unpredictable or long execution durations (> 1.5 seconds, such as video rendering, large PDF exports, batch imports, or complex report generation) must never block synchronous HTTP request threads:
37
+
38
+ ```mermaid
39
+ sequenceDiagram
40
+ autonumber
41
+ actor Client
42
+ participant Gateway as API Gateway
43
+ participant Queue as Task Queue / Worker
44
+
45
+ Client->>Gateway: POST /reports/export (Long-running > 1.5s)
46
+ Gateway->>Queue: Dispatch background job
47
+ Gateway-->>Client: 202 Accepted (Location: /api/v1/tasks/tsk_123)
48
+ Note over Client,Gateway: Client polls GET /api/v1/tasks/tsk_123 until complete
49
+ ```
50
+
51
+ ### Protocol Standards:
52
+ 1. Dispatch the payload to a persistent worker queue (e.g., BullMQ, Temporal, Celery).
53
+ 2. Respond immediately with **`202 Accepted`** containing:
54
+ - Header: `Location: /api/v1/tasks/:taskId`
55
+ - Envelope:
56
+ ```json
57
+ {
58
+ "taskId": "tsk_123",
59
+ "status": "QUEUED",
60
+ "pollIntervalMs": 2000,
61
+ "_links": {
62
+ "status": { "href": "/api/v1/tasks/tsk_123", "method": "GET" },
63
+ "cancel": { "href": "/api/v1/tasks/tsk_123", "method": "DELETE" }
64
+ }
65
+ }
66
+ ```
67
+ 3. Polling endpoint (`GET /api/v1/tasks/:taskId`) returns:
68
+ - In-progress: `200 OK` with status `PROCESSING` and progress percentage.
69
+ - Finished: `303 See Other` with `Location: /api/v1/reports/rep_789` or `200 OK` with `status: "COMPLETED"` and the final artifact URI.
70
+
71
+ ---
72
+
73
+ ## 3. Allowed Actions & Capability Metadata (`_actions` Envelope)
74
+
75
+ Clients must not duplicate complex server-side business and authorization rules to decide whether UI actions (edit, delete, approve, cancel, refund) are permitted. **The server is the authoritative source of truth.**
76
+
77
+ ### Pattern: `_actions` and `_links` Envelope
78
+ Every resource response must embed an `_actions` boolean map and optional `_links` hypermedia block indicating what the requesting caller is permitted to do based on their role, tenant boundaries, and the entity's current lifecycle state:
79
+
80
+ ```json
81
+ {
82
+ "id": "ord_9876",
83
+ "status": "SHIPPED",
84
+ "totalAmount": 149.99,
85
+ "currency": "USD",
86
+ "_actions": {
87
+ "canEdit": false,
88
+ "canCancel": false,
89
+ "canTrack": true,
90
+ "canRequestRefund": true
91
+ },
92
+ "_links": {
93
+ "self": { "href": "/api/v1/orders/ord_9876", "method": "GET" },
94
+ "track": { "href": "/api/v1/orders/ord_9876/tracking", "method": "GET" },
95
+ "refund": { "href": "/api/v1/orders/ord_9876/refunds", "method": "POST" }
96
+ }
97
+ }
98
+ ```
99
+
100
+ ### Frontend Binding:
101
+ - UI action buttons directly bind visibility or disabled state to `resource._actions.canCancel`.
102
+ - When business logic evolves (e.g. orders over $1,000 require manager approval), only backend policy changes—zero frontend redeployment required.
103
+
104
+ ---
105
+
106
+ ## 4. Safe Mutations via Idempotency Keys (IETF Draft)
107
+
108
+ To prevent duplicate execution (double charging, duplicate orders) caused by network retries or transient connection drops:
109
+
110
+ ### Protocol Standards:
111
+ - Clients generating mutating requests (`POST`, `PATCH`) must supply a unique `Idempotency-Key: <uuid-v4>` header.
112
+ - **Server Execution Lifecycle**:
113
+ 1. Check distributed idempotency cache for key `idemp:<tenantId>:<idempotencyKey>`.
114
+ 2. If found with status `IN_FLIGHT`: return **`409 Conflict`** (`IDEMPOTENT_OPERATION_IN_PROGRESS`).
115
+ 3. If found with status `COMPLETED`: return the cached HTTP status code, headers, and response payload without re-executing.
116
+ 4. If not found: Acquire distributed lock, execute mutation within an atomic database transaction, cache the response envelope with a 24-hour TTL, and release the lock.
117
+
118
+ ---
119
+
120
+ ## 5. High-Scale Keyset / Cursor-Based Pagination
121
+
122
+ Never use offset pagination (`OFFSET 10000 LIMIT 20`) on large tables. Offsets degrade linearly ($O(N)$) and suffer from page-drift anomalies as rows are inserted or deleted.
123
+
124
+ ### Specification & Envelope:
125
+ - Query Parameters: `?cursor=<opaque_base64>&limit=20` (default limit 20, max 100).
126
+ - Response Envelope:
127
+ ```json
128
+ {
129
+ "data": [...],
130
+ "pagination": {
131
+ "nextCursor": "ZXlKaWRI...==",
132
+ "hasMore": true,
133
+ "limit": 20
134
+ }
135
+ }
136
+ ```
137
+ - **Agnostic Keyset Query Pattern**:
138
+ ```sql
139
+ SELECT * FROM orders
140
+ WHERE tenant_id = :tenantId
141
+ AND (created_at, id) < (:cursorCreatedAt, :cursorId)
142
+ ORDER BY created_at DESC, id DESC
143
+ LIMIT :limit + 1;
144
+ ```
145
+ If `results.length > limit`, slice the extra item and encode its composite values (`created_at`, `id`) into the base64 `nextCursor`.
146
+
147
+ ---
148
+
149
+ ## 6. Optimistic Concurrency Control (OCC)
150
+
151
+ Prevent lost-update anomalies during concurrent edits without pessimistic database row locking:
152
+
153
+ ### Protocol Standards:
154
+ - Every mutable entity contains an incrementing integer `version` column.
155
+ - The server returns the current entity version in the `ETag` response header: `ETag: W/"v4"`.
156
+ - Clients submitting updates (`PUT`, `PATCH`) must include `If-Match: W/"v4"`.
157
+ - **Atomic Concurrency Handling**:
158
+ ```sql
159
+ UPDATE orders
160
+ SET status = :status, version = version + 1
161
+ WHERE id = :id AND version = :expectedVersion;
162
+ ```
163
+ - If `rows_affected == 0`: Return **`409 Conflict`** with error code `CONCURRENCY_CONFLICT` and the latest entity representation.
164
+
165
+ ---
166
+
167
+ ## 7. API Versioning & RFC 8594 Lifecycle Deprecation
168
+
169
+ ### URI Versioning Standard
170
+ - Standardize on explicit path versioning: `/v1/`, `/v2/`.
171
+ - Never introduce breaking changes within an active major version:
172
+ - *Non-Breaking (Permitted in `/v1/`):* Adding optional fields, adding new endpoints, adding new enum variants.
173
+ - *Breaking (Demands `/v2/`):* Renaming/removing fields, changing validation constraints, altering status codes.
174
+
175
+ ### RFC 8594 Sunset & Deprecation Headers
176
+ When deprecating an endpoint, provide clients with a minimum 90-day grace period:
177
+ - `Deprecation: @<unix-timestamp>`: Date when the endpoint was deprecated.
178
+ - `Sunset: <HTTP-date>`: Absolute date when the endpoint will return `410 Gone`.
179
+ - `Link: </api/v2/docs>; rel="sunset"`: Link to migration documentation.
@@ -4,20 +4,37 @@
4
4
 
5
5
  ---
6
6
 
7
- ## 1. Abstract Cache Port & Cache-Aside Pattern
7
+ ## 1. The YAGNI Gate: Database First, Caching Second
8
8
 
9
- Application services interact with caching infrastructure through a swappable **Cache Port**, supporting any backend (Redis, Valkey, Dragonfly, KeyDB, Memcached, or in-memory LRU):
9
+ Caching introduces state duplication, cache invalidation race conditions, and memory overhead. **Caching is never a substitute for missing database indexes or poorly structured SQL queries.**
10
10
 
11
+ ```mermaid
12
+ flowchart TD
13
+ subgraph CachingGate["Caching YAGNI Gate"]
14
+ B1["1. Simple Baseline (Day 1)<br/>• Relational queries with composite indexes<br/>• Request-scoped in-memory DataLoader batching to eliminate N+1<br/>• Zero distributed cache infrastructure (no Redis / Memcached)"]
15
+ B2["2. Anti-Triggers (Forbidden)<br/>• Queries that are slow due to missing indexes or sequential scans<br/>• High-write / high-churn entities (write-heavy mutation streams)<br/>• Low-traffic administrative or internal operational queries"]
16
+ B3["3. The Tipping Point (Graduation)<br/>• Query has been optimized with EXPLAIN ANALYZE, but p99 latency still exceeds SLA (> 100ms)<br/>• Read-to-write asymmetry on the entity exceeds 20:1<br/>• Downstream external API rate limits or third-party egress costs demand response caching"]
17
+ B1 -->|Forbidden if missing indexes| B2
18
+ B1 -->|Triggered by high read/write ratio| B3
19
+ end
11
20
  ```
12
- ┌────────────────────────────────────────────────────────┐
13
- │ Cache Port Interface (Agnostic Contract) │
14
- ├────────────────────────────────────────────────────────┤
15
- │ get(key): Optional<String> │
16
- │ set(key, value, ttlSeconds): void │
17
- │ delete(key): void │
18
- │ deletePattern(pattern): void │
19
- │ acquireLock(lockKey, ttlMs): boolean │
20
- └────────────────────────────────────────────────────────┘
21
+
22
+ ---
23
+
24
+ ## 2. Abstract Cache Port & Cache-Aside Pattern
25
+
26
+ Application services interact with caching infrastructure through a swappable **Cache Port**, supporting any backend (Redis, Valkey, Dragonfly, KeyDB, Memcached, or in-memory LRU):
27
+
28
+ ```mermaid
29
+ classDiagram
30
+ class CachePort {
31
+ <<interface>>
32
+ +get(key: string) Optional~string~
33
+ +set(key: string, value: string, ttlSeconds: number) void
34
+ +delete(key: string) void
35
+ +deletePattern(pattern: string) void
36
+ +acquireLock(lockKey: string, ttlMs: number) boolean
37
+ }
21
38
  ```
22
39
 
23
40
  ### Cache-Aside Implementation & Stampede Defense
@@ -38,7 +55,7 @@ For high-throughput cache regeneration, employ the **XFetch algorithm** (probabi
38
55
 
39
56
  ---
40
57
 
41
- ## 2. Key Namespacing & Event-Driven Invalidation
58
+ ## 3. Key Namespacing & Event-Driven Invalidation
42
59
 
43
60
  - **Universal Key Hierarchy**: Structure all keys hierarchically:
44
61
  `tenant:{tenantId}:{entity}:{entityId}` (e.g. `tenant:123:order:987`)
@@ -46,7 +63,7 @@ For high-throughput cache regeneration, employ the **XFetch algorithm** (probabi
46
63
 
47
64
  ---
48
65
 
49
- ## 3. HTTP Conditional Caching (ETags)
66
+ ## 4. HTTP Conditional Caching (ETags)
50
67
 
51
68
  - Generate strong cryptographic `ETag` hashes (e.g. SHA-256 of representation or resource version) for cacheable `GET` endpoints.
52
69
  - Return **`304 Not Modified`** with zero payload body when inbound requests present matching `If-None-Match` headers, preserving bandwidth and client CPU.
@@ -28,16 +28,14 @@ All application processes and containers must handle graceful termination:
28
28
  - Drain active, in-flight connections within a bounded timeout window (e.g. 10 seconds).
29
29
  - Gracefully flush telemetry buffers, terminate background workers, and close database/cache connection pools cleanly before exiting with code 0:
30
30
 
31
- ```
32
- ┌────────────────────────────────────────────────────────┐
33
- │ Graceful Shutdown Flow (Universal / Agnostic) │
34
- ├────────────────────────────────────────────────────────┤
35
- │ onSignal(SIGTERM | SIGINT): │
36
- │ 1. Set health check probe to UNHEALTHY (drain LB) │
37
- │ 2. Stop server listening for new connections │
38
- │ 3. Wait for in-flight requests (timeout: 10s) │
39
- │ 4. Close database and cache connection pools │
40
- │ 5. Flush OpenTelemetry trace & log buffers │
41
- │ 6. Terminate process with exit code 0 │
42
- └────────────────────────────────────────────────────────┘
31
+ ```mermaid
32
+ flowchart TD
33
+ subgraph GracefulShutdown["Graceful Shutdown Flow (Universal / Agnostic)"]
34
+ Sig["onSignal (SIGTERM | SIGINT)"] --> S1["1. Set health check probe to UNHEALTHY (drain LB)"]
35
+ S1 --> S2["2. Stop server listening for new connections"]
36
+ S2 --> S3["3. Wait for in-flight requests (timeout: 10s)"]
37
+ S3 --> S4["4. Close database and cache connection pools"]
38
+ S4 --> S5["5. Flush OpenTelemetry trace & log buffers"]
39
+ S5 --> S6["6. Terminate process with exit code 0"]
40
+ end
43
41
  ```