specweave 0.22.2 → 0.22.4

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 (93) hide show
  1. package/CLAUDE.md +300 -920
  2. package/dist/src/cli/commands/repair-status-desync.d.ts +69 -0
  3. package/dist/src/cli/commands/repair-status-desync.d.ts.map +1 -0
  4. package/dist/src/cli/commands/repair-status-desync.js +221 -0
  5. package/dist/src/cli/commands/repair-status-desync.js.map +1 -0
  6. package/dist/src/cli/commands/sync-specs.d.ts +4 -1
  7. package/dist/src/cli/commands/sync-specs.d.ts.map +1 -1
  8. package/dist/src/cli/commands/sync-specs.js +99 -49
  9. package/dist/src/cli/commands/sync-specs.js.map +1 -1
  10. package/dist/src/cli/commands/validate-status-sync.d.ts +52 -0
  11. package/dist/src/cli/commands/validate-status-sync.d.ts.map +1 -0
  12. package/dist/src/cli/commands/validate-status-sync.js +176 -0
  13. package/dist/src/cli/commands/validate-status-sync.js.map +1 -0
  14. package/dist/src/cli/update-status-line.d.ts +16 -0
  15. package/dist/src/cli/update-status-line.d.ts.map +1 -0
  16. package/dist/src/cli/update-status-line.js +44 -0
  17. package/dist/src/cli/update-status-line.js.map +1 -0
  18. package/dist/src/core/cicd/workflow-monitor.d.ts +4 -0
  19. package/dist/src/core/cicd/workflow-monitor.d.ts.map +1 -1
  20. package/dist/src/core/cicd/workflow-monitor.js +6 -2
  21. package/dist/src/core/cicd/workflow-monitor.js.map +1 -1
  22. package/dist/src/core/increment/completion-validator.d.ts +56 -0
  23. package/dist/src/core/increment/completion-validator.d.ts.map +1 -0
  24. package/dist/src/core/increment/completion-validator.js +102 -0
  25. package/dist/src/core/increment/completion-validator.js.map +1 -0
  26. package/dist/src/core/increment/increment-archiver.d.ts +4 -1
  27. package/dist/src/core/increment/increment-archiver.d.ts.map +1 -1
  28. package/dist/src/core/increment/increment-archiver.js +21 -9
  29. package/dist/src/core/increment/increment-archiver.js.map +1 -1
  30. package/dist/src/core/increment/metadata-manager.d.ts +22 -0
  31. package/dist/src/core/increment/metadata-manager.d.ts.map +1 -1
  32. package/dist/src/core/increment/metadata-manager.js +62 -0
  33. package/dist/src/core/increment/metadata-manager.js.map +1 -1
  34. package/dist/src/core/increment/spec-frontmatter-updater.d.ts +78 -0
  35. package/dist/src/core/increment/spec-frontmatter-updater.d.ts.map +1 -0
  36. package/dist/src/core/increment/spec-frontmatter-updater.js +152 -0
  37. package/dist/src/core/increment/spec-frontmatter-updater.js.map +1 -0
  38. package/dist/src/core/increment/spec-sync-manager.d.ts +5 -1
  39. package/dist/src/core/increment/spec-sync-manager.d.ts.map +1 -1
  40. package/dist/src/core/increment/spec-sync-manager.js +4 -2
  41. package/dist/src/core/increment/spec-sync-manager.js.map +1 -1
  42. package/dist/src/core/increment-utils.d.ts.map +1 -1
  43. package/dist/src/core/increment-utils.js +18 -1
  44. package/dist/src/core/increment-utils.js.map +1 -1
  45. package/dist/src/core/living-docs/living-docs-sync.d.ts +5 -1
  46. package/dist/src/core/living-docs/living-docs-sync.d.ts.map +1 -1
  47. package/dist/src/core/living-docs/living-docs-sync.js +36 -33
  48. package/dist/src/core/living-docs/living-docs-sync.js.map +1 -1
  49. package/dist/src/core/living-docs/task-project-specific-generator.d.ts.map +1 -1
  50. package/dist/src/core/living-docs/task-project-specific-generator.js +13 -8
  51. package/dist/src/core/living-docs/task-project-specific-generator.js.map +1 -1
  52. package/dist/src/core/status-line/status-line-manager.d.ts +3 -2
  53. package/dist/src/core/status-line/status-line-manager.d.ts.map +1 -1
  54. package/dist/src/core/status-line/status-line-manager.js +42 -17
  55. package/dist/src/core/status-line/status-line-manager.js.map +1 -1
  56. package/dist/src/core/status-line/status-line-updater.d.ts +67 -0
  57. package/dist/src/core/status-line/status-line-updater.d.ts.map +1 -0
  58. package/dist/src/core/status-line/status-line-updater.js +203 -0
  59. package/dist/src/core/status-line/status-line-updater.js.map +1 -0
  60. package/dist/src/core/status-line/types.d.ts +19 -5
  61. package/dist/src/core/status-line/types.d.ts.map +1 -1
  62. package/dist/src/core/status-line/types.js +3 -3
  63. package/dist/src/core/status-line/types.js.map +1 -1
  64. package/dist/src/integrations/jira/jira-incremental-mapper.d.ts.map +1 -1
  65. package/dist/src/integrations/jira/jira-incremental-mapper.js +4 -0
  66. package/dist/src/integrations/jira/jira-incremental-mapper.js.map +1 -1
  67. package/dist/src/integrations/jira/jira-mapper.d.ts.map +1 -1
  68. package/dist/src/integrations/jira/jira-mapper.js +4 -0
  69. package/dist/src/integrations/jira/jira-mapper.js.map +1 -1
  70. package/dist/src/utils/logger.d.ts +48 -0
  71. package/dist/src/utils/logger.d.ts.map +1 -0
  72. package/dist/src/utils/logger.js +53 -0
  73. package/dist/src/utils/logger.js.map +1 -0
  74. package/package.json +3 -2
  75. package/plugins/specweave/agents/code-standards-detective/AGENT.md +828 -0
  76. package/plugins/specweave/agents/test-aware-planner/templates/task-non-testable.md.template +12 -0
  77. package/plugins/specweave/agents/test-aware-planner/templates/task-testable.md.template +12 -0
  78. package/plugins/specweave/commands/specweave-analyze-standards.sh +315 -0
  79. package/plugins/specweave/commands/specweave-done.md +91 -4
  80. package/plugins/specweave/commands/specweave-reopen.md +29 -2
  81. package/plugins/specweave/commands/specweave-sync-docs.md +137 -22
  82. package/plugins/specweave/commands/specweave-update-status.md +151 -0
  83. package/plugins/specweave/hooks/lib/update-status-line.sh +39 -8
  84. package/plugins/specweave/hooks/user-prompt-submit.sh +21 -0
  85. package/plugins/specweave/hooks/validate-increment-completion.sh +113 -0
  86. package/plugins/specweave/skills/brownfield-analyzer/SKILL.md +40 -3
  87. package/plugins/specweave/skills/code-standards-analyzer/SKILL.md +455 -0
  88. package/plugins/specweave/templates/coding-standards.md.template +447 -0
  89. package/plugins/specweave-ado/lib/ado-multi-project-sync.js +0 -1
  90. package/plugins/specweave-github/commands/specweave-github-cleanup-duplicates.md +21 -0
  91. package/plugins/specweave-jira/lib/enhanced-jira-sync.js +3 -3
  92. package/plugins/specweave-ado/lib/enhanced-ado-sync.js +0 -170
  93. package/plugins/specweave-release/hooks/.specweave/logs/dora-tracking.log +0 -3222
package/CLAUDE.md CHANGED
@@ -1,1117 +1,497 @@
1
1
  # SpecWeave - Development Guide
2
2
 
3
3
  **Project**: SpecWeave - Spec-Driven Development Framework
4
- **Type**: Open Source NPM Package (TypeScript CLI)
4
+ **Type**: TypeScript CLI (NPM Package)
5
5
  **Repository**: https://github.com/anton-abyzov/specweave
6
- **Website**: https://spec-weave.com
7
6
 
8
- This CLAUDE.md is for **contributors to SpecWeave itself**, not users of SpecWeave.
9
- Users receive a different CLAUDE.md via the template system.
7
+ For **contributors to SpecWeave itself** (not users).
10
8
 
11
9
  ---
12
10
 
13
- ## 🚨 CRITICAL: NEVER POLLUTE PROJECT ROOT!
11
+ ## 🚨 CRITICAL SAFETY RULES
14
12
 
15
- **⛔ THIS IS THE #1 RULE - VIOLATING THIS WILL GET YOUR PR REJECTED ⛔**
13
+ ### 1. Symlink Setup (MANDATORY for Contributors)
16
14
 
17
- **ALL AI-generated files MUST go into the CURRENT INCREMENT folder**, NOT in the project root!
15
+ **Problem**: Claude Code executes hooks from `~/.claude/plugins/marketplaces/specweave/`. If this is a **directory** (not symlink), hooks fail with "No such file or directory".
18
16
 
