@damphuquy/agent-init 1.4.4 → 2.0.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # agent-instructions (@damphuquy/agent-init)
2
2
 
3
- > **AI Coding Agent Scaffolding & Orchestration System (RIPER-5 Framework)**
3
+ > **AI Coding Agent Scaffolding & Orchestration System v2.0 (RIPER-5 Framework)**
4
4
 
5
5
  <p align="center">
6
6
  <b>English</b> • <a href="README.vi.md">Tiếng Việt</a>
@@ -8,7 +8,13 @@
8
8
 
9
9
  ---
10
10
 
11
- A structured scaffolding framework for AI Coding Agents following the **RIPER-5 Framework** — cleanly separated into three layers: `AGENTS.md` (project configuration), `.agents/` (agent behavioral controls), and `process/` (task execution and verification workflow).
11
+ A structured scaffolding framework for AI Coding Agents following the **RIPER-5 Framework v2.0** — cleanly separated into three layers: `AGENTS.md` (project configuration), `.agents/` (agent behavioral controls), and `process/` (task execution and verification workflow).
12
+
13
+ Featuring four core **v2.0 Engineering Protocols**:
14
+ * **Subagent Orchestration v2.0:** Parallel vertical slicing with zero write collision and reactive wakeup.
15
+ * **Implementation Standards v2.0:** Strict typing (zero `any`), domain purity, fail-fast boundary validation, and deterministic teardown.
16
+ * **Planning & Slicing Standards v2.0:** INVEST-compliant vertical slices (2–5 per task) with mandatory automated verifiers.
17
+ * **Testing Standards & Harness v2.0:** Deterministic test pyramid with frozen clocks, fixture factories, and strict mocking boundaries.
12
18
 
13
19
  ```bash
14
20
  # Bootstrap immediately into your project (takes 30 seconds)
@@ -23,11 +29,11 @@ Designed for minimal overhead, practical focus, and zero fluff:
23
29
 
24
30
  ### 1. For Daily Development (Start Here)
25
31
  * **[01 · Hands-on Walkthrough from A–Z](docs/en/01-getting-started.md)**: **The core guide to get started in 10–15 minutes**. Step-by-step instructions with **2 practical examples** (Task 1 Strict Track $\rightarrow$ Handoff $\rightarrow$ Task 2 Fast-Track with knowledge inheritance), prompt templates, and quality gate sign-offs.
26
- * **[02 · Daily Cheat Sheet](docs/en/02-cheat-sheet.md)**: Copy-paste prompt templates for each phase, quality gates summary (Gates G0–G3), and file ownership matrix (Human vs Agent).
32
+ * **[02 · Daily Cheat Sheet](docs/en/02-cheat-sheet.md)**: Copy-paste prompt templates for each phase, quality gates summary (Gates G0–G3), subagent delegation prompts, and v2.0 protocol matrix.
27
33
  * **[03 · Advanced Workflows & Production Edge Cases](docs/en/03-advanced-workflows.md)**: Complex real-world scenarios: Epics in `process/features/`, multi-developer concurrency, git rebase conflicts, P0 emergency hotfixes, secret scanning, model switching, complex test harnesses, and task parking (`paused.md`).
28
34
 
29
35
  ### 2. In-Depth Reference (For Tech Leads & Maintainers)
30
- * **[3-Layer Architecture & Context Router](docs/en/reference/architecture.md)**: Deep dive into the 3-layer decoupled architecture and Minimum Sufficient Context principles (No Full-Repo Scan).
36
+ * **[3-Layer Architecture & Context Router (v2.0)](docs/en/reference/architecture.md)**: Deep dive into the 3-layer decoupled architecture, the 11-seed catalog, and the v2.0 Engineering Protocols.
31
37
  * **[DevOps & Release Automation](docs/en/reference/devops-release.md)**: CI/CD release lifecycle, automated Semantic Versioning, and NPM package publishing.
32
38
 
33
39
  ---
package/README.vi.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # agent-instructions (@damphuquy/agent-init)
2
2
 
3
- > **Hệ thống điều phối và khởi tạo AI Coding Agent theo chuẩn RIPER-5**
3
+ > **Hệ thống điều phối và khởi tạo AI Coding Agent v2.0 theo chuẩn RIPER-5**
4
4
 
5
5
  <p align="center">
6
6
  <a href="README.md">English</a> • <b>Tiếng Việt</b>
@@ -8,7 +8,13 @@
8
8
 
9
9
  ---
10
10
 
11
- Hệ thống mẫu (scaffold) điều phối AI Coding Agent theo chuẩn **RIPER-5 Framework** — phân tách thành ba layer rõ ràng: `AGENTS.md` (cấu hình dự án), `.agents/` (quy chuẩn hành vi của Agent), và `process/` (quy trình thực thi task và kiểm thử).
11
+ Hệ thống mẫu (scaffold) điều phối AI Coding Agent theo chuẩn **RIPER-5 Framework v2.0** — phân tách thành ba layer rõ ràng: `AGENTS.md` (cấu hình dự án), `.agents/` (quy chuẩn hành vi của Agent), và `process/` (quy trình thực thi task và kiểm thử).
12
+
13
+ Tích hợp 4 **Giao thức Kỹ thuật v2.0** cốt lõi:
14
+ * **Điều phối Subagent v2.0:** Chia lát cắt song song, không xung đột ghi (zero write collision) và đánh thức phản ứng.
15
+ * **Quy chuẩn Hiện thực Mã nguồn v2.0:** Kiểm soát kiểu nghiêm ngặt (không `any`), domain thuần khiết, fail-fast tại ranh giới và dọn dẹp tài nguyên xác định.
16
+ * **Quy chuẩn Lập kế hoạch & Cắt lát v2.0:** Lát cắt dọc theo chuẩn INVEST (2–5 slice/task) với lệnh kiểm chứng tự động bắt buộc.
17
+ * **Quy chuẩn Kiểm thử & Test Harness v2.0:** Kim tự tháp kiểm thử xác định với đóng băng thời gian (frozen clocks), fixture factories và mock có kiểm soát.
12
18
 
13
19
  ```bash
