azcodr 1.2.2 → 1.4.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 (69) hide show
  1. package/.agents/hooks.json.example +42 -0
  2. package/.agents/mcp_config.json.example +24 -0
  3. package/.agents/skills/agentic-architect/SKILL.md +14 -7
  4. package/.agents/skills/agentic-architect/references/agents_md_template.md +6 -3
  5. package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +1 -1
  6. package/.agents/skills/agentic-architect/references/skill_template.md +2 -1
  7. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +156 -4
  8. package/.agents/skills/clean-code-refactor/SKILL.md +6 -6
  9. package/.agents/skills/compliance-audit/SKILL.md +1 -1
  10. package/.agents/skills/lets-build/SKILL.md +12 -4
  11. package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +1 -1
  12. package/.agents/skills/lets-build/references/project_readme_template.md +4 -4
  13. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +63 -35
  14. package/.agents/skills/relentless-questioner/SKILL.md +10 -5
  15. package/AGENTS.md +25 -41
  16. package/README.md +27 -43
  17. package/bin/azcodr.js +3 -82
  18. package/docs/knowledge/ubiquitous_language.md +1 -6
  19. package/docs/rules/agentic_configuration.md +120 -32
  20. package/docs/rules/api_architecture.md +179 -0
  21. package/docs/rules/caching.md +30 -13
  22. package/docs/rules/cloud_native.md +10 -12
  23. package/docs/rules/cqrs.md +203 -0
  24. package/docs/rules/database_design.md +125 -0
  25. package/docs/rules/database_operations.md +56 -14
  26. package/docs/rules/design_patterns.md +18 -11
  27. package/docs/rules/devops_ci_cd.md +76 -0
  28. package/docs/rules/domain_driven_design.md +17 -13
  29. package/docs/rules/feature_flags.md +21 -4
  30. package/docs/rules/frontend_architecture.md +157 -0
  31. package/docs/rules/multitenancy_architecture.md +98 -0
  32. package/docs/rules/product_ownership.md +22 -27
  33. package/docs/rules/requirements_engineering.md +16 -14
  34. package/docs/rules/security_compliance.md +53 -0
  35. package/docs/rules/server_driven_ui.md +20 -3
  36. package/docs/rules/test_driven_development.md +118 -62
  37. package/docs/rules/type_safety.md +65 -0
  38. package/docs/rules/ui_ux_architecture.md +33 -30
  39. package/docs/rules/workflow_state_machines.md +20 -3
  40. package/lib/index.d.ts +0 -30
  41. package/lib/scaffold.js +9 -46
  42. package/memory.md +158 -14
  43. package/package.json +2 -3
  44. package/changes.md +0 -79
  45. package/docs/rules/accessibility.md +0 -31
  46. package/docs/rules/advanced_api_patterns.md +0 -104
  47. package/docs/rules/api_versioning.md +0 -113
  48. package/docs/rules/application_security.md +0 -23
  49. package/docs/rules/architecture_decision_records.md +0 -42
  50. package/docs/rules/compliance.md +0 -25
  51. package/docs/rules/container_infrastructure.md +0 -32
  52. package/docs/rules/continuous_deployment.md +0 -24
  53. package/docs/rules/continuous_integration.md +0 -20
  54. package/docs/rules/continuous_learning.md +0 -29
  55. package/docs/rules/database_integrity.md +0 -80
  56. package/docs/rules/database_migrations.md +0 -41
  57. package/docs/rules/database_performance.md +0 -44
  58. package/docs/rules/database_transactions.md +0 -81
  59. package/docs/rules/devsecops.md +0 -33
  60. package/docs/rules/multitenancy_isolation.md +0 -88
  61. package/docs/rules/react.md +0 -78
  62. package/docs/rules/rest_api_conventions.md +0 -46
  63. package/docs/rules/tenant_dynamic_schemas.md +0 -88
  64. package/docs/rules/tenant_pluggable_logic.md +0 -59
  65. package/docs/rules/test_isolation.md +0 -26
  66. package/docs/rules/typescript.md +0 -55
  67. package/docs/rules/ui_navigation.md +0 -20
  68. package/docs/rules/upstream_synchronization.md +0 -53
  69. package/docs/rules/workspace_isolation.md +0 -25
@@ -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,26 @@ 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`
40
43
 
41
44
  **Standard:** Maintain identical configuration across all harnesses by establishing filesystem symbolic links:
42
45
  ```bash
43
46
  ln -sf AGENTS.md agents.md
44
47
  ln -sf AGENTS.md CLAUDE.md