19
- ### ❌ NEVER Create in Root (Pollutes Repository)
20
-
21
- ```
22
- WRONG - ROOT FILES (REJECTED!):
23
- /PLUGIN-MIGRATION-COMPLETE.md # NO! Goes to increment reports/
24
- /SESSION-SUMMARY-2025-10-28.md # NO! Goes to increment reports/
25
- /ADR-006-DEEP-ANALYSIS.md # NO! Goes to .specweave/docs/internal/architecture/adr/
26
- /ANALYSIS-MULTI-TOOL-COMPARISON.md # NO! Goes to increment reports/
27
- /QUICK-START.md # NO! Goes to increment reports/
28
- /migration-helper.sh # NO! Goes to increment scripts/
29
- /execution.log # NO! Goes to increment logs/
30
-
31
- ✅ CORRECT - INCREMENT FOLDERS:
32
- .specweave/increments/0004-plugin-architecture/
33
- ├── spec.md # ⚠️ ONLY THESE 3 FILES in root!
34
- ├── plan.md
35
- ├── tasks.md # Tasks with embedded tests
36
- ├── reports/ # ✅ ALL REPORTS HERE!
37
- │ ├── PLUGIN-MIGRATION-COMPLETE.md # ✅ Completion reports
38
- │ ├── SESSION-SUMMARY.md # ✅ Session summaries
39
- │ ├── QUICK-START.md # ✅ Quick start guides
40
- │ └── ANALYSIS-*.md # ✅ Analysis files
41
- ├── scripts/ # ✅ ALL SCRIPTS HERE!
42
- │ └── migration-helper.sh # ✅ Helper scripts
43
- └── logs/ # ✅ ALL LOGS HERE!
44
- └── execution.log # ✅ Execution logs
45
-
46
- .specweave/docs/internal/architecture/ # ✅ PUT ADRS/DIAGRAMS HERE!
47
- └── adr/
48
- └── 0006-deep-analysis.md # ✅ Architecture decisions
49
- ```
17
+ **Fix**:
18
+ ```bash
19
+ # Verify symlink exists:
20
+ ls -ld ~/.claude/plugins/marketplaces/specweave
21
+ # Must show: lrwxr-xr-x ... -> /path/to/repo (SYMLINK, not drwxr-xr-x)
50
22
 
51
- **Before committing, ALWAYS check**: `git status` - If you see `.md` files in root, MOVE THEM!
23
+ # If directory, fix it:
24
+ rm -rf ~/.claude/plugins/marketplaces/specweave
25
+ ln -s "$(pwd)" ~/.claude/plugins/marketplaces/specweave
52
26
 
53
- ### 📁 Increment Structure Rules (MANDATORY)
27
+ # Verify:
28
+ bash .specweave/increments/0043-spec-md-desync-fix/scripts/verify-dev-setup.sh
29
+ ```
54
30
 
55
- **ONLY 3 files allowed in increment root**:
56
- 1. `spec.md` - Specification
57
- 2. ✅ `plan.md` - Implementation plan
58
- 3. ✅ `tasks.md` - Tasks with embedded tests
31
+ **Without symlink**: Hooks fail, status line broken, living docs don't sync.
32
+ **Protection**: Pre-commit hook verifies symlink before each commit.
59
33
 
60
- **Everything else MUST be in subfolders**:
61
- - `reports/` - Session summaries, completion reports, analysis files, quick-start guides
62
- - `scripts/` - Helper scripts, migrations, utilities
63
- - `logs/` - Execution logs, debug output, temp files
34
+ ### 2. NEVER Pollute Increment Folders
64
35
 
65
- **Examples of files that belong in subfolders**:
66
- - `QUICK-START.md` `reports/QUICK-START.md`
67
- - `SESSION-NOTES.md` → `reports/SESSION-NOTES.md`
68
- - `ULTRATHINK-*.md` → `reports/ULTRATHINK-*.md`
69
- - `validation.sh` → `scripts/validation.sh`
70
- - `debug.log` → `logs/debug.log`
36
+ **ONLY 4 files allowed in `.specweave/increments/####/` root**:
37
+ - `spec.md`, `plan.md`, `tasks.md`, `metadata.json`
71
38
 
72
- **Why this matters**:
73
- - Clean, predictable structure
74
- - Easy to find files by type
75
- - No increment root clutter
76
- - ✅ Consistent across all increments
39
+ **Everything else → subfolders**:
40
+ - `reports/` - Analysis, completion reports, validation
41
+ - `scripts/` - Helper scripts, automation
42
+ - `logs/` - Execution logs, debug output
77
43
 
78
- ---
44
+ **Examples**:
45
+ ```bash
46
+ # ❌ WRONG
47
+ .specweave/increments/0046/analysis-report.md
79
48
 
80
- ## 🛡️ CRITICAL: NEVER DELETE .specweave/ DIRECTORIES!
49
+ # CORRECT
50
+ .specweave/increments/0046/reports/analysis-report.md
81
51
 
82
- **⛔ MASS DELETION PROTECTION IS ACTIVE ⛔**
52
+ # Fix before committing:
53
+ mkdir -p .specweave/increments/0046/reports
54
+ mv .specweave/increments/0046/*.md .specweave/increments/0046/reports/
55
+ git restore .specweave/increments/0046/{spec,plan,tasks}.md
56
+ ```
83
57
 
84
- **PROTECTED DIRECTORIES**:
85
- - `.specweave/docs/` - All project documentation (internal + public)
86
- - `.specweave/increments/` - All increment history and specifications
58
+ ### 3. NEVER Delete .specweave/ Directories
87
59
 
88
- **WHAT THIS MEANS**:
89
- - ❌ **NEVER** run `rm -rf .specweave/docs` or `rm -rf .specweave/increments`
90
- - ❌ **NEVER** delete more than 50 files in these directories at once
91
- - ✅ Pre-commit hook will **BLOCK** accidental mass deletions
92
- - ✅ If intentional, bypass with `git commit --no-verify`
60
+ **Protected**: `.specweave/docs/`, `.specweave/increments/`
93
61
 
94
- **WHY THIS EXISTS**:
95
- On 2025-11-17, an accidental mass deletion occurred (1,200+ files). All files were recovered via `git restore`, but this protection prevents future incidents.
62
+ **Pre-commit hook blocks**:
63
+ - `rm -rf .specweave/docs` or `rm -rf .specweave/increments`
64
+ - Deletion of 50+ files at once in these directories
96
65
 
97
- **IF YOU ACCIDENTALLY DELETE**:
66
+ **If accidental deletion**:
98
67
  ```bash
99
- # Immediately restore:
100
68
  git restore .specweave/
101
-
102
- # Verify restoration:
103
- git status
104
69
  ```
105
70
 
106
- **See**: `.specweave/increments/0039/reports/ACCIDENTAL-DELETION-RECOVERY-2025-11-17.md`
71
+ ### 4. Test Cleanup Safety (MANDATORY)
107
72
 
108
- ---
73
+ **Danger**: `rm -rf` with wrong `pwd` = delete entire test suite.
109
74
 
110
- ## 🚨 CRITICAL: DANGEROUS TEST CLEANUP OPERATIONS!
75
+ **REQUIRED steps before any `rm -rf`**:
76
+ 1. Verify `pwd` (MUST be project root)
77
+ 2. Dry-run with `-print` (NO deletion)
78
+ 3. Count files/directories to delete
79
+ 4. Manual confirmation (type "DELETE")
80
+ 5. Execute deletion
81
+ 6. Verify results
82
+ 7. Run tests
111
83
 
112
- **⛔ WARNING: Test cleanup can cause CATASTROPHIC deletion ⛔**
84
+ **Never** use `rm -rf` without ALL safety checks above.
113
85
 
114
- **INCIDENT**: On 2025-11-18, during increment 0042 (test infrastructure cleanup), a bash command nearly deleted the entire `tests/integration/` directory (209 test files). The command failed due to working directory confusion, but demonstrated the EXACT catastrophic risk identified in ultrathink analysis.
86
+ ### 5. NEVER Use `specweave init . --force`
115
87
 
116
- **THE DANGER**:
117
- ```bash
118
- # ❌ EXTREMELY DANGEROUS (can delete entire test suite):
119
- cd tests/integration
120
- find . -maxdepth 1 -type d ... -exec rm -rf {} +
121
- # Risk: Working directory confusion + no confirmation = catastrophic deletion
122
-
123
- # ❌ DANGEROUS (no verification):
124
- find tests/integration -type d -exec rm -rf {} +
125
- # Risk: Too broad, deletes everything
126
-
127
- # ❌ DANGEROUS (assumes pwd):
128
- rm -rf tests/integration/*/
129
- # Risk: If pwd is wrong, deletes unintended directories
130
- ```
88
+ **Danger**: Deletes ALL increments and docs without backup (unless you bypass warnings).
131
89
 
