azcodr 1.0.1 → 1.2.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 (35) hide show
  1. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +24 -8
  2. package/.agents/skills/lets-build/SKILL.md +71 -78
  3. package/.agents/skills/lets-build/references/architecture_interview_matrix.md +78 -157
  4. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +75 -35
  5. package/.editorconfig +19 -0
  6. package/.gitignore +3 -0
  7. package/AGENTS.md +12 -10
  8. package/README.md +3 -8
  9. package/bin/azcodr.js +170 -97
  10. package/changes.md +26 -0
  11. package/docs/rules/api_versioning.md +0 -15
  12. package/docs/rules/clean_code.md +37 -0
  13. package/docs/rules/continuous_learning.md +14 -13
  14. package/docs/rules/database_integrity.md +9 -17
  15. package/docs/rules/design_patterns.md +1 -0
  16. package/docs/rules/domain_driven_design.md +31 -21
  17. package/docs/rules/error_handling.md +14 -1
  18. package/docs/rules/multitenancy_isolation.md +2 -0
  19. package/docs/rules/product_ownership.md +0 -18
  20. package/docs/rules/project_management.md +0 -17
  21. package/docs/rules/react.md +4 -14
  22. package/docs/rules/requirements_engineering.md +0 -17
  23. package/docs/rules/rest_api_conventions.md +0 -16
  24. package/docs/rules/test_driven_development.md +42 -20
  25. package/docs/rules/transactional_email.md +11 -4
  26. package/docs/rules/ui_ux_architecture.md +5 -26
  27. package/docs/rules/upstream_synchronization.md +0 -15
  28. package/docs/rules/workflow_state_machines.md +0 -18
  29. package/lib/index.d.ts +153 -0
  30. package/lib/scaffold.js +86 -24
  31. package/memory.md +85 -219
  32. package/package.json +14 -4
  33. package/docs/knowledge/dos_and_donts.md +0 -540
  34. package/docs/knowledge/issue_log.md +0 -25
  35. package/docs/knowledge/lessons_learned.md +0 -107
package/changes.md CHANGED
@@ -34,3 +34,29 @@ When an AI agent or engineer discovers a generic architectural improvement, bug
34
34
  - **Rationale:** Remove fragile git repo resolution and merge scripts; replace with atomic change logging in `changes.md`.
35
35
  - **Description:** Retired `merge-ai` skill and removed machine-specific hardcoded paths. All upstream improvements are now recorded atomically in `changes.md`.
36
36
  - **Domain Filter Verification:** Verified 100% generic.
37
+
38
+ ### [2026-09-25] Harden CLI, achieve 100% test coverage gates, add multi-OS CI workflow, and TypeScript declarations
39
+ - **Category:** CLI
40
+ - **Target File(s):** bin/azcodr.js, lib/scaffold.js, lib/index.d.ts, .github/workflows/ci.yml
41
+ - **Rationale:** Fulfill 100.00% test coverage mandate, cross-platform CI matrix, and library type safety
42
+ - **Description:** Remediate gap assessment findings: add --dry-run and --silent flags, enforce 100.00% line/branch/function coverage gates, add GitHub Actions CI matrix across Node 18/20/22/24 and Linux/macOS/Windows, add .editorconfig template item, and export ambient TypeScript typings.
43
+ - **Domain Filter Verification:** Verified 100% generic; purged of all project-specific business entities and models.
44
+
45
+ ### [2026-09-25] Resolve macOS/Windows Git Case-Collision and Cross-Version CI Matrix Coverage
46
+ - **Category:** Infrastructure & CI
47
+ - **Target File(s):** .gitignore, lib/scaffold.js, scripts/test_coverage.js, validate_agentic_configs.sh
48
+ - **Rationale:** Ensure flawless cross-platform and multi-version Node execution across macOS, Windows, and Linux on Node 18, 20, 22, 24.
49
+ - **Description:** Untracked agents.md from Git to prevent cyclic symlink overwrite on case-insensitive filesystems; hardened ensureSymlink with isSameCaseInsensitiveFile check; added cross-version test coverage runner script; updated npm test runner to use native discovery.
50
+ - **Domain Filter Verification:** Verified 100% generic; purged of all project-specific business entities and models.
51
+
52
+ ### [2026-09-25] Problem-First Architecture, Evolutionary Tipping Points, and Incremental Nano-Cycle TDD
53
+ - **Category:** Architecture, Rule & Skill
54
+ - **Target File(s):** `AGENTS.md`, `docs/rules/clean_code.md`, `docs/rules/domain_driven_design.md`, `docs/rules/test_driven_development.md`, `.agents/skills/lets-build/SKILL.md`, `.agents/skills/lets-build/references/architecture_interview_matrix.md`, `.agents/skills/lets-build/scripts/bootstrap_workspace.sh`, `memory.md`
55
+ - **Rationale:** Eliminate tool-first bias ("Solution-in-Search-of-a-Problem"), stop accidental complexity (as seen in `force-dark-light` where Chrome extension received Kubernetes and OpenAPI specs), prevent AI-accelerated architectural drift, and halt the "Test-First Waterfall" batch-test anti-pattern.
56
+ - **Description:**
57
+ 1. Enforced Problem Space vs Solution Space decoupling with zero tool bias.
58
+ 2. Made scaffolding strictly topology-aware (Web SaaS, Browser Extension, Game/Engine, CLI, Library) with zero speculative bloat.
59
+ 3. Codified Evolutionary Architecture, the 5 Architectural Tipping Points, and Kent Beck's "Refactor-Before-Add" protocol.
60
+ 4. Codified Uncle Bob's Three Laws of TDD, banned batch-test dumps, and introduced the Incremental Nano-Cycle and Ping-Pong Pair Programming protocol.
61
+ - **Domain Filter Verification:** Verified 100% generic; applicable across any language, stack, and project topology.
62
+
@@ -111,18 +111,3 @@ specs/
111
111
  │ └── openapi.yaml
