maestro-flow 0.3.43 → 0.3.44

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 (169) hide show
  1. package/.claude/commands/learn-decompose.md +10 -15
  2. package/.claude/commands/learn-follow.md +11 -16
  3. package/.claude/commands/learn-investigate.md +18 -22
  4. package/.claude/commands/learn-retro.md +23 -26
  5. package/.claude/commands/learn-second-opinion.md +11 -16
  6. package/.claude/commands/maestro-analyze.md +8 -0
  7. package/.claude/commands/maestro-brainstorm.md +8 -0
  8. package/.claude/commands/maestro-execute.md +11 -3
  9. package/.claude/commands/maestro-learn.md +4 -4
  10. package/.claude/commands/maestro-milestone-complete.md +6 -6
  11. package/.claude/commands/maestro-plan.md +8 -0
  12. package/.claude/commands/maestro-ralph-execute.md +1 -2
  13. package/.claude/commands/maestro-tools-execute.md +117 -0
  14. package/.claude/commands/maestro-tools-register.md +137 -0
  15. package/.claude/commands/maestro-ui-codify.md +67 -0
  16. package/.claude/commands/manage-harvest.md +1 -1
  17. package/.claude/commands/manage-learn.md +5 -7
  18. package/.claude/commands/manage-wiki.md +1 -1
  19. package/.claude/commands/quality-auto-test.md +1 -1
  20. package/.claude/commands/quality-debug.md +8 -0
  21. package/.claude/commands/quality-retrospective.md +4 -5
  22. package/.claude/commands/quality-review.md +8 -0
  23. package/.claude/commands/spec-add.md +25 -4
  24. package/.claude/commands/spec-load.md +26 -6
  25. package/.claude/commands/spec-setup.md +2 -2
  26. package/.claude/commands/wiki-connect.md +1 -1
  27. package/.claude/commands/wiki-digest.md +5 -6
  28. package/.claude/skills/codify-to-knowhow/SKILL.md +167 -0
  29. package/.claude/skills/codify-to-knowhow/phases/01-load-manifest.md +101 -0
  30. package/.claude/skills/codify-to-knowhow/phases/02-generate-knowhow.md +97 -0
  31. package/.claude/skills/codify-to-knowhow/phases/03-generate-specs.md +92 -0
  32. package/.claude/skills/codify-to-knowhow/phases/04-index-verify.md +119 -0
  33. package/.codex/skills/codify-to-knowhow/SKILL.md +427 -0
  34. package/.codex/skills/learn-decompose/SKILL.md +8 -8
  35. package/.codex/skills/learn-follow/SKILL.md +6 -6
  36. package/.codex/skills/learn-investigate/SKILL.md +4 -4
  37. package/.codex/skills/learn-retro/SKILL.md +7 -7
  38. package/.codex/skills/learn-second-opinion/SKILL.md +6 -6
  39. package/.codex/skills/maestro-analyze/SKILL.md +491 -491
  40. package/.codex/skills/maestro-collab/SKILL.md +1 -1
  41. package/.codex/skills/maestro-learn/SKILL.md +1 -1
  42. package/.codex/skills/maestro-milestone-complete/SKILL.md +122 -122
  43. package/.codex/skills/maestro-plan/SKILL.md +485 -485
  44. package/.codex/skills/maestro-tools-execute/SKILL.md +105 -0
  45. package/.codex/skills/maestro-tools-register/SKILL.md +144 -0
  46. package/.codex/skills/maestro-ui-codify/SKILL.md +398 -0
  47. package/.codex/skills/maestro-verify/SKILL.md +486 -486
  48. package/.codex/skills/manage-harvest/SKILL.md +3 -3
  49. package/.codex/skills/manage-issue-discover/SKILL.md +431 -431
  50. package/.codex/skills/manage-learn/SKILL.md +13 -13
  51. package/.codex/skills/manage-wiki/SKILL.md +1 -1
  52. package/.codex/skills/quality-auto-test/SKILL.md +553 -553
  53. package/.codex/skills/quality-refactor/SKILL.md +151 -151
  54. package/.codex/skills/quality-retrospective/SKILL.md +6 -6
  55. package/.codex/skills/spec-add/SKILL.md +17 -4
  56. package/.codex/skills/spec-load/SKILL.md +24 -28
  57. package/.codex/skills/team-quality-assurance/roles/executor/role.md +1 -1
  58. package/.codex/skills/team-review/roles/reviewer/role.md +1 -1
  59. package/.codex/skills/team-tech-debt/roles/scanner/role.md +1 -1
  60. package/.codex/skills/team-testing/roles/executor/role.md +1 -1
  61. package/.codex/skills/team-testing/roles/generator/role.md +1 -1
  62. package/.codex/skills/wiki-connect/SKILL.md +5 -5
  63. package/.codex/skills/wiki-digest/SKILL.md +8 -8
  64. package/dashboard/dist-server/dashboard/src/server/routes/specs.js +1 -1
  65. package/dashboard/dist-server/dashboard/src/server/routes/specs.js.map +1 -1
  66. package/dashboard/dist-server/dashboard/src/server/routes/wiki.js +2 -1
  67. package/dashboard/dist-server/dashboard/src/server/routes/wiki.js.map +1 -1
  68. package/dashboard/dist-server/dashboard/src/server/state/fs-watcher.js +2 -2
  69. package/dashboard/dist-server/dashboard/src/server/state/fs-watcher.js.map +1 -1
  70. package/dashboard/dist-server/dashboard/src/server/supervisor/self-learning-service.d.ts +1 -1
  71. package/dashboard/dist-server/dashboard/src/server/supervisor/self-learning-service.js +1 -1
  72. package/dashboard/dist-server/dashboard/src/server/supervisor/self-learning-service.js.map +1 -1
  73. package/dashboard/dist-server/dashboard/src/server/wiki/search.js +2 -2
  74. package/dashboard/dist-server/dashboard/src/server/wiki/search.js.map +1 -1
  75. package/dashboard/dist-server/dashboard/src/server/wiki/spec-entry-parser.d.ts +7 -3
  76. package/dashboard/dist-server/dashboard/src/server/wiki/spec-entry-parser.js +47 -15
  77. package/dashboard/dist-server/dashboard/src/server/wiki/spec-entry-parser.js.map +1 -1
  78. package/dashboard/dist-server/dashboard/src/server/wiki/stress.test.js +1 -1
  79. package/dashboard/dist-server/dashboard/src/server/wiki/stress.test.js.map +1 -1
  80. package/dashboard/dist-server/dashboard/src/server/wiki/virtual-wiki-adapters.d.ts +1 -2
  81. package/dashboard/dist-server/dashboard/src/server/wiki/virtual-wiki-adapters.js +3 -52
  82. package/dashboard/dist-server/dashboard/src/server/wiki/virtual-wiki-adapters.js.map +1 -1
  83. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.js +67 -21
  84. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.js.map +1 -1
  85. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-types.d.ts +6 -1
  86. package/dashboard/dist-server/dashboard/src/server/wiki/writer-stress.test.js +1 -11
  87. package/dashboard/dist-server/dashboard/src/server/wiki/writer-stress.test.js.map +1 -1
  88. package/dashboard/dist-server/dashboard/src/server/wiki/writer.d.ts +7 -4
  89. package/dashboard/dist-server/dashboard/src/server/wiki/writer.js +27 -12
  90. package/dashboard/dist-server/dashboard/src/server/wiki/writer.js.map +1 -1
  91. package/dashboard/dist-server/src/tools/spec-entry-parser.d.ts +10 -2
  92. package/dashboard/dist-server/src/tools/spec-entry-parser.js +46 -12
  93. package/dashboard/dist-server/src/tools/spec-entry-parser.js.map +1 -1
  94. package/dashboard/dist-server/src/tools/spec-loader.d.ts +6 -2
  95. package/dashboard/dist-server/src/tools/spec-loader.js +119 -23
  96. package/dashboard/dist-server/src/tools/spec-loader.js.map +1 -1
  97. package/dist/src/commands/knowhow.d.ts.map +1 -1
  98. package/dist/src/commands/knowhow.js +21 -2
  99. package/dist/src/commands/knowhow.js.map +1 -1
  100. package/dist/src/commands/spec.d.ts +1 -1
  101. package/dist/src/commands/spec.d.ts.map +1 -1
  102. package/dist/src/commands/spec.js +78 -4
  103. package/dist/src/commands/spec.js.map +1 -1
  104. package/dist/src/commands/wiki.d.ts.map +1 -1
  105. package/dist/src/commands/wiki.js +51 -3
  106. package/dist/src/commands/wiki.js.map +1 -1
  107. package/dist/src/hooks/keyword-spec-injector.js +1 -1
  108. package/dist/src/hooks/keyword-spec-injector.js.map +1 -1
  109. package/dist/src/hooks/plugins/spec-injection-plugin.js +11 -11
  110. package/dist/src/hooks/plugins/spec-injection-plugin.js.map +1 -1
  111. package/dist/src/hooks/spec-injector.d.ts +1 -0
  112. package/dist/src/hooks/spec-injector.d.ts.map +1 -1
  113. package/dist/src/hooks/spec-injector.js +55 -22
  114. package/dist/src/hooks/spec-injector.js.map +1 -1
  115. package/dist/src/hooks/wiki-role-loader.d.ts +18 -0
  116. package/dist/src/hooks/wiki-role-loader.d.ts.map +1 -0
  117. package/dist/src/hooks/wiki-role-loader.js +43 -0
  118. package/dist/src/hooks/wiki-role-loader.js.map +1 -0
  119. package/dist/src/tools/spec-entry-parser.d.ts +10 -2
  120. package/dist/src/tools/spec-entry-parser.d.ts.map +1 -1
  121. package/dist/src/tools/spec-entry-parser.js +46 -12
  122. package/dist/src/tools/spec-entry-parser.js.map +1 -1
  123. package/dist/src/tools/spec-init.d.ts.map +1 -1
  124. package/dist/src/tools/spec-init.js +19 -0
  125. package/dist/src/tools/spec-init.js.map +1 -1
  126. package/dist/src/tools/spec-loader.d.ts +6 -2
  127. package/dist/src/tools/spec-loader.d.ts.map +1 -1
  128. package/dist/src/tools/spec-loader.js +119 -23
  129. package/dist/src/tools/spec-loader.js.map +1 -1
  130. package/dist/src/tools/spec-writer.d.ts +6 -1
  131. package/dist/src/tools/spec-writer.d.ts.map +1 -1
  132. package/dist/src/tools/spec-writer.js +29 -2
  133. package/dist/src/tools/spec-writer.js.map +1 -1
  134. package/dist/src/tools/store-knowhow.d.ts.map +1 -1
  135. package/dist/src/tools/store-knowhow.js +56 -27
  136. package/dist/src/tools/store-knowhow.js.map +1 -1
  137. package/package.json +1 -1
  138. package/workflows/analyze.md +2 -2
  139. package/workflows/auto-test.md +2 -2
  140. package/workflows/brainstorm.md +1 -1
  141. package/workflows/codebase-rebuild.md +1 -1
  142. package/workflows/codebase-refresh.md +1 -1
  143. package/workflows/debug.md +1 -1
  144. package/workflows/execute.md +3 -3
  145. package/workflows/harvest.md +13 -13
  146. package/workflows/integration-test.md +2 -2
  147. package/workflows/issue-discover.md +1 -1
  148. package/workflows/knowhow.md +72 -11
  149. package/workflows/learn.md +70 -58
  150. package/workflows/map.md +1 -1
  151. package/workflows/milestone-complete.md +2 -2
  152. package/workflows/plan.md +1 -1
  153. package/workflows/quick.md +1 -1
  154. package/workflows/refactor.md +1 -1
  155. package/workflows/retrospective.md +51 -57
  156. package/workflows/review.md +1 -1
  157. package/workflows/roadmap-common.md +1 -1
  158. package/workflows/specs-add.md +11 -2
  159. package/workflows/specs-load.md +17 -15
  160. package/workflows/test-gen.md +1 -1
  161. package/workflows/tools-spec.md +98 -0
  162. package/workflows/ui-codify-extract.md +373 -0
  163. package/workflows/ui-codify-knowhow.md +258 -0
  164. package/workflows/ui-codify-package.md +161 -0
  165. package/workflows/ui-codify.md +225 -0
  166. package/workflows/verify.md +1 -1
  167. package/workflows/wiki-connect.md +7 -7
  168. package/workflows/wiki-digest.md +13 -13
  169. package/workflows/wiki-manage.md +1 -1