14
20
  # Khởi tạo ngay vào project của bạn (chỉ mất 30 giây)
@@ -23,11 +29,11 @@ Tài liệu được thiết kế tối giản, tập trung vào thực hành, k
23
29
 
24
30
  ### 1. Dành cho công việc hằng ngày (Bắt đầu tại đây)
25
31
  * 📘 **[01 · Hướng dẫn Thực chiến từ A–Z](docs/vi/01-getting-started.md)**: **Tài liệu cốt lõi để bắt đầu trong 10–15 phút**. Hướng dẫn từng bước với **2 ví dụ thực tế liên hoàn** (Task 1 Strict Track $\rightarrow$ Bàn giao $\rightarrow$ Task 2 Fast-Track kế thừa tri thức), prompt mẫu và cách duyệt qua các cổng.
26
- * ⚡ **[02 · Sổ tay Tra cứu Nhanh (Cheat Sheet)](docs/vi/02-cheat-sheet.md)**: Bảng copy-paste prompt mẫu cho từng giai đoạn, bảng 4 cổng kiểm soát (Gates G0–G3), và ma trận quyền hạn file (Human vs Agent).
32
+ * ⚡ **[02 · Sổ tay Tra cứu Nhanh (Cheat Sheet)](docs/vi/02-cheat-sheet.md)**: Bảng copy-paste prompt mẫu cho từng giai đoạn, bảng 4 cổng kiểm soát (Gates G0–G3), prompt ủy quyền subagent và ma trận giao thức v2.0.
27
33
  * 🚀 **[03 · Quy trình Nâng cao & Tình huống Thực chiến](docs/vi/03-advanced-workflows.md)**: Các kịch bản production phức tạp: Epic trong `process/features/`, đa lập trình viên đồng thời, xử lý xung đột rebase, hotfix P0 khẩn cấp, quét secret bảo mật, đổi model chat, và đóng băng task dài hạn (`paused.md`).
28
34
 
29
35
  ### 2. Tài liệu Chuyên sâu & Tham khảo (Dành cho Lead / Maintainer)
30
- * 🏛️ **[Kiến trúc 3 Tầng & Cơ chế Context Router](docs/vi/reference/architecture.md)**: Giải thích sâu về thiết kế tách rời 3 layer chế nạp ngữ cảnh tối thiểu (No Full-Repo Scan).
36
+ * 🏛️ **[Kiến trúc 3 Tầng & Cơ chế Context Router (v2.0)](docs/vi/reference/architecture.md)**: Giải thích sâu về thiết kế tách rời 3 layer, danh mục 11 seed template 4 Giao thức Kỹ thuật v2.0.
31
37
  * 🚢 **[Cẩm nang DevOps & Tự động hóa Phát hành](docs/vi/reference/devops-release.md)**: Quy trình CI/CD tự động tính Semantic Versioning và publish package lên NPM.