112
112
  ```
113
113
 
114
- ---
115
-
116
- ## 5. Invariants, DO's & DONT's
117
-
118
- ### DO's:
119
- - **DO:** Prefix all public REST endpoints with major version identifiers (`/api/v1/`, `/api/v2/`).
120
- - **DO:** Bump MAJOR and cut a new `/api/v2/` prefix whenever request or response breaking changes occur.
121
- - **DO:** Inject RFC 8594 `Sunset` and `Deprecation` headers on all retired endpoints and provide a 90-day grace period.
122
- - **DO:** Organize specs into versioned folders (`specs/openapi/v1/`, `v2/`) with an interactive Swagger selector.
123
-
124
- ### DONT's:
125
- - **DONT:** Never expose minor or patch numbers in the URL path (e.g. `/api/v1.2/`).
126
- - **DONT:** Never introduce breaking schema or status code changes within an existing major version.
127
- - **DONT:** Never delete an active endpoint without a formal deprecation lifecycle.
128
-
@@ -23,3 +23,40 @@
23
23
  - **Orthogonality**: Eliminate coupling between unrelated modules. Changing one component must not cascade unexpected side effects into another.
24
24
  - **Broken Windows Theory**: Never leave bad code, failing lint checks, or out-of-date documentation unfixed. Fix defects immediately before entropy normalizes.
25
25
  - **Design by Contract (DbC)**: Define explicit preconditions (runtime boundary validation), postconditions (guaranteed response envelopes), and domain invariants.
26
+
27
+ ---
28
+
29
+ ## 3. Evolutionary Architecture & Architectural Tipping Points (Ford, Parsons & Fowler)
30
+
31
+ Architecture is not a static Day 1 monument; it evolves incrementally as complexity grows. AI coding tools naturally take the path of least resistance (local token minimization), repeatedly appending code to simple files until they rot into a Big Ball of Mud. To eliminate **AI-Accelerated Architectural Drift**, the agent must pause and execute an architectural upgrade whenever code hits a **Deterministic Tipping Point**:
32
+
33
+ | Simple Baseline (Day 1) | Tipping Point / Mutation Trigger | Required Architectural Upgrade |
34
+ |---|---|---|
35
+ | **Flat Script / Single File** | File exceeds **250 lines**, or coordinates **>2 distinct I/O resources**, or is imported by **>3 distinct callers**. | **Extract Modular Subsystems:** Decouple domain logic from platform I/O; split into dedicated, focused submodules. |
36
+ | **Inline `if/else` or `switch` Cascades** | **Rule of Three:** The 3rd branching variant, payment provider, or protocol format is introduced. | **Strategy Pattern / Registry:** Replace conditional branching with a polymorphic Strategy interface or handler registry; update `memory.md`. |
37
+ | **In-Memory Store / Global State** | State requires **concurrent mutations**, **persistence across process restarts**, or **transactional rollback**. | **Repository Pattern & Persistence Port:** Introduce an explicit storage port contract; swap in-memory mock for a persistent database adapter. |
38
+ | **Direct Platform / Third-Party Calls** | External SDK or platform API is called from **>2 places**, or SDK throws untyped exceptions across boundaries. | **Adapter Pattern (Anti-Corruption Layer):** Wrap external SDK inside an application-owned port interface; mock only the owned interface in tests. |
39
+ | **Monolithic Domain Model** | The same business noun represents divergent lifecycles or definitions across workflows (e.g. `User` in Auth vs `User` in Billing). | **Bounded Context Split:** Separate into isolated domain contexts with explicit DTO / Anti-Corruption translation between them. |
40
+
41
+ ---
42
+
43
+ ## 4. The "Refactor-Before-Add" Protocol (Kent Beck's Rule)
44
+
45
+ > *"Make the change easy (warning: this may be hard), then make the easy change."* — Kent Beck
46
+
47
+ Before writing production code for any new feature or user story, the agent must execute the **Refactor-Before-Add Check**:
48
+ 1. **Assess Tipping Points**: Will adding this requirement cause any module, function, or data structure to cross an architectural tipping point?
49
+ 2. **Phase A — Structural Refactoring (Under Green)**: If yes, refactor the existing architecture *first* while existing test suites remain 100% green. Zero behavioral changes; purely structural evolution.
50
+ 3. **Phase B — ADR Mutation**: When an architectural tipping point is crossed, log a Lightweight Architectural Decision Record in `memory.md` summarizing the new structural boundary and trade-off.
51
+ 4. **Phase C — Feature Implementation (Inner TDD)**: Only once the architecture cleanly accommodates the new capability, write the failing micro-test and implement the feature.
52
+
53
+ ---
54
+
55
+ ## 5. Architectural Fitness Functions (Automated Tripwires)
56
+
57
+ Prevent AI-generated code rot using automated fitness functions integrated into linting and continuous verification:
58
+ - **File Length Gates**: Maximum 250–300 lines per file (ESLint `max-lines`).
59
+ - **Function Length Gates**: Maximum 20–30 lines per function (ESLint `max-lines-per-function`).
60
+ - **Dependency Direction Gates**: Enforce unidirectional import rules (e.g. `import/no-restricted-paths`, `dependency-cruiser`, `ArchUnit`) ensuring domain core never imports infrastructure or transport adapters.
61
+ - **Complexity Budgets**: Enforce cyclomatic complexity limits (maximum 10 per function).
62
+ If an AI attempt to add code violates any fitness function, the build fails immediately, blocking completion until the architecture is refactored.
@@ -1,29 +1,30 @@
1
1
  # Continuous Learning & Automated Rule Ingestion
2
2
 
3
- > **Core Mandate:** Automatically log development defects, post-mortems, and lessons learned into workspace memory, dynamically updating or generating atomic rules to permanently prevent recurrence.
3
+ > **Core Mandate:** Automatically capture development defects, analyze root causes, and directly update domain rules or skills to permanently prevent recurrence without intermediate bloat.
4
4
 
5
5
  ---
6
6
 
7
- ## 1. The Automated Rule Ingestion Loop
7
+ ## 1. The Direct Rule Ingestion Loop
8
8
 
9
- Whenever an error, test failure, build friction, or architectural anti-pattern occurs during development, immediately execute the 5-step loop:
9
+ Whenever an error, test failure, build friction, or architectural anti-pattern occurs during development, immediately execute the 4-step loop:
10
10
 
11
11
  ```