132
- **SAFE APPROACH** (MANDATORY for test cleanup):
90
+ **Safe alternative**:
133
91
  ```bash
134
- # STEP 1: Verify working directory (ALWAYS FIRST!)
135
- pwd
136
- # Must output: /Users/antonabyzov/Projects/github/specweave
137
-
138
- # ✅ STEP 2: DRY RUN (list only, NO deletion)
139
- find tests/integration -maxdepth 1 -type d \
140
- ! -name "integration" \
141
- ! -name "core" ! -name "features" ! -name "external-tools" ! -name "generators" \
142
- -print
143
- # Review output MANUALLY before proceeding
144
-
145
- # ✅ STEP 3: Count directories to delete
146
- find tests/integration -maxdepth 1 -type d \
147
- ! -name "integration" \
148
- ! -name "core" ! -name "features" ! -name "external-tools" ! -name "generators" \
149
- -print | wc -l
150
- # Verify count matches expectations
151
-
152
- # ✅ STEP 4: Manual confirmation (REQUIRED)
153
- echo "About to delete XX directories. Type 'DELETE' to confirm:"
154
- read confirmation
155
- if [ "$confirmation" != "DELETE" ]; then
156
- echo "Cancelled"
157
- exit 1
158
- fi
159
-
160
- # ✅ STEP 5: Execute deletion (ONLY after all checks pass)
161
- find tests/integration -maxdepth 1 -type d \
162
- ! -name "integration" \
163
- ! -name "core" ! -name "features" ! -name "external-tools" ! -name "generators" \
164
- -exec rm -rf {} +
165
-
166
- # ✅ STEP 6: Verify results
167
- ls tests/integration/
168
- find tests/integration -name "*.test.ts" | wc -l
169
-
170
- # ✅ STEP 7: Run tests (MANDATORY)
171
- npm run test:integration
92
+ specweave init . # Interactive, never deletes without confirmation
172
93
  ```
173
94
 
174
- **MANDATORY SAFETY RULES**:
175
- 1. ✅ **ALWAYS** verify `pwd` before ANY deletion command
176
- 2. ✅ **ALWAYS** use dry-run (`-print`) before `-exec rm`
177
- 3. ✅ **ALWAYS** count directories/files before deletion
178
- 4. ✅ **ALWAYS** require manual confirmation for deletion
179
- 5. ✅ **ALWAYS** verify results after deletion
180
- 6. ✅ **ALWAYS** run tests after structural changes
181
- 7. ✅ **NEVER** use `rm -rf` without multiple safety checks
182
-
183
- **WHY THIS MATTERS**:
184
- - 🔴 One wrong command = entire test suite deleted
185
- - 🔴 213 unsafe `process.cwd()` patterns exist in tests (increment 0042 audit)
186
- - 🔴 Working directory confusion is COMMON
187
- - 🔴 Recovery requires git restore (assumes uncommitted changes)
188
- - 🔴 If changes committed, recovery requires time-consuming rollback
189
-
190
- **LESSONS FROM INCIDENT 0042**:
191
- 1. **Dry-run is NOT optional** - Always list before deleting
192
- 2. **Working directory matters** - Verify pwd FIRST
193
- 3. **Confirmation prevents accidents** - Require manual "DELETE" confirmation
194
- 4. **Test after changes** - Structural changes can break tests
195
- 5. **Incremental commits** - Commit after each phase (easier rollback)
196
-
197
- **IF CATASTROPHIC DELETION OCCURS**:
198
- ```bash
199
- # Immediately restore from git (if not committed):
200
- git restore tests/
201
-
202
- # If committed, restore from previous commit:
203
- git log --oneline -- tests/
204
- git checkout <previous-commit-hash> -- tests/
95
+ ### 6. Increment Completion Validation
205
96
 
206
- # Verify restoration:
207
- find tests -name "*.test.ts" | wc -l
208
- npm run test:all
209
- ```
97
+ **NEVER** mark increment "completed" without:
98
+ 1. All acceptance criteria checked (`- [x] **AC-...`)
99
+ 2. All tasks completed
100
+ 3. All tests passing
101
+ 4. Coverage target met
210
102
 
211
- **REFERENCES**:
212
- - Incident report: `.specweave/increments/0042-test-infrastructure-cleanup/reports/CATASTROPHIC-DELETION-INCIDENT-2025-11-18.md`
213
- - Ultrathink analysis: `.specweave/increments/0041-living-docs-test-fixes/reports/ULTRATHINK-TEST-DUPLICATION-ANALYSIS-2025-11-18.md`
214
- - Safe cleanup approach: Increment 0042 Phase 1 tasks
103
+ **Always use**: `/specweave:done 0043` (validates before closing)
104
+ **Never**: Manual `metadata.json` edit (blocked by pre-commit hook)
215
105
 
216
- **NEVER delete test directories without following ALL safety steps above!**
106
+ ### 7. Source of Truth: tasks.md and spec.md (CRITICAL!)
217
107
 
218
- ---
108
+ **THE MOST CRITICAL RULE**: Internal TODO lists are ONLY for tracking work during execution. The SOURCE OF TRUTH is ALWAYS:
109
+ 1. **tasks.md** - Task completion status (`[x]` checkboxes)
110
+ 2. **spec.md** - Acceptance criteria status (`[x]` checkboxes)
219
111
 
220
- ## ⚠️ CRITICAL: NEVER USE `specweave init . --force` FOR REINSTALLS!
112
+ **MANDATORY Workflow When Using TodoWrite Tool**:
221
113
 
222
- **⛔ COMMON MISTAKE THAT DELETES ALL DATA ⛔**
223
-
224
- **THE DANGER**:
225
- ```bash
226
- # ❌ DANGEROUS (deletes ALL increments and docs):
227
- specweave init . --force
228
-
229
- # What --force actually does:
230
- # 1. Skips all confirmation prompts
231
- # 2. AUTOMATICALLY DELETES .specweave/ entirely
232
- # 3. Loses all increments, docs, and history
233
- # 4. No backup unless you create one manually
234
114
  ```
235
-
236
- **SAFE ALTERNATIVES**:
237
- ```bash
238
- # SAFE - Update files, keep all data:
239
- specweave init .
240
- # When prompted, select: "Continue working"
241
-
242
- # ✅ SAFE - Always interactive, never deletes:
243
- npx specweave init .
115
+ For EVERY task marked complete in internal TODO:
116
+ 1. ✅ Mark task as completed in internal TODO
117
+ 2. ⚠️ IMMEDIATELY update tasks.md checkbox: `[ ] pending` → `[x] completed`
118
+ 3. ⚠️ IMMEDIATELY update spec.md AC checkbox: `[ ]` → `[x]`
119
+ 4. Verify both files updated BEFORE moving to next task
244
120
  ```
245
121
 
246
- **WHY THIS MATTERS**:
247
- - Documentation used to recommend `--force` for troubleshooting (FIXED in v0.21.4+)
248
- - Users followed the docs and lost all their work
249
- - Now `--force` has multiple safeguards:
250
- - ⚠️ BIG RED WARNING before deletion
251
- - ✅ ALWAYS requires confirmation (even in force mode)
252
- - 📦 Automatic backup created before deletion
253
- - 🔒 Pre-commit hook blocks accidental commits
254
-
255
- **IF YOU NEED A FRESH START**:
256
- 1. Backup first: `cp -r .specweave .specweave.backup-$(date +%Y%m%d)`
257
- 2. Run: `specweave init .` (select "Fresh start" option)
258
- 3. Or: `specweave init . --force` (requires confirmation + creates auto-backup)
259
-
260
- **NEVER use `--force` unless you want to DELETE EVERYTHING!**
261
-
262
- ---
263
-
264
- ## Tool Support
265
-
266
- SpecWeave supports multiple AI coding tools with varying automation levels:
267
- - **Claude Code** (Recommended): Native support via plugins, hooks, MCP
268
- - **Cursor**: Partial support via AGENTS.md compilation
269
- - **Other tools** (Copilot, ChatGPT, Gemini): Basic support via AGENTS.md
270
-
271
- For adapter implementation details, see "Multi-Tool Support via Adapters" section below.
272
-
273
- ---
274
-
275
- ## Development Workflow
276
-
277
- ### Core SpecWeave Commands
122
+ **Example of CORRECT workflow**:
123
+ ```typescript
124
+ // Step 1: Complete the work
125
+ await createIntegrationTest();
278
126
 
279
- **Note**: Detailed rules (naming, discipline, archiving) are in skills that auto-load when you use these commands.
127
+ // Step 2: Update internal TODO
128
+ TodoWrite([{task: "T-013", status: "completed"}]);
280
129
 
281
- **Primary Workflow**:
282
- ```bash
283
- /specweave:increment "feature name" # Plan new work (increment-planner skill)
284
- /specweave:do # Execute tasks
285
- /specweave:progress # Check status
286
- /specweave:done # Close increment
287
- ```
130
+ // Step 3: IMMEDIATELY update tasks.md (NEVER skip this!)
131
+ Edit("tasks.md", "**Status**: [ ] pending", "**Status**: [x] completed");
288
132
 
289
- **State Management**:
290
- ```bash
291
- /specweave:pause 0002 --reason="..." # Pause increment
292
- /specweave:resume 0002 # Resume paused
293
- /specweave:abandon 0002 # Abandon incomplete
294
- ```
133
+ // Step 4: IMMEDIATELY update spec.md ACs
134
+ Edit("spec.md", "- [ ] **AC-US1-01**", "- [x] **AC-US1-01**");
295
135
 
296
- **Archiving** (MANUAL ONLY):
297
- ```bash
298
- /specweave:archive 0031 # Archive specific
299
- /specweave:archive --keep-last 10 # Archive old work
300
- /specweave:restore 0031 # Restore from archive
136
+ // Step 5: Move to next task
301
137
  ```
302
138
 
303
- **Quality**:
304
- ```bash
305
- /specweave:validate 0001 # Rule-based validation
306
- /specweave:qa 0001 # AI quality assessment
139
+ **❌ CRITICAL ERROR - Never Do This**:
140
+ ```typescript
141
+ // ❌ WRONG: Marking TODO as complete WITHOUT updating source files
142
+ TodoWrite([
143
+ {task: "T-013", status: "completed"}, // ❌ Only internal tracking
144
+ {task: "T-014", status: "completed"}, // ❌ Only internal tracking
145
+ {task: "T-015", status: "completed"} // ❌ Only internal tracking
146
+ ]);
147
+ // tasks.md still shows `[ ] pending` → DESYNC!
148
+ // This is a CRITICAL VIOLATION!
307
149
  ```