32
38
 
33
39
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@damphuquy/agent-init",
3
- "version": "1.4.4",
3
+ "version": "2.0.0",
4
4
  "description": "Scaffolding CLI to bootstrap RIPER-5 Coding Agents & Operational Workspace",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,6 +24,7 @@ process/
24
24
  │ ├── review-template.md.seed # Review phase artifact (Gate 3)
25
25
  │ ├── handoff-template.md.seed # Final projection (short)
26
26
  │ ├── cancellation-template.md.seed # Knowledge-preserving cancellation record
27
+ │ ├── pause-template.md.seed # Task pause & parking record (temporary blockages)
27
28
  │ ├── results-template.tsv.seed # Benchmark & quantitative metrics tracker
28
29
  │ └── program-template.md.seed # Multi-phase program blueprint
29
30
  ├── context/ # Durable knowledge base & context routers
@@ -45,6 +46,7 @@ process/
45
46
  │ │ ├── review.md # Review phase output
46
47
  │ │ ├── handoff.md # Final projection
47
48
  │ │ ├── results.tsv # (Optional) Benchmark & metric iteration tracking
49
+ │ │ ├── paused.md # (If paused) Parking record & resumption criteria
48
50
  │ │ └── cancelled.md # (If aborted) Cancellation findings & rollback status
49
51
  │ ├── completed/ # Archived task workspaces
50
52
  │ └── backlog/ # Backlog notes: {note_slug}_NOTE_{dd-mm-yy}.md
@@ -107,8 +109,10 @@ handoff.md ← (Complete) Short final projection
107
109
  | Execute | source code + tests + `state.md` |
108
110
  | Review | `review.md` |
109
111
  | Handoff | `handoff.md` |
112
+ | Pause / Park | `paused.md` (clean freeze & resumption criteria upon temporary block) |
110
113
  | Cancellation | `cancelled.md` (knowledge preservation upon abort) |
111
114
  | Benchmark / Metrics | `results.tsv` (performance and eval metrics) |
115
+ | Program | `program.md` (multi-phase umbrella epic blueprint) |
112
116
  | Gate 1 | `decision.md` approval |
113
117
  | Gate 2 | `plan.md` approval |
114
118
  | Gate 3 | `review.md` approval |
@@ -121,6 +121,10 @@ handoff.md ← Final projection (short)
121
121
  | Execute | source code + tests + `state.md` |
122
122
  | Review | `review.md` |
123
123
  | Handoff | `handoff.md` |
124
+ | Pause / Park | `paused.md` (clean freeze & resumption checklist) |
125
+ | Cancellation | `cancelled.md` (knowledge preservation upon abort) |
126
+ | Benchmark / Metrics | `results.tsv` (performance and eval metrics) |
127
+ | Program | `program.md` (multi-phase umbrella epic blueprint) |
124
128
  | Gate 1 | `decision.md` approval |
125
129
  | Gate 2 | `plan.md` approval |
126
130
  | Gate 3 | `review.md` approval |
@@ -6,9 +6,11 @@
6
6
  SECTION 0 — TASK CONTROL (master state record)
7
7
  ════════════════════════════════════════════ -->
8
8
  <task_control>
9
- <status>BACKLOG</status> <!-- BACKLOG | ACTIVE | BLOCKED | REVIEW | COMPLETED -->
9
+ <status>BACKLOG</status> <!-- BACKLOG | ACTIVE | BLOCKED | PAUSED | REVIEW | COMPLETED | CANCELLED -->
10
10
  <spec_level>S1</spec_level> <!-- S0=sketch | S1=defined | S2=verified | S3=locked -->
11
+ <priority>P2</priority> <!-- P0=urgent | P1=high | P2=normal | P3=low -->
11
12
  <risk>MEDIUM</risk> <!-- LOW | MEDIUM | HIGH -->
13
+ <estimated_story_points>2</estimated_story_points> <!-- 1 SP ≈ 2-4 focused engineering hours -->
12
14
  <working_mode>PAIR</working_mode> <!-- MANUAL | PAIR | DELEGATED | DIAGNOSE-ONLY -->