12
- 1. Capture Defect ──► 2. Root Cause Analysis ──► 3. Log Post-Mortem ──► 4. Synthesize Rule ──► 5. Update Rulebase
12
+ 1. Capture Defect ──► 2. Root Cause Analysis ──► 3. Synthesize Invariant ──► 4. Update Rule / Skill
13
13
  ```
14
14
 
15
- 1. **Capture Defect**: Record the failure symptoms and stack trace.
15
+ 1. **Capture Defect**: Record the failure symptoms, stack trace, and failing test case.
16
16
  2. **Root Cause Analysis**: Identify the fundamental architectural or operational gap (not just the surface symptom).
17
- 3. **Log Post-Mortem**: Append an entry to [`docs/knowledge/issue_log.md`](../knowledge/issue_log.md) documenting Symptom, Root Cause, Anti-Pattern, and Resolution.
18
- 4. **Synthesize Rule**: Formulate the preventative DO and DONT directives and add them to [`docs/knowledge/dos_and_donts.md`](../knowledge/dos_and_donts.md).
19
- 5. **Update Rulebase**:
20
- - If the issue falls under an existing domain rule in `docs/rules/<domain>.md`, update that rule immediately.
21
- - If it represents a new domain, author a new atomic rule file and index it in [`AGENTS.md`](../../AGENTS.md).
22
- - Run the configuration validation script to ensure integrity.
17
+ 3. **Synthesize Invariant**: Formulate a concrete, positive architectural invariant and code example showing the correct implementation.
18
+ 4. **Update Rule / Skill**:
19
+ - Update the governing domain rule in `docs/rules/<domain>.md` or specialized skill in `.agents/skills/` directly.
20
+ - If the lesson introduces an architectural trade-off or paradigm shift, record a lightweight ADR in [`memory.md`](../../memory.md).
21
+ - If it unlocks a new domain, author a new atomic rule file and index it in [`AGENTS.md`](../../AGENTS.md).
22
+ - Run verification (`npm test && npm run validate`) to ensure 100% integrity.
23
23
 
24
24
  ---
25
25
 
26
26
  ## 2. Institutional Memory Maintenance
27
27
 
28
- - **ADR Synchronization**: Major technical decisions must be logged in [`memory.md`](../../memory.md) before or immediately upon implementation.
29
- - **Knowledge Graph Updates**: Keep [`docs/knowledge/knowledge_graph.md`](../knowledge/knowledge_graph.md) synchronized with new services, database models, or adapters to avoid repetitive token-expensive codebase discovery in future sessions.
28
+ - **Lightweight ADR Ledger**: Major technical decisions and invariant shifts are logged in [`memory.md`](../../memory.md) linking directly to the governing rule or skill.
29
+ - **System Knowledge Graph**: Keep [`docs/knowledge/knowledge_graph.md`](../knowledge/knowledge_graph.md) synchronized with new services, ports, or adapters to avoid repetitive token-expensive codebase discovery in future sessions.
30
+ - **Living Glossary**: Keep [`docs/knowledge/ubiquitous_language.md`](../knowledge/ubiquitous_language.md) updated with canonical domain terminology and forbidden synonyms.
@@ -69,20 +69,12 @@ Pure financial ledgers (e.g. `PaymentLedgerEntry`, `JournalEntry`) and event out
69
69
 
70
70
  ---
71
71
 
72
- ## 6. Invariants, DO's & DONT's
73
-
74
- ### DO's:
75
- - **DO:** Include the canonical total audit fields (`createdAt`, `createdBy`, `updatedAt`, `updatedBy`, `deletedAt`, `deletedBy`) on every mutable entity model.
76
- - **DO:** Populate `createdBy`, `updatedBy`, and `deletedBy` from the verified session actor (`req.user.id`), falling back explicitly to `'SYSTEM'` only for background daemons or public bootstrap.
77
- - **DO:** Default foreign keys to `RESTRICT` for root aggregates and financial ledgers to prevent accidental cascading data loss.
78
- - **DO:** Enforce foreign key validation in use cases before persistence, returning RFC 7807 problem details if referenced records do not exist.
79
- - **DO:** Render foreign key associations using relational selectors (`shadcn/ui` `<Select>`) showing human-readable business metadata (names, labels, numbers, emails).
80
- - **DO:** Ensure every entity/feature implements full lifecycle CRUD (Create, Read/Detail, Update/Status Transition, Delete/Archive) before considering it complete.
81
- - **DO:** Filter active records with `WHERE deleted_at IS NULL` and pair uniqueness with partial indexes (`WHERE deleted_at IS NULL`).
82
-
83
- ### DONT's:
84
- - **DONT:** Never create a database table or entity without `createdAt` and `createdBy`.
85
- - **DONT:** Never omit `updatedBy` or `deletedBy` on mutable tables. Every mutation and deletion must have an accountable actor.
86
- - **DONT:** Never expose raw string text inputs for foreign key identifiers in the user interface.
87
- - **DONT:** Never consider a feature complete if it only implements creation or listing without update, transition, or deletion capabilities.
88
- - **DONT:** Never allow cascading deletes on master entities with dependent transactional history.
72
+ ## 6. Semi-Structured Evolution & Cryptographic Audit Trails
73
+
74
+ - **Non-Destructive Schema Evolution via JSON**: For contractual covenants, dynamic conditions, or variable metadata subject to rapid domain iteration, employ semi-structured JSON fields (`termsJson`, `metadataJson`) validated against JSON Schema rather than premature table migrations.
75
+ - **Cryptographic Electronic Signatures & Execution Auditing**: Legal agreements and execution records require defensible evidence beyond a boolean `isSigned` flag. All executed agreements must capture:
76
+ 1. Typed signer legal name and designated role.
77
+ 2. ISO 8601 UTC execution timestamp.
78
+ 3. Authenticated actor ID (`userId`).
79
+ 4. Client network IP address and User-Agent string.
80
+ 5. Deterministic cryptographic checksum / hash of the executed terms.
@@ -10,6 +10,7 @@
10
10
  - **Factory Method**: Encapsulate complex collaborator instantiation (e.g. tenant-specific payment gateways or notification dispatchers) behind factory functions.
11
11
  - **Facade Pattern**: Expose a unified, simplified interface to complex underlying multi-service subsystems.
12
12
  - **Decorator / Middleware**: Compose cross-cutting concerns (observability, authentication, tenant context resolution, rate limiting) via middleware pipelines.
13
+ - **Dependency Injection & Composition Hygiene**: Application factories (`createApp(deps)`) must accept an explicit composite container (`AppDependencies`). Never provide silent default fallback instances inside factories that instantiate disconnected repositories or services when partial dependencies are passed (the Split-Brain Anti-Pattern). Assemble the full dependency graph explicitly at the composition root.
13
14
 
14
15
  ---
15
16
 
@@ -1,10 +1,35 @@
1
1
  # Domain-Driven Design (DDD) & Ubiquitous Language
2
2
 
3
- > **Core Mandate:** Establish unambiguous Ubiquitous Language definitions, isolate Bounded Contexts, guarantee Domain-Code Language Agreement across all architectural layers, and separate Value Objects, Entities, and Aggregates.
3
+ > **Core Mandate:** Separate Problem Space from Solution Space, establish unambiguous Ubiquitous Language definitions, isolate Bounded Contexts, guarantee Domain-Code Language Agreement, and protect Aggregate invariants.
4
4
 
5
5
  ---
6
6
 
7
- ## 1. Domain-Code Language Agreement
7
+ ## 1. Problem Space vs. Solution Space (Evans & Vernon)
8
+
9
+ Software engineering fails when teams jump directly into the **Solution Space** (choosing languages, frameworks, databases, and microservices) before fully defining the **Problem Space**.
10
+
11
+ ```
12
+ ┌────────────────────────────────────────────────────────────────────────┐
13
+ │ THE PROBLEM SPACE │
14
+ │ Business Problem ➔ Subdomains (Core/Supporting/Generic) ➔ Invariants │
15
+ │ Operational Constraints: Execution target, Latency budget, GC limits │
16
+ └───────────────────────────────────┬────────────────────────────────────┘
17
+ │ Shapes & Dictates
18
+ ▼
19
+ ┌────────────────────────────────────────────────────────────────────────┐
20
+ │ THE SOLUTION SPACE │
21
+ │ Bounded Contexts ➔ Architectural Style (DOD, Hexagonal, Pipeline) │
22
+ │ Emergent Toolchain: Programming Language, Runtime, Persistence │
23
+ └────────────────────────────────────────────────────────────────────────┘
24
+ ```
25
+
26
+ - **The Problem Space (The Essence - Fred Brooks):** Concerns *what* problem is being solved, the entities, state transitions, and operational constraints (e.g. 16.6ms frame budget for games, zero-install browser sandbox for extensions, or ACID compliance for banking). **Zero technology, stack, or database choices are permitted in the Problem Space.**
27
+ - **The Solution Space (The Accidents):** Concerns *how* the system is realized. Runtimes, programming languages (C, Rust, TS, Go, Java), and storage engines are **emergent outputs** derived strictly from Problem Space constraints.
28
+ - **The Golden Hammer Anti-Pattern:** Selecting tools (e.g., "Let's use Next.js and PostgreSQL") before mapping problem constraints forces the domain to fit the tool, creating massive accidental complexity.
29
+
30
+ ---
31
+
32
+ ## 2. Domain-Code Language Agreement
8
33
 
9
34
  The fundamental premise of Domain-Driven Design (Eric Evans) is that **the code is the model, and the model is the code**. Any divergence between the mental model of domain experts and the source code is called **Linguistic Drift**.
10
35
 
@@ -16,7 +41,7 @@ The fundamental premise of Domain-Driven Design (Eric Evans) is that **the code
16
41
 
17
42
  ---
18
43
 
19
- ## 2. Living Ubiquitous Language Glossary
44
+ ## 3. Living Ubiquitous Language Glossary
20
45
 
21
46
  Every project must maintain an authoritative, version-controlled **Living Ubiquitous Language Glossary** at [`docs/knowledge/ubiquitous_language.md`](../knowledge/ubiquitous_language.md).
22
47
 
@@ -30,7 +55,7 @@ Each entry must define:
30
55
 
31
56
  ---
32
57
 
33
- ## 3. Automated Enforcement & Linters
58
+ ## 4. Automated Enforcement & Linters
34
59
 
35
60
  To prevent linguistic drift over time, teams must employ mechanical enforcement:
36
61
 
@@ -60,25 +85,10 @@ Acceptance criteria must be written strictly in Ubiquitous Language, serving as
60
85
 
61
86
  ---
62
87
 
63
- ## 4. Tactical Patterns & Invariants
88
+ ## 5. Tactical Patterns & Invariants
64
89
 
65
90
  1. **Entities**: Objects defined by identity that persists across state changes (e.g. `User`, `Order`, `Invoice`).
66
91
  2. **Value Objects**: Immutable objects defined strictly by their attributes with no identity (e.g. `Money`, `DateRange`, `EmailAddress`).
67
92
  3. **Aggregates & Aggregate Roots**: Clusters of domain objects treated as a single transactional consistency boundary. All mutations must pass through explicit methods on the Aggregate Root.
68
93
  4. **Anti-Corruption Layer (ACL)**: When integrating with third-party APIs or legacy systems that use different terminology, translate external payloads into the internal Ubiquitous Language at the boundary adapter before they enter the domain core.
69
-
70
- ---
71
-
72
- ## 5. Invariants (DO's & DONT's)
73
-
74
- ### DO
75
- - **DO** use identical terminology in domain conversations, PRDs, code, database schemas, and user interfaces.
76
- - **DO** maintain an authoritative `ubiquitous_language.md` and treat it as a binding architectural contract.
77
- - **DO** use branded nominal types for IDs to catch cross-entity domain mixups at compile time.
78
- - **DO** translate foreign data structures at the perimeter using an Anti-Corruption Layer (ACL).
79
-
80
- ### DONT
81
- - **DONT** use technical jargon (`dto`, `entity_row`, `table_item`) in domain business logic.
82
- - **DONT** allow competing synonyms for the same concept within the same Bounded Context.
83
- - **DONT** overload words with dual meanings across technical architecture and business domain.
84
- - **DONT** rename domain terms in code without updating the living glossary and recording an ADR.
94
+ 5. **Cross-Aggregate Coordination in Use Cases**: While an Aggregate Root guards its own internal invariants, business operations frequently span multiple aggregates (e.g. reserving an inventory item for an agreement). Application use cases or orchestrators must coordinate aggregate transitions atomically: asserting resource availability prior to state change, transitioning the constrained entity (e.g. `ALLOCATED`), and restoring state (`AVAILABLE`) upon cancellation, avoiding double-allocation race conditions without coupling aggregates directly.
@@ -1,6 +1,6 @@
1
1
  # Error Handling, Request Tracing & Schema Validation
2
2
 
3
- > **Core Mandate:** Enforce fail-fast schema validation at startup, structured OpenTelemetry/JSON request tracing, and standardized RFC 7807 / REST error envelopes.
3
+ > **Core Mandate:** Enforce fail-fast schema validation at startup, structured OpenTelemetry/JSON request tracing, standardized RFC 7807 problem details, and an explicit canonical DomainError hierarchy.
4
4
 
5
5
  ---
6
6
 
@@ -37,3 +37,16 @@ Enforce a uniform error envelope across all external HTTP/REST endpoints conform
37
37
  ```
