specjig 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/LICENSE +24 -0
  3. package/README.md +106 -2
  4. package/bin/specjig.mjs +7 -0
  5. package/harness.lock.json +61 -0
  6. package/package.json +54 -4
  7. package/src/cli.mjs +278 -0
  8. package/src/lib/install.mjs +242 -0
  9. package/src/lib/openspec.mjs +83 -0
  10. package/src/lib/util.mjs +86 -0
  11. package/templates/.claude/hooks/sdd-commit-guard.mjs +39 -0
  12. package/templates/.claude/hooks/sdd-fix-mode-guard.mjs +34 -0
  13. package/templates/.claude/hooks/sdd-lib/change-id.mjs +47 -0
  14. package/templates/.claude/hooks/sdd-lib/io.mjs +29 -0
  15. package/templates/.claude/hooks/sdd-lib/patterns.mjs +130 -0
  16. package/templates/.claude/hooks/sdd-prompt-guard.mjs +17 -0
  17. package/templates/.claude/hooks/sdd-protect-secrets.mjs +32 -0
  18. package/templates/.claude/rules/openspec.md +14 -0
  19. package/templates/.claude/rules/security.md +31 -0
  20. package/templates/.claude/rules/test-data.md +22 -0
  21. package/templates/.claude/settings.json +97 -0
  22. package/templates/.claude/skills/change-pr/SKILL.md +61 -0
  23. package/templates/.claude/skills/spec-challenge/SKILL.md +63 -0
  24. package/templates/.claude/skills/spec-compaction/SKILL.md +47 -0
  25. package/templates/.claude/skills/trace-why/SKILL.md +30 -0
  26. package/templates/.githooks/commit-msg +4 -0
  27. package/templates/.github/workflows/sdd-ci-triage.yml +61 -0
  28. package/templates/.github/workflows/sdd-confluence-sync.yml +24 -0
  29. package/templates/.github/workflows/sdd-drift-check.yml +50 -0
  30. package/templates/.github/workflows/sdd-fix-pr-guard.yml +25 -0
  31. package/templates/.github/workflows/sdd-release-notes.yml +45 -0
  32. package/templates/.github/workflows/sdd-security-review.yml +23 -0
  33. package/templates/.github/workflows/sdd-spec-gate.yml +23 -0
  34. package/templates/.github/workflows/sdd-spec-review.yml +51 -0
  35. package/templates/.mcp.json +8 -0
  36. package/templates/.sdd/harness.json +21 -0
  37. package/templates/.sdd/scripts/check-commit-msg.mjs +15 -0
  38. package/templates/.sdd/scripts/check-trailers.mjs +27 -0
  39. package/templates/.sdd/scripts/confluence-sync.mjs +110 -0
  40. package/templates/.sdd/scripts/drift-check.mjs +30 -0
  41. package/templates/.sdd/scripts/fix-pr-guard.mjs +17 -0
  42. package/templates/.sdd/scripts/lib.mjs +31 -0
  43. package/templates/.sdd/scripts/release-notes.mjs +63 -0
  44. package/templates/AGENTS.md +87 -0
  45. package/templates/CLAUDE.md +30 -0
  46. package/templates/openspec/config.yaml +38 -0
  47. package/templates/openspec/schemas/sdd/schema.yaml +379 -0
  48. package/templates/openspec/schemas/sdd/templates/design.md +29 -0
  49. package/templates/openspec/schemas/sdd/templates/impact.md +27 -0
  50. package/templates/openspec/schemas/sdd/templates/proposal.md +43 -0
  51. package/templates/openspec/schemas/sdd/templates/spec.md +13 -0
  52. package/templates/openspec/schemas/sdd/templates/tasks.md +15 -0
  53. package/templates/openspec/schemas/sdd/templates/tests.md +17 -0
  54. package/vendor/skills/grilling/.upstream.json +8 -0
  55. package/vendor/skills/grilling/SKILL.md +30 -0
  56. package/vendor/skills/receiving-code-review/.upstream.json +8 -0
  57. package/vendor/skills/receiving-code-review/SKILL.md +205 -0
  58. package/vendor/skills/systematic-debugging/.upstream.json +8 -0
  59. package/vendor/skills/systematic-debugging/SKILL.md +283 -0
  60. package/vendor/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  61. package/vendor/skills/systematic-debugging/condition-based-waiting.md +115 -0
  62. package/vendor/skills/systematic-debugging/defense-in-depth.md +122 -0
  63. package/vendor/skills/systematic-debugging/find-polluter.sh +72 -0
  64. package/vendor/skills/systematic-debugging/root-cause-tracing.md +169 -0
  65. package/vendor/skills/test-driven-development/.upstream.json +8 -0
  66. package/vendor/skills/test-driven-development/SKILL.md +330 -0
  67. package/vendor/skills/test-driven-development/writing-good-tests.md +198 -0
  68. package/vendor/skills/two-axis-review/.upstream.json +8 -0
  69. package/vendor/skills/two-axis-review/SKILL.md +89 -0