13
15
  <current_phase>RESEARCH</current_phase> <!-- RESEARCH | INNOVATE | PLAN | EXECUTE | REVIEW -->
14
16
  <owner>@engineer</owner>
@@ -63,6 +65,11 @@
63
65
  - `tests/[path/to/test_file]` — [Target assertions and test fixtures]
64
66
  </target_files>
65
67
 
68
+ <context_groups>
69
+ <!-- References to registered context groups from process/context/all-context.md -->
70
+ - [planning | tests | protocols | domain-specific-group]
71
+ </context_groups>
72
+
66
73
  <source_of_truth>
67
74
  <requirement>[Link to requirement or spec]</requirement>
68
75
  <architecture>[Link to architecture doc or ADR]</architecture>
@@ -154,6 +161,7 @@
154
161
  - [ ] Run verifier after each slice.
155
162
  - [ ] Inspect diff after each slice.
156
163
  - [ ] Update `state.md` after each slice.
164
+ - [ ] (Optional) Record quantitative metric deltas in `results.tsv` if tracking benchmarks/performance.
157
165
  </phase>
158
166
 
159
167
  <phase name="Review" order="5">
@@ -26,7 +26,7 @@
26
26
  <group id="seeds">
27
27
  <title>Seeds & Archetypes Guide</title>
28
28
  <path>[`../_seeds/_GUIDE.md`](../_seeds/_GUIDE.md)</path>
29
- <scope>Scaffolding seeds for tasks, research, decisions, plans, state, reviews, handoffs, and programs. Full artifact chain and instantiation commands.</scope>
29
+ <scope>Scaffolding seeds for tasks, research, decisions, plans, state, reviews, handoffs, pause, cancellation, benchmarks, and programs. Full artifact chain and instantiation commands.</scope>
30
30
  </group>
31
31
 
32
32
  <group id="tests">
@@ -1,31 +1,87 @@
1
1
  # Planning Standards & Calibration Context
2
2
 
3
- <planning_context version="1.0">
3
+ <planning_context version="2.0">
4
4
 
5
5
  <overview>
6
- Guidelines for story point estimation, vertical slicing, and capacity calibration.
6
+ Engineering guidelines for story point estimation, vertical slicing, rollback checkpointing, and capacity calibration.
7
7
  </overview>
8
8
 
9
- ## 1. Quality Standards
9
+ ---
10
+
11
+ ## 1. Quality Standards (INVEST Criteria)
12
+
10
13
  <quality_standards>
11
14
  <standard name="INVEST">
12
- - **Independent:** Deliverable without cross-story blockers.
13
- - **Negotiable:** Implementation details are flexibly refined.
14
- - **Valuable:** Delivers measurable user or business value.
15
- - **Estimable:** Scoped clearly to estimate effort.
16
- - **Small:** Fits within 1-3 engineering days.
17
- - **Testable:** Concrete Acceptance Criteria defined.
18
- </standard>
19
-
20
- <standard name="Vertical Slicing">
21
- Avoid horizontal silos. Deliver end-to-end vertical slices across API, logic, and persistence.
15
+ - **Independent:** Deliverable and verifiable without cross-story circular blockers.
16
+ - **Negotiable:** Implementation details and technical approaches can be flexibly evaluated during the Innovate phase.
17
+ - **Valuable:** Delivers demonstrable capability or verifiable engineering progress.
18
+ - **Estimable:** Scoped tightly enough that effort and file touchpoints can be calculated.
19
+ - **Small:** Sized to fit comfortably within 13 engineering days (or 1–3 Story Points).
20
+ - **Testable:** Accompanied by unambiguous, verifiable Acceptance Criteria (`- [ ]`).
22
21
  </standard>
23
22
  </quality_standards>
24
23
 