308
150
 
309
- **Documentation**:
151
+ **Pre-Closure Validation** (MANDATORY before `/specweave:done`):
310
152
  ```bash
311
- /specweave:sync-docs update # Sync living docs
312
- /specweave:sync-tasks # Sync task status
313
- ```
314
-
315
- **For complete command reference**: See "Quick Reference" section below.
316
-
317
- ---
318
-
319
- ## Project Structure
153
+ # 1. Verify ALL tasks marked in tasks.md
154
+ grep "^\*\*Status\*\*:" tasks.md | grep -c "\[x\] completed"
155
+ # Output MUST equal total_tasks in frontmatter
320
156
 
321
- ### Source of Truth Principle
157
+ # 2. Verify ALL ACs checked in spec.md
158
+ grep -c "^- \[x\] \*\*AC-" spec.md
159
+ # Output MUST equal total ACs
322
160
 
161
+ # 3. Only then close increment
162
+ /specweave:done 0044
323
163
  ```
324
- src/ # TypeScript code ONLY (compiled to dist/)
325
- plugins/ # ALL Claude Code components (skills, agents, commands, hooks)
326
- ├── specweave/ # Core plugin (auto-loaded)
327
- └── specweave-*/ # Optional plugins (GitHub, JIRA, etc.)
328
- .specweave/ # Framework data (increments, docs, logs)
329
- ```
330
-
331
- **Key Rules**:
332
- - ✅ `src/` = TypeScript code ONLY
333
- - ✅ ALL skills/agents/commands/hooks = Inside `plugins/`
334
- - ✅ Marketplace = GLOBAL via CLI (no per-project `.claude/`)
335
- - ❌ NEVER mix `*.ts` and `SKILL.md` in same directory
336
- - ❌ NEVER create new files in project root (use increment folders)
337
-
338
- **For complete structure**: See `README.md`
339
-
340
- ---
341
164
 
342
- ## Plugin Architecture
343
-
344
- ### Core Plugin (Always Auto-Loaded)
345
-
346
- **Plugin**: `specweave` - The essential SpecWeave plugin loaded in every project:
347
- - **Skills**: 9 skills (increment-planner, tdd-workflow, spec-generator, etc.)
348
- - **Agents**: 22 agents (PM, Architect, Tech Lead, + 19 specialized)
349
- - **Commands**: 22 commands (/specweave:increment, /specweave:do, etc.)
350
- - **Hooks**: 8 lifecycle hooks
351
- - **Size**: ~12K tokens
352
-
353
- ### Available Plugins
165
+ **Why This Matters**:
166
+ - Internal TODO is ephemeral (lost between sessions)
167
+ - tasks.md is permanent source of truth
168
+ - spec.md is contract with stakeholders
169
+ - Desync = broken promises to users/team
354
170
 
355
- All plugins are auto-installed during `specweave init`. Skills activate based on context keywords.
171
+ **Incident Reference**: 2025-11-19 - Increment 0044 was incorrectly closed with tasks.md showing `[ ] pending` while internal TODO showed "completed". This violated SpecWeave's core principle. See `.specweave/increments/0044-integration-testing-status-hooks/reports/INCIDENT-SOURCE-OF-TRUTH-VIOLATION.md` for full post-mortem.
356
172
 
357
- **Plugin List**: `ls plugins/` or `/plugin list --installed`
173
+ ### 8. NEVER Use `console.*` in Production Code
358
174
 
359
- **Example plugins**:
360
- - `specweave` - Core (increment lifecycle, living docs)
361
- - `specweave-github` - GitHub Issues sync
362
- - `specweave-{frontend|backend|infrastructure}` - Tech stacks
363
- - `specweave-{ml|payments}` - Domain-specific
175
+ **Rule**: ALL `src/` code MUST use logger abstraction, NEVER `console.log/error/warn`.
364
176
 
365
- ### Plugin Installation
177
+ **Why**: `console.*` pollutes test output even when errors are expected and properly handled.
366
178
 
367
- `specweave init` automatically:
368
- 1. Registers marketplace: `claude plugin marketplace add anton-abyzov/specweave`
369
- 2. Installs all plugins via Claude CLI
370
- 3. Marketplace is GLOBAL (persists across projects)
179
+ **Use logger injection**:
180
+ ```typescript
181
+ import { Logger, consoleLogger } from '../../utils/logger.js';
371
182
 
372
- After init, all plugins are ready. Skills auto-activate based on keywords.
183
+ export class MyClass {
184
+ private logger: Logger;
373
185
 
374
- ### Local Development Setup (Contributors Only)
186
+ constructor(options: { logger?: Logger } = {}) {
187
+ this.logger = options.logger ?? consoleLogger;
188
+ }
375
189
 
376
- **🚨 CRITICAL for SpecWeave Contributors:**
190
+ doSomething() {
191
+ this.logger.log('Info message');
192
+ this.logger.error('Error message', error);
193
+ }
194
+ }
195
+ ```
377
196
 
378
- When developing SpecWeave itself, you MUST use a **symlink** from the marketplace to your local repository. This ensures:
379
- - ✅ All code/hook/skill changes are immediately reflected
380
- - No need to reinstall plugins after every change
381
- - ✅ Real-time testing of hooks, skills, and commands
197
+ **In tests, use `silentLogger`**:
198
+ ```typescript
199
+ import { silentLogger } from '../../src/utils/logger.js';
382
200
 
383
- **Setup Instructions:**
201
+ const instance = new MyClass({ logger: silentLogger });
202
+ ```
384
203
 
204
+ **Protection**: Code review + search before commit:
385
205
  ```bash
386
- # 1. Remove any existing marketplace installation
387
- rm -rf ~/.claude/plugins/marketplaces/specweave
388
-
389
- # 2. Create symlink to your local SpecWeave repository
390
- ln -s /path/to/your/specweave/repo ~/.claude/plugins/marketplaces/specweave
391
-
392
- # Example:
393
- ln -s ~/Projects/github/specweave ~/.claude/plugins/marketplaces/specweave
394
-
395
- # 3. Register the local marketplace with Claude Code
396
- cd /path/to/your/specweave/repo
397
- claude plugin marketplace add ./.
398
-
399
- # 4. Verify the marketplace is registered
400
- claude plugin marketplace list
401
- # Should show: specweave (Source: Directory /path/to/your/repo)
402
-
403
- # 5. Update marketplace to discover all plugins
404
- claude plugin marketplace update specweave
405
-
406
- # 6. Verify hooks are accessible
407
- test -f ~/.claude/plugins/marketplaces/specweave/plugins/specweave/hooks/user-prompt-submit.sh && \
408
- echo "✅ Hooks accessible" || echo "❌ Setup failed"
206
+ # Check for console.* in src/ before committing:
207
+ git diff --cached --name-only | grep '^src/.*\.ts$' | xargs grep -n 'console\.' 2>/dev/null
409
208
  ```
410
209
 
411
- **If you see "Plugin not found" errors:**
210
+ ### 9. Coding Standards
412
211
 
413
- This means the plugin registry is out of sync. Fix it:
212
+ **Full standards**: `.specweave/docs/internal/governance/coding-standards.md`
213
+ **Auto-discovery**: Runs during brownfield analysis or `/specweave:analyze-standards`
414
214
 
415
- ```bash
416
- # 1. Backup current registry
417
- cp ~/.claude/plugins/installed_plugins.json ~/.claude/plugins/installed_plugins.json.backup
418
-
419
- # 2. Clear registry (forces rediscovery)
420
- echo '{"version": 1, "plugins": {}}' > ~/.claude/plugins/installed_plugins.json
215
+ **Critical rules (enforced during code generation)**:
421
216
 
422
- # 3. Update marketplace
423
- claude plugin marketplace update specweave
217
+ 1. **NEVER use `console.*`** - Use logger abstraction (already enforced above)
218
+ 2. **ALWAYS import with `.js` extensions** - Required for ESM (already enforced in Build section)
219
+ 3. ✅ **Test files MUST use `.test.ts`** suffix, never `.spec.ts` (already enforced in Testing section)
220
+ 4. **Avoid `any` type** - Use specific types or generics
221
+ 5. **Functions < 50 lines** (ideal), < 100 lines (max)
222
+ 6. **Use custom error types**, not generic Error
223
+ 7. **Comment "why" not "what"**
224
+ 8. **No hardcoded secrets** - Use environment variables
225
+ 9. **No N+1 queries** - Batch database operations
226
+ 10. **Naming**: camelCase (vars), PascalCase (classes), UPPER_SNAKE_CASE (constants)
424
227
 
425
- # 4. Restart Claude Code
426
- # All 25 plugins will be rediscovered from your local repo
427
- ```
228
+ **Auto-discovery features**:
229
+ - **Brownfield projects**: Standards auto-detected during project analysis
230
+ - **Manual analysis**: `/specweave:analyze-standards` - Generate comprehensive standards report
231
+ - **Drift detection**: `/specweave:analyze-standards --drift` - Check compliance with declared standards
232
+ - **Update standards**: `/specweave:analyze-standards --update` - Update official standards from analysis
428
233
 
