@izkac/forgekit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/bin/forge.mjs +100 -0
  2. package/bin/forgekit.mjs +84 -0
  3. package/bin/review.mjs +82 -0
  4. package/package.json +46 -0
  5. package/scripts/prepack.mjs +78 -0
  6. package/scripts/run-tests.mjs +43 -0
  7. package/src/adr.mjs +236 -0
  8. package/src/adr.test.mjs +170 -0
  9. package/src/change.mjs +234 -0
  10. package/src/change.test.mjs +83 -0
  11. package/src/cleanup-sessions.mjs +70 -0
  12. package/src/config.mjs +103 -0
  13. package/src/defer.mjs +75 -0
  14. package/src/doctor.mjs +341 -0
  15. package/src/doctor.test.mjs +114 -0
  16. package/src/init.mjs +575 -0
  17. package/src/install.mjs +777 -0
  18. package/src/install.test.mjs +104 -0
  19. package/src/integrity-check.mjs +58 -0
  20. package/src/integrity.mjs +317 -0
  21. package/src/integrity.test.mjs +296 -0
  22. package/src/lib/workspaces.mjs +55 -0
  23. package/src/lib.mjs +138 -0
  24. package/src/models.defaults.json +41 -0
  25. package/src/new-session.mjs +82 -0
  26. package/src/openspec-overlays/README.md +19 -0
  27. package/src/openspec-overlays/openspec-apply-change-footer.md +14 -0
  28. package/src/openspec-overlays/opsx-apply-completion-step.md +1 -0
  29. package/src/openspec-overlays/opsx-apply-implement-step.md +11 -0
  30. package/src/paths.mjs +92 -0
  31. package/src/plan-engine.mjs +260 -0
  32. package/src/plan-engine.test.mjs +245 -0
  33. package/src/preferences.defaults.json +78 -0
  34. package/src/preferences.mjs +438 -0
  35. package/src/preferences.test.mjs +174 -0
  36. package/src/record-evidence.mjs +204 -0
  37. package/src/record-evidence.test.mjs +260 -0
  38. package/src/resolve-model.mjs +312 -0
  39. package/src/resolve-model.test.mjs +194 -0
  40. package/src/review/carryforward.mjs +413 -0
  41. package/src/review/carryforward.test.mjs +587 -0
  42. package/src/review/cli.test.mjs +117 -0
  43. package/src/review/export.mjs +172 -0
  44. package/src/review/export.test.mjs +197 -0
  45. package/src/review/fixtures/valid-review.json +42 -0
  46. package/src/review/lib.mjs +894 -0
  47. package/src/review/lib.test.mjs +266 -0
  48. package/src/review/merge-tentative.mjs +292 -0
  49. package/src/review/merge-tentative.test.mjs +363 -0
  50. package/src/review/new-review.mjs +200 -0
  51. package/src/review/render.mjs +108 -0
  52. package/src/review/schema-consistency.test.mjs +83 -0
  53. package/src/review/schema.json +196 -0
  54. package/src/review/signals.mjs +144 -0
  55. package/src/review/signals.test.mjs +62 -0
  56. package/src/score-cli.mjs +68 -0
  57. package/src/score.mjs +489 -0
  58. package/src/score.test.mjs +253 -0
  59. package/src/session-reminder.mjs +168 -0
  60. package/src/session-status.mjs +70 -0
  61. package/src/set-models.mjs +186 -0
  62. package/src/set-phase.mjs +177 -0
  63. package/src/set-phase.test.mjs +317 -0
  64. package/src/set-prefs.mjs +294 -0
  65. package/src/spine.mjs +91 -0
  66. package/src/triage-prompt.mjs +175 -0
  67. package/src/triage-prompt.test.mjs +50 -0
  68. package/src/vendor-openspec-overlays.mjs +176 -0
  69. package/src/vendor-openspec-overlays.test.mjs +62 -0
  70. package/vendor/skills/archive-to-adr/SKILL.md +149 -0
  71. package/vendor/skills/forge/SKILL.md +136 -0
  72. package/vendor/skills/forge/phases/brainstorm.md +23 -0
  73. package/vendor/skills/forge/phases/finish.md +87 -0
  74. package/vendor/skills/forge/phases/implement.md +76 -0
  75. package/vendor/skills/forge/phases/plan-openspec.md +40 -0
  76. package/vendor/skills/forge/phases/plan-specs.md +97 -0
  77. package/vendor/skills/forge/phases/review.md +25 -0
  78. package/vendor/skills/forge/phases/verify.md +120 -0
  79. package/vendor/skills/forge/references/forge-layout.md +85 -0
  80. package/vendor/skills/forge/references/pace.md +115 -0
  81. package/vendor/skills/forge/references/plan-routing.md +51 -0
  82. package/vendor/skills/forge/references/runtime-integrity.md +157 -0
  83. package/vendor/skills/forge/references/substantial-work.md +37 -0
  84. package/vendor/skills/forge/references/tdd-core.md +29 -0
  85. package/vendor/skills/forge/references/test-evidence.md +30 -0
  86. package/vendor/skills/forge/references/test-strategy.md +68 -0
  87. package/vendor/skills/forge/skills/NOTICE.md +17 -0
  88. package/vendor/skills/forge/skills/brainstorming/SKILL.md +120 -0
  89. package/vendor/skills/forge/skills/requesting-code-review/SKILL.md +67 -0
  90. package/vendor/skills/forge/skills/requesting-code-review/code-reviewer.md +146 -0
  91. package/vendor/skills/forge/skills/subagent-driven-development/SKILL.md +87 -0
  92. package/vendor/skills/forge/skills/systematic-debugging/SKILL.md +234 -0
  93. package/vendor/skills/forge/skills/systematic-debugging/condition-based-waiting.md +115 -0
  94. package/vendor/skills/forge/skills/systematic-debugging/defense-in-depth.md +122 -0
  95. package/vendor/skills/forge/skills/systematic-debugging/find-polluter.sh +63 -0
  96. package/vendor/skills/forge/skills/systematic-debugging/root-cause-tracing.md +169 -0
  97. package/vendor/skills/forge/skills/test-driven-development/SKILL.md +290 -0
  98. package/vendor/skills/forge/skills/test-driven-development/testing-anti-patterns.md +299 -0
  99. package/vendor/skills/forge/skills/verification-before-completion/SKILL.md +59 -0
  100. package/vendor/skills/forge/subagents/final-reviewer-prompt.md +53 -0
  101. package/vendor/skills/forge/subagents/implementer-prompt.md +38 -0
  102. package/vendor/skills/forge/subagents/task-reviewer-prompt.md +61 -0
  103. package/vendor/skills/git-resolve-adr-conflict/SKILL.md +132 -0
  104. package/vendor/skills/thorough-code-review/SKILL.md +290 -0
  105. package/vendor/skills/thorough-code-review/examples/accepted-risks-janus.md +32 -0
  106. package/vendor/skills/thorough-code-review/examples.md +133 -0
  107. package/vendor/skills/thorough-code-review/reference/accepted-risks.md +26 -0
  108. package/vendor/skills/thorough-code-review/reference/lenses.md +96 -0
  109. package/vendor/skills/thorough-code-review/reference/phase1-scout.md +62 -0
  110. package/vendor/skills/thorough-code-review/reference/phase1c-coverage.md +44 -0
  111. package/vendor/skills/thorough-code-review/reference/phase2-skeptic.md +105 -0
  112. package/vendor/skills/thorough-code-review/reference/report-schema.json +222 -0
  113. package/vendor/skills/thorough-code-review/reference/report-template.md +115 -0
  114. package/vendor/skills/thorough-code-review/reference/severity-rubric.md +49 -0
  115. package/vendor/skills/thorough-code-review/reference/signals-preflight.md +55 -0
  116. package/vendor/templates/adr/README.md +7 -0
  117. package/vendor/templates/adr/decisions.md +141 -0
  118. package/vendor/templates/adr/hooks/check-pending-adrs.mjs +74 -0
  119. package/vendor/templates/adr/hooks/check-pending-adrs.sh +3 -0
  120. package/vendor/templates/adr/hooks/openspec-archive-agent-message.mjs +52 -0
  121. package/vendor/templates/adr/hooks/openspec-archive-agent-message.sh +3 -0
  122. package/vendor/templates/project/claude/commands/forge-apply.md +75 -0
  123. package/vendor/templates/project/claude/commands/forge-brainstorm.md +7 -0
  124. package/vendor/templates/project/claude/commands/forge-build.md +17 -0
  125. package/vendor/templates/project/claude/commands/forge-plan.md +12 -0
  126. package/vendor/templates/project/claude/commands/forge-skip.md +14 -0
  127. package/vendor/templates/project/claude/commands/forge-status.md +16 -0
  128. package/vendor/templates/project/claude/commands/forge.md +16 -0
  129. package/vendor/templates/project/claude/hooks/forge-prompt-hook.mjs +73 -0
  130. package/vendor/templates/project/claude/hooks/forge-session-start.mjs +19 -0
  131. package/vendor/templates/project/claude/hooks/forge-triage-hook.mjs +77 -0
  132. package/vendor/templates/project/claude/rules/forge.md +16 -0
  133. package/vendor/templates/project/codex/rules/forge.md +10 -0
  134. package/vendor/templates/project/cursor/commands/forge-apply.md +75 -0
  135. package/vendor/templates/project/cursor/commands/forge-brainstorm.md +10 -0
  136. package/vendor/templates/project/cursor/commands/forge-build.md +17 -0
  137. package/vendor/templates/project/cursor/commands/forge-plan.md +15 -0
  138. package/vendor/templates/project/cursor/commands/forge-skip.md +14 -0
  139. package/vendor/templates/project/cursor/commands/forge-status.md +16 -0
  140. package/vendor/templates/project/cursor/commands/forge.md +16 -0
  141. package/vendor/templates/project/cursor/hooks/forge-session-start.mjs +30 -0
  142. package/vendor/templates/project/cursor/hooks/forge-session-start.sh +3 -0
  143. package/vendor/templates/project/cursor/rules/forge.mdc +21 -0