25
- ## 2. Capacity Calibration
24
+ ---
25
+
26
+ ## 2. Vertical Slicing Discipline
27
+
28
+ <vertical_slicing>
29
+ ### Vertical Slice vs Horizontal Silo
30
+ - **The Vertical Slice Rule:** Each slice must cut through all required technical layers (e.g. Domain Model $\rightarrow$ Service/Logic $\rightarrow$ Port Adapter/API $\rightarrow$ Automated Test) to deliver one complete, verifiable increment of behavior.
31
+ - **The Horizontal Silo Anti-Pattern:** Never slice horizontally (e.g., Slice 1: create all database tables, Slice 2: create all services, Slice 3: create all endpoints). Horizontal layers cannot be verified independently, leaving the system in a broken or unprovable state until the final slice.
32
+
33
+ ### Vertical Slicing Workflow
34
+ ```text
35
+ [Slice 1: Thin End-to-End Core] ──► Domain Entity + In-Memory Repo + Minimal Endpoint + Passing Test
36
+ [Slice 2: Persistence & Boundary] ──► Real Database Adapter + Migration + Integration Verifier
37
+ [Slice 3: Edge Cases & Validation] ──► Strict Input Sanitization + Error Handlers + Boundary Tests
38
+ ```
39
+ </vertical_slicing>
40
+
41
+ ---
42
+
43
+ ## 3. Slice Sizing, Atomic Verifiability & Checkpoints
44
+
45
+ <slice_sizing>
46
+ <rule id="slice_cardinality">
47
+ A standard task should contain between **2 and 5 vertical slices**. If a task requires more than 5 slices, it has high blast radius and must be decomposed into a Multi-Phase Program (`program-template.md.seed`).
48
+ </rule>
49
+
50
+ <rule id="autonomous_verifier">
51
+ Every single slice in `plan.md` must have an explicit, executable `<verifier>` command (e.g. `npm run test -- test/path/test.js` or `pytest tests/unit/test_slice.py`). A slice is NOT complete until its verifier exits with code 0.
52
+ </rule>
53
+
54
+ <rule id="atomic_checkpoint">
55
+ Commit or checkpoint each slice atomically upon verification passing. This guarantees clean git history and enables instant rollback if subsequent slices encounter irrecoverable regressions.
56
+ </rule>
57
+ </slice_sizing>
58
+
59
+ ---
60
+
61
+ ## 4. Rollback Strategy per Slice
62
+
63
+ <rollback_strategy>
64
+ Every slice in `plan.md` MUST specify a concrete `<rollback_point>`:
65
+ - **Git Checkpoint:** `git checkout -- <allowed_files>` or revert commit hash.
66
+ - **Stash Checkpoint:** `git stash pop` or dedicated WIP branch.
67
+ - **Data/Schema Rollback:** Down-migration script or drop ephemeral test container.
68
+
69
+ If the agent exhausts its 3-attempt retry budget on a slice, it must execute the rollback point before halting and escalating to human guidance.
70
+ </rollback_strategy>
71
+
72
+ ---
73
+
74
+ ## 5. Story Point Capacity Calibration
75
+
26
76
  <capacity_calibration>
27
- <unit>1 Story Point ≈ 2-4 focused engineering hours</unit>
28
- <max_task_size>3-5 Story Points (larger tasks must be decomposed)</max_task_size>
77
+ <unit>1 Story Point (SP) ≈ 24 focused engineering hours</unit>
78
+ <scale>
79
+ - **1 SP:** Straightforward change with clear scope (1-3 files touched, 1-2 slices).
80
+ - **2 SP:** Standard feature or refactoring (3-5 files touched, 2-3 slices).
81
+ - **3 SP:** Moderately complex task touching domain contracts and persistence (4-7 files, 3-4 slices).
82
+ - **5 SP:** Maximum size for a single active task in `process/features/active/`.
83
+ - **> 5 SP:** Oversized. Must be split into multiple standalone tasks or organized under `program-template.md.seed`.
84
+ </scale>
29
85
  </capacity_calibration>
30
86
 
31
87
  </planning_context>
@@ -1,56 +1,113 @@
1
1
  # Testing Standards & Harness Strategy Context
2
2
 
3
- <testing_context version="1.0">
3
+ <testing_context version="2.0">
4
4
 
5
5
  <overview>
6
- Guidelines for test pyramid calibration, isolation policies, mock conventions, and automated verification harness across the system.
6
+ Guidelines for test pyramid calibration, isolation policies, mock conventions, fixture hygiene, and automated verification harness across the system.
7
7
  </overview>
8
8
 
9
- ## 1. Test Pyramid & Classification
9
+ ---
10
+
11
+ ## 1. Test Pyramid & Layer Calibration
12
+
10
13
  <test_pyramid>
11
14
  <layer name="Unit Tests" path="tests/unit/">