429
- **Verification:**
234
+ **How it works**:
235
+ 1. Scans codebase (src/**/*.ts) for naming patterns, import styles, function characteristics
236
+ 2. Parses ESLint, Prettier, TypeScript configs for enforced rules
237
+ 3. Analyzes existing CLAUDE.md, CONTRIBUTING.md for declared standards
238
+ 4. Generates evidence-based standards with confidence levels (90%+ = HIGH confidence)
239
+ 5. Detects anti-patterns: hardcoded secrets, large files (>500 lines), missing error handling
240
+ 6. Outputs to `.specweave/docs/internal/governance/coding-standards-analysis.md`
430
241
 
431
- ```bash
432
- # Check symlink target
433
- readlink ~/.claude/plugins/marketplaces/specweave
434
- # Should output: /path/to/your/specweave/repo
242
+ **Note**: Most standards are enforced by ESLint/Prettier. This list focuses on SpecWeave-specific rules and patterns that can't be auto-fixed by linters.
435
243
 
436
- # Check all plugins are accessible
437
- ls ~/.claude/plugins/marketplaces/specweave/plugins/
438
- # Should list: specweave, specweave-github, specweave-jira, etc.
439
- ```
244
+ ---
440
245
 
441
- **Why This Matters:**
246
+ ## Project Structure
442
247
 
443
- Without the symlink, Claude Code will try to execute hooks from a non-existent location:
444
248
  ```
445
- Plugin hook error: /bin/sh:
446
- ~/.claude/plugins/marketplaces/specweave/plugins/specweave/hooks/user-prompt-submit.sh:
447
- No such file or directory
249
+ src/ # TypeScript code (compiled to dist/)
250
+ plugins/ # Claude Code components (skills, agents, commands, hooks)
251
+ ├── specweave/ # Core plugin
252
+ └── specweave-*/ # Optional plugins (GitHub, JIRA, etc.)
253
+ .specweave/ # Framework data (increments, docs, logs)
448
254
  ```
449
255
 
450
- **Troubleshooting:**
451
-
452
- If you see "Plugin not found in marketplace 'specweave'" errors:
453
- 1. Check symlink exists: `ls -la ~/.claude/plugins/marketplaces/specweave`
454
- 2. Verify it points to your repo: `readlink ~/.claude/plugins/marketplaces/specweave`
455
- 3. Recreate symlink if needed (see setup instructions above)
456
-
457
- **What NOT to Do:**
458
-
459
- - ❌ Don't copy the repository - use a symlink
460
- - ❌ Don't use relative paths in symlink - use absolute paths
461
- - ❌ Don't register the marketplace via `claude plugin marketplace add` - symlink is enough for local dev
256
+ **Rules**:
257
+ - `src/` = TypeScript ONLY
258
+ - ALL skills/agents/commands/hooks = `plugins/`
259
+ - Marketplace = GLOBAL via CLI
260
+ - NEVER mix `*.ts` and `SKILL.md` in same directory
261
+ - NEVER create files in project root
462
262
 
463
263
  ---
464
264
 
465
- ## Multi-Tool Support via Adapters
466
-
467
- SpecWeave supports multiple AI coding tools through an adapter system. Tool selection happens during `specweave init`.
468
-
469
- **Adapter Architecture**:
470
- - **Location**: `src/adapters/` (interface, loader, tool-specific implementations)
471
- - **Selection**: Auto-detected or via `--adapter` flag
472
- - **Files**: Tool-specific files (`.cursorrules`, `AGENTS.md`, etc.)
473
-
474
- **Supported Tools**:
475
-
476
- | Tool | Automation Level | Implementation | Status |
477
- |------|------------------|----------------|--------|
478
- | **Claude Code** | Full | Native plugins (no adapter) | ✅ Recommended |
479
- | **Cursor** | Partial | AGENTS.md compilation | ✅ Supported |
480
- | **Generic** | Basic | AGENTS.md static file | ✅ Supported |
481
-
482
- **Key Differences**:
483
- - **Claude Code**: No adapter needed - uses native plugin system
484
- - **Cursor/Generic**: Require compilation step to generate AGENTS.md
485
- - **All tools**: Share same `.specweave/` data structure
265
+ ## Development Workflow
486
266
 
487
- **For contributors**: Adapter code is in `src/adapters/`. Tests in `tests/unit/adapter-loader.test.ts`.
267
+ ### Core Commands
488
268
 
489
- ---
490
-
491
- ## Development Principles
269
+ ```bash
270
+ # Primary workflow
271
+ /specweave:increment "feature" # Plan new work
272
+ /specweave:do # Execute tasks
273
+ /specweave:progress # Check status
274
+ /specweave:done # Close (validates ACs, tasks, tests)
492
275
 
493
- See [.github/CONTRIBUTING.md](.github/CONTRIBUTING.md#core-development-principles) for:
494
- - Source of Truth Discipline
495
- - Documentation = Code
496
- - Testing Requirements
497
- - Incremental Development
498
- - Multi-Tool Support
276
+ # State management
277
+ /specweave:pause 0002 --reason="..."
278
+ /specweave:resume 0002
279
+ /specweave:abandon 0002
499
280
 
500
- ---
281
+ # Quality
282
+ /specweave:validate 0001
283
+ /specweave:qa 0001
501
284
 
502
- ## Recent Architectural Enhancements (v0.18.3+)
503
-
504
- ### Project-Specific Tasks in User Stories
285
+ # Documentation
286
+ /specweave:sync-docs update
287
+ /specweave:sync-tasks
288
+ ```
505
289
 
506
- **New in v0.18.3**: User stories now include project-specific checkable task lists instead of just links to increment tasks.
290
+ ### Local Development Setup
507
291
 
508
- **Key Changes**:
509
- 1. **TaskProjectSpecificGenerator** (`src/core/living-docs/task-project-specific-generator.ts`):
510
- - Filters increment tasks by User Story ID (via AC-IDs)
511
- - Optional project keyword filtering (backend vs frontend)
512
- - Preserves completion status from increment tasks.md
292
+ ```bash
293
+ # 1. Clone and install
294
+ git clone https://github.com/YOUR_USERNAME/specweave.git
295
+ cd specweave
296
+ npm install
513
297
 
514
- 2. **User Story File Format** - New `## Tasks` section:
515
- ```markdown
516
- ## Tasks
298
+ # 2. Create symlink (CRITICAL!)
299
+ mkdir -p ~/.claude/plugins/marketplaces
300
+ rm -rf ~/.claude/plugins/marketplaces/specweave
301
+ ln -s "$(pwd)" ~/.claude/plugins/marketplaces/specweave
517
302
 
518
- - [ ] **T-001**: Setup API endpoint
519
- - [x] **T-003**: Add DB migration (completed)
303
+ # 3. Verify setup
304
+ bash .specweave/increments/0043-spec-md-desync-fix/scripts/verify-dev-setup.sh
520
305
 
521
- > **Note**: Tasks are project-specific. See increment tasks.md for full list
306
+ # 4. Install git hooks
307
+ bash scripts/install-git-hooks.sh
522
308
  ```
523
309
 
524
- 3. **GitHub Sync** - Issues now have checkable task lists:
525
- - Stakeholders can tick/untick tasks in GitHub
526
- - Task completion syncs from user story files
527
- - Backward compatible (falls back to legacy extraction)
528
-
529
- **Benefits**:
530
- - **Project Isolation**: Backend tasks ≠ Frontend tasks
531
- - **Traceability**: Each user story explicitly lists its tasks
532
- - **GitHub UX**: Checkable task lists in issues
533
- - **Completion Tracking**: Status preserved from increment
534
-
535
- **Data Flow**:
536
- ```
537
- Increment tasks.md (All tasks, source of truth)
538
-
539
- TaskProjectSpecificGenerator (Filters by US + Project)
540
-
541
- User Story ## Tasks Section (Project-specific checkboxes)
542
-
543
- GitHub Issue (Checkable task list for stakeholders)
310
+ **If "Plugin not found" errors**:
311
+ ```bash
312
+ echo '{"version": 1, "plugins": {}}' > ~/.claude/plugins/installed_plugins.json
313
+ claude plugin marketplace update specweave
544
314
  ```
545
315
 
546
- **See Also**:
547
- - Implementation: `.specweave/increments/0034-github-ac-checkboxes-fix/reports/PROJECT-SPECIFIC-TASKS-IMPLEMENTATION-COMPLETE.md`
548
- - Architecture: `.specweave/increments/0034-github-ac-checkboxes-fix/reports/ULTRATHINK-PROJECT-SPECIFIC-TASKS-ARCHITECTURE.md`
549
-
550
316
  ---
551
317
 
552
318
  ## Build & Test
553
319
 
554
- ### Build Commands
320
+ ### Build
555
321
 
556
322
  ```bash
557
- # ALWAYS use clean build during development (prevents TS5055 errors)
558
- npm run rebuild # Clean + build (RECOMMENDED)
323
+ npm run rebuild # Clean + build (use this during development)
324
+ npm run build # Compile TypeScript
325
+ npm run clean # Remove dist/
326
+ ```
559
327
 
560
- # Or manual steps:
561
- npm run clean # Remove dist/ folder
562
- npm run build # Compile TypeScript
328
+ **Critical**: Always import with `.js` extensions:
329
+ ```typescript
330
+ // CORRECT
331
+ import { foo } from './bar.js';
332
+
333
+ // ❌ WRONG
334
+ import { foo } from './bar';
563
335
  ```
564
336
 
337
+ **Fix missing extensions**: `node scripts/fix-js-extensions.js`
338
+
565
339
  ### Testing
566
340
 
567
- **Test Framework**: **Vitest** (migrated from Jest on 2025-11-17)
341
+ **Framework**: Vitest (migrated from Jest 2025-11-17)
568
342
 
569
343
  ```bash