@@ -1,553 +1,553 @@
1
- ---
2
- name: quality-auto-test
3
- description: Auto-generate and run tests from specs or coverage gaps
4
- argument-hint: "<phase> [-y] [-c N] [--max-iter N] [--layer L0-L3] [--dry-run] [--re-run]"
5
- allowed-tools: spawn_agents_on_csv, Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion
6
- ---
7
-
8
- <purpose>
9
- Unified automated testing using `spawn_agents_on_csv` for parallel test writing and failure diagnosis. Reads project state to auto-select scenario source (PRD specs, coverage gaps, or code exploration). All sources converge into a shared CSV pipeline: discover infrastructure → plan → write tests via CSV parallel → execute per layer → diagnose failures via CSV parallel → iterate → report.
10
-
11
- **Core workflow**: Route → Source Scenarios → Build CSV → Layer-by-Layer Parallel Execution → Iterate (Diagnose CSV) → Report
12
-
13
- **Topology**: Layers as waves (L0→L1→L2→L3 sequential, scenarios within layer parallel)
14
-
15
- ```
16
- +---------------------------------------------------------------------------+
17
- | AUTO-TEST CSV LAYER PIPELINE |
18
- +---------------------------------------------------------------------------+
19
- | |
20
- | Phase 1: Route & Plan -> CSV |
21
- | +-- Read project state, auto-select route (spec/gap/code) |
22
- | +-- Extract scenarios per route, normalize to unified format |
23
- | +-- Discover test infrastructure (framework, patterns) |
24
- | +-- Build scenarios.csv with one row per scenario |
25
- | +-- Layers = waves (L1, L2, L3 sequential; L0 = static pre-check) |
26
- | +-- User validates test plan (skip if -y) |
27
- | |
28
- | Phase 2: Layer Execution Engine (write + run) |
29
- | +-- L0: Static analysis (tsc + eslint) — no CSV needed |
30
- | +-- For each layer L1→L3 (sequential, fail-fast on critical): |
31
- | | +-- Layer N: Write Tests (parallel via spawn_agents_on_csv) |
32
- | | | +-- Each agent writes one test file (RED-GREEN) |
33
- | | | +-- Agent reads target source + infrastructure patterns |
34
- | | | +-- Agent verifies RED (run test, check it targets behavior) |
35
- | | | +-- Results: test_file written, red_result, findings |
36
- | | +-- Merge write-results into master scenarios.csv |
37
- | | +-- Run all layer tests together (full layer execution) |
38
- | | +-- Record per-scenario pass/fail results |
39
- | |
40
- | Phase 3: Iteration Engine (diagnose + fix) |
41
- | +-- OUTER LOOP (max_iter iterations): |
42
- | | +-- For each layer with failures: |
43
- | | | +-- Build diagnosis.csv from failed scenarios |
44
- | | | +-- Diagnose & Fix (parallel via spawn_agents_on_csv) |
45
- | | | | +-- Each agent classifies one failure cluster |
46
- | | | | +-- test_defect: agent provides fix diff |
47
- | | | | +-- code_defect: agent documents evidence |
48
- | | | +-- Apply test_defect fixes, re-run layer |
49
- | | +-- Reflect: analyze trends, log strategy |
50
- | | +-- Adjust: select next strategy (conservative/aggressive/...) |
51
- | | +-- Convergence check: >=95% → done |
52
- | +-- discoveries.ndjson shared across all iterations |
53
- | |
54
- | Phase 4: Results & Routing |
55
- | +-- Export results.csv |
56
- | +-- Write report.json, state.json, reflection-log.md |
57
- | +-- Conditional: traceability.md, issue creation |
58
- | +-- Route to next step based on convergence |
59
- | |
60
- +---------------------------------------------------------------------------+
61
- ```
62
- </purpose>
63
-
64
- <context>
65
- ```bash
66
- $quality-auto-test "3" # auto-detect source, full iteration
67
- $quality-auto-test -c 4 "3" # max 4 concurrent test writers per layer
68
- $quality-auto-test -y "3 --max-iter 1" # single-pass generation only
69
- $quality-auto-test "3 --dry-run" # plan only, no execution
70
- $quality-auto-test "3 --re-run" # re-run only previously failed scenarios
71
- $quality-auto-test "3 --layer L2" # restrict to L2 integration tests
72
- ```
73
-
74
- **Flags**:
75
- - `-y, --yes`: Skip all confirmations
76
- - `-c, --concurrency N`: Max concurrent agents within each layer (default: 5)
77
- - `--max-iter N`: Max outer iterations (default 5). **1 = single-pass** generation only
78
- - `--layer L`: Start from or restrict to specific layer (L0|L1|L2|L3)
79
- - `--strategy conservative|aggressive|surgical|reflective`: Override starting iteration strategy (default: auto-selected)
80
- - `--dry-run`: Generate test plan only, do not execute
81
- - `--re-run`: Re-run only previously failed/blocked scenarios
82
-
83
- **Intelligent routing** (auto-detected, priority order):
84
-
85
- | Priority | Condition | Route |
86
- |----------|-----------|-------|
87
- | 1 | Active session (state.json status=running) | Resume |
88
- | 2 | --re-run flag + previous failures | Re-run |
89
- | 3 | Spec package exists (REQ-*.md) | spec (PRD-forward) |
90
- | 4 | Nyquist gaps exist (verification.json) | gap (coverage-forward) |
91
- | 5 | Default | code (exploration-forward) |
92
-
93
- **Session Directory**: `.tests/auto-test/.csv-session/`
94
- **Core Output**: `scenarios.csv` (master state) + `results.csv` (final) + `discoveries.ndjson` (shared) + `report.json` + `state.json`
95
- </context>
96
-
97
- <csv_schema>
98
-
99
- ### scenarios.csv (Master State — Test Writing Phase)
100
-
101
- ```csv
102
- id,name,layer,priority,category,target_file,test_file,description,test_cases,fixtures,req_ref,infrastructure_hints,prev_context,status,red_result,findings,error
103
- "AT-001","Auth token validation","L1","critical","api_contract","src/auth/token.ts","src/auth/__tests__/token.test.ts","Validate JWT token verification returns correct payload","verify valid token returns payload;verify expired token throws;verify malformed token throws","valid_token fixture;expired_token fixture","REQ-001:AC-1","vitest;describe/it pattern;see src/utils/__tests__/hash.test.ts","","","","",""
104
- "AT-002","Login endpoint integration","L2","high","business_rule","src/routes/login.ts","src/routes/__tests__/login.integration.test.ts","POST /api/login returns JWT on valid credentials","valid login returns 200+token;invalid password returns 401;missing email returns 400","user_fixture;credentials_fixture","REQ-002:AC-1","supertest;see src/routes/__tests__/health.test.ts","AT-001 findings: token module exports verifyToken/generateToken","","","",""
105
- ```
106
-
107
- **Columns**:
108
-
109
- | Column | Phase | Description |
110
- |--------|-------|-------------|
111
- | `id` | Input | Scenario ID (AT-NNN format) |
112
- | `name` | Input | Short scenario name |
113
- | `layer` | Input | L1/L2/L3 (determines wave order) |
114
- | `priority` | Input | critical/high/medium |
115
- | `category` | Input | api_contract/business_rule/state_transition/user_flow/... |
116
- | `target_file` | Input | Source file being tested |
117
- | `test_file` | Input | Target test file path to create |
118
- | `description` | Input | What this scenario validates |
119
- | `test_cases` | Input | Semicolon-separated test cases |
120
- | `fixtures` | Input | Required fixtures/mocks (semicolon-separated) |
121
- | `req_ref` | Input | Requirement reference (REQ-NNN:AC-N or gap-id or empty) |
122
- | `infrastructure_hints` | Input | Framework + pattern references from Step 3 |
123
- | `prev_context` | Computed | Findings from prior layer scenarios (cross-layer propagation) |
124
- | `status` | Output | pending → written → passed → failed → blocked |
125
- | `red_result` | Output | expected_fail / unexpected_fail / pass (RED phase result) |
126
- | `findings` | Output | Implementation notes, patterns discovered (max 500 chars) |
127
- | `error` | Output | Error message if failed |
128
-
129
- ### diagnosis.csv (Iteration Phase — Failure Diagnosis)
130
-
131
- ```csv
132
- id,scenario_id,layer,test_file,error_detail,expected,actual,target_file,source_context,classification,fix_code,evidence,error
133
- "DX-001","AT-003","L1","src/auth/__tests__/token.test.ts","TypeError: verifyToken is not a function","verifyToken returns decoded payload","Function not exported from module","src/auth/token.ts","token.ts exports: generateToken only","test_defect","import { verifyToken } from '../token' → import { verifyToken } from '../verify-token'","src/auth/verify-token.ts:15 exports verifyToken",""
134
- "DX-002","AT-005","L2","src/routes/__tests__/login.test.ts","Expected 200, received 500","POST /login returns 200 with valid credentials","Internal server error: database connection refused","src/routes/login.ts","login.ts calls UserModel.findByEmail","env_issue","","Database not available in test environment",""
135
- ```
136
-
137
- **Columns**:
138
-
139
- | Column | Phase | Description |
140
- |--------|-------|-------------|
141
- | `id` | Input | Diagnosis ID (DX-NNN) |
142
- | `scenario_id` | Input | Reference to AT-NNN scenario |
143
- | `layer` | Input | Layer where failure occurred |
144
- | `test_file` | Input | Test file that failed |
145
- | `error_detail` | Input | Full error message/stack trace excerpt |
146
- | `expected` | Input | Expected behavior from scenario |
147
- | `actual` | Input | Actual behavior observed |
148
- | `target_file` | Input | Source file being tested |
149
- | `source_context` | Input | Relevant source code context (exports, imports) |
150
- | `classification` | Output | test_defect / code_defect / env_issue |
151
- | `fix_code` | Output | Fix diff for test_defect (old → new) |
152
- | `evidence` | Output | file:line references for diagnosis |
153
- | `error` | Output | Agent error if diagnosis failed |
154
-
155
- ### Session Structure
156
-
157
- ```
158
- .tests/auto-test/.csv-session/
159
- +-- scenarios.csv (master state)
160
- +-- results.csv (final export)
161
- +-- discoveries.ndjson (shared across iterations)
162
- +-- layer-L{N}-write.csv (temporary, per-layer write input)
163
- +-- layer-L{N}-write-results.csv
164
- +-- diagnosis-iter-{N}.csv (temporary, per-iteration diagnosis)
165
- +-- diagnosis-iter-{N}-results.csv
166
- ```
167
- </csv_schema>
168
-
169
- <invariants>
170
- 1. **Start Immediately**: First action is session initialization
171
- 2. **Layer Order is Sacred**: Never execute L(N+1) before L(N) completes (fail-fast on critical)
172
- 3. **CSV is Source of Truth**: Master scenarios.csv holds all test execution state
173
- 4. **Context Propagation**: prev_context built from prior-layer findings in CSV, not memory
174
- 5. **Discovery Board Append-Only**: Never clear or modify discoveries.ndjson
175
- 6. **Route Auto-Detected**: Read state, never ask user for mode
176
- 7. **RED-GREEN Methodology**: Tests target real behavior; failing test = bug discovery (never fix source)
177
- 8. **Max 3 Inner Fix Attempts**: Per layer, fix test_defects up to 3 times via diagnosis CSV
178
- 9. **Convergence Threshold**: 95% pass rate = converged
179
- 10. **DO NOT STOP**: Continuous execution until convergence, max_iter, or all remaining = code_defect
180
- </invariants>
181
-
182
- <execution>
183
-
184
- ### Session Initialization
185
-
186
- ```
187
- Parse from $ARGUMENTS:
188
- AUTO_YES ← --yes | -y
189
- maxConcurrency ← --concurrency | -c N (default: 5)
190
- MAX_ITER ← --max-iter N (default: 5)
191
- layerFilter ← --layer L (default: null = all)
192
- startStrategy ← --strategy conservative|aggressive|surgical|reflective (default: null = auto)
193
- dryRun ← --dry-run
194
- reRun ← --re-run
195
- phaseArg ← remaining text
196
-
197
- Derive:
198
- dateStr ← UTC+8 YYYYMMDD
199
- sessionFolder ← ".tests/auto-test/.csv-session"
200
-
201
- mkdir -p {sessionFolder}
202
- ```
203
-
204
- ### Phase 1: Route & Plan → CSV
205
-
206
- #### Step 0: Parse & Load
207
-
208
- Resolve phase dir from `state.json` artifact registry (`type='execute'`, matching phase). Error E002 if not found.
209
-
210
- ```
211
- specs_test = maestro spec load --category test
212
- specs_arch = maestro spec load --category arch
213
- ```
214
-
215
- #### Step 1: Read State & Route
216
-
217
- ```
218
- Priority: Resume > Re-run > Spec > Gap > Code
219
-
220
- 1. RESUME: .csv-session/scenarios.csv exists AND state.json status == "running"
221
- → offer resume or restart (resume = reload CSV, jump to current iteration)
222
-
223
- 2. RE-RUN: --re-run flag AND report.json has failed/blocked scenarios
224
- → load failed scenarios into CSV with status reset to pending
225
-
226
- 3. SPEC: .workflow/.spec/SPEC-*/requirements/REQ-*.md exists
227
- → ROUTE = "spec", SPEC_MODE = "full" | "degraded"
228
-
229
- 4. GAP: verification.json has gaps[] (MISSING/PARTIAL)
230
- → ROUTE = "gap"
231
-
232
- 5. CODE: Default fallback → ROUTE = "code"
233
- ```
234
-
235
- #### Step 2: Source Scenarios
236
-
237
- Execute route-specific extraction, normalize to unified format.
238
-
239
- **Route A: spec** — Parse REQ acceptance criteria, classify layers, generate fixtures.
240
- **Route B: gap** — Read verification/coverage gaps, classify files by type.
241
- **Route C: code** — Explore module boundaries, API endpoints, integration points.
242
-
243
- All routes produce unified scenario objects (see csv_schema).
244
-
245
- #### Step 3: Discover Infrastructure
246
-
247
- Detect framework, read 2-3 existing tests for patterns. Build `infrastructure_hints` string per scenario.
248
-
249
- #### Step 4: Build scenarios.csv & Confirm
250
-
251
- 1. Build master `scenarios.csv` — one row per scenario, grouped by layer
252
- 2. Set `prev_context` for L2 scenarios from L1 scenario descriptions (cross-layer dependency)
253
- 3. Set `prev_context` for L3 from L2 findings
254
-
255
- Display plan summary:
256
- ```
257
- === AUTO-TEST PLAN ===
258
- 来源: {ROUTE} | 阶段: {phase_name} | Spec: {spec_ref or "N/A"}
259
-
260
- L0 Static: {N} checks
261
- L1 Unit/API: {N} scenarios ({X} critical, {Y} high)
262
- L2 Integration: {N} scenarios ({X} critical, {Y} high)
263
- L3 E2E: {N} scenarios ({X} critical, {Y} high)
264
-
265
- Total: {N} scenarios | Max iterations: {MAX_ITER} | Concurrency: {maxConcurrency}
266
- Proceed? (yes/edit/cancel)
267
- ```
268
-
269
- - `--dry-run`: stop here. `-y`: skip confirmation.
270
-
271
- ### Phase 2: Layer Execution Engine (Write + Run)
272
-
273
- #### L0: Static Analysis (no CSV)
274
-
275
- ```bash
276
- tsc --noEmit && eslint src/
277
- ```
278
-
279
- If L0 fails → stop, do not proceed to L1.
280
-
281
- #### Per-Layer Write Loop (L1 → L2 → L3)
282
-
283
- For each layer (sequential, respecting --layer filter):
284
-
285
- **1. Extract layer rows** from master `scenarios.csv` (filter by `layer == L{N}`, status == pending)
286
-
287
- **2. Populate `prev_context`** from completed prior-layer findings in master CSV
288
-
289
- **3. Write `layer-L{N}-write.csv`** then execute parallel test writing:
290
-
291
- ```javascript
292
- spawn_agents_on_csv({
293
- csv_path: `${sessionFolder}/layer-L${N}-write.csv`,
294
- id_column: "id",
295
- instruction: buildTestWriterInstruction(infrastructure, specsContent, phaseDir),
296
- max_concurrency: maxConcurrency,
297
- max_runtime_seconds: 1800,
298
- output_csv_path: `${sessionFolder}/layer-L${N}-write-results.csv`,
299
- output_schema: { id, status: [written|failed], red_result: [expected_fail|unexpected_fail|pass], findings, error }
300
- })
301
- ```
302
-
303
- **Test Writer Agent Instruction** (per scenario row):
304
- ```
305
- You are a test writer. Write ONE test file for the given scenario.
306
-
307
- ## Task
308
- - Read the target_file to understand the module under test
309
- - Write test file at test_file path following infrastructure_hints patterns
310
- - Each test case in test_cases becomes one it() block
311
- - Use fixtures from fixtures column (infer from source if empty)
312
- - Include scenario id in describe: describe("AT-NNN: {name}", ...)
313
- - Run the test file once after writing
314
-
315
- ## RED-GREEN Rules
316
- - If test PASSES immediately: note "pass" — may need strengthening
317
- - If test FAILS as expected (tests real behavior): note "expected_fail" — good
318
- - If test FAILS unexpectedly (setup/import error): fix test setup, note "unexpected_fail"
319
- - NEVER modify source code — only write/fix test files
320
-
321
- ## Output
322
- - status: "written" if test file created successfully, "failed" if unable
323
- - red_result: the RED phase outcome
324
- - findings: patterns discovered, notes for dependent scenarios (max 500 chars)
325
- - error: only if status == "failed"
326
-
327
- ## Context
328
- - prev_context: {prev_context} (findings from prior layer)
329
- - Read discoveries.ndjson for shared patterns before starting
330
- - Append to discoveries.ndjson if you find reusable patterns
331
- ```
332
-
333
- **4. Merge write-results** into master `scenarios.csv`, delete temp CSV
334
-
335
- **5. Run full layer test suite:**
336
- ```bash
337
- {run_command} --testPathPattern="{layer_pattern}"
338
- ```
339
-
340
- **6. Record per-scenario results** (pass/fail/blocked with error_detail)
341
-
342
- **7. Fail-fast check:** If ANY critical-priority scenario failed → do NOT proceed to next layer
343
-
344
- **If `--max-iter 1`:** After all layers written and run once, jump to Phase 4 (single-pass).
345
-
346
- ### Phase 3: Iteration Engine (Diagnose + Fix)
347
-
348
- ```
349
- OUTER LOOP (max_iter iterations):
350
-
351
- FOR each layer with failures (L1 through current):
352
-
353
- INNER LOOP (max 3 per layer):
354
-
355
- 1. Build diagnosis.csv from failed scenarios in master CSV
356
- (only scenarios with status=failed AND classification != code_defect)
357
-
358
- 2. IF diagnosis rows >= 1:
359
- spawn_agents_on_csv({
360
- csv_path: `${sessionFolder}/diagnosis-iter-${iter}.csv`,
361
- id_column: "id",
362
- instruction: buildDiagnosisInstruction(infrastructure),
363
- max_concurrency: maxConcurrency,
364
- max_runtime_seconds: 1200,
365
- output_csv_path: `${sessionFolder}/diagnosis-iter-${iter}-results.csv`,
366
- output_schema: { id, classification, fix_code, evidence, error }
367
- })
368
-
369
- 3. Merge diagnosis results:
370
- - test_defect with fix_code → apply fix, update scenario status to "pending"
371
- - code_defect → mark as confirmed failure (stop retrying)
372
- - env_issue → mark as blocked
373
-
374
- 4. Re-run ALL scenarios in this layer (catch regressions)
375
- 5. IF no test_defects remain: break inner loop
376
-
377
- END INNER
378
-
379
- Record final layer results
380
- IF critical code_defects: stop layer progression (fail-fast)
381
-
382
- END FOR
383
-
384
- REFLECT:
385
- Analyze: pass rate delta, failure clusters, strategy effectiveness
386
- Append to reflection-log.md
387
-
388
- **Test confidence scoring** (at each REFLECT step):
389
- Dimensions (5): scenario_coverage, test_quality, diagnostic_accuracy, strategy_effectiveness, infrastructure_fitness. Factors (weights): completeness(.30), pass_rate_trend(.25), classification_accuracy(.20), coverage_breadth(.15), consistency(.10). Enhanced convergence: BOTH pass_rate ≥ threshold AND confidence ≥ 60%. Add confidence to `report.json`.
390
-
391
- ADJUST (Adaptive Strategy):
392
- IF startStrategy provided AND iteration == 1: use startStrategy as initial
393
- OTHERWISE auto-select:
394
-
395
- | Condition | Strategy |
396
- |-----------|----------|
397
- | Iteration 1-2 | Conservative: fix obvious test_defects only |
398
- | Pass rate >80% | Aggressive: batch-fix related failures |
399
- | New regressions | Surgical: revert, fix regression only |
400
- | Stuck 3+ iters | Reflective: re-analyze root cause pattern |
401
-
402
- CONVERGENCE:
403
- pass_rate >= 95% → Phase 4 (converged)
404
- iteration >= max_iter → Phase 4 (max_iter_reached)
405
- all remaining = code_defect → Phase 4 (confirmed_defects)
406
- ELSE → next iteration
407
-
408
- END OUTER
409
- ```
410
-
411
- **Diagnosis Agent Instruction** (per failure row):
412
- ```
413
- You are a test failure diagnostician. Classify ONE test failure and provide fix if applicable.
414
-
415
- ## Task
416
- - Read test_file and target_file to understand the failure context
417
- - Analyze error_detail against expected vs actual
418
- - Classify the failure:
419
- - test_defect: Test is wrong (bad import, wrong endpoint, bad fixture, incorrect assertion)
420
- - code_defect: Source code violates business rule (actual behavior != expected requirement)
421
- - env_issue: Environment problem (service down, config missing, timeout)
422
-
423
- ## Output
424
- - classification: one of test_defect / code_defect / env_issue
425
- - fix_code: If test_defect, provide the fix (format: "old_line → new_line" or full replacement)
426
- If code_defect or env_issue, leave empty
427
- - evidence: file:line references supporting your classification
428
- - error: only if you cannot determine classification
429
-
430
- ## Rules
431
- - NEVER suggest source code changes — only test code fixes for test_defect
432
- - A test that correctly catches a real bug is a code_defect, not test_defect
433
- - When uncertain between test_defect and code_defect, prefer code_defect (conservative)
434
- ```
435
-
436
- ### Shared Discovery Board Protocol
437
-
438
- | Type | Dedup Key | Data Schema |
439
- |------|-----------|-------------|
440
- | `test_pattern` | `data.name` | `{name, file, description}` |
441
- | `mock_setup` | `data.target` | `{target, setup_code, file}` |
442
- | `fixture` | `data.name` | `{name, schema, file}` |
443
- | `convention` | singleton | `{describe_style, assertion_lib, import_pattern}` |
444
- | `blocker` | `data.issue` | `{issue, severity, layer}` |
445
-
446
- Read before writing tests. Append-only. Dedup by type+key.
447
-
448
- ### Phase 4: Results & Routing
449
-
450
- 1. Export final `scenarios.csv` as `results.csv`
451
-
452
- 2. Write `.tests/auto-test/state.json`:
453
- ```json
454
- {
455
- "session_id": "auto-test-{YYYYMMDD-HHmmss}",
456
- "phase": "{phase}", "phase_dir": "{PHASE_DIR}",
457
- "source_route": "spec|gap|code|re-run",
458
- "status": "converged|max_iter_reached|confirmed_defects|single_pass",
459
- "iteration": N, "strategy": "conservative",
460
- "strategy_history": [...],
461
- "threshold": 95, "current_layer": "L2",
462
- "layer_state": {
463
- "L0": { "inner_iter": 1, "pass_rate": 100.0, "status": "passed" },
464
- "L1": { "inner_iter": 2, "pass_rate": 95.0, "status": "passed" },
465
- "L2": { ... }, "L3": { ... }
466
- },
467
- "pass_rate_history": [...],
468
- "scenario_count": 30,
469
- "csv_session": ".tests/auto-test/.csv-session/"
470
- }
471
- ```
472
-
473
- 3. Write `.tests/auto-test/report.json` (same schema as workflow reference)
474
-
475
- 4. **Conditional: Traceability** (spec source only) — build REQ→AC→scenario→result mapping
476
-
477
- 5. **Conditional: Issue Creation** (code_defect failures):
478
- ```
479
- FOR each failure WHERE classification == "code_defect":
480
- Append to .workflow/issues/issues.jsonl
481
- ```
482
-
483
- 6. **Register artifact** in state.json:
484
- ```json
485
- { "id": "TST-NNN", "type": "test", "status": "completed|failed" }
486
- ```
487
-
488
- 7. **Report Display:**
489
- ```
490
- === AUTO-TEST RESULTS ===
491
- 阶段: {phase_name}
492
- 来源: {ROUTE}
493
- 迭代: {N} (策略: {strategy_history})
494
- 收敛: {status} ({final_pass_rate}%)
495
-
496
- 层级结果:
497
- L0 Static: {pass_rate}% ({passed}/{total})
498
- L1 Unit/API: {pass_rate}% ({passed}/{total})
499
- L2 Integration: {pass_rate}% ({passed}/{total})
500
- L3 E2E: {pass_rate}% ({passed}/{total})
501
-
502
- 场景: {passed} passed, {failed} failed, {blocked} blocked
503
- Bugs: {N} discovered
504
- {IF spec: "需求覆盖: {pct}% | 已验证: {n}/{total}"}
505
-
506
- CSV Session: .tests/auto-test/.csv-session/
507
- ```
508
-
509
- 8. **Route:**
510
-
511
- | Result | Next Step |
512
- |--------|-----------|
513
- | Converged (>=95%) | `$maestro-verify "{phase}"` |
514
- | All requirements verified (spec) | `$maestro-milestone-audit` |
515
- | Bugs discovered | `$quality-debug "--from-auto-test {phase}"` |
516
- | Max iter, >80% | `$quality-test "{phase}"` for manual UAT |
517
- | Max iter, <80% | `$quality-debug "{phase}"` |
518
- | Coverage still low | `$quality-auto-test "{phase} --layer {missing}"` |
519
- | Re-run all pass | `$maestro-verify "{phase}"` |
520
- | Single pass, all pass | `$quality-test "{phase}"` |
521
-
522
- </execution>
523
-
524
- <error_codes>
525
- | Error | Resolution |
526
- |-------|------------|
527
- | Phase not found in artifact registry | Abort: "Phase {N} not found" |
528
- | No test framework detected | Abort: E003. Install framework or configure runner |
529
- | Agent spawn fails (write or diagnosis) | Retry once, then mark scenario as blocked |
530
- | Convergence not met after max_iter | Report max_iter_reached, suggest debug |
531
- | All scenarios in layer blocked | Stop layer, report env_issue |
532
- | CSV parse error | Validate format, show line |
533
- | discoveries.ndjson corrupt | Ignore malformed lines, continue |
534
- | Resume: no session found | Start fresh |
535
- </error_codes>
536
-
537
- <success_criteria>
538
- - [ ] Session folder created with valid scenarios.csv
539
- - [ ] Route auto-selected from project state (spec/gap/code)
540
- - [ ] All layers executed in order with fail-fast on critical
541
- - [ ] Test writing parallelized via spawn_agents_on_csv per layer
542
- - [ ] Failure diagnosis parallelized via spawn_agents_on_csv per iteration
543
- - [ ] discoveries.ndjson append-only throughout
544
- - [ ] Cross-layer context propagation via prev_context column
545
- - [ ] Iteration engine ran (inner: test_defect fix, outer: strategy adjust)
546
- - [ ] Test confidence scored per iteration with 5-dimension factor model
547
- - [ ] Convergence check includes confidence >= 60% alongside pass_rate
548
- - [ ] Confidence section added to report.json
549
- - [ ] state.json, report.json, reflection-log.md written
550
- - [ ] If spec: traceability.md produced
551
- - [ ] If failures: issues auto-created in issues.jsonl
552
- - [ ] Next step routed based on convergence status
553
- </success_criteria>
1
+ ---
2
+ name: quality-auto-test
3
+ description: Auto-generate and run tests from specs or coverage gaps
4
+ argument-hint: "<phase> [-y] [-c N] [--max-iter N] [--layer L0-L3] [--dry-run] [--re-run]"
5
+ allowed-tools: spawn_agents_on_csv, Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion
6
+ ---
7
+
8
+ <purpose>
9
+ Unified automated testing using `spawn_agents_on_csv` for parallel test writing and failure diagnosis. Reads project state to auto-select scenario source (PRD specs, coverage gaps, or code exploration). All sources converge into a shared CSV pipeline: discover infrastructure → plan → write tests via CSV parallel → execute per layer → diagnose failures via CSV parallel → iterate → report.
10
+
11
+ **Core workflow**: Route → Source Scenarios → Build CSV → Layer-by-Layer Parallel Execution → Iterate (Diagnose CSV) → Report
12
+
13
+ **Topology**: Layers as waves (L0→L1→L2→L3 sequential, scenarios within layer parallel)
14
+
15
+ ```
16
+ +---------------------------------------------------------------------------+
17
+ | AUTO-TEST CSV LAYER PIPELINE |
18
+ +---------------------------------------------------------------------------+
19
+ | |
20
+ | Phase 1: Route & Plan -> CSV |
21
+ | +-- Read project state, auto-select route (spec/gap/code) |
22
+ | +-- Extract scenarios per route, normalize to unified format |
23
+ | +-- Discover test infrastructure (framework, patterns) |
24
+ | +-- Build scenarios.csv with one row per scenario |
25
+ | +-- Layers = waves (L1, L2, L3 sequential; L0 = static pre-check) |
26
+ | +-- User validates test plan (skip if -y) |
27
+ | |
28
+ | Phase 2: Layer Execution Engine (write + run) |
29
+ | +-- L0: Static analysis (tsc + eslint) — no CSV needed |
30
+ | +-- For each layer L1→L3 (sequential, fail-fast on critical): |
31
+ | | +-- Layer N: Write Tests (parallel via spawn_agents_on_csv) |
32
+ | | | +-- Each agent writes one test file (RED-GREEN) |
33
+ | | | +-- Agent reads target source + infrastructure patterns |
34
+ | | | +-- Agent verifies RED (run test, check it targets behavior) |
35
+ | | | +-- Results: test_file written, red_result, findings |
36
+ | | +-- Merge write-results into master scenarios.csv |
37
+ | | +-- Run all layer tests together (full layer execution) |
38
+ | | +-- Record per-scenario pass/fail results |
39
+ | |
40
+ | Phase 3: Iteration Engine (diagnose + fix) |
41
+ | +-- OUTER LOOP (max_iter iterations): |
42
+ | | +-- For each layer with failures: |
43
+ | | | +-- Build diagnosis.csv from failed scenarios |
44
+ | | | +-- Diagnose & Fix (parallel via spawn_agents_on_csv) |
45
+ | | | | +-- Each agent classifies one failure cluster |
46
+ | | | | +-- test_defect: agent provides fix diff |
47
+ | | | | +-- code_defect: agent documents evidence |
48
+ | | | +-- Apply test_defect fixes, re-run layer |
49
+ | | +-- Reflect: analyze trends, log strategy |
50
+ | | +-- Adjust: select next strategy (conservative/aggressive/...) |
51
+ | | +-- Convergence check: >=95% → done |
52
+ | +-- discoveries.ndjson shared across all iterations |
53
+ | |
54
+ | Phase 4: Results & Routing |
55
+ | +-- Export results.csv |
56
+ | +-- Write report.json, state.json, reflection-log.md |
57
+ | +-- Conditional: traceability.md, issue creation |
58
+ | +-- Route to next step based on convergence |
59
+ | |
60
+ +---------------------------------------------------------------------------+
61
+ ```
62
+ </purpose>
63
+
64
+ <context>
65
+ ```bash
66
+ $quality-auto-test "3" # auto-detect source, full iteration
67
+ $quality-auto-test -c 4 "3" # max 4 concurrent test writers per layer
68
+ $quality-auto-test -y "3 --max-iter 1" # single-pass generation only
69
+ $quality-auto-test "3 --dry-run" # plan only, no execution
70
+ $quality-auto-test "3 --re-run" # re-run only previously failed scenarios
71
+ $quality-auto-test "3 --layer L2" # restrict to L2 integration tests
72
+ ```
73
+
74
+ **Flags**:
75
+ - `-y, --yes`: Skip all confirmations
76
+ - `-c, --concurrency N`: Max concurrent agents within each layer (default: 5)
77
+ - `--max-iter N`: Max outer iterations (default 5). **1 = single-pass** generation only
78
+ - `--layer L`: Start from or restrict to specific layer (L0|L1|L2|L3)
79
+ - `--strategy conservative|aggressive|surgical|reflective`: Override starting iteration strategy (default: auto-selected)
80
+ - `--dry-run`: Generate test plan only, do not execute
81
+ - `--re-run`: Re-run only previously failed/blocked scenarios
82
+
83
+ **Intelligent routing** (auto-detected, priority order):
84
+
85
+ | Priority | Condition | Route |
86
+ |----------|-----------|-------|
87
+ | 1 | Active session (state.json status=running) | Resume |
88
+ | 2 | --re-run flag + previous failures | Re-run |
89
+ | 3 | Spec package exists (REQ-*.md) | spec (PRD-forward) |
90
+ | 4 | Nyquist gaps exist (verification.json) | gap (coverage-forward) |
91
+ | 5 | Default | code (exploration-forward) |
92
+
93
+ **Session Directory**: `.tests/auto-test/.csv-session/`
94
+ **Core Output**: `scenarios.csv` (master state) + `results.csv` (final) + `discoveries.ndjson` (shared) + `report.json` + `state.json`
95
+ </context>
96
+
97
+ <csv_schema>
98
+
99
+ ### scenarios.csv (Master State — Test Writing Phase)
100
+
101
+ ```csv
102
+ id,name,layer,priority,category,target_file,test_file,description,test_cases,fixtures,req_ref,infrastructure_hints,prev_context,status,red_result,findings,error
103
+ "AT-001","Auth token validation","L1","critical","api_contract","src/auth/token.ts","src/auth/__tests__/token.test.ts","Validate JWT token verification returns correct payload","verify valid token returns payload;verify expired token throws;verify malformed token throws","valid_token fixture;expired_token fixture","REQ-001:AC-1","vitest;describe/it pattern;see src/utils/__tests__/hash.test.ts","","","","",""
104
+ "AT-002","Login endpoint integration","L2","high","business_rule","src/routes/login.ts","src/routes/__tests__/login.integration.test.ts","POST /api/login returns JWT on valid credentials","valid login returns 200+token;invalid password returns 401;missing email returns 400","user_fixture;credentials_fixture","REQ-002:AC-1","supertest;see src/routes/__tests__/health.test.ts","AT-001 findings: token module exports verifyToken/generateToken","","","",""
105
+ ```
106
+
107
+ **Columns**:
108
+
109
+ | Column | Phase | Description |
110
+ |--------|-------|-------------|
111
+ | `id` | Input | Scenario ID (AT-NNN format) |
112
+ | `name` | Input | Short scenario name |
113
+ | `layer` | Input | L1/L2/L3 (determines wave order) |
114
+ | `priority` | Input | critical/high/medium |
115
+ | `category` | Input | api_contract/business_rule/state_transition/user_flow/... |
116
+ | `target_file` | Input | Source file being tested |
117
+ | `test_file` | Input | Target test file path to create |
118
+ | `description` | Input | What this scenario validates |
119
+ | `test_cases` | Input | Semicolon-separated test cases |
120
+ | `fixtures` | Input | Required fixtures/mocks (semicolon-separated) |
121
+ | `req_ref` | Input | Requirement reference (REQ-NNN:AC-N or gap-id or empty) |
122
+ | `infrastructure_hints` | Input | Framework + pattern references from Step 3 |
123
+ | `prev_context` | Computed | Findings from prior layer scenarios (cross-layer propagation) |
124
+ | `status` | Output | pending → written → passed → failed → blocked |
125
+ | `red_result` | Output | expected_fail / unexpected_fail / pass (RED phase result) |
126
+ | `findings` | Output | Implementation notes, patterns discovered (max 500 chars) |
127
+ | `error` | Output | Error message if failed |
128
+
129
+ ### diagnosis.csv (Iteration Phase — Failure Diagnosis)
130
+
131
+ ```csv
132
+ id,scenario_id,layer,test_file,error_detail,expected,actual,target_file,source_context,classification,fix_code,evidence,error
133
+ "DX-001","AT-003","L1","src/auth/__tests__/token.test.ts","TypeError: verifyToken is not a function","verifyToken returns decoded payload","Function not exported from module","src/auth/token.ts","token.ts exports: generateToken only","test_defect","import { verifyToken } from '../token' → import { verifyToken } from '../verify-token'","src/auth/verify-token.ts:15 exports verifyToken",""
134
+ "DX-002","AT-005","L2","src/routes/__tests__/login.test.ts","Expected 200, received 500","POST /login returns 200 with valid credentials","Internal server error: database connection refused","src/routes/login.ts","login.ts calls UserModel.findByEmail","env_issue","","Database not available in test environment",""
135
+ ```
136
+
137
+ **Columns**:
138
+
139
+ | Column | Phase | Description |
140
+ |--------|-------|-------------|
141
+ | `id` | Input | Diagnosis ID (DX-NNN) |
142
+ | `scenario_id` | Input | Reference to AT-NNN scenario |
143
+ | `layer` | Input | Layer where failure occurred |
144
+ | `test_file` | Input | Test file that failed |
145
+ | `error_detail` | Input | Full error message/stack trace excerpt |
146
+ | `expected` | Input | Expected behavior from scenario |
147
+ | `actual` | Input | Actual behavior observed |
148
+ | `target_file` | Input | Source file being tested |
149
+ | `source_context` | Input | Relevant source code context (exports, imports) |
150
+ | `classification` | Output | test_defect / code_defect / env_issue |
151
+ | `fix_code` | Output | Fix diff for test_defect (old → new) |
152
+ | `evidence` | Output | file:line references for diagnosis |
153
+ | `error` | Output | Agent error if diagnosis failed |
154
+
155
+ ### Session Structure
156
+
157
+ ```
158
+ .tests/auto-test/.csv-session/
159
+ +-- scenarios.csv (master state)
160
+ +-- results.csv (final export)
161
+ +-- discoveries.ndjson (shared across iterations)
162
+ +-- layer-L{N}-write.csv (temporary, per-layer write input)
163
+ +-- layer-L{N}-write-results.csv
164
+ +-- diagnosis-iter-{N}.csv (temporary, per-iteration diagnosis)
165
+ +-- diagnosis-iter-{N}-results.csv
166
+ ```
167
+ </csv_schema>
168
+
169
+ <invariants>
170
+ 1. **Start Immediately**: First action is session initialization
171
+ 2. **Layer Order is Sacred**: Never execute L(N+1) before L(N) completes (fail-fast on critical)
172
+ 3. **CSV is Source of Truth**: Master scenarios.csv holds all test execution state
173
+ 4. **Context Propagation**: prev_context built from prior-layer findings in CSV, not memory
174
+ 5. **Discovery Board Append-Only**: Never clear or modify discoveries.ndjson
175
+ 6. **Route Auto-Detected**: Read state, never ask user for mode
176
+ 7. **RED-GREEN Methodology**: Tests target real behavior; failing test = bug discovery (never fix source)
177
+ 8. **Max 3 Inner Fix Attempts**: Per layer, fix test_defects up to 3 times via diagnosis CSV
178
+ 9. **Convergence Threshold**: 95% pass rate = converged
179
+ 10. **DO NOT STOP**: Continuous execution until convergence, max_iter, or all remaining = code_defect
180
+ </invariants>
181
+
182
+ <execution>
183
+
184
+ ### Session Initialization
185
+
186
+ ```
187
+ Parse from $ARGUMENTS:
188
+ AUTO_YES ← --yes | -y
189
+ maxConcurrency ← --concurrency | -c N (default: 5)
190
+ MAX_ITER ← --max-iter N (default: 5)
191
+ layerFilter ← --layer L (default: null = all)
192
+ startStrategy ← --strategy conservative|aggressive|surgical|reflective (default: null = auto)
193
+ dryRun ← --dry-run
194
+ reRun ← --re-run
195
+ phaseArg ← remaining text
196
+
197
+ Derive:
198
+ dateStr ← UTC+8 YYYYMMDD
199
+ sessionFolder ← ".tests/auto-test/.csv-session"
200
+
201
+ mkdir -p {sessionFolder}
202
+ ```
203
+
204
+ ### Phase 1: Route & Plan → CSV
205
+
206
+ #### Step 0: Parse & Load
207
+
208
+ Resolve phase dir from `state.json` artifact registry (`type='execute'`, matching phase). Error E002 if not found.
209
+
210
+ ```
211
+ specs_test = maestro spec load --role test
212
+ specs_arch = maestro spec load --role plan
213
+ ```
214
+
215
+ #### Step 1: Read State & Route
216
+
217
+ ```
218
+ Priority: Resume > Re-run > Spec > Gap > Code
219
+
220
+ 1. RESUME: .csv-session/scenarios.csv exists AND state.json status == "running"
221
+ → offer resume or restart (resume = reload CSV, jump to current iteration)
222
+
223
+ 2. RE-RUN: --re-run flag AND report.json has failed/blocked scenarios
224
+ → load failed scenarios into CSV with status reset to pending
225
+
226
+ 3. SPEC: .workflow/.spec/SPEC-*/requirements/REQ-*.md exists
227
+ → ROUTE = "spec", SPEC_MODE = "full" | "degraded"
228
+
229
+ 4. GAP: verification.json has gaps[] (MISSING/PARTIAL)
230
+ → ROUTE = "gap"
231
+
232
+ 5. CODE: Default fallback → ROUTE = "code"
233
+ ```
234
+
235
+ #### Step 2: Source Scenarios
236
+
237
+ Execute route-specific extraction, normalize to unified format.
238
+
239
+ **Route A: spec** — Parse REQ acceptance criteria, classify layers, generate fixtures.
240
+ **Route B: gap** — Read verification/coverage gaps, classify files by type.
241
+ **Route C: code** — Explore module boundaries, API endpoints, integration points.
242
+
243
+ All routes produce unified scenario objects (see csv_schema).
244
+
245
+ #### Step 3: Discover Infrastructure
246
+
247
+ Detect framework, read 2-3 existing tests for patterns. Build `infrastructure_hints` string per scenario.
248
+
249
+ #### Step 4: Build scenarios.csv & Confirm
250
+
251
+ 1. Build master `scenarios.csv` — one row per scenario, grouped by layer
252
+ 2. Set `prev_context` for L2 scenarios from L1 scenario descriptions (cross-layer dependency)
253
+ 3. Set `prev_context` for L3 from L2 findings
254
+
255
+ Display plan summary:
256
+ ```
257
+ === AUTO-TEST PLAN ===
258
+ 来源: {ROUTE} | 阶段: {phase_name} | Spec: {spec_ref or "N/A"}
259
+
260
+ L0 Static: {N} checks
261
+ L1 Unit/API: {N} scenarios ({X} critical, {Y} high)
262
+ L2 Integration: {N} scenarios ({X} critical, {Y} high)
263
+ L3 E2E: {N} scenarios ({X} critical, {Y} high)
264
+
265
+ Total: {N} scenarios | Max iterations: {MAX_ITER} | Concurrency: {maxConcurrency}
266
+ Proceed? (yes/edit/cancel)
267
+ ```
268
+
269
+ - `--dry-run`: stop here. `-y`: skip confirmation.
270
+
271
+ ### Phase 2: Layer Execution Engine (Write + Run)
272
+
273
+ #### L0: Static Analysis (no CSV)
274
+
275
+ ```bash
276
+ tsc --noEmit && eslint src/
277
+ ```
278
+
279
+ If L0 fails → stop, do not proceed to L1.
280
+
281
+ #### Per-Layer Write Loop (L1 → L2 → L3)
282
+
283
+ For each layer (sequential, respecting --layer filter):
284
+
285
+ **1. Extract layer rows** from master `scenarios.csv` (filter by `layer == L{N}`, status == pending)
286
+
287
+ **2. Populate `prev_context`** from completed prior-layer findings in master CSV
288
+
289
+ **3. Write `layer-L{N}-write.csv`** then execute parallel test writing:
290
+
291
+ ```javascript
292
+ spawn_agents_on_csv({
293
+ csv_path: `${sessionFolder}/layer-L${N}-write.csv`,
294
+ id_column: "id",
295
+ instruction: buildTestWriterInstruction(infrastructure, specsContent, phaseDir),
296
+ max_concurrency: maxConcurrency,
297
+ max_runtime_seconds: 1800,
298
+ output_csv_path: `${sessionFolder}/layer-L${N}-write-results.csv`,
299
+ output_schema: { id, status: [written|failed], red_result: [expected_fail|unexpected_fail|pass], findings, error }
300
+ })
301
+ ```
302
+
303
+ **Test Writer Agent Instruction** (per scenario row):
304
+ ```
305
+ You are a test writer. Write ONE test file for the given scenario.
306
+
307
+ ## Task
308
+ - Read the target_file to understand the module under test
309
+ - Write test file at test_file path following infrastructure_hints patterns
310
+ - Each test case in test_cases becomes one it() block
311
+ - Use fixtures from fixtures column (infer from source if empty)
312
+ - Include scenario id in describe: describe("AT-NNN: {name}", ...)
313
+ - Run the test file once after writing
314
+
315
+ ## RED-GREEN Rules
316
+ - If test PASSES immediately: note "pass" — may need strengthening
317
+ - If test FAILS as expected (tests real behavior): note "expected_fail" — good
318
+ - If test FAILS unexpectedly (setup/import error): fix test setup, note "unexpected_fail"
319
+ - NEVER modify source code — only write/fix test files
320
+
321
+ ## Output
322
+ - status: "written" if test file created successfully, "failed" if unable
323
+ - red_result: the RED phase outcome
324
+ - findings: patterns discovered, notes for dependent scenarios (max 500 chars)
325
+ - error: only if status == "failed"
326
+
327
+ ## Context
328
+ - prev_context: {prev_context} (findings from prior layer)
329
+ - Read discoveries.ndjson for shared patterns before starting
330
+ - Append to discoveries.ndjson if you find reusable patterns
331
+ ```
332
+
333
+ **4. Merge write-results** into master `scenarios.csv`, delete temp CSV
334
+
335
+ **5. Run full layer test suite:**
336
+ ```bash
337
+ {run_command} --testPathPattern="{layer_pattern}"
338
+ ```
339
+
340
+ **6. Record per-scenario results** (pass/fail/blocked with error_detail)
341
+
342
+ **7. Fail-fast check:** If ANY critical-priority scenario failed → do NOT proceed to next layer
343
+
344
+ **If `--max-iter 1`:** After all layers written and run once, jump to Phase 4 (single-pass).
345
+
346
+ ### Phase 3: Iteration Engine (Diagnose + Fix)
347
+
348
+ ```
349
+ OUTER LOOP (max_iter iterations):
350
+
351
+ FOR each layer with failures (L1 through current):
352
+
353
+ INNER LOOP (max 3 per layer):
354
+
355
+ 1. Build diagnosis.csv from failed scenarios in master CSV
356
+ (only scenarios with status=failed AND classification != code_defect)
357
+
358
+ 2. IF diagnosis rows >= 1:
359
+ spawn_agents_on_csv({
360
+ csv_path: `${sessionFolder}/diagnosis-iter-${iter}.csv`,
361
+ id_column: "id",
362
+ instruction: buildDiagnosisInstruction(infrastructure),
363
+ max_concurrency: maxConcurrency,
364
+ max_runtime_seconds: 1200,
365
+ output_csv_path: `${sessionFolder}/diagnosis-iter-${iter}-results.csv`,
366
+ output_schema: { id, classification, fix_code, evidence, error }
367
+ })
368
+
369
+ 3. Merge diagnosis results:
370
+ - test_defect with fix_code → apply fix, update scenario status to "pending"
371
+ - code_defect → mark as confirmed failure (stop retrying)
372
+ - env_issue → mark as blocked
373
+
374
+ 4. Re-run ALL scenarios in this layer (catch regressions)
375
+ 5. IF no test_defects remain: break inner loop
376
+
377
+ END INNER
378
+
379
+ Record final layer results
380
+ IF critical code_defects: stop layer progression (fail-fast)
381
+
382
+ END FOR
383
+
384
+ REFLECT:
385
+ Analyze: pass rate delta, failure clusters, strategy effectiveness
386
+ Append to reflection-log.md
387
+
388
+ **Test confidence scoring** (at each REFLECT step):
389
+ Dimensions (5): scenario_coverage, test_quality, diagnostic_accuracy, strategy_effectiveness, infrastructure_fitness. Factors (weights): completeness(.30), pass_rate_trend(.25), classification_accuracy(.20), coverage_breadth(.15), consistency(.10). Enhanced convergence: BOTH pass_rate ≥ threshold AND confidence ≥ 60%. Add confidence to `report.json`.
390
+
391
+ ADJUST (Adaptive Strategy):
392
+ IF startStrategy provided AND iteration == 1: use startStrategy as initial
393
+ OTHERWISE auto-select:
394
+
395
+ | Condition | Strategy |
396
+ |-----------|----------|
397
+ | Iteration 1-2 | Conservative: fix obvious test_defects only |
398
+ | Pass rate >80% | Aggressive: batch-fix related failures |
399
+ | New regressions | Surgical: revert, fix regression only |
400
+ | Stuck 3+ iters | Reflective: re-analyze root cause pattern |
401
+
402
+ CONVERGENCE:
403
+ pass_rate >= 95% → Phase 4 (converged)
404
+ iteration >= max_iter → Phase 4 (max_iter_reached)
405
+ all remaining = code_defect → Phase 4 (confirmed_defects)
406
+ ELSE → next iteration
407
+
408
+ END OUTER
409
+ ```
410
+
411
+ **Diagnosis Agent Instruction** (per failure row):
412
+ ```
413
+ You are a test failure diagnostician. Classify ONE test failure and provide fix if applicable.
414
+
415
+ ## Task
416
+ - Read test_file and target_file to understand the failure context
417
+ - Analyze error_detail against expected vs actual
418
+ - Classify the failure:
419
+ - test_defect: Test is wrong (bad import, wrong endpoint, bad fixture, incorrect assertion)
420
+ - code_defect: Source code violates business rule (actual behavior != expected requirement)
421
+ - env_issue: Environment problem (service down, config missing, timeout)
422
+
423
+ ## Output
424
+ - classification: one of test_defect / code_defect / env_issue
425
+ - fix_code: If test_defect, provide the fix (format: "old_line → new_line" or full replacement)
426
+ If code_defect or env_issue, leave empty
427
+ - evidence: file:line references supporting your classification
428
+ - error: only if you cannot determine classification
429
+
430
+ ## Rules
431
+ - NEVER suggest source code changes — only test code fixes for test_defect
432
+ - A test that correctly catches a real bug is a code_defect, not test_defect
433
+ - When uncertain between test_defect and code_defect, prefer code_defect (conservative)
434
+ ```
435
+
436
+ ### Shared Discovery Board Protocol
437
+
438
+ | Type | Dedup Key | Data Schema |
439
+ |------|-----------|-------------|
440
+ | `test_pattern` | `data.name` | `{name, file, description}` |
441
+ | `mock_setup` | `data.target` | `{target, setup_code, file}` |
442
+ | `fixture` | `data.name` | `{name, schema, file}` |
443
+ | `convention` | singleton | `{describe_style, assertion_lib, import_pattern}` |
444
+ | `blocker` | `data.issue` | `{issue, severity, layer}` |
445
+
446
+ Read before writing tests. Append-only. Dedup by type+key.
447
+
448
+ ### Phase 4: Results & Routing
449
+
450
+ 1. Export final `scenarios.csv` as `results.csv`
451
+
452
+ 2. Write `.tests/auto-test/state.json`:
453
+ ```json
454
+ {
455
+ "session_id": "auto-test-{YYYYMMDD-HHmmss}",
456
+ "phase": "{phase}", "phase_dir": "{PHASE_DIR}",
457
+ "source_route": "spec|gap|code|re-run",
458
+ "status": "converged|max_iter_reached|confirmed_defects|single_pass",
459
+ "iteration": N, "strategy": "conservative",
460
+ "strategy_history": [...],
461
+ "threshold": 95, "current_layer": "L2",
462
+ "layer_state": {
463
+ "L0": { "inner_iter": 1, "pass_rate": 100.0, "status": "passed" },
464
+ "L1": { "inner_iter": 2, "pass_rate": 95.0, "status": "passed" },
465
+ "L2": { ... }, "L3": { ... }
466
+ },
467
+ "pass_rate_history": [...],
468
+ "scenario_count": 30,
469
+ "csv_session": ".tests/auto-test/.csv-session/"
470
+ }
471
+ ```
472
+
473
+ 3. Write `.tests/auto-test/report.json` (same schema as workflow reference)
474
+
475
+ 4. **Conditional: Traceability** (spec source only) — build REQ→AC→scenario→result mapping
476
+
477
+ 5. **Conditional: Issue Creation** (code_defect failures):
478
+ ```
479
+ FOR each failure WHERE classification == "code_defect":
480
+ Append to .workflow/issues/issues.jsonl
481
+ ```
482
+
483
+ 6. **Register artifact** in state.json:
484
+ ```json
485
+ { "id": "TST-NNN", "type": "test", "status": "completed|failed" }
486
+ ```
487
+
488
+ 7. **Report Display:**
489
+ ```
490
+ === AUTO-TEST RESULTS ===
491
+ 阶段: {phase_name}
492
+ 来源: {ROUTE}
493
+ 迭代: {N} (策略: {strategy_history})
494
+ 收敛: {status} ({final_pass_rate}%)
495
+
496
+ 层级结果:
497
+ L0 Static: {pass_rate}% ({passed}/{total})
498
+ L1 Unit/API: {pass_rate}% ({passed}/{total})
499
+ L2 Integration: {pass_rate}% ({passed}/{total})
500
+ L3 E2E: {pass_rate}% ({passed}/{total})
501
+
502
+ 场景: {passed} passed, {failed} failed, {blocked} blocked
503
+ Bugs: {N} discovered
504
+ {IF spec: "需求覆盖: {pct}% | 已验证: {n}/{total}"}
505
+
506
+ CSV Session: .tests/auto-test/.csv-session/
507
+ ```
508
+
509
+ 8. **Route:**
510
+
511
+ | Result | Next Step |
512
+ |--------|-----------|
513
+ | Converged (>=95%) | `$maestro-verify "{phase}"` |
514
+ | All requirements verified (spec) | `$maestro-milestone-audit` |
515
+ | Bugs discovered | `$quality-debug "--from-auto-test {phase}"` |
516
+ | Max iter, >80% | `$quality-test "{phase}"` for manual UAT |
517
+ | Max iter, <80% | `$quality-debug "{phase}"` |
518
+ | Coverage still low | `$quality-auto-test "{phase} --layer {missing}"` |
519
+ | Re-run all pass | `$maestro-verify "{phase}"` |
520
+ | Single pass, all pass | `$quality-test "{phase}"` |
521
+
522
+ </execution>
523
+
524
+ <error_codes>
525
+ | Error | Resolution |
526
+ |-------|------------|
527
+ | Phase not found in artifact registry | Abort: "Phase {N} not found" |
528
+ | No test framework detected | Abort: E003. Install framework or configure runner |
529
+ | Agent spawn fails (write or diagnosis) | Retry once, then mark scenario as blocked |
530
+ | Convergence not met after max_iter | Report max_iter_reached, suggest debug |
531
+ | All scenarios in layer blocked | Stop layer, report env_issue |
532
+ | CSV parse error | Validate format, show line |
533
+ | discoveries.ndjson corrupt | Ignore malformed lines, continue |
534
+ | Resume: no session found | Start fresh |
535
+ </error_codes>
536
+
537
+ <success_criteria>
538
+ - [ ] Session folder created with valid scenarios.csv
539
+ - [ ] Route auto-selected from project state (spec/gap/code)
540
+ - [ ] All layers executed in order with fail-fast on critical
541
+ - [ ] Test writing parallelized via spawn_agents_on_csv per layer
542
+ - [ ] Failure diagnosis parallelized via spawn_agents_on_csv per iteration
543
+ - [ ] discoveries.ndjson append-only throughout
544
+ - [ ] Cross-layer context propagation via prev_context column
545
+ - [ ] Iteration engine ran (inner: test_defect fix, outer: strategy adjust)
546
+ - [ ] Test confidence scored per iteration with 5-dimension factor model
547
+ - [ ] Convergence check includes confidence >= 60% alongside pass_rate
548
+ - [ ] Confidence section added to report.json
549
+ - [ ] state.json, report.json, reflection-log.md written
550
+ - [ ] If spec: traceability.md produced
551
+ - [ ] If failures: issues auto-created in issues.jsonl
552
+ - [ ] Next step routed based on convergence status
553
+ </success_criteria>