48
+ ln -sf AGENTS.md GEMINI.md
49
+ ln -sf AGENTS.md .cursorrules
50
+ ln -sf AGENTS.md .windsurfrules
45
51
  ```
46
52
  Never duplicate content into separate files.
47
53
 
54
+ ### Context Budget & Token Economy Directives
55
+ To prevent LLM context exhaustion, attention dilution, and model degradation:
56
+ - **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.
57
+ - **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.
58
+ - **Progressive Offloading:** Offload deep specifications, schemas, or large lookup matrices to dedicated reference files loaded on demand.
59
+
48
60
  ---
49
61
 
50
62
  ## 4. Skills Architecture (`.agents/skills/<skill-name>/`)
@@ -71,9 +83,34 @@ description: <Imperative trigger description under 1024 characters. MUST start w
71
83
  - Include structured response templates and self-validation checklists for deterministic output.
72
84
 
73
85
  ### Progressive Disclosure Subdirectories
74
- - `references/`: Detailed sub-domain markdown files loaded on demand by the skill.
86
+ Adhere strictly to the standard agent skills folder taxonomy:
75
87
  - `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.
88
+ - `references/`: Detailed sub-domain markdown manuals loaded on demand by the skill.
89
+ - `resources/`: Static templates, lookup tables, JSON schemas, or mock artifacts.
90
+ - `examples/`: Reference implementations and concrete code patterns.
91
+
92
+ ### Deterministic Lifecycle Hooks (`.agents/hooks.json`)
93
+ To enforce non-negotiable safety guardrails and automated verification without stochastic agent failure:
94
+ - **`PreToolUse`**: Intercept destructive or dangerous CLI commands (`rm -rf`, DROP DATABASE, git push --force) and force explicit confirmation (`decision: ask`).
95
+ - **`PostToolUse`**: Automatically trigger fast linters (`npm run lint`), formatters, or unit test verification after tool runs.
96
+ - **`Stop`**: Intercept premature agent termination when background tasks are running or tests remain failing (`decision: continue`).
97
+
98
+ ### Model Context Protocol (MCP) Integration (`.agents/mcp_config.json`)
99
+ When external tool capabilities are required (database introspectors, cloud telemetry, documentation search):
100
+ - Standardize on vendor-neutral **Model Context Protocol (MCP)** specifications.
101
+ - Declare local or containerized MCP tool servers in `.agents/mcp_config.json`.
102
+ - Treat MCP tools as secondary adapter driving ports, keeping domain logic decoupled from proprietary platform APIs.
103
+
104
+ ### Explicit Prohibition: The "Library-as-a-Skill" Anti-Pattern
105
+ Never author or dynamically generate skills for commodity open-source packages or libraries (e.g. `react`, `tanstack`, `shadcn`, `zustand`, `testing-library`, `vitest`):
106
+ - **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.
107
+ - **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.
108
+ - **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.
109
+ - **The 4-Layer Resolution Standard:** Always resolve library stack knowledge through the **4-Layer Resolution Model**:
110
+ 1. *Layer 1 (Manifest Ground Truth):* Read `package.json`, `components.json`, or `tsconfig.json`.
111
+ 2. *Layer 2 (Stack Contract in `AGENTS.md`):* 3–5 line declaration in project entrypoint stamped by `/lets-build`.
112
+ 3. *Layer 3 (Universal Domain Rules):* Enforce architectural invariants (`frontend_architecture.md`, `test_driven_development.md`) rather than library syntax.
113
+ 4. *Layer 4 (Tool & CLI Execution):* Direct execution of official CLIs (`npx shadcn@latest add ...`) or local component inspection.
77
114
 
78
115
  ---
79
116
 
@@ -111,38 +148,40 @@ Coding tasks and agentic skills exhibit an explicit **Many-to-Many ($M:N$) Relat
111
148
  - **Zero Cross-Contamination:** No skill may write code or modify files outside its declared functional boundary.
112
149
  - **Pure Function Semantics:** Analysis skills must remain read-only and side-effect free.
113
150
 
151
+ ## 6. The Mandatory YAGNI Gate Triad (Rules & Skills)
152
+
153
+ 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.
154
+
155
+ To prevent premature abstraction, every architectural pattern rule and skill must enforce the **YAGNI Gate Triad**:
156
+
157
+ 1. **The Simple Baseline (Day 1 Default):**
158
+ - 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).
159
+ 2. **The Anti-Triggers (Strictly Forbidden Scenarios):**
160
+ - 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).
161
+ 3. **The Empirical Tipping Point (Graduation Threshold):**
162
+ - 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).
163
+
164
+ ### Foundational Leverage vs. Speculative Over-Engineering
165
+ A common misunderstanding is that YAGNI forbids using external libraries. **This is completely false**:
166
+ - **YAGNI Attacks:** Speculative custom code, home-grown frameworks, custom wheel reinvention, and premature multi-tier distributed architectures.
167
+ - **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).
168
+
114
169
  ---
115
170
 
116
- ## 6. The Relentless Skill Architecture Inquiry
171
+ ## 7. The Relentless Skill Architecture Inquiry
117
172
 