38
38
 
39
39
  - **Production Masking Invariant**: Strictly mask internal database error codes, raw SQL queries, file system paths, and stack traces from external client responses in non-local environments.
40
+
41
+ ---
42
+
43
+ ## 4. Canonical Domain Error Hierarchy & Type-Safe Narrowing
44
+
45
+ - **Canonical DomainError Hierarchy**: Model operational domain failures using an explicit `DomainError` base class with canonical subclasses:
46
+ - `ValidationError` (maps to HTTP 400 / 422)
47
+ - `UnauthorizedError` (maps to HTTP 401)
48
+ - `ForbiddenError` (maps to HTTP 403)
49
+ - `NotFoundError` (maps to HTTP 404)
50
+ - `ConflictError` (maps to HTTP 409)
51
+ - `ExpiredError` (maps to HTTP 410)
52
+ - **Eliminate Untyped Error Monkey-Patching**: Strictly prohibit monkey-patching arbitrary properties onto error objects at catch sites (e.g. `(err as any).statusCode = 404`). Use clean `instanceof` narrowing in HTTP error middleware to map domain errors deterministically to RFC 7807 status codes with full compiler type safety.
@@ -14,6 +14,8 @@ Resolve tenant identity dynamically in an inbound gateway or middleware pipeline
14
14
 