12
- - Scope: Pure business logic, domain models, utility functions, edge case branching.
13
- - Execution speed: Fast (< 50ms per test), zero network/disk/external I/O.
14
- - Mock policy: Mock all I/O boundaries, external clients, and port interfaces.
15
+ - **Scope:** Pure domain models, business logic calculations, utility functions, edge-case branching.
16
+ - **Speed & Constraints:** Ultra-fast (< 50ms per test). Zero network calls, zero disk I/O, zero real database connections.
17
+ - **Mocking Policy:** Mock all port interfaces, external clients, and I/O boundaries.
15
18
  </layer>
16
19
 
17
20
  <layer name="Integration Tests" path="tests/integration/">
18
- - Scope: Database persistence, external API client adapters, framework wiring.
19
- - Isolation: Ephemeral test containers (e.g. Testcontainers) or dedicated isolated test database per suite.
20
- - Teardown: Must guarantee zero state leakage across test runs.
21
+ - **Scope:** Repository persistence adapters, database queries, migration scripts, HTTP client wrappers, framework wiring.
22
+ - **Isolation:** Ephemeral test containers (e.g. Testcontainers), in-memory databases, or isolated schema instances per test worker.
23
+ - **Teardown:** Must guarantee 100% state cleanup with zero leakage across test runs.
21
24
  </layer>
22
25
 
23
26
  <layer name="End-to-End Tests" path="tests/e2e/">
24
- - Scope: Critical user journeys, full HTTP/gRPC API lifecycle, regression smoke tests.
25
- - Verification: Validates end-to-end contract integrity across subsystems.
27
+ - **Scope:** Critical user journeys, public API lifecycle, full authentication flows, regression smoke tests.
28
+ - **Verification:** Validates end-to-end contract integrity across the entire system.
26
29
  </layer>
27
30
  </test_pyramid>
28
31
 
29
- ## 2. Test Harness Policies
30
- <test_policies>
31
- <policy name="Determinism">
32
- Zero flaky tests. Tests must not depend on real wall-clock time (use frozen clocks or fake timers) or randomized execution order.
33
- </policy>
32
+ ---
33
+
34
+ ## 2. Mocking Boundaries & Anti-Patterns
35
+
36
+ <mocking_boundaries>
37
+ <rule id="mock_at_architectural_boundary">
38
+ **Mock at the boundaries, never at the core.** Only mock external infrastructure: third-party HTTP APIs, message brokers, email services, or system clock.
39
+ </rule>
40
+
41
+ <rule id="do_not_mock_domain_or_sut">
42
+ Never mock the System Under Test (SUT) or pure domain entities/value objects. If a domain entity is hard to instantiate without mocks, its design is coupled and requires refactoring.
43
+ </rule>
44
+
45
+ <rule id="verify_mock_interactions_sparingly">
46
+ Prefer asserting on return values and observable state changes rather than verifying exact method call counts (`toHaveBeenCalledTimes`), which couples tests to private implementation details.
47
+ </rule>
48
+ </mocking_boundaries>
49
+
50
+ ---
51
+
52
+ ## 3. Test Fixture & Data Factory Hygiene
53
+
54
+ <fixture_hygiene>
55
+ <rule id="data_factories_over_preseeded_db">
56
+ Use explicit test factories (or builder functions) with sensible defaults rather than relying on brittle, shared SQL seed dumps.
57
+ </rule>
58
+
59
+ <rule id="no_shared_mutable_fixtures">
60
+ Every test must instantiate its own data fixtures. Never share mutable state or global test variables between tests.
61
+ </rule>
62
+
63
+ <rule id="deterministic_teardown">
64
+ Always clean up database records, temp files, or mock registries in `afterEach` / `teardown` hooks to prevent cascading cross-test failures.
65
+ </rule>
66
+ </fixture_hygiene>
67
+
68
+ ---
69
+
70
+ ## 4. Determinism & Flaky Test Zero-Tolerance
71
+
72
+ <determinism>
73
+ <rule id="frozen_clock">
74
+ Never use real wall-clock time (`Date.now()`, `datetime.now()`) in time-sensitive assertions. Use frozen clocks or fake timers to ensure absolute reproducibility.
75
+ </rule>
76
+
77
+ <rule id="order_independence">
78
+ Tests must pass when run individually or in random order (`--randomize`). Never rely on one test running before another.
79
+ </rule>
80
+
81
+ <rule id="no_arbitrary_sleeps">
82
+ Never use arbitrary `sleep(1000)` in async tests. Use explicit polling helpers with timeouts (`waitFor`, `eventually`) that resolve as soon as the expected condition is met.
83
+ </rule>
84
+ </determinism>
85
+
86
+ ---
87
+
88
+ ## 5. Assertion Precision & Failure Clarity
89
+
90
+ <assertion_precision>
91
+ <rule id="exact_assertions">
92
+ Avoid vague assertions (e.g. `expect(res).toBeTruthy()`). Always assert exact expected values, HTTP status codes, and error codes.
93
+ </rule>
34
94
 