@@ -0,0 +1,87 @@
1
+ ---
2
+ name: subagent-driven-development
3
+ description: Forge — subagent per task with a combined spec+quality review. Internal skill; read via forge orchestrator.
4
+ ---
5
+
6
+ # Subagent-Driven Development
7
+
8
+ Execute a plan by dispatching a fresh implementer subagent per task, followed by one **task reviewer** subagent that checks spec compliance first, then code quality.
9
+
10
+ **Why subagents:** isolated context per task. You craft exactly the instructions and context each one needs — they never inherit session history — and your own context stays free for coordination.
11
+
12
+ **Core principle:** fresh implementer per task + combined review (spec gate, then quality) = high quality, fast iteration.
13
+
14
+ ## When to use
15
+
16
+ Use when you have an implementation plan with mostly independent tasks and you're staying in this session. Tightly coupled tasks or no plan → execute manually or brainstorm first.
17
+
18
+ ## Pace
19
+
20
+ Honor [../../references/pace.md](../../references/pace.md) (`forge prefs` / session `resolvedPace`). Reviewers may be deferred to **OpenSpec group** boundaries under `standard` (`per-group`), or skipped for low-risk work under `brisk`/`lite`; **never** skip review for money/auth/contracts/migrations (immediate per-task review). Tier-2 test evidence stays mandatory for behavior changes on every task.
21
+
22
+ ## Per-task loop
23
+
24
+ 1. Extract full task text + context from the plan (read the plan file **once**, up front; never make a subagent read it). Note which OpenSpec **group** (`##` section) the task belongs to.
25
+ 2. Dispatch **implementer** — [../../subagents/implementer-prompt.md](../../subagents/implementer-prompt.md). Answer any questions it asks before letting it proceed.
26
+ 3. Dispatch **reviewer** when pace requires it — [../../subagents/task-reviewer-prompt.md](../../subagents/task-reviewer-prompt.md) (spec compliance gates quality):
27
+ - `always` → after this task
28
+ - `per-group` → after the last task in the current `##` group (or immediately if high-risk); mid-group low-risk → self-check only
29
+ - `high-risk-only` / `never` → only high-risk (hard floor)
30
+ If skipped, write a pace self-check `task-review.md`. Group reviews write `group-review.md` covering every task in the section.
31
+ 4. Reviewer REJECTED → same implementer fixes → re-review. Repeat until APPROVED (cap at `review.maxRounds`). Never skip the re-review when a reviewer was dispatched.
32
+ 5. Save test evidence; mark task complete.
33
+ 6. After all tasks: proceed to verify/review phases (final reviewer subject to pace).
34
+
35
+ ## Task batching (small tasks only)
36
+
37
+ Each dispatch pays a full fresh context. Batch **consecutive, small, same-area tasks** (doc edits, config values, wording, mechanical renames) into one implementer brief listing them all, reviewed together in one review pass.
38
+
39
+ **Never batch** tasks that touch money, auth, shared contracts, or migrations — those keep 1:1 dispatch. When in doubt, don't batch.
40
+
41
+ ## Model selection
42
+
43
+ Subagent models use **two axes** — never invent host model IDs from memory:
44
+
45
+ | Axis | Values | Default |
46
+ | ---- | ------ | ------- |
47
+ | Capability | `fast` · `standard` · `capable` | role-based (below) |
48
+ | Billing | `included` · `metered` | **`included`** |
49
+
50
+ **Billing `included` unless the user explicitly asks for API/metered models** (or has set `forge models -- metered`). Do **not** auto-switch to `metered` on failure.
51
+
52
+ Capability by role:
53
+
54
+ - Touches 1–2 files with a complete spec → `fast` (most tasks, when the plan is well-specified)
55
+ - Multi-file integration, pattern matching, debugging → `standard`
56
+ - Design judgment, broad codebase understanding, review → `capable`
57
+
58
+ Before every Task/Agent dispatch, resolve:
59
+
60
+ ```bash
61
+ forge resolve-model --tier <fast|standard|capable>
62
+ ```
63
+
64
+ Honor the JSON: if `omitModel` is true, **omit** the host `model` parameter; otherwise pass `model` exactly as returned. Defaults live in `models.defaults.json`. Checkout overlay `.forge/models.local.json` exists only after `forge models included|metered` (bare `forge models` only prints).
65
+
66
+ ## Handling implementer status
67
+
68
+ - **DONE** → proceed to review.
69
+ - **DONE_WITH_CONCERNS** → read the concerns; correctness/scope concerns get addressed before review, observations are noted.
70
+ - **NEEDS_CONTEXT** → provide the missing context, re-dispatch.
71
+ - **BLOCKED** → context problem: add context, re-dispatch. Needs more reasoning: escalate **capability tier** within the current billing lane (still `included` by default). Task too large: split it. Plan wrong: escalate to the human. Never force the same model to retry unchanged; never flip to `metered` without an explicit user request.
72
+
73
+ ## Red flags — never
74
+
75
+ - Start implementation on main/master without explicit user consent
76
+ - Skip the review, proceed with unfixed spec gaps or Critical/Important issues, or accept "close enough" on spec compliance
77
+ - Dispatch multiple implementer subagents in parallel (conflicts)
78
+ - Make a subagent read the plan file, skip scene-setting context, or ignore its questions
79
+ - Let implementer self-review replace the reviewer (both are needed)
80
+ - Fix a failed task manually in coordinator context — dispatch a fix subagent with specific instructions
81
+
82
+ ## Integration
83
+
84
+ - **Plan source:** OpenSpec (`openspec/changes/<name>/tasks.md`)
85
+ - **Subagents must follow:** [references/tdd-core.md](../../references/tdd-core.md) (condensed TDD rules; full skill at [skills/test-driven-development](../test-driven-development/SKILL.md) when stuck)
86
+ - **On blockers:** [skills/systematic-debugging](../systematic-debugging/SKILL.md) before guessing fixes
87
+ - **After all tasks:** [phases/verify.md](../../phases/verify.md) → [phases/review.md](../../phases/review.md) → [phases/finish.md](../../phases/finish.md)
@@ -0,0 +1,234 @@
1
+ ---
2
+ name: systematic-debugging
3
+ description: Forge — root-cause debugging before fixes. Internal skill; read via forge orchestrator.
4
+ ---
5
+
6
+ # Systematic Debugging
7
+
8
+ ## Overview
9
+
10
+ Random fixes waste time and create new bugs. Quick patches mask underlying issues.
11
+
12
+ **Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
13
+
14
+ **Violating the letter of this process is violating the spirit of debugging.**
15
+
16
+ ## The Iron Law
17
+
18
+ ```
19
+ NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
20
+ ```
21
+
22
+ If you haven't completed Phase 1, you cannot propose fixes.
23
+
24
+ ## When to Use
25
+
26
+ Use for ANY technical issue:
27
+ - Test failures
28
+ - Bugs in production
29
+ - Unexpected behavior
30
+ - Performance problems
31
+ - Build failures
32
+ - Integration issues
33
+
34
+ **Use this ESPECIALLY when:**
35
+ - Under time pressure (emergencies make guessing tempting)
36
+ - "Just one quick fix" seems obvious
37
+ - You've already tried multiple fixes
38
+ - Previous fix didn't work
39
+ - You don't fully understand the issue
40
+
41
+ **Don't skip when:**
42
+ - Issue seems simple (simple bugs have root causes too)
43
+ - You're in a hurry (rushing guarantees rework)
44
+ - Manager wants it fixed NOW (systematic is faster than thrashing)
45
+
46
+ ## The Four Phases
47
+
48
+ You MUST complete each phase before proceeding to the next.
49
+
50
+ ### Phase 1: Root Cause Investigation
51
+
52
+ **BEFORE attempting ANY fix:**
53
+
54
+ 1. **Read Error Messages Carefully**
55
+ - Don't skip past errors or warnings
56
+ - They often contain the exact solution
57
+ - Read stack traces completely
58
+ - Note line numbers, file paths, error codes
59
+
60
+ 2. **Reproduce Consistently**
61
+ - Can you trigger it reliably?
62
+ - What are the exact steps?
63
+ - Does it happen every time?
64
+ - If not reproducible → gather more data, don't guess
65
+
66
+ 3. **Check Recent Changes**
67
+ - What changed that could cause this?
68
+ - Git diff, recent commits
69
+ - New dependencies, config changes
70
+ - Environmental differences
71
+
72
+ 4. **Gather Evidence in Multi-Component Systems**
73
+
74
+ **WHEN system has multiple components (CI → build → signing, API → service → database):**
75
+
76
+ **BEFORE proposing fixes, add diagnostic instrumentation:**
77
+ ```
78
+ For EACH component boundary:
79
+ - Log what data enters component
80
+ - Log what data exits component
81
+ - Verify environment/config propagation
82
+ - Check state at each layer
83
+
84
+ Run once to gather evidence showing WHERE it breaks
85
+ THEN analyze evidence to identify failing component
86
+ THEN investigate that specific component
87
+ ```
88
+
89
+ 5. **Trace Data Flow**
90
+
91
+ **WHEN error is deep in call stack:**
92
+
93
+ See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
94
+
95
+ **Quick version:**
96
+ - Where does bad value originate?
97
+ - What called this with bad value?
98
+ - Keep tracing up until you find the source
99
+ - Fix at source, not at symptom
100
+
101
+ ### Phase 2: Pattern Analysis
102
+
103
+ **Find the pattern before fixing:**
104
+
105
+ 1. **Find Working Examples**
106
+ - Locate similar working code in same codebase
107
+ - What works that's similar to what's broken?
108
+
109
+ 2. **Compare Against References**
110
+ - If implementing pattern, read reference implementation COMPLETELY
111
+ - Don't skim - read every line
112
+ - Understand the pattern fully before applying
113
+
114
+ 3. **Identify Differences**
115
+ - What's different between working and broken?
116
+ - List every difference, however small
117
+ - Don't assume "that can't matter"
118
+
119
+ 4. **Understand Dependencies**
120
+ - What other components does this need?
121
+ - What settings, config, environment?
122
+ - What assumptions does it make?
123
+
124
+ ### Phase 3: Hypothesis and Testing
125
+
126
+ **Scientific method:**
127
+
128
+ 1. **Form Single Hypothesis**
129
+ - State clearly: "I think X is the root cause because Y"
130
+ - Write it down
131
+ - Be specific, not vague
132
+
133
+ 2. **Test Minimally**
134
+ - Make the SMALLEST possible change to test hypothesis
135
+ - One variable at a time
136
+ - Don't fix multiple things at once
137
+
138
+ 3. **Verify Before Continuing**
139
+ - Did it work? Yes → Phase 4
140
+ - Didn't work? Form NEW hypothesis
141
+ - DON'T add more fixes on top
142
+
143
+ 4. **When You Don't Know**
144
+ - Say "I don't understand X"
145
+ - Don't pretend to know
146
+ - Ask for help
147
+ - Research more
148
+
149
+ ### Phase 4: Implementation
150
+
151
+ **Fix the root cause, not the symptom:**
152
+
153
+ 1. **Create Failing Test Case**
154
+ - Simplest possible reproduction
155
+ - Automated test if possible
156
+ - One-off test script if no framework
157
+ - MUST have before fixing
158
+ - Use the `forge/skills/test-driven-development` skill for writing proper failing tests
159
+
160
+ 2. **Implement Single Fix**
161
+ - Address the root cause identified
162
+ - ONE change at a time
163
+ - No "while I'm here" improvements
164
+ - No bundled refactoring
165
+
166
+ 3. **Verify Fix**
167
+ - Test passes now?
168
+ - No other tests broken?
169
+ - Issue actually resolved?
170
+
171
+ 4. **If Fix Doesn't Work**
172
+ - STOP
173
+ - Count: How many fixes have you tried?
174
+ - If < 3: Return to Phase 1, re-analyze with new information
175
+ - **If ≥ 3: STOP and question the architecture (step 5 below)**
176
+ - DON'T attempt Fix #4 without architectural discussion
177
+
178
+ 5. **If 3+ Fixes Failed: Question Architecture**
179
+
180
+ **Pattern indicating architectural problem:**
181
+ - Each fix reveals new shared state/coupling/problem in different place
182
+ - Fixes require "massive refactoring" to implement
183
+ - Each fix creates new symptoms elsewhere
184
+
185
+ **STOP and question fundamentals:**
186
+ - Is this pattern fundamentally sound?
187
+ - Are we "sticking with it through sheer inertia"?
188
+ - Should we refactor architecture vs. continue fixing symptoms?
189
+
190
+ **Discuss with your human partner before attempting more fixes**
191
+
192
+ This is NOT a failed hypothesis - this is a wrong architecture.
193
+
194
+ ## Red Flags - STOP and Follow Process
195
+
196
+ If you catch yourself thinking:
197
+ - "Quick fix for now, investigate later"
198
+ - "Just try changing X and see if it works"
199
+ - "Add multiple changes, run tests"
200
+ - "Skip the test, I'll manually verify"
201
+ - "It's probably X, let me fix that"
202
+ - "I don't fully understand but this might work"
203
+ - "Pattern says X but I'll adapt it differently"
204
+ - "Here are the main problems: [lists fixes without investigation]"
205
+ - Proposing solutions before tracing data flow
206
+ - **"One more fix attempt" (when already tried 2+)**
207
+ - **Each fix reveals new problem in different place**
208
+
209
+ **ALL of these mean: STOP. Return to Phase 1.**
210
+
211
+ **If 3+ fixes failed:** Question the architecture (see Phase 4.5)
212
+
213
+ ## When Process Reveals "No Root Cause"
214
+
215
+ If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
216
+
217
+ 1. You've completed the process
218
+ 2. Document what you investigated
219
+ 3. Implement appropriate handling (retry, timeout, error message)
220
+ 4. Add monitoring/logging for future investigation
221
+
222
+ **But:** 95% of "no root cause" cases are incomplete investigation.
223
+
224
+ ## Supporting Techniques
225
+
226
+ These techniques are part of systematic debugging and available in this directory:
227
+
228
+ - **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
229
+ - **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
230
+ - **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
231
+
232
+ **Related skills:**
233
+ - **forge/skills/test-driven-development** - For creating failing test case (Phase 4, Step 1)
234
+ - **forge/skills/verification-before-completion** - Verify fix worked before claiming success
@@ -0,0 +1,115 @@
1
+ # Condition-Based Waiting
2
+
3
+ ## Overview
4
+
5
+ Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.
6
+
7
+ **Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.
8
+
9
+ ## When to Use
10
+
11
+ ```dot
12
+ digraph when_to_use {
13
+ "Test uses setTimeout/sleep?" [shape=diamond];
14
+ "Testing timing behavior?" [shape=diamond];
15
+ "Document WHY timeout needed" [shape=box];
16
+ "Use condition-based waiting" [shape=box];
17
+
18
+ "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
19
+ "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
20
+ "Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
21
+ }
22
+ ```
23
+
24
+ **Use when:**
25
+ - Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)
26
+ - Tests are flaky (pass sometimes, fail under load)
27
+ - Tests timeout when run in parallel
28
+ - Waiting for async operations to complete
29
+
30
+ **Don't use when:**
31
+ - Testing actual timing behavior (debounce, throttle intervals)
32
+ - Always document WHY if using arbitrary timeout
33
+
34
+ ## Core Pattern
35
+
36
+ ```typescript
37
+ // ❌ BEFORE: Guessing at timing
38
+ await new Promise(r => setTimeout(r, 50));
39
+ const result = getResult();
40
+ expect(result).toBeDefined();
41
+
42
+ // ✅ AFTER: Waiting for condition
43
+ await waitFor(() => getResult() !== undefined);
44
+ const result = getResult();
45
+ expect(result).toBeDefined();
46
+ ```
47
+
48
+ ## Quick Patterns
49
+
50
+ | Scenario | Pattern |
51
+ |----------|---------|
52
+ | Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |
53
+ | Wait for state | `waitFor(() => machine.state === 'ready')` |
54
+ | Wait for count | `waitFor(() => items.length >= 5)` |
55
+ | Wait for file | `waitFor(() => fs.existsSync(path))` |
56
+ | Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |
57
+
58
+ ## Implementation
59
+
60
+ Generic polling function:
61
+ ```typescript
62
+ async function waitFor<T>(
63
+ condition: () => T | undefined | null | false,
64
+ description: string,
65
+ timeoutMs = 5000
66
+ ): Promise<T> {
67
+ const startTime = Date.now();
68
+
69
+ while (true) {
70
+ const result = condition();
71
+ if (result) return result;
72
+
73
+ if (Date.now() - startTime > timeoutMs) {
74
+ throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
75
+ }
76
+
77
+ await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
78
+ }
79
+ }
80
+ ```
81
+
82
+ Domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) all reduce to this poll-until-condition-or-timeout pattern.
83
+
84
+ ## Common Mistakes
85
+
86
+ **❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU
87
+ **✅ Fix:** Poll every 10ms
88
+
89
+ **❌ No timeout:** Loop forever if condition never met
90
+ **✅ Fix:** Always include timeout with clear error
91
+
92
+ **❌ Stale data:** Cache state before loop
93
+ **✅ Fix:** Call getter inside loop for fresh data
94
+
95
+ ## When Arbitrary Timeout IS Correct
96
+
97
+ ```typescript
98
+ // Tool ticks every 100ms - need 2 ticks to verify partial output
99
+ await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition
100
+ await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior
101
+ // 200ms = 2 ticks at 100ms intervals - documented and justified
102
+ ```
103
+
104
+ **Requirements:**
105
+ 1. First wait for triggering condition
106
+ 2. Based on known timing (not guessing)
107
+ 3. Comment explaining WHY
108
+
109
+ ## Real-World Impact
110
+
111
+ From debugging session (2025-10-03):
112
+ - Fixed 15 flaky tests across 3 files
113
+ - Pass rate: 60% → 100%
114
+ - Execution time: 40% faster
115
+ - No more race conditions
@@ -0,0 +1,122 @@
1
+ # Defense-in-Depth Validation
2
+
3
+ ## Overview
4
+
5
+ When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.
6
+
7
+ **Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible.
8
+
9
+ ## Why Multiple Layers
10
+
11
+ Single validation: "We fixed the bug"
12
+ Multiple layers: "We made the bug impossible"
13
+
14
+ Different layers catch different cases:
15
+ - Entry validation catches most bugs
16
+ - Business logic catches edge cases
17
+ - Environment guards prevent context-specific dangers
18
+ - Debug logging helps when other layers fail
19
+
20
+ ## The Four Layers
21
+
22
+ ### Layer 1: Entry Point Validation
23
+ **Purpose:** Reject obviously invalid input at API boundary
24
+
25
+ ```typescript
26
+ function createProject(name: string, workingDirectory: string) {
27
+ if (!workingDirectory || workingDirectory.trim() === '') {
28
+ throw new Error('workingDirectory cannot be empty');
29
+ }
30
+ if (!existsSync(workingDirectory)) {
31
+ throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
32
+ }
33
+ if (!statSync(workingDirectory).isDirectory()) {
34
+ throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);
35
+ }
36
+ // ... proceed
37
+ }
38
+ ```
39
+
40
+ ### Layer 2: Business Logic Validation
41
+ **Purpose:** Ensure data makes sense for this operation
42
+
43
+ ```typescript
44
+ function initializeWorkspace(projectDir: string, sessionId: string) {
45
+ if (!projectDir) {
46
+ throw new Error('projectDir required for workspace initialization');
47
+ }
48
+ // ... proceed
49
+ }
50
+ ```
51
+
52
+ ### Layer 3: Environment Guards
53
+ **Purpose:** Prevent dangerous operations in specific contexts
54
+
55
+ ```typescript
56
+ async function gitInit(directory: string) {
57
+ // In tests, refuse git init outside temp directories
58
+ if (process.env.NODE_ENV === 'test') {
59
+ const normalized = normalize(resolve(directory));
60
+ const tmpDir = normalize(resolve(tmpdir()));
61
+
62
+ if (!normalized.startsWith(tmpDir)) {
63
+ throw new Error(
64
+ `Refusing git init outside temp dir during tests: ${directory}`
65
+ );
66
+ }
67
+ }
68
+ // ... proceed
69
+ }
70
+ ```
71
+
72
+ ### Layer 4: Debug Instrumentation
73
+ **Purpose:** Capture context for forensics
74
+
75
+ ```typescript
76
+ async function gitInit(directory: string) {
77
+ const stack = new Error().stack;
78
+ logger.debug('About to git init', {
79
+ directory,
80
+ cwd: process.cwd(),
81
+ stack,
82
+ });
83
+ // ... proceed
84
+ }
85
+ ```
86
+
87
+ ## Applying the Pattern
88
+
89
+ When you find a bug:
90
+
91
+ 1. **Trace the data flow** - Where does bad value originate? Where used?
92
+ 2. **Map all checkpoints** - List every point data passes through
93
+ 3. **Add validation at each layer** - Entry, business, environment, debug
94
+ 4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it
95
+
96
+ ## Example from Session
97
+
98
+ Bug: Empty `projectDir` caused `git init` in source code
99
+
100
+ **Data flow:**
101
+ 1. Test setup → empty string
102
+ 2. `Project.create(name, '')`
103
+ 3. `WorkspaceManager.createWorkspace('')`
104
+ 4. `git init` runs in `process.cwd()`
105
+
106
+ **Four layers added:**
107
+ - Layer 1: `Project.create()` validates not empty/exists/writable
108
+ - Layer 2: `WorkspaceManager` validates projectDir not empty
109
+ - Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests
110
+ - Layer 4: Stack trace logging before git init
111
+
112
+ **Result:** All 1847 tests passed, bug impossible to reproduce
113
+
114
+ ## Key Insight
115
+
116
+ All four layers were necessary. During testing, each layer caught bugs the others missed:
117
+ - Different code paths bypassed entry validation
118
+ - Mocks bypassed business logic checks
119
+ - Edge cases on different platforms needed environment guards
120
+ - Debug logging identified structural misuse
121
+
122
+ **Don't stop at one validation point.** Add checks at every layer.
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env bash
2
+ # Bisection script to find which test creates unwanted files/state
3
+ # Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
4
+ # Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'
5
+
6
+ set -e
7
+
8
+ if [ $# -ne 2 ]; then
9
+ echo "Usage: $0 <file_to_check> <test_pattern>"
10
+ echo "Example: $0 '.git' 'src/**/*.test.ts'"
11
+ exit 1
12
+ fi
13
+
14
+ POLLUTION_CHECK="$1"
15
+ TEST_PATTERN="$2"
16
+
17
+ echo "🔍 Searching for test that creates: $POLLUTION_CHECK"
18
+ echo "Test pattern: $TEST_PATTERN"
19
+ echo ""
20
+
21
+ # Get list of test files
22
+ TEST_FILES=$(find . -path "$TEST_PATTERN" | sort)
23
+ TOTAL=$(echo "$TEST_FILES" | wc -l | tr -d ' ')
24
+
25
+ echo "Found $TOTAL test files"
26
+ echo ""
27
+
28
+ COUNT=0
29
+ for TEST_FILE in $TEST_FILES; do
30
+ COUNT=$((COUNT + 1))
31
+
32
+ # Skip if pollution already exists
33
+ if [ -e "$POLLUTION_CHECK" ]; then
34
+ echo "⚠️ Pollution already exists before test $COUNT/$TOTAL"
35
+ echo " Skipping: $TEST_FILE"
36
+ continue
37
+ fi
38
+
39
+ echo "[$COUNT/$TOTAL] Testing: $TEST_FILE"
40
+
41
+ # Run the test
42
+ npm test "$TEST_FILE" > /dev/null 2>&1 || true
43
+
44
+ # Check if pollution appeared
45
+ if [ -e "$POLLUTION_CHECK" ]; then
46
+ echo ""
47
+ echo "🎯 FOUND POLLUTER!"
48
+ echo " Test: $TEST_FILE"
49
+ echo " Created: $POLLUTION_CHECK"
50
+ echo ""
51
+ echo "Pollution details:"
52
+ ls -la "$POLLUTION_CHECK"
53
+ echo ""
54
+ echo "To investigate:"
55
+ echo " npm test $TEST_FILE # Run just this test"
56
+ echo " cat $TEST_FILE # Review test code"
57
+ exit 1
58
+ fi
59
+ done
60
+
61
+ echo ""
62
+ echo "✅ No polluter found - all tests clean!"
63
+ exit 0