570
- npm test # Smoke tests (quick validation)
571
- npm run test:unit # Unit tests with Vitest
572
- npm run test:integration # Integration tests with Vitest
344
+ npm test # Smoke tests
345
+ npm run test:unit # Unit tests
346
+ npm run test:integration # Integration tests
573
347
  npm run test:e2e # E2E tests (Playwright)
574
348
  npm run test:all # All tests
575
349
  npm run test:coverage # Coverage report
576
350
  ```
577
351
 
578
- **Why Vitest?**
579
- - ESM-native (no tsconfig hacks)
580
- - Faster than Jest
581
- - Better TypeScript integration
582
- - ✅ Native import.meta.url support
583
- - ✅ Modern, actively maintained
584
-
585
- **Test Organization** (4 categories):
586
- - `tests/unit/` - Pure logic tests (no I/O) - **Vitest**
587
- - `tests/plugin-validation/` - Plugin structure contracts
588
- - `tests/integration/` - 4 semantic categories - **Vitest**:
589
- - `external-tools/` - GitHub, JIRA, ADO, Kafka sync
590
- - `core/` - Core framework + workflows
591
- - `generators/` - Code generation (frontend, backend, ML)
592
- - `features/` - Feature plugins (Figma, i18n, diagrams, etc.)
593
- - `tests/e2e/` - Full user scenarios - **Playwright**
594
-
595
- **Test Naming Convention** (standardized 2025-11-18):
596
- - ✅ ALL tests use `.test.ts` extension (unit, integration, E2E)
597
- - ❌ NEVER use `.spec.ts` extension (deprecated)
598
- - **Why**: Consistent glob patterns, simpler test discovery, aligned with Vitest conventions
599
-
600
- **Writing Tests**:
601
- ```typescript
602
- // Import from vitest (NOT jest)
603
- import { describe, it, expect, beforeEach, vi } from 'vitest';
604
-
605
- // Mocking
606
- vi.mock('fs/promises');
607
- const mockFn = vi.fn();
608
- vi.clearAllMocks();
609
- ```
610
-
611
- **Details**: `.specweave/docs/internal/architecture/TEST-ORGANIZATION-PROPOSAL.md`
612
-
613
- ### Test Isolation (CRITICAL - Prevents .specweave/ Deletion!)
614
-
615
- **🚨 MANDATORY FOR ALL TESTS creating .specweave/ structures:**
616
-
617
- **THE PROBLEM**: Tests using `process.cwd()` can accidentally delete the project `.specweave/` folder containing all your work!
618
-
619
- **CORRECT PATTERN** (ALWAYS use this):
620
- ```typescript
621
- import * as os from 'os';
622
- import * as path from 'path';
623
-
624
- // ✅ SAFE: Uses isolated temp directory
625
- const testRoot = path.join(os.tmpdir(), 'test-name-' + Date.now());
626
- ```
627
-
628
- **DANGEROUS PATTERN** (NEVER use this):
629
- ```typescript
630
- // ❌ DANGER: Creates directories in project root!
631
- const testRoot = path.join(process.cwd(), '.test-something');
632
- const testPath = path.join(__dirname, '..', '.specweave', 'increments');
633
- ```
352
+ **Test structure**:
353
+ - `tests/unit/` - Pure logic (no I/O)
354
+ - `tests/integration/` - Organized by: `core/`, `external-tools/`, `generators/`, `features/`
355
+ - `tests/e2e/` - Full user scenarios
634
356
 
635
- ### Vitest Mock Best Practices
357
+ **Naming**: ALL tests use `.test.ts` (NEVER `.spec.ts`)
636
358
 
637
- **🚨 MANDATORY FOR ALL TESTS using mocks:**
359
+ ### Writing Tests
638
360
 
639
- **CORRECT PATTERN** (vi.mocked() for type-safe mocks):
640
361
  ```typescript
362
+ // ✅ CORRECT
641
363
  import { describe, it, expect, beforeEach, vi } from 'vitest';
642
364
  import fs from 'fs-extra';
643
365
 
644
- // Mock fs-extra BEFORE using it
645
366
  vi.mock('fs-extra');
646
367
 
647
- // Type-safe mocked functions
648
368
  const mockReadFile = vi.mocked(fs.readFile);
649
- const mockWriteFile = vi.mocked(fs.writeFile);
650
- const mockExistsSync = vi.mocked(fs.existsSync);
651
369
 
652
370
  beforeEach(() => {
653
371
  vi.clearAllMocks();
654
- mockExistsSync.mockReturnValue(true);
655
372
  mockReadFile.mockResolvedValue('content');
656
373
  });
657
374
  ```
658
375
 
659
- **DANGEROUS PATTERN** (NEVER use this):
376
+ **Critical anti-patterns**:
660
377
  ```typescript
661
- // ❌ WRONG: Invalid anyed<> syntax (pre-Vitest migration)
662
- const mockFs = fs as anyed<typeof fs> & {
663
- readFile: anyedFunction<typeof fs.readFile>;
664
- };
665
- // This causes TypeScript errors and test failures!
666
- ```
667
-
668
- **Why This Matters**:
669
- 1. `vi.mocked()` provides full type safety
670
- 2. Catches mock setup errors at compile time
671
- 3. Works correctly with Vitest's mock system
672
- 4. Prevents runtime "Cannot read properties of undefined" errors
378
+ // ❌ NEVER use jest APIs
379
+ jest.fn() // Use: vi.fn()
380
+ jest.mock() // Use: vi.mock()
673
381
 
674
- **Common Mock Gotchas**:
675
- - Always call `vi.clearAllMocks()` in beforeEach
676
- - Use `mockResolvedValue` for async functions
677
- - Use `mockReturnValue` for sync functions
678
- - Check that mocks are actually called: `expect(mockFn).toHaveBeenCalled()`
679
-
680
- ### Testing Best Practices & Anti-Patterns
681
-
682
- **Lessons from fixing 72+ test failures (2025-11-17 Vitest migration)**
683
-
684
- #### Critical Rules (Will Fail Tests)
382
+ // NEVER use project root in tests
383
+ const testRoot = path.join(process.cwd(), '.test-something');
685
384
 
686
- ```typescript
687
- // WRONG // CORRECT
688
- require('../src/module') import { Module } from '../src/module.js'
689
- jest.fn() vi.fn()
690
- jest.mock() vi.mock()
691
- fs as anyed<typeof fs> vi.mocked(fs.readFile)
692
- const mock = vi.fn() vi.mock('mod', () => ({
693
- vi.mock('mod', () => ({ mock })) method: vi.fn() // inline!
694
- }))
695
- mockReadJson.mockResolvedValue(arr) mockReadJson.mockResolvedValue([...arr]) // copy!
385
+ // ✅ ALWAYS use temp directory
386
+ const testRoot = path.join(os.tmpdir(), 'test-' + Date.now());
696
387
  ```
697
388
 
698
- #### Quick Template
699
-
389
+ **Use test utilities**:
700
390
  ```typescript
701
- import { describe, it, expect, vi } from 'vitest';
702
- vi.mock('fs-extra', () => ({ default: { readFile: vi.fn() } }));
703
- import fs from 'fs-extra';
391
+ import { createIsolatedTestDir } from '../test-utils/isolated-test-dir';
704
392
 