35
- <policy name="Clean State">
36
- Every test must seed its own data or fixtures. Tests must never assume pre-existing database rows.
37
- </policy>
95
+ <rule id="actionable_failure_messages">
96
+ When custom assertions are used, provide clear error messages indicating what input was given and what specific invariant was violated.
97
+ </rule>
98
+ </assertion_precision>
38
99
 
39
- <policy name="Assertion Precision">
40
- Avoid vague assertions (e.g. `expect(res).toBeTruthy()`). Always assert exact expected structures, status codes, and error types.
41
- </policy>
100
+ ---
42
101
 
43
- <policy name="Fast Feedback">
44
- Unit tests must execute in under 30 seconds for the entire suite. Slow integration suites must be cleanly partitioned.
45
- </policy>
46
- </test_policies>
102
+ ## 6. Verification Commands Mapping
47
103
 
48
- ## 3. Verification Commands Mapping
49
104
  <verification_commands>
50
105
  <!-- Keep aligned with AGENTS.md <validation_commands> -->
51
- <command type="unit">Run fast unit test suite</command>
52
- <command type="integration">Run integration/e2e tests</command>
53
- <command type="coverage">Run test coverage check</command>
106
+ <command type="unit">Run fast unit test suite (< 30 seconds total)</command>
107
+ <command type="integration">Run isolated integration/e2e tests</command>
108
+ <command type="typecheck">Run static type checker (zero errors, strict mode)</command>
109
+ <command type="lint">Run linter and format checker (zero warnings)</command>
110
+ <command type="coverage">Run test coverage report and threshold check</command>
54
111
  </verification_commands>
55
112
 
56
113
  </testing_context>
@@ -1,28 +1,117 @@
1
1
  # Implementation & Harness Standards
2
2
 
3
- <implementation_standards version="1.0">
3
+ <implementation_standards version="2.0">
4
4
 
5
5
  <description>
6
- Engineering quality, type safety, and testing conventions for this codebase.
6
+ Engineering quality, strict typing, clean architecture, and defensive execution conventions. Project-agnostic.
7
7
  </description>
8
8
 
9
- ## 1. Type Safety & Code Hygiene
10
- <conventions>
9
+ ---
10
+
11
+ ## 1. Type Safety & Static Analysis
12
+
13
+ <type_safety>
11
14
  <rule id="strict_typing">
12
- All functions, methods, and class attributes must have explicit type annotations. Use modern union types (`int | None` or `string | null`) and avoid untyped `Any`/`any` unless interfacing with raw external payloads.
15
+ All functions, methods, and class attributes must have explicit type annotations. Use modern union types (`int | None` or `string | null`). Avoid untyped `Any`/`any` unless deserializing unvalidated external payloads at boundary gateways.
16
+ </rule>
17
+
18
+ <rule id="explicit_return_types">
19
+ Always declare explicit return types on public functions and methods to enforce compile-time contracts and prevent accidental type widening.
20
+ </rule>
21
+
22
+ <rule id="no_suppression">
23
+ Never silence linter, formatter, or type-checker errors with inline suppression directives (`# type: ignore`, `eslint-disable`, `@SuppressWarnings`) to artificially pass a validation gate. Fix the underlying root cause.
13
24
  </rule>
25
+ </type_safety>
26
+
27
+ ---
28
+
29
+ ## 2. Clean Architecture & Layered Domain Purity
30
+
31
+ <clean_architecture>
32
+ <rule id="dependency_rule">
33
+ Dependencies must only point inward toward the core domain. Inner domain layers must never import or depend on outer infrastructure frameworks, databases, or UI modules.
34
+ </rule>
35
+
14
36
  <rule id="domain_purity">