118
173
  Never architect or modify a skill based on assumptions. Before authoring any `SKILL.md`, run the **7 Core Skill Inquiry Branches**:
119
174
 
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]
175
+ ```mermaid
176
+ flowchart TD
177
+ Req["New Skill / Rule Request"] --> B1["Branch 1: Placement<br/>AGENTS.md, Rule, or Skill?"]
178
+ B1 --> B2["Branch 2: Trigger Boundaries<br/>Exact 'Use when...' & 'Do NOT use for...'?"]
179
+ B2 --> B3["Branch 3: Domain Ground Truth<br/>Generic textbook tutorials purged?"]
180
+ B3 --> B4["Branch 4: Gotchas & Anti-Patterns<br/>What AI mistakes MUST be forbidden?"]
181
+ B4 --> B5["Branch 5: Determinism vs LLM<br/>Deterministic steps scripted in scripts/?"]
182
+ B5 --> B6["Branch 6: Progressive Bloat<br/>SKILL.md < 500 lines with sub-docs in references/?"]
183
+ B6 --> B7["Branch 7: Verification Loop<br/>Output templates & self-checklists present?"]
184
+ B7 --> Ready["Ready to Author / Update Skill"]
146
185
  ```
147
186
 
148
187
  ### The 7 Core Inquiry Branches
@@ -159,10 +198,59 @@ Never architect or modify a skill based on assumptions. Before authoring any `SK
159
198
 
160
199
  ---
161
200
 
162
- ## 7. The Continuous Refinement Loop
201
+ ## 8. The Continuous Refinement Loop
163
202
 
164
203
  When an AI produces suboptimal code or documentation:
165
204
  1. Preserve the original AI output draft.
166
205
  2. Make manual corrections to produce the desired gold-standard output.
167
206
  3. Diff the original draft against the corrected version to identify specific gaps.
168
207
  4. Update the relevant skill's "What NOT to do" or guideline section to prevent repeating that mistake.
208
+
209
+ ---
210
+
211
+ ## 9. Workspace Sovereignty & Zero Global Interference
212
+
213
+ Enforce strict workspace containment within the workspace root (`./`):
214
+ - **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.
215
+ - **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.
216
+ - **Sibling Project Isolation**: Strictly ignore external or legacy projects. Do not read from or write to directories outside the local repository (`./`).
217
+ - **Subagent Context Sandboxing**: When spawning subagents or executing commands, ensure working directories are anchored strictly to `./`.
218
+
219
+ ---
220
+
221
+ ## 10. Continuous Learning & The Direct Rule Ingestion Loop
222
+
223
+ Whenever an error, test failure, build friction, or architectural anti-pattern occurs during development, immediately execute the 4-step loop:
224
+
225
+ ```
226
+ 1. Capture Defect ──► 2. Root Cause Analysis ──► 3. Synthesize Invariant ──► 4. Update Rule / Skill
227
+ ```
228
+
229
+ 1. **Capture Defect**: Record the failure symptoms, stack trace, and failing test case.
230
+ 2. **Root Cause Analysis**: Identify the fundamental architectural or operational gap (not just the surface symptom).
231
+ 3. **Synthesize Invariant**: Formulate a concrete, positive architectural invariant and code example showing the correct implementation.
232
+ 4. **Update Rule / Skill**:
233
+ - Update the governing domain rule in `docs/rules/<domain>.md` or specialized skill in `.agents/skills/` directly.
234
+ - If the lesson introduces an architectural trade-off or paradigm shift, record a lightweight ADR in [`memory.md`](../../memory.md).
235
+ - Run verification (`npm test && npm run validate`) to ensure 100% integrity.
236
+
237
+ ---
238
+
239
+ ## 11. Architectural Decision Records (ADR) Standards
240
+
241
+ Significant architectural, technical stack, or invariant decisions must be captured in [`memory.md`](../../memory.md):
242
+
243
+ ### Required ADR Envelope:
244
+ ```markdown
245
+ #### ADR-XXX: <Imperative Action-Oriented Title>
246
+ - **Date:** YYYY-MM-DD | **Status:** PROPOSED | ACCEPTED | SUPERSEDED | DEPRECATED
247
+ - **Context:** The specific operational or technical problem, constraint, or trade-off requiring a decision.
248
+ - **Decision:** Concrete, unambiguous architecture choice and positive invariants.
249
+ - **Consequences:** Direct benefits and deliberate operational trade-offs accepted.
250
+ - **Enforced In:** Links to specific rule files in `docs/rules/` or code paths.
251
+ ```
252
+
253
+ ### Numbering & Immutability:
254
+ - ADR numbers are monotonically increasing (`ADR-001`, `ADR-002`, ...).
255
+ - ADR entries are **immutable history**. Never edit past accepted ADRs to represent new decisions; author a new ADR that explicitly supersedes the former.
256
+
@@ -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
  ```