15
15
  *Validation:* If the resolved tenant does not exist or is in `SUSPENDED` status, immediately return **`403 Forbidden`** (`TENANT_SUSPENDED` or `TENANT_INVALID`). Propagate `TenantContext` across service calls using standard W3C Baggage headers or request contexts.
16
16
 
17
+ - **Fail-Closed Multi-Tenancy Invariant**: Never trust client-supplied tenant headers (`X-Tenant-ID`) without cryptographically verifying that the authenticated session actor actually belongs to the requested tenant organization/workspace. Mismatched tenant headers must immediately fail closed with HTTP 403 `FORBIDDEN_TENANT_ACCESS`.
18
+
17
19
  ---
18
20
 
19
21
  ## 2. Four Universal Data Isolation Models
@@ -130,21 +130,3 @@ Following Gunther Verheyen's backlog topology, the Product Backlog serves as an
130
130
  1. **Single & Ordered:** Exactly one backlog exists per product.
131
131
  2. **Dynamic Splitting:** As coarse items approach the top of the backlog, they must be split into fine, sprintable INVEST slices.
132
132
  3. **Continuous Pruning:** Items may be reordered, added, split, or permanently deleted at any time based on empirical learning. If an item lingers at the bottom of the backlog for months without business justification, remove it.
133
-
134
- ---
135
-
136
- ## 6. Invariants, DO's & DONT's
137
-
138
- ### DO's:
139
- - **DO:** Formulate a clear, inspiring Product Goal that guides all backlog prioritization.
140
- - **DO:** Ground prioritization in quantitative models (RICE, Kano, MoSCoW) rather than executive opinion.
141
- - **DO:** Measure outcomes (satisfaction gap closure, conversion, retention) instead of pure output (story points, lines of code).
142
- - **DO:** Explicitly state what will NOT be done (Won't Have this time) to preserve engineering focus.
143
- - **DO:** Ensure every sprint increment complies 100% with the Definition of Done.
144
-
145
- ### DONT's:
146
- - **DONT:** Never confuse output (features shipped) with outcome (value realized).
147
- - **DONT:** Never treat OKRs as a task checklist; Key Results must be measurable outcomes.
148
- - **DONT:** Never prioritize speculative features when core "Must-be" baseline capabilities are unfulfilled.
149
- - **DONT:** Never maintain separate, disconnected backlogs for the same product.
150
- - **DONT:** Never deliver "un-done" work carrying forward technical debt.
@@ -47,20 +47,3 @@ A user story or task is only marked `DONE` when all of the following verifiable
47
47
 
48
48
  - If a blocker or ambiguity arises, immediately transition the task to `BLOCKED`, halt execution, and interrogate the root cause.
49
49
  - Never guess or write speculative code to bypass an unresolved requirement.
50
-
51
- ---
52
-
53
- ## 5. Invariants, DO's & DONT's
54
-
55
- ### DO's:
56
- - **DO:** Maintain strict WIP = 1 limit. Never work on multiple active tasks concurrently.
57
- - **DO:** Deliver features in vertical slices (UI ➔ API ➔ Domain ➔ DB) rather than isolated horizontal stubs.
58
- - **DO:** Apply SMART criteria to developer tasks, time-boxing them to under 4 hours.
59
- - **DO:** Halt and transition to `BLOCKED` whenever assumptions are required.
60
- - **DO:** Satisfy all 7 criteria of the Definition of Done before declaring any increment complete.
61
-
62
- ### DONT's:
63
- - **DONT:** Never mark a task `DONE` with skipped, failing, or unwritten tests.
64
- - **DONT:** Never bypass the 5-Phase Agile Domain Lifecycle provenance gate.
65
- - **DONT:** Never create untracked, open-ended developer tasks without measurable completion tests.
66
- - **DONT:** Never leave unresolved blockers or silent errors in working branches.
@@ -72,17 +72,7 @@
72
72
 
73
73
  ---
74
74
 
75
- ## 5. Invariants, DO's & DONT's
76
-
77
- ### DO's:
78
- - **DO:** Use `shadcn/ui` components backed by `@radix-ui` primitives for all interactive elements.
79
- - **DO:** Use `@tanstack/react-query` (`useQuery`, `useMutation`) for all server data fetching, caching, and mutation invalidation.
80
- - **DO:** Validate all form inputs using formal Zod schemas and `react-hook-form` / `tanstack-form`.
81
- - **DO:** Display user feedback and errors using accessible ARIA live regions (`role="alert"` for errors, `role="status"` for confirmations) and `<ConfirmDialog>`.
82
- - **DO:** Synchronize pagination, active tabs, and search filters into URL search parameters.
83
-
84
- ### DONT's:
85
- - **DONT:** Never use `window.alert()` or `window.confirm()`.
86
- - **DONT:** Never fetch data in raw `useEffect` hooks with manual `loading` / `error` boolean state.
87
- - **DONT:** Never manage multi-field forms using raw `useState` and manual imperative string validations.
88
- - **DONT:** Never use unstyled raw HTML select or dialog elements when `shadcn/ui` components exist.
75
+ ## 5. Theme Architecture & Design Token Completeness
76
+
77
+ - **Symmetric Design Tokens**: Ensure foundational CSS variables (`--background`, `--foreground`, `--card`, `--border`, `--popover`) are symmetrically declared across `:root` and `.dark`. Omitted root tokens in `.dark` result in unstyled backgrounds and illegible text when switching themes.
78
+ - **System Preference Detection & Reactive Synchronization**: `ThemeProvider` implementations must listen to `window.matchMedia('(prefers-color-scheme: dark)')` with dynamic event listeners so OS appearance toggles seamlessly propagate in real-time, and synchronize `document.documentElement.style.colorScheme = resolvedTheme` to ensure browser-native elements (scrollbars, input widgets) match the active theme.
@@ -94,20 +94,3 @@ Scenario: Successful Digital Agreement Execution
94
94
  - `422 Unprocessable Entity`: Semantic domain invariant violations.
95
95
  - `429 Too Many Requests`: Rate limiter token exhaustion.
96
96
  - `500 Internal Server Error`: Unhandled upstream infrastructure failures.
97
-
98
- ---
99
-
100
- ## 5. Invariants, DO's & DONT's
101
-
102
- ### DO's:
103
- - **DO:** Embody Ron Jeffries' 3 C's (Card, Conversation, Confirmation) for all user-facing stories.
104
- - **DO:** Slice user stories vertically through all layers (UI ➔ API ➔ Domain ➔ DB).
105
- - **DO:** Model technical constraints, invariants, and spikes as explicit non-story requirements.
106
- - **DO:** Write Gherkin scenarios with active voice covering happy and unhappy paths.
107
- - **DO:** Map edge cases to standard HTTP status codes and RFC 7807 problem details.
108
-
109
- ### DONT's:
110
- - **DONT:** Never write horizontal technical stories that lack end-user observable value.
111
- - **DONT:** Never treat user stories as complete formal specification documents.
112
- - **DONT:** Never omit negative scope (out-of-scope / non-goals) in requirements.
113
- - **DONT:** Never skip edge cases or map errors to ambiguous status codes.
@@ -44,19 +44,3 @@
44
44
  - `PUT /api/v1/<resources>/:id` or `PATCH`: Update attributes or mutate state machine status.
45
45
  - `DELETE /api/v1/<resources>/:id`: Remove or archive returning `204 No Content`.
46
46
  - **Defensive Route Tolerances for Infrastructure Probes:** Operational probes (`/healthz`, `/readyz`) must defensively support trailing slashes (`/healthz/`) and common typos (`/healtz/`) to prevent reverse proxy routing mismatches between frontend dev servers (e.g. Vite) and ingress gateways.
47
-
48
- ---
49
-
50
- ## 5. Invariants, DO's & DONT's
51
-
52
- ### DO's:
53
- - **DO:** Return standard HTTP status codes (`200 OK`, `201 Created`, `204 No Content`, `400 Bad Request`, `404 Not Found`, `409 Conflict`).
54
- - **DO:** Return RFC 7807 Problem Details envelopes for all `4xx` and `5xx` error responses.
55
- - **DO:** Mask cross-tenant resources with `404 Not Found` (enumeration masking) to avoid leaking existence of foreign records.
56
- - **DO:** Implement full lifecycle CRUD verbs across all primary resources.
57
- - **DO:** Support defensive trailing slashes on health and readiness probes.
58
-
59
- ### DONT's:
60
- - **DONT:** Never return `200 OK` with an error object inside the response body (the anti-pattern of masking errors).
61
- - **DONT:** Never return detailed database stack traces or raw internal errors to client API callers in production.
62
- - **DONT:** Never use singular nouns for collection endpoints (use `/api/v1/users`, not `/api/v1/user`).
@@ -83,24 +83,46 @@ Deviating from this lifecycle introduces catastrophic defects and architectural
83
83
  | **Skipping Outer Acceptance Tests** | In-memory unit tests pass, but user interactions and network routing fail. | "The In-Memory Supertest Illusion": App says "Offline/Connecting" while 100% unit tests pass. |
84
84
  | **Skipping the Refactor Phase** | Technical debt accumulates immediately behind green tests. | Code rot, duplicated logic, bloated monolithic functions (> 30 lines), violated DRY/SLAP. |
85
85
 
86
- ### The Immutable Laws of TDD Execution:
87
- 1. **No Production Code Without a Failing Test:** You are not allowed to write any production code unless it is to make a failing unit or acceptance test pass.
88
- 2. **No Test Without Prior Domain Understanding:** You are not allowed to write a test without knowing the Ubiquitous Language, Aggregate Root, and business invariants it asserts.
89
- 3. **Minimal Code Only:** Write only the minimal amount of code necessary to turn the failing test green. Do not anticipate speculative future requirements.
90
- 4. **Refactor Under Green Only:** Never alter production code structure while tests are red. Refactor only when all existing assertions are green.
91
-
92
- ### DO's:
93
- - **DO:** Strictly adhere to the 5-Phase Agile Domain Lifecycle: Requirements ➔ Domain Analysis ➔ Outer Acceptance Test (RED) ➔ Inner Unit Test (RED-GREEN-REFACTOR) ➔ Outer Verification (GREEN).
94
- - **DO:** Follow Outside-In TDD (London School): Outer acceptance test ➔ collaborator discovery ➔ unit tests with test doubles.
95
- - **DO:** Maintain 100.00% line, branch, statement, and function coverage across all backend, contract, and frontend suites.
96
- - **DO:** Verify cross-package integration boundaries (Vite dev server reverse proxy, real network sockets, HTTP client JSON parsing) with automated full-stack smoke tests (`scripts/smoke_test.sh`).
97
- - **DO:** Keep functions small (under 20–30 lines) adhering to Single Level of Abstraction (SLAP) and Command-Query Separation (CQS).
98
-
99
- ### DONT's:
100
- - **DONT:** Never write a single line of production code without an existing failing test driving it.
101
- - **DONT:** Never write a test without prior domain analysis (Ubiquitous Language and invariant definition). Tests must assert domain invariants, not arbitrary syntax.
102
- - **DONT:** Never mock types you do not own; always wrap third-party dependencies in application-owned adapters.
103
- - **DONT:** Never equate in-memory test double passes (e.g. Supertest against in-memory Express instances) with real network transport, reverse proxying, or end-to-end user connectivity.
104
- - **DONT:** Never skip the Refactor phase under green; technical debt must not accumulate behind green tests.
105
- - **DONT:** Never use arbitrary `setTimeout()` or `sleep()` in tests; use deterministic event polling (`waitFor`).
86
+ ### The Immutable Three Laws of TDD (Uncle Bob & Kent Beck):
87
+ 1. **First Law:** You are not allowed to write any production code unless it is to make a single failing unit or acceptance test pass.
88
+ 2. **Second Law (Strict Incremental Boundary):** You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
89
+ 3. **Third Law (Minimal Production Code):** You are not allowed to write any more production code than is sufficient to pass the one currently failing test.
90
+
91
+ ---
92
+
93
+ ## 4. The Batch-Test Anti-Pattern & The Incremental Nano-Cycle
94
+
95
+ ### The "Test-First Waterfall" Anti-Pattern (BANNED)
96
+ A rampant anti-pattern in AI coding is dumping 10–20 test cases in a single test file, and then writing a 300-line implementation file in one shot so all tests pass simultaneously. **This is strictly prohibited.**
97
+ - **Why It Fails:** Writing all tests upfront is Waterfall in disguise. It forces the AI to hallucinate and lock in speculative method signatures and class structures before any code runs. If test #3 reveals a design flaw, tests #4–20 are broken legacy code before running.
98
+ - **Falsifiability Failure:** When 20 tests fail at once, you never prove that each individual assertion would catch its specific regression. Many batch tests are tautologies that pass by coincidence.
99
+
100
+ ### The Mandatory Incremental Nano-Cycle
101
+ Every collaborator discovered in Phase 4 must progress through micro-cycles of one behavior at a time:
102
+ 1. **RED (Micro-Assertion):** Write **ONE** test asserting a single micro-behavior (e.g. `expect(cart.total()).toBe(0)`).
103
+ 2. **VERIFY RED:** Run the test suite (`npm test`). **Inspect and verify the specific failure message** (e.g. "method not defined" or "expected 0, got undefined"). Never skip running the test while RED.
104
+ 3. **GREEN (Minimal Implementation):** Write the **absolute minimum production code** required to pass the single failing assertion (even hardcoding `return 0` if appropriate).
105
+ 4. **VERIFY GREEN:** Run the test suite. Confirm the test turns green with zero side effects.
106
+ 5. **REFACTOR (Under Green):** Clean up names, eliminate duplication (DRY), enforce SLAP and Clean Code standards while tests remain 100% green.
107
+ 6. **REPEAT:** Move to the next micro-behavior (e.g. `cart with 1 item returns item price`).
108
+
109
+ ---
110
+
111
+ ## 5. Ping-Pong Pair Programming Protocol with AI
112
+
113
+ When pairing with the human developer, operate in true **Ping-Pong TDD**:
114
+ ```
115
+ ┌─────────────────────────────────────────────────────────────┐
116
+ │ PING-PONG PAIR PROGRAMMING │
117
+ │ │
118
+ │ Turn 1 [Partner A]: Writes ONE micro-test assertion (RED) │
119
+ │ Turn 2 [System]: Runs test & displays verified failure │
120
+ │ Turn 3 [Partner B]: Writes MINIMAL code to pass (GREEN) │
121
+ │ Turn 4 [System]: Runs test & displays verified pass │
122
+ │ Turn 5 [Both]: Refactors under green (REFACTOR) │
123
+ │ Turn 6: Roles swap; repeat for next behavior │
124
+ └─────────────────────────────────────────────────────────────┘
125
+ ```
126
+ - **Collaborative Steering**: The human developer can write the test while the AI writes the minimal pass, or the AI can present each micro-test and await confirmation before implementing.
127
+ - **Continuous Alignment**: Design and data structures emerge organically through mutual feedback rather than monolithic code dumps.
106
128
 
@@ -1,20 +1,27 @@
1
1
  # Transactional Email Subsystem
2
2
 
3
- > **Core Mandate:** Enforce declarative email templates, safe variable interpolation, and deterministic local test delivery through Mailpit SMTP routing.
3
+ > **Core Mandate:** Enforce declarative email templates, strict HTML sanitization, decoupled asynchronous dispatch, and deterministic local test delivery through Mailpit SMTP routing.
4
4
 
5
5
  ---
6
6
 
7
7
  ## 1. Declarative & Typed Email Templates
8
8
 
9
9
  - **Declarative Template Definition**: Author transactional email templates using language-agnostic markup formats (such as **MJML - Mailjet Markup Language**) or typed component schemas to ensure cross-client rendering consistency across Outlook, Gmail, and Apple Mail.
10
- - **Safe Variable Interpolation**: Strictly prohibit unescaped raw HTML string concatenation. Always use context-aware template engines that automatically escape HTML special characters to prevent Cross-Site Scripting (XSS) and injection vulnerabilities.
10
+ - **Strict HTML Sanitization & Injection Defense**: Strictly prohibit unescaped raw HTML string concatenation. Centralize variable interpolation through a strict escaping utility neutralizing `&`, `<`, `>`, `"`, and `'` to prevent Cross-Site Scripting (XSS) and template injection vulnerabilities.
11
11
 
12
12
  ---
13
13
 
14
- ## 2. Local Mail Transport & Integration Verification
14
+ ## 2. Decoupled Transport & Background Queues
15
+
16
+ - **Async Queue Decoupling**: Decouple notification delivery from synchronous HTTP request-response cycles via an asynchronous job queue (e.g. BullMQ, Celery, or Transactional Outbox workers). API responses must never block on external network SMTP socket round-trips.
17
+ - **Zero-Dependency Native Sockets**: Prefer socket-based SMTP adapters adhering to RFC 5321 commands over heavy third-party mailer libraries to eliminate supply chain risks and transitive dependencies.
18
+
19
+ ---
20
+
21
+ ## 3. Local Mail Transport & Integration Verification
15
22
 
16
23
  - **Local SMTP via Mailpit**:
17
24
  - Route local and CI SMTP traffic to **Mailpit** (SMTP port 1025 / Web UI port 8025).
18
25
  - Never route emails to public mail transfer agents (MTAs) or external API gateways during automated test runs or local development.
19
26
  - **Deterministic API Assertion Protocol**:
20
- - Assert email delivery in integration tests by querying Mailpit's REST API (`GET /api/v1/messages`) to inspect recipient headers, delivery status, HTML body content, and verification links without timing dependencies.
27
+ - Assert email delivery in integration tests by querying Mailpit's REST API (`GET /api/v1/messages`) or testing against in-memory notification sinks to inspect recipient headers, delivery status, HTML body content, and verification links without timing dependencies.
@@ -139,30 +139,9 @@ Per [`docs/rules/ui_navigation.md`](./ui_navigation.md), all view state that rep
139
139
  4. **Pagination**: `?page=2&pageSize=25`
140
140
  5. **Drawers / Modals**: `?drawer=resource-102` or `?modal=create-order`
141
141
 
142
- ---
142
+ ## 7. Production UI Hygiene & Resilience Standards
143
143
 
144
- ## 7. Invariants, DO's & DONT's
145
-
146
- ### DO:
147
- - **DO** execute the 7-Pillar Design Architecture Triage before writing any UI code.
148
- - **DO** provide a collapsible left sidebar for operators that transitions into a slim 64px icon rail with hover tooltips and persists state in `localStorage`.
149
- - **DO** provide a dedicated, consumer-focused `/portal` layout for Members/Consumers with top and mobile-bottom navigation.
150
- - **DO** provide a public `/catalog` view for unauthenticated visitors to discover resources.
151
- - **DO** isolate developer demo personas into a dedicated dev-only floating toolbar (`import.meta.env.DEV`), completely decoupled from the real sign-in form.
152
- - **DO** enforce route guards on all routes, automatically redirecting users according to their authenticated role.
153
- - **DO** synchronize tabs, search terms, and pagination with URL search parameters.
154
- - **DO** use accessible Radix UI dialogs (`<ConfirmDialog>`) for destructive actions and ARIA live regions for status alerts.
155
- - **DO** synchronize authentication and tenant selection across browser tabs via `window.addEventListener('storage')`, and isolate complex subcomponents or page outlets using accessible `<ErrorBoundary>` components to prevent unhandled render exceptions from crashing the application shell.
156
- - **DO** decouple all technical internal telemetry (API gateway connection states, hexagonal port health, database adapter indicators, and active security roles) from user-facing screens and confine them exclusively to development tools and harnesses gated by `import.meta.env.DEV`.
157
- - **DO** centralize all user interface copy, status labels, error notifications, action titles, and templated messages into configuration constants (`UI_STRINGS`) to eliminate scattered hardcoded strings.
158
-
159
- ### DONT:
160
- - **DONT** build UI views on assumptions without completing the Design Architecture Triage Gate.
161
- - **DONT** embed mock/demo personas inside user-facing login or registration forms.
162
- - **DONT** force Member/Consumer users to navigate the enterprise operator sidebar with disabled buttons.
163
- - **DONT** expose multi-tenant organization switchers or system audit fields to consumer roles.
164
- - **DONT** expose internal architecture jargon (e.g. "ACID ledger", "Hexagonal ports", "API Connected", "Active Role") in production user-facing or administrator views.
165
- - **DONT** hardcode error messages, status labels, or button copy directly in page components; reference centralized configuration constants.
166
- - **DONT** use browser-native `window.alert()` or `window.confirm()` popups.
167
- - **DONT** rely solely on hiding UI buttons to enforce authorization; always wrap routes in `<ProtectedRoute>`.
168
- - **DONT** lose search queries or active tab states upon page reload; always sync to URL search params.
144
+ - **Multi-Tab State Synchronization**: Synchronize authentication and tenant selection across browser tabs using native `window.addEventListener('storage')`.
145
+ - **Fault-Tolerant Error Boundaries**: Wrap complex widgets, charts, and page outlets in accessible `<ErrorBoundary>` components to prevent runtime render exceptions from crashing the persistent application shell.
146
+ - **Strict Decoupling of Diagnostics & Telemetry**: Never expose internal architectural diagnostics (port health, connection badges, active role indicators) in production user-facing screens; gate diagnostic widgets strictly behind `import.meta.env.DEV`.
147
+ - **Centralized UI Copy (`UI_STRINGS`)**: Centralize all user interface copy, status labels, error notifications, and action button labels into configuration constants (`UI_STRINGS`) rather than scattering hardcoded strings across templates.
@@ -51,18 +51,3 @@ Every upstream-bound proposal logged to `changes.md` must follow the standardize
51
51
  - **Description:** Concise summary of the mutation or invariant added.
52
52
  - **Domain Filter Verification:** Verified 100% generic; purged of all project-specific business entities and models.
53
53
  ```
54
-
55
- ---
56
-
57
- ## 4. Invariants, DO's & DONT's
58
-
59
- ### DO's:
60
- - **DO:** Record candidate generic architectural improvements in `changes.md`.
61
- - **DO:** Distill all lessons and post-mortems into generic, domain-agnostic language before logging.
62
- - **DO:** Colocate DOs and DONTs directly inside the relevant atomic rules and skills.
63
- - **DO:** Verify that all entries in `changes.md` are 100% stack- and domain-agnostic.
64
-
65
- ### DONT's:
66
- - **DONT:** Never execute automated upstream git cloning or merge AI workflows during project work.
67
- - **DONT:** Never contaminate `changes.md` with project-specific business logic, schemas, or customer requirements.
68
- - **DONT:** Never leave machine-specific or absolute user paths in scripts or documentation.