705
- describe('Feature', () => {
706
- const mockReadFile = vi.mocked(fs.readFile);
707
-
708
- beforeEach(() => {
709
- vi.clearAllMocks();
710
- mockReadFile.mockResolvedValue('data');
711
- });
712
-
713
- it('works', async () => {
714
- const result = await MyModule.doSomething();
715
- expect(mockReadFile).toHaveBeenCalled();
716
- });
717
- });
393
+ const { testDir, cleanup } = await createIsolatedTestDir('my-test');
394
+ try {
395
+ // Test code here
396
+ } finally {
397
+ await cleanup(); // ALWAYS cleanup
398
+ }
718
399
  ```
719
400
 
720
- #### Pre-Commit Checklist
721
-
722
- - [ ] ES6 imports (NOT require())
723
- - [ ] vi.* APIs (NOT jest.*)
724
- - [ ] vi.mocked() for mocks (NOT anyed<>)
725
- - [ ] Inline mock factories (NO external variables)
726
- - [ ] Array copies in mocks (NO shared references)
727
- - [ ] vi.clearAllMocks() in beforeEach()
728
-
729
- **Full guide**: `tests/test-template.test.ts`
401
+ ### Build Architecture
730
402
 
731
- **Why This Matters**:
732
- 1. Tests create mock `.specweave/` structures for testing
733
- 2. Cleanup uses `fs.rm(testRoot, { recursive: true })`
734
- 3. If `testRoot` points to project root → **DELETES REAL .specweave/!**
735
- 4. You lose all increments, docs, and history
403
+ **Dual compilation**:
404
+ - `tsc`: `src/` `dist/src/` (source files)
405
+ - `esbuild`: `plugins/**/lib/hooks/*.ts` in-place `.js` (hooks only)
736
406
 
737
- **Use Test Utilities** (RECOMMENDED):
407
+ **Hook imports**:
738
408
  ```typescript
739
- import { createIsolatedTestDir, createSpecweaveStructure } from '../test-utils/isolated-test-dir';
740
-
741
- test('my test', async () => {
742
- const { testDir, cleanup } = await createIsolatedTestDir('my-test');
743
-
744
- try {
745
- // Setup .specweave structure in isolated directory
746
- await createSpecweaveStructure(testDir);
747
-
748
- // Test code here - NEVER touches project .specweave/
749
- const incrementPath = path.join(testDir, '.specweave', 'increments', '0001-test');
750
- // ...
751
- } finally {
752
- await cleanup(); // ALWAYS cleanup
753
- }
754
- });
755
- ```
756
-
757
- **Protection Layers**:
758
- 1. ✅ **Pre-commit hook**: Blocks commits with dangerous test patterns
759
- 2. ✅ **Test utilities**: `tests/test-utils/isolated-test-dir.ts`
760
- 3. ✅ **Documentation**: This section
761
-
762
- **Related Incident**: 2025-11-17 - Multiple `.specweave/` deletions traced to dangerous test patterns
763
- **Root Cause Analysis**: `.specweave/increments/0037/reports/DELETION-ROOT-CAUSE-2025-11-17.md`
764
-
765
- ### Build Health Checks
766
-
767
- **CRITICAL**: TypeScript ES Modules require specific practices:
768
-
769
- 1. **Always Import with .js Extensions**:
770
- ```typescript
771
- // ❌ WRONG (will break at runtime):
772
- import { foo } from './bar';
773
-
774
- // ✅ CORRECT:
775
- import { foo } from './bar.js';
776
- ```
777
-
778
- 2. **Fix Missing Extensions**:
779
- ```bash
780
- # Auto-fix all missing .js extensions:
781
- node scripts/fix-js-extensions.js
782
-
783
- # Preview changes first:
784
- node scripts/fix-js-extensions.js --dry-run
785
- ```
786
-
787
- 3. **Verify Build is Clean**:
788
- ```bash
789
- # Check for polluted dist/ (TS5055 indicator):
790
- find dist/src -name "*.ts" -not -name "*.d.ts"
791
- # Should return NOTHING
792
-
793
- # If files found, clean rebuild:
794
- npm run rebuild
795
- ```
796
-
797
- 4. **Test Hook Execution**:
798
- ```bash
799
- # Hooks must import correctly at runtime:
800
- node plugins/specweave/lib/hooks/update-ac-status.js 0001
801
- # Should execute without "Cannot find module" errors
802
- ```
803
-
804
- 5. **Install Git Hooks** (RECOMMENDED):
805
- ```bash
806
- bash scripts/install-git-hooks.sh
807
- # Verifies build health before every commit
808
- ```
809
-
810
- ### Common Build Errors & Fixes
811
-
812
- **Error: TS5055 - Cannot write file (would overwrite input)**
813
- ```bash
814
- # Cause: dist/ polluted with .ts source files
815
- # Fix:
816
- npm run clean && npm run build
817
- ```
818
-
819
- **Error: Cannot find module 'src/...' (hook execution)**
820
- ```bash
821
- # Cause: Hooks importing from src/ instead of dist/src/
822
- # OR: Missing .js extensions in imports
823
- # Fix:
824
- node scripts/fix-js-extensions.js
825
- npm run rebuild
826
- ```
827
-
828
- **Error: Module import without .js extension**
829
- ```bash
830
- # Cause: TypeScript ES modules REQUIRE .js in relative imports
831
- # Fix:
832
- node scripts/fix-js-extensions.js
409
+ #!/usr/bin/env node
410
+ import { ACStatusManager } from '../../../../dist/src/core/...'; // Use dist/
833
411
  ```
834
412
 
835
- ### Build Architecture
836
-
837
- SpecWeave uses **dual compilation**:
838
- - `tsc`: Compiles `src/` → `dist/src/` (source files)
839
- - `esbuild`: Compiles `plugins/**/lib/hooks/*.ts` → in-place `.js` (hooks only)
840
-
841
- **Why?** Hooks must import from `dist/src/` (compiled), but TypeScript would try to compile them before `dist/` exists (chicken-and-egg). Solution: Exclude hooks from `tsconfig.json`, compile separately with esbuild.
842
-
843
- ### Increment Scripts vs Hooks
844
-
845
- **CRITICAL DISTINCTION**: Increment scripts and hooks have different purposes and import patterns.
846
-
847
- **Hooks** (`plugins/**/lib/hooks/*.ts`):
848
- - **Purpose**: Production runtime executables (called by shell scripts)
849
- - **Execution**: `#!/usr/bin/env node` (JavaScript runtime)
850
- - **Imports**: MUST use `dist/src/` (compiled JavaScript)
851
- - **Compilation**: esbuild (separate from main build)
852
- - **Example**:
853
- ```typescript
854
- #!/usr/bin/env node
855
- import { ACStatusManager } from '../../../../dist/src/core/increment/ac-status-manager.js';
856
- ```
857
-
858
- **Increment Scripts** (`.specweave/increments/####/scripts/*.ts`):
859
- - **Purpose**: Development utilities (one-off tasks, migrations, analysis)
860
- - **Execution**: `#!/usr/bin/env tsx` (TypeScript runtime with ESM support)
861
- - **Imports**: MUST use `src/` (TypeScript source, NOT compiled)
862
- - **Compilation**: None (tsx transpiles on-the-fly)
863
- - **Example**:
864
- ```typescript
865
- #!/usr/bin/env tsx
866
- import { ACStatusManager } from '../../../../src/core/increment/ac-status-manager.js';
867
- ```
868
-
869
- **Why Different Patterns?**
870
-
871
- | Aspect | Hooks (dist/) | Increment Scripts (src/) |
872
- |--------|---------------|-------------------------|
873
- | **Context** | Production runtime | Development only |
874
- | **Tooling** | Node.js only | TypeScript tooling (tsx) |
875
- | **Build dependency** | Yes (requires dist/) | No (live source code) |
876
- | **Live reload** | No (must rebuild) | Yes (tsx auto-transpiles) |
877
- | **Purpose** | Permanent infrastructure | Temporary dev utilities |
878
-
879
- **Common Mistake**: Copying hook import patterns to increment scripts.
880
-
413
+ **Increment script imports**:
881
414
  ```typescript
882
- // ❌ WRONG (increment script importing from dist/):
883
415
  #!/usr/bin/env tsx
884
- import { ACStatusManager } from '../../../../dist/src/core/...';
885
- // Issues:
886
- // - Requires npm run build before execution
887
- // - Stale code if src/ changes without rebuild
888
- // - Semantic confusion (TS runtime + JS imports)
889
-
890
- // ✅ CORRECT (increment script importing from src/):
891
- #!/usr/bin/env tsx
892
- import { ACStatusManager } from '../../../../src/core/...';
893
- // Benefits:
894
- // - No build dependency
895
- // - Always uses latest source code
896
- // - Clear dev script pattern
416
+ import { ACStatusManager } from '../../../../src/core/...'; // Use src/
897
417
  ```
898
418
 
899
- **Note**: Use `tsx` (not `ts-node`) for increment scripts - it has better ESM + TypeScript support.
900
-
901
- ### Running Increment Scripts
902
-
903
- **CRITICAL**: Increment scripts use `#!/usr/bin/env tsx` shebang, which assumes tsx is in your PATH. This often fails in development environments.
904
-
905
- **Recommended Execution Method** (Always Works):
419
+ **Running increment scripts**:
906
420
  ```bash
907
- # ✅ Use npx - finds tsx in node_modules/.bin/ automatically
908
421
  npx tsx .specweave/increments/####/scripts/script-name.ts
909
-
910
- # Example:
911
- npx tsx .specweave/increments/0037-project-specific-tasks/scripts/validate-task-consistency.ts
912
- ```
913
-
914
- **Why npx?**
915
- - ✅ Works without global tsx installation
916
- - ✅ Uses project's tsx version (consistent across team)
917
- - ✅ No PATH configuration needed
918
- - ✅ Same behavior in CI/CD and local dev
919
-
920
- **Alternative Methods** (Less Recommended):
921
- ```bash
922
- # Option 1: Direct execution (requires global tsx)
923
- chmod +x script.ts
924
- ./script.ts
925
- # ❌ Fails if tsx not globally installed
926
-
927
- # Option 2: Install tsx globally (not recommended for teams)
928
- npm install -g tsx
929
- ./script.ts
930
- # ❌ Every contributor must install globally
931
- # ❌ Version inconsistencies across team
932
-
933
- # Option 3: Full path
934
- ./node_modules/.bin/tsx script.ts
935
- # ✅ Works, but verbose
936
- ```
937
-
938
- **Troubleshooting "command not found: tsx" (Exit Code 127)**:
939
-
940
- This error means tsx isn't in your shell's PATH.
941
-
942
- **Root Cause**:
943
- - tsx is a **dev dependency** (installed in `node_modules/`)
944
- - Shell can't find commands in `node_modules/.bin/` automatically
945
- - npm scripts add `node_modules/.bin/` to PATH, but direct shell execution doesn't
946
-
947
- **Fix**:
948
- ```bash
949
- # Instead of:
950
- tsx script.ts # ❌ Fails with error 127
951
-
952
- # Use:
953
- npx tsx script.ts # ✅ Always works
954
422
  ```
955
423
 
956
- **Why This Happens "Sometimes"**:
957
- - **npm scripts**: Work (PATH includes node_modules/.bin/)
958
- - **Direct shell**: Fails (PATH doesn't include node_modules/.bin/)
959
- - **Global tsx installed**: Works (tsx in system PATH)
960
- - **CI/CD**: Depends on environment setup
961
-
962
- **Execution Context Comparison**:
963
-
964
- | Method | tsx in PATH? | Works? |
965
- |--------|--------------|--------|
966
- | `npm run script` | ✅ Yes (npm adds it) | ✅ Yes |
967
- | `./script.ts` | ❌ No (unless global) | ❌ Usually fails |
968
- | `tsx script.ts` | ❌ No (unless global) | ❌ Usually fails |
969
- | `npx tsx script.ts` | ✅ Yes (npx finds it) | ✅ Always works |
970
-
971
- **Best Practice for Contributors**:
972
- - **Creating scripts**: Use `#!/usr/bin/env tsx` shebang (conventional)
973
- - **Running scripts**: Always use `npx tsx script.ts` (reliable)
974
- - **Documentation**: Show npx execution method in examples
975
-
976
- ### Coverage Requirements
424
+ ### Coverage
977
425
 
978
426
  - Critical paths: 90%+
979
427
  - Overall: 80%+
980
428
 
981
- ### Related Documentation
982
-
983
- - Build process details: `.github/CONTRIBUTING.md` → "Build Process & Best Practices"
984
- - Ultrathink analysis: `.specweave/increments/0039/reports/HOOK-IMPORT-ERROR-ULTRATHINK-ANALYSIS.md`
985
- - Build verification tests: `tests/integration/build/build-verification.test.ts`
986
-
987
429
  ---
988
430
 
989
431
  ## Common Tasks
990
432
 
991
- ### Adding Skills, Agents, or Commands
433
+ ### Adding Components
992
434
 
993
- **All components go into plugins**:
994
- - **Core components**: `plugins/specweave/{skills|agents|commands|hooks}/`
995
- - **Plugin components**: `plugins/specweave-{name}/{skills|agents|commands}/`
996
- - **Tests**: `tests/integration/{component-name}/` or `tests/unit/`
435
+ All components go into `plugins/`:
436
+ - Core: `plugins/specweave/{skills|agents|commands|hooks}/`
437
+ - Plugins: `plugins/specweave-{name}/{skills|agents|commands}/`
438
+ - Tests: `tests/integration/` or `tests/unit/`
997
439
 
998
- **See**: `.github/CONTRIBUTING.md` for complete instructions
440
+ See `.github/CONTRIBUTING.md` for details.
999
441
 
1000
442
  ### Updating Documentation
1001
443
 
1002
444
  ```bash
1003
- # Internal docs (architecture, ADRs)
445
+ # Internal docs
1004
446
  vim .specweave/docs/internal/architecture/hld-system.md
1005
447
 
1006
- # Public docs (user-facing guides)
448
+ # Public docs
1007
449
  vim .specweave/docs/public/guides/user-guide.md
1008
-
1009
- # Build docs site
1010
- cd docs-site && npm run build
1011
450
  ```
1012
451
 
1013
452
  ---
1014
453
 
1015
454
  ## Troubleshooting
1016
455
 
1017
- **Skills not activating?**
1018
- 1. Check plugin installed: `/plugin list --installed`
1019
- 2. Verify YAML frontmatter in skill SKILL.md
1020
- 3. Restart Claude Code
1021
- 4. Check description has trigger keywords
1022
-
1023
- **Commands not working?**
1024
- 1. Check plugin installed: `/plugin list --installed`
1025
- 2. Verify command exists in plugin
1026
- 3. Restart Claude Code
1027
-
1028
- **Tests failing?**
1029
- 1. Run `npm run build` first
1030
- 2. Check test output
1031
- 3. Verify test data in `tests/fixtures/`
1032
-
1033
- **Root folder polluted?**
1034
- 1. Move files to `.specweave/increments/####/reports/`
1035
- 2. Update `.gitignore` if needed
1036
-
1037
- **Plugin hooks not working? (Development)**
1038
- See `.claude/CONTRIBUTING.md` for plugin marketplace setup.
1039
-
1040
- ---
1041
-
1042
- ## Getting Help
1043
-
1044
- **Documentation**:
1045
- - User docs: https://spec-weave.com
1046
- - Contributor docs: `.specweave/docs/internal/`
1047
- - Architecture: `.specweave/docs/internal/architecture/`
1048
-
1049
- **Community**:
1050
- - GitHub Issues: https://github.com/anton-abyzov/specweave/issues
1051
- - Discussions: https://github.com/anton-abyzov/specweave/discussions
1052
-
1053
- **Current Increment**:
1054
- ```bash
1055
- /specweave:status # Show all increments
1056
- ```
456
+ **Skills not activating**: Check YAML frontmatter, restart Claude Code
457
+ **Commands not working**: Verify plugin installed, restart Claude Code
458
+ **Tests failing**: Run `npm run rebuild`, check test output
459
+ **Root folder polluted**: Move files to `.specweave/increments/####/reports/`
460
+ **Hooks failing**: Verify symlink (see "Symlink Setup" above)
1057
461
 
1058
462
  ---
1059
463
 
1060
464
  ## Quick Reference
1061
465
 
1062
- **Commands** (all use `/specweave:*` namespace):
1063
-
1064
- *Primary*:
1065
- - `/specweave:increment "feature"` - Plan new increment
1066
- - `/specweave:do` - Execute tasks
1067
- - `/specweave:done 0002` - Close increment
1068
- - `/specweave:validate 0002` - Validate increment
1069
- - `/specweave:qa 0002` - Quality assessment
466
+ **Commands**:
467
+ - `/specweave:increment "feature"` - Plan
468
+ - `/specweave:do` - Execute
469
+ - `/specweave:done 0002` - Close (validates)
1070
470
  - `/specweave:status` - Show status
1071
471
  - `/specweave:progress` - Check progress
1072
-
1073
- *State management*:
1074
- - `/specweave:pause 0002 --reason="..."` - Pause
1075
- - `/specweave:resume 0002` - Resume
1076
- - `/specweave:abandon 0002 --reason="..."` - Abandon
1077
-
1078
- *Archiving (MANUAL ONLY)*:
1079
- - `/specweave:archive 0031` - Archive specific
1080
- - `/specweave:archive --keep-last 10` - Archive old
1081
- - `/specweave:restore 0031` - Restore
1082
- - `/specweave:fix-duplicates` - Resolve duplicates
1083
-
1084
- *Documentation*:
472
+ - `/specweave:validate 0002` - Validate
473
+ - `/specweave:qa 0002` - Quality check
474
+ - `/specweave:pause/resume/abandon` - State management
475
+ - `/specweave:archive/restore` - Archiving (manual only)
1085
476
  - `/specweave:sync-docs update` - Sync living docs
1086
- - `/specweave:sync-tasks` - Sync task status
1087
-
1088
- *Other*:
1089
- - `/specweave:costs` - AI cost dashboard
1090
- - `/specweave:translate` - Translate content
1091
- - `/specweave:update-scope` - Log scope changes
1092
- - `/specweave:next` - Smart transition
1093
477
 
1094
- **Build & Test**:
1095
- - `npm run build` - Compile TypeScript
1096
- - `npm test` - Unit tests
1097
- - `npm run test:e2e` - E2E tests
1098
- - `npm run test:integration` - Integration tests
478
+ **Build**:
479
+ - `npm run rebuild` - Clean + build
480
+ - `npm test` - Smoke tests
481
+ - `npm run test:all` - All tests
482
+ - `npm run test:coverage` - Coverage
1099
483
 
1100
484
  **File Structure**:
1101
- - Source: `src/` (TypeScript) and `plugins/` (skills/agents/commands)
1102
- - Marketplace: GLOBAL (via CLI)
485
+ - Source: `src/` (TypeScript), `plugins/` (skills/agents/commands/hooks)
1103
486
  - Increments: `.specweave/increments/`
1104
- - Docs: `.specweave/docs/internal/` and `.specweave/docs/public/`
487
+ - Docs: `.specweave/docs/internal/`, `.specweave/docs/public/`
1105
488
  - Tests: `tests/` (unit, integration, E2E)
1106
489
 
1107
- ---
1108
-
1109
490
  **Remember**:
1110
- 1. Edit source files in `src/` and `plugins/`, not `.claude/`
1111
- 2. Keep root folder clean (use increment folders)
1112
- 3. Test before committing (E2E + unit + integration)
1113
- 4. Skills/agents/commands auto-activate when needed
1114
- 5. All detailed rules are in skills (progressive disclosure)
1115
-
1116
- **SpecWeave Documentation**: https://spec-weave.com
1117
- **Last Updated**: 2025-11-15
491
+ 1. Symlink setup is MANDATORY for contributors
492
+ 2. Keep root clean (use increment folders)
493
+ 3. Test before committing
494
+ 4. Never delete .specweave/ directories
495
+ 5. Use `/specweave:done` (never manual metadata edits)
496
+
497
+ **See also**: `.github/CONTRIBUTING.md`, https://spec-weave.com