15
- Code in domain layers must remain pure with zero external infrastructure dependencies.
37
+ Core business logic, domain entities, and value objects must remain 100% pure with zero side-effects, zero filesystem I/O, and zero network calls.
16
38
  </rule>
17
- <rule id="immutability">
18
- Prefer immutable models for domain events, value objects, and DTOs.
39
+
40
+ <rule id="ports_and_adapters">
41
+ Define abstract interfaces (ports) in the application/domain layer for persistence, external APIs, and messaging. Implement concrete drivers (adapters) strictly within infrastructure packages.
42
+ </rule>
43
+
44
+ <rule id="no_premature_abstraction">
45
+ Do not introduce speculative abstraction layers, dynamic factories, or unnecessary indirection for simple single-purpose utilities.
46
+ </rule>
47
+ </clean_architecture>
48
+
49
+ ---
50
+
51
+ ## 3. Error Handling & Fail-Fast Principles
52
+
53
+ <error_handling>
54
+ <rule id="fail_fast_at_boundaries">
55
+ Validate all incoming parameters, payloads, and environment variables at system entrypoints. Reject malformed input immediately before invoking business logic.
56
+ </rule>
57
+
58
+ <rule id="no_silent_swallowing">
59
+ Never use empty `catch {}`, `except: pass`, or unlogged exception handlers. Every caught exception must either be handled, transformed into a typed domain error, or cleanly propagated.
60
+ </rule>
61
+
62
+ <rule id="typed_domain_errors">
63
+ Create explicit domain error classes with machine-readable error codes (e.g. `ResourceNotFoundError`, `ValidationError`, `ConcurrencyConflictError`) rather than throwing generic exceptions.
19
64
  </rule>
20
- </conventions>
65
+ </error_handling>
21
66
 
22
- ## 2. Test Architecture
23
- <test_structure>
24
- - `tests/unit/`: Fast, isolated tests for domain models, core logic, and mock adapters.
25
- - `tests/integration/`: End-to-end flow tests with test services or local databases.
26
- </test_structure>
67
+ ---
68
+
69
+ ## 4. Immutability & Concurrency Safety
70
+
71
+ <concurrency_and_immutability>
72
+ <rule id="immutable_data_structures">
73
+ Prefer immutable models (`dataclass(frozen=True)`, `readonly` interfaces, or `Readonly<T>`) for domain events, configuration objects, and Data Transfer Objects (DTOs).
74
+ </rule>
75
+
76
+ <rule id="no_shared_mutable_state">
77
+ Avoid global mutable variables, module-level state caches, or singletons with mutable fields. Pass dependencies explicitly via constructors (Dependency Injection).
78
+ </rule>
79
+
80
+ <rule id="safe_async_lifecycle">
81
+ Always handle asynchronous error rejection and cancellation cleanly. Ensure timeouts are specified for external network calls and database queries.
82
+ </rule>
83
+ </concurrency_and_immutability>
84
+
85
+ ---
86
+
87
+ ## 5. Observability & Logging Hygiene
88
+
89
+ <observability_hygiene>
90
+ <rule id="structured_logging">
91
+ Use structured logging with key-value context (`task_id`, `user_id`, `component`) instead of unstructured string concatenation.
92
+ </rule>
93
+
94
+ <rule id="no_credential_leakage">
95
+ Never log sensitive data: passwords, tokens, API keys, cookies, or personally identifiable information (PII).
96
+ </rule>
97
+
98
+ <rule id="clean_production_diff">
99
+ Remove all temporary debug logs (`console.log`, `print()`, `debugger`, `dump()`) before requesting Gate G3 sign-off.
100
+ </rule>
101
+ </observability_hygiene>
102
+
103
+ ---
104
+
105
+ ## 6. Defensive Resource Management & Teardown
106
+
107
+ <resource_management>
108
+ <rule id="deterministic_teardown">
109
+ Always manage file handles, network sockets, and database transactions using deterministic scoping constructs (`try...finally`, Python `with`, TypeScript `using`, or language-native RAII).
110
+ </rule>
111
+
112
+ <rule id="isolated_test_state">
113
+ Test fixtures must create and destroy their own temporary state. Tests must leave the system in a clean state upon completion.
114
+ </rule>
115
+ </resource_management>
27
116
 
28
117
  </implementation_standards>