@@ -0,0 +1,205 @@
1
+ ---
2
+ name: receiving-code-review
3
+ description: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation
4
+ ---
5
+
6
+ # Code Review Reception
7
+
8
+ ## Overview
9
+
10
+ Code review requires technical evaluation, not emotional performance.
11
+
12
+ **Core principle:** Verify before implementing. Ask before assuming. Technical correctness over social comfort.
13
+
14
+ ## The Response Pattern
15
+
16
+ ```
17
+ WHEN receiving code review feedback:
18
+
19
+ 1. READ: Complete feedback without reacting
20
+ 2. UNDERSTAND: Restate requirement in own words (or ask)
21
+ 3. VERIFY: Check against codebase reality
22
+ 4. EVALUATE: Technically sound for THIS codebase?
23
+ 5. RESPOND: Technical acknowledgment or reasoned pushback
24
+ 6. IMPLEMENT: One item at a time, test each
25
+ ```
26
+
27
+ ## Forbidden Responses
28
+
29
+ **NEVER:**
30
+ - "You're absolutely right!" (explicit instruction-file violation)
31
+ - "Great point!" / "Excellent feedback!" (performative)
32
+ - "Let me implement that now" (before verification)
33
+
34
+ **INSTEAD:**
35
+ - Restate the technical requirement
36
+ - Ask clarifying questions
37
+ - Push back with technical reasoning if wrong
38
+ - Just start working (actions > words)
39
+
40
+ ## Handling Unclear Feedback
41
+
42
+ ```
43
+ IF any item is unclear:
44
+ STOP - do not implement anything yet
45
+ ASK for clarification on unclear items
46
+
47
+ WHY: Items may be related. Partial understanding = wrong implementation.
48
+ ```
49
+
50
+ **Example:**
51
+ ```
52
+ your human partner: "Fix 1-6"
53
+ You understand 1,2,3,6. Unclear on 4,5.
54
+
55
+ ❌ WRONG: Implement 1,2,3,6 now, ask about 4,5 later
56
+ ✅ RIGHT: "I understand items 1,2,3,6. Need clarification on 4 and 5 before proceeding."
57
+ ```
58
+
59
+ ## Source-Specific Handling
60
+
61
+ ### From your human partner
62
+ - **Trusted** - implement after understanding
63
+ - **Still ask** if scope unclear
64
+ - **No performative agreement**
65
+ - **Skip to action** or technical acknowledgment
66
+
67
+ ### From External Reviewers
68
+ ```
69
+ BEFORE implementing:
70
+ 1. Check: Technically correct for THIS codebase?
71
+ 2. Check: Breaks existing functionality?
72
+ 3. Check: Reason for current implementation?
73
+ 4. Check: Works on all platforms/versions?
74
+ 5. Check: Does reviewer understand full context?
75
+
76
+ IF suggestion seems wrong:
77
+ Push back with technical reasoning
78
+
79
+ IF can't easily verify:
80
+ Say so: "I can't verify this without [X]. Should I [investigate/ask/proceed]?"
81
+
82
+ IF conflicts with your human partner's prior decisions:
83
+ Stop and discuss with your human partner first
84
+ ```
85
+
86
+ **your human partner's rule:** "External feedback - be skeptical, but check carefully"
87
+
88
+ ## YAGNI Check for "Professional" Features
89
+
90
+ ```
91
+ IF reviewer suggests "implementing properly":
92
+ grep codebase for actual usage
93
+
94
+ IF unused: "This endpoint isn't called. Remove it (YAGNI)?"
95
+ IF used: Then implement properly
96
+ ```
97
+
98
+ **your human partner's rule:** "You and reviewer both report to me. If we don't need this feature, don't add it."
99
+
100
+ ## Implementation Order
101
+
102
+ ```
103
+ FOR multi-item feedback:
104
+ 1. Clarify anything unclear FIRST
105
+ 2. Then implement in this order:
106
+ - Blocking issues (breaks, security)
107
+ - Simple fixes (typos, imports)
108
+ - Complex fixes (refactoring, logic)
109
+ 3. Test each fix individually
110
+ 4. Verify no regressions
111
+ ```
112
+
113
+ ## When To Push Back
114
+
115
+ Push back when:
116
+ - Suggestion breaks existing functionality
117
+ - Reviewer lacks full context
118
+ - Violates YAGNI (unused feature)
119
+ - Technically incorrect for this stack
120
+ - Legacy/compatibility reasons exist
121
+ - Conflicts with your human partner's architectural decisions
122
+
123
+ **How to push back:**
124
+ - Use technical reasoning, not defensiveness
125
+ - Ask specific questions
126
+ - Reference working tests/code
127
+ - Involve your human partner if architectural
128
+
129
+ **If you're uncomfortable pushing back out loud:** Name that tension, then tell your partner about the issue you've seen. They'll appreciate your honesty.
130
+
131
+ ## Acknowledging Correct Feedback
132
+
133
+ When feedback IS correct:
134
+ ```
135
+ ✅ "Fixed. [Brief description of what changed]"
136
+ ✅ "Good catch - [specific issue]. Fixed in [location]."
137
+ ✅ [Just fix it and show in the code]
138
+
139
+ ❌ "You're absolutely right!"
140
+ ❌ "Great point!"
141
+ ❌ "Thanks for catching that!"
142
+ ❌ "Thanks for [anything]"
143
+ ❌ ANY gratitude expression
144
+ ```
145
+
146
+ **Why no thanks:** Actions speak. Just fix it. The code itself shows you heard the feedback.
147
+
148
+ **If you catch yourself about to write "Thanks":** DELETE IT. State the fix instead.
149
+
150
+ ## Gracefully Correcting Your Pushback
151
+
152
+ If you pushed back and were wrong:
153
+ ```
154
+ ✅ "You were right - I checked [X] and it does [Y]. Implementing now."
155
+ ✅ "Verified this and you're correct. My initial understanding was wrong because [reason]. Fixing."
156
+
157
+ ❌ Long apology
158
+ ❌ Defending why you pushed back
159
+ ❌ Over-explaining
160
+ ```
161
+
162
+ State the correction factually and move on.
163
+
164
+ ## Common Mistakes
165
+
166
+ | Mistake | Fix |
167
+ |---------|-----|
168
+ | Performative agreement | State requirement or just act |
169
+ | Blind implementation | Verify against codebase first |
170
+ | Batch without testing | One at a time, test each |
171
+ | Assuming reviewer is right | Check if breaks things |
172
+ | Avoiding pushback | Technical correctness > comfort |
173
+ | Partial implementation | Clarify all items first |
174
+ | Can't verify, proceed anyway | State limitation, ask for direction |
175
+
176
+ ## Real Examples
177
+
178
+ **Performative Agreement (Bad):**
179
+ ```
180
+ Reviewer: "Remove legacy code"
181
+ ❌ "You're absolutely right! Let me remove that..."
182
+ ```
183
+
184
+ **Technical Verification (Good):**
185
+ ```
186
+ Reviewer: "Remove legacy code"
187
+ ✅ "Checking... build target is 10.15+, this API needs 13+. Need legacy for backward compat. Current impl has wrong bundle ID - fix it or drop pre-13 support?"
188
+ ```
189
+
190
+ **YAGNI (Good):**
191
+ ```
192
+ Reviewer: "Implement proper metrics tracking with database, date filters, CSV export"
193
+ ✅ "Grepped codebase - nothing calls this endpoint. Remove it (YAGNI)? Or is there usage I'm missing?"
194
+ ```
195
+
196
+ **Unclear Item (Good):**
197
+ ```
198
+ your human partner: "Fix items 1-6"
199
+ You understand 1,2,3,6. Unclear on 4,5.
200
+ ✅ "Understand 1,2,3,6. Need clarification on 4 and 5 before implementing."
201
+ ```
202
+
203
+ ## GitHub Thread Replies
204
+
205
+ When replying to inline review comments on GitHub, reply in the comment thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level PR comment.
@@ -0,0 +1,8 @@
1
+ {
2
+ "repo": "obra/superpowers",
3
+ "path": "skills/systematic-debugging",
4
+ "sha": "22f0b463e7a5e579904dd6211a520321035526f7",
5
+ "license": "MIT",
6
+ "url": "https://github.com/obra/superpowers/tree/22f0b463e7a5e579904dd6211a520321035526f7/skills/systematic-debugging",
7
+ "note": "Vendored by specjig. Do not edit; bump the pin in harness.lock.json instead."
8
+ }
@@ -0,0 +1,283 @@
1
+ ---
2
+ name: systematic-debugging
3
+ description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
4
+ ---
5
+
6
+ # Systematic Debugging
7
+
8
+ ## Overview
9
+
10
+ **Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
11
+
12
+ **Violating the letter of this process is violating the spirit of debugging.**
13
+
14
+ ## The Iron Law
15
+
16
+ ```
17
+ NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
18
+ ```
19
+
20
+ If you haven't completed Phase 1, you cannot propose fixes.
21
+
22
+ ## When to Use
23
+
24
+ Use for ANY technical issue:
25
+ - Test failures
26
+ - Bugs in production
27
+ - Unexpected behavior
28
+ - Performance problems
29
+ - Build failures
30
+ - Integration issues
31
+
32
+ **Use this ESPECIALLY when:**
33
+ - Under time pressure (emergencies make guessing tempting)
34
+ - "Just one quick fix" seems obvious
35
+ - You've already tried multiple fixes
36
+ - Previous fix didn't work
37
+ - You don't fully understand the issue
38
+
39
+ **Don't skip when:**
40
+ - Issue seems simple (simple bugs have root causes too)
41
+ - You're in a hurry (rushing guarantees rework)
42
+ - Manager wants it fixed NOW (systematic is faster than thrashing)
43
+
44
+ ## The Four Phases
45
+
46
+ You MUST complete each phase before proceeding to the next.
47
+
48
+ ### Phase 1: Root Cause Investigation
49
+
50
+ **BEFORE attempting ANY fix:**
51
+
52
+ 1. **Read Error Messages Carefully**
53
+ - Don't skip past errors or warnings
54
+ - They often contain the exact solution
55
+ - Read stack traces completely
56
+ - Note line numbers, file paths, error codes
57
+
58
+ 2. **Reproduce Consistently**
59
+ - Can you trigger it reliably?
60
+ - What are the exact steps?
61
+ - Does it happen every time?
62
+ - If not reproducible → gather more data, don't guess
63
+
64
+ 3. **Check Recent Changes**
65
+ - What changed that could cause this?
66
+ - Git diff, recent commits
67
+ - New dependencies, config changes
68
+ - Environmental differences
69
+
70
+ 4. **Gather Evidence in Multi-Component Systems**
71
+
72
+ **WHEN system has multiple components (CI → build → signing, API → service → database):**
73
+
74
+ **BEFORE proposing fixes, add diagnostic instrumentation:**
75
+ ```
76
+ For EACH component boundary:
77
+ - Log what data enters component
78
+ - Log what data exits component
79
+ - Verify environment/config propagation
80
+ - Check state at each layer
81
+
82
+ Run once to gather evidence showing WHERE it breaks
83
+ THEN analyze evidence to identify failing component
84
+ THEN investigate that specific component
85
+ ```
86
+
87
+ **Example (multi-layer system):**
88
+ ```bash
89
+ # Layer 1: Workflow
90
+ echo "=== Secrets available in workflow: ==="
91
+ echo "IDENTITY: $([ -n "${IDENTITY:-}" ] && echo SET || echo UNSET)"
92
+
93
+ # Layer 2: Build script
94
+ echo "=== Env vars in build script: ==="
95
+ printenv IDENTITY >/dev/null 2>&1 && echo "IDENTITY in environment" || echo "IDENTITY not in environment"
96
+
97
+ # Layer 3: Signing script
98
+ echo "=== Keychain state: ==="
99
+ security list-keychains
100
+ security find-identity -v
101
+
102
+ # Layer 4: Actual signing
103
+ codesign --sign "$IDENTITY" --verbose=4 "$APP"
104
+ ```
105
+
106
+ **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)
107
+
108
+ 5. **Trace Data Flow**
109
+
110
+ **WHEN error is deep in call stack:**
111
+
112
+ See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
113
+
114
+ **Quick version:**
115
+ - Where does bad value originate?
116
+ - What called this with bad value?
117
+ - Keep tracing up until you find the source
118
+ - Fix at source, not at symptom
119
+
120
+ ### Phase 2: Pattern Analysis
121
+
122
+ **Find the pattern before fixing:**
123
+
124
+ 1. **Find Working Examples**
125
+ - Locate similar working code in same codebase
126
+ - What works that's similar to what's broken?
127
+
128
+ 2. **Compare Against References**
129
+ - If implementing pattern, read reference implementation COMPLETELY
130
+ - Don't skim - read every line
131
+ - Understand the pattern fully before applying
132
+
133
+ 3. **Identify Differences**
134
+ - What's different between working and broken?
135
+ - List every difference, however small
136
+ - Don't assume "that can't matter"
137
+
138
+ 4. **Understand Dependencies**
139
+ - What other components does this need?
140
+ - What settings, config, environment?
141
+ - What assumptions does it make?
142
+
143
+ ### Phase 3: Hypothesis and Testing
144
+
145
+ **Scientific method:**
146
+
147
+ 1. **Form Single Hypothesis**
148
+ - State clearly: "I think X is the root cause because Y"
149
+ - Write it down
150
+ - Be specific, not vague
151
+
152
+ 2. **Test Minimally**
153
+ - Make the SMALLEST possible change to test hypothesis
154
+ - One variable at a time
155
+ - Don't fix multiple things at once
156
+
157
+ 3. **Verify Before Continuing**
158
+ - Did it work? Yes → Phase 4
159
+ - Didn't work? Form NEW hypothesis
160
+ - DON'T add more fixes on top
161
+
162
+ 4. **When You Don't Know**
163
+ - Say "I don't understand X"
164
+ - Don't pretend to know
165
+ - Ask for help
166
+ - Research more
167
+
168
+ ### Phase 4: Implementation
169
+
170
+ **Fix the root cause, not the symptom:**
171
+
172
+ 1. **Create Failing Test Case**
173
+ - Simplest possible reproduction
174
+ - Automated test if possible
175
+ - One-off test script if no framework
176
+ - MUST have before fixing
177
+ - Use the `superpowers:test-driven-development` skill for writing proper failing tests
178
+
179
+ 2. **Implement Single Fix**
180
+ - Address the root cause identified
181
+ - ONE change at a time
182
+ - No "while I'm here" improvements
183
+ - No bundled refactoring
184
+
185
+ 3. **Verify Fix**
186
+ - Test passes now?
187
+ - No other tests broken?
188
+ - Issue actually resolved?
189
+ - Use the `superpowers:verification-before-completion` skill before claiming success
190
+
191
+ 4. **If Fix Doesn't Work**
192
+ - STOP
193
+ - Count: How many fixes have you tried?
194
+ - If < 3: Return to Phase 1, re-analyze with new information
195
+ - **If ≥ 3: STOP and question the architecture (step 5 below)**
196
+ - DON'T attempt Fix #4 without architectural discussion
197
+
198
+ 5. **If 3+ Fixes Failed: Question Architecture**
199
+
200
+ **Pattern indicating architectural problem:**
201
+ - Each fix reveals new shared state/coupling/problem in different place
202
+ - Fixes require "massive refactoring" to implement
203
+ - Each fix creates new symptoms elsewhere
204
+
205
+ **STOP and question fundamentals:**
206
+ - Is this pattern fundamentally sound?
207
+ - Are we "sticking with it through sheer inertia"?
208
+ - Should we refactor architecture vs. continue fixing symptoms?
209
+
210
+ **Discuss with your human partner before attempting more fixes**
211
+
212
+ This is NOT a failed hypothesis - this is a wrong architecture.
213
+
214
+ ## Red Flags - STOP and Follow Process
215
+
216
+ If you catch yourself thinking:
217
+ - "Quick fix for now, investigate later"
218
+ - "Just try changing X and see if it works"
219
+ - "Add multiple changes, run tests"
220
+ - "Skip the test, I'll manually verify"
221
+ - "It's probably X, let me fix that"
222
+ - "I don't fully understand but this might work"
223
+ - "Pattern says X but I'll adapt it differently"
224
+ - "Here are the main problems: [lists fixes without investigation]"
225
+ - Proposing solutions before tracing data flow
226
+ - **"One more fix attempt" (when already tried 2+)**
227
+ - **Each fix reveals new problem in different place**
228
+
229
+ **ALL of these mean: STOP. Return to Phase 1.**
230
+
231
+ **If 3+ fixes failed:** Question the architecture (see Phase 4.5)
232
+
233
+ ## your human partner's Signals You're Doing It Wrong
234
+
235
+ **Watch for these redirections:**
236
+ - "Is that not happening?" - You assumed without verifying
237
+ - "Will it show us...?" - You should have added evidence gathering
238
+ - "Stop guessing" - You're proposing fixes without understanding
239
+ - "Ultra-think this" - Question fundamentals, not just symptoms
240
+ - "We're stuck?" (frustrated) - Your approach isn't working
241
+
242
+ **When you see these:** STOP. Return to Phase 1.
243
+
244
+ ## Common Rationalizations
245
+
246
+ | Excuse | Reality |
247
+ |--------|---------|
248
+ | "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
249
+ | "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
250
+ | "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
251
+ | "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
252
+ | "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
253
+ | "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
254
+ | "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
255
+ | "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
256
+
257
+ ## Quick Reference
258
+
259
+ | Phase | Key Activities | Success Criteria |
260
+ |-------|---------------|------------------|
261
+ | **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
262
+ | **2. Pattern** | Find working examples, compare | Identify differences |
263
+ | **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
264
+ | **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |
265
+
266
+ ## When Process Reveals "No Root Cause"
267
+
268
+ If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
269
+
270
+ 1. You've completed the process
271
+ 2. Document what you investigated
272
+ 3. Implement appropriate handling (retry, timeout, error message)
273
+ 4. Add monitoring/logging for future investigation
274
+
275
+ **But:** 95% of "no root cause" cases are incomplete investigation.
276
+
277
+ ## Supporting Techniques
278
+
279
+ These techniques are part of systematic debugging and available in this directory:
280
+
281
+ - **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
282
+ - **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
283
+ - **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
@@ -0,0 +1,158 @@
1
+ // Complete implementation of condition-based waiting utilities
2
+ // From: Lace test infrastructure improvements (2025-10-03)
3
+ // Context: Fixed 15 flaky tests by replacing arbitrary timeouts
4
+
5
+ import type { ThreadManager } from '~/threads/thread-manager';
6
+ import type { LaceEvent, LaceEventType } from '~/threads/types';
7
+
8
+ /**
9
+ * Wait for a specific event type to appear in thread
10
+ *
11
+ * @param threadManager - The thread manager to query
12
+ * @param threadId - Thread to check for events
13
+ * @param eventType - Type of event to wait for
14
+ * @param timeoutMs - Maximum time to wait (default 5000ms)
15
+ * @returns Promise resolving to the first matching event
16
+ *
17
+ * Example:
18
+ * await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT');
19
+ */
20
+ export function waitForEvent(
21
+ threadManager: ThreadManager,
22
+ threadId: string,
23
+ eventType: LaceEventType,
24
+ timeoutMs = 5000
25
+ ): Promise<LaceEvent> {
26
+ return new Promise((resolve, reject) => {
27
+ const startTime = Date.now();
28
+
29
+ const check = () => {
30
+ const events = threadManager.getEvents(threadId);
31
+ const event = events.find((e) => e.type === eventType);
32
+
33
+ if (event) {
34
+ resolve(event);
35
+ } else if (Date.now() - startTime > timeoutMs) {
36
+ reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`));
37
+ } else {
38
+ setTimeout(check, 10); // Poll every 10ms for efficiency
39
+ }
40
+ };
41
+
42
+ check();
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Wait for a specific number of events of a given type
48
+ *
49
+ * @param threadManager - The thread manager to query
50
+ * @param threadId - Thread to check for events
51
+ * @param eventType - Type of event to wait for
52
+ * @param count - Number of events to wait for
53
+ * @param timeoutMs - Maximum time to wait (default 5000ms)
54
+ * @returns Promise resolving to all matching events once count is reached
55
+ *
56
+ * Example:
57
+ * // Wait for 2 AGENT_MESSAGE events (initial response + continuation)
58
+ * await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2);
59
+ */
60
+ export function waitForEventCount(
61
+ threadManager: ThreadManager,
62
+ threadId: string,
63
+ eventType: LaceEventType,
64
+ count: number,
65
+ timeoutMs = 5000
66
+ ): Promise<LaceEvent[]> {
67
+ return new Promise((resolve, reject) => {
68
+ const startTime = Date.now();
69
+
70
+ const check = () => {
71
+ const events = threadManager.getEvents(threadId);
72
+ const matchingEvents = events.filter((e) => e.type === eventType);
73
+
74
+ if (matchingEvents.length >= count) {
75
+ resolve(matchingEvents);
76
+ } else if (Date.now() - startTime > timeoutMs) {
77
+ reject(
78
+ new Error(
79
+ `Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})`
80
+ )
81
+ );
82
+ } else {
83
+ setTimeout(check, 10);
84
+ }
85
+ };
86
+
87
+ check();
88
+ });
89
+ }
90
+
91
+ /**
92
+ * Wait for an event matching a custom predicate
93
+ * Useful when you need to check event data, not just type
94
+ *
95
+ * @param threadManager - The thread manager to query
96
+ * @param threadId - Thread to check for events
97
+ * @param predicate - Function that returns true when event matches
98
+ * @param description - Human-readable description for error messages
99
+ * @param timeoutMs - Maximum time to wait (default 5000ms)
100
+ * @returns Promise resolving to the first matching event
101
+ *
102
+ * Example:
103
+ * // Wait for TOOL_RESULT with specific ID
104
+ * await waitForEventMatch(
105
+ * threadManager,
106
+ * agentThreadId,
107
+ * (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123',
108
+ * 'TOOL_RESULT with id=call_123'
109
+ * );
110
+ */
111
+ export function waitForEventMatch(
112
+ threadManager: ThreadManager,
113
+ threadId: string,
114
+ predicate: (event: LaceEvent) => boolean,
115
+ description: string,
116
+ timeoutMs = 5000
117
+ ): Promise<LaceEvent> {
118
+ return new Promise((resolve, reject) => {
119
+ const startTime = Date.now();
120
+
121
+ const check = () => {
122
+ const events = threadManager.getEvents(threadId);
123
+ const event = events.find(predicate);
124
+
125
+ if (event) {
126
+ resolve(event);
127
+ } else if (Date.now() - startTime > timeoutMs) {
128
+ reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`));
129
+ } else {
130
+ setTimeout(check, 10);
131
+ }
132
+ };
133
+
134
+ check();
135
+ });
136
+ }
137
+
138
+ // Usage example from actual debugging session:
139
+ //
140
+ // BEFORE (flaky):
141
+ // ---------------
142
+ // const messagePromise = agent.sendMessage('Execute tools');
143
+ // await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms
144
+ // agent.abort();
145
+ // await messagePromise;
146
+ // await new Promise(r => setTimeout(r, 50)); // Hope results arrive in 50ms
147
+ // expect(toolResults.length).toBe(2); // Fails randomly
148
+ //
149
+ // AFTER (reliable):
150
+ // ----------------
151
+ // const messagePromise = agent.sendMessage('Execute tools');
152
+ // await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start
153
+ // agent.abort();
154
+ // await messagePromise;
155
+ // await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results
156
+ // expect(toolResults.length).toBe(2); // Always succeeds
157
+ //
158
+ // Result: 60% pass rate → 100%, 40% faster execution