xonecas.io
56101
Df

dotfiles / commit c0c400f

feat: use agents with good prompts instead of indexed AGENTS. uses less

tokens

xonecas2026-01-31 c0c400f4a7625ac59e6ba5da0fa9f067fa74d97c parent f6d6cd8

32 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

opencode/.agent-docs/debugging/01-overview-iron-law.md+0−44
@@ -1,44 +0,0 @@
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-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)
opencode/.agent-docs/debugging/02-phase1-root-cause.md+0−75
@@ -1,75 +0,0 @@
1-## The Four Phases
2-
3-You MUST complete each phase before proceeding to the next.
4-
5-### Phase 1: Root Cause Investigation
6-
7-**BEFORE attempting ANY fix:**
8-
9-1. **Read Error Messages Carefully**
10- - Don't skip past errors or warnings
11- - They often contain the exact solution
12- - Read stack traces completely
13- - Note line numbers, file paths, error codes
14-
15-2. **Reproduce Consistently**
16- - Can you trigger it reliably?
17- - What are the exact steps?
18- - Does it happen every time?
19- - If not reproducible → gather more data, don't guess
20-
21-3. **Check Recent Changes**
22- - What changed that could cause this?
23- - Git diff, recent commits
24- - New dependencies, config changes
25- - Environmental differences
26-
27-4. **Gather Evidence in Multi-Component Systems**
28-
29- **WHEN system has multiple components (CI → build → signing, API → service → database):**
30-
31- **BEFORE proposing fixes, add diagnostic instrumentation:**
32- ```
33- For EACH component boundary:
34- - Log what data enters component
35- - Log what data exits component
36- - Verify environment/config propagation
37- - Check state at each layer
38-
39- Run once to gather evidence showing WHERE it breaks
40- THEN analyze evidence to identify failing component
41- THEN investigate that specific component
42- ```
43-
44- **Example (multi-layer system):**
45- ```bash
46- # Layer 1: Workflow
47- echo "=== Secrets available in workflow: ==="
48- echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}"
49-
50- # Layer 2: Build script
51- echo "=== Env vars in build script: ==="
52- env | grep IDENTITY || echo "IDENTITY not in environment"
53-
54- # Layer 3: Signing script
55- echo "=== Keychain state: ==="
56- security list-keychains
57- security find-identity -v
58-
59- # Layer 4: Actual signing
60- codesign --sign "$IDENTITY" --verbose=4 "$APP"
61- ```
62-
63- **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)
64-
65-5. **Trace Data Flow**
66-
67- **WHEN error is deep in call stack:**
68-
69- See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
70-
71- **Quick version:**
72- - Where does bad value originate?
73- - What called this with bad value?
74- - Keep tracing up until you find the source
75- - Fix at source, not at symptom
opencode/.agent-docs/debugging/03-phase2-pattern-analysis.md+0−22
@@ -1,22 +0,0 @@
1-### Phase 2: Pattern Analysis
2-
3-**Find the pattern before fixing:**
4-
5-1. **Find Working Examples**
6- - Locate similar working code in same codebase
7- - What works that's similar to what's broken?
8-
9-2. **Compare Against References**
10- - If implementing pattern, read reference implementation COMPLETELY
11- - Don't skim - read every line
12- - Understand the pattern fully before applying
13-
14-3. **Identify Differences**
15- - What's different between working and broken?
16- - List every difference, however small
17- - Don't assume "that can't matter"
18-
19-4. **Understand Dependencies**
20- - What other components does this need?
21- - What settings, config, environment?
22- - What assumptions does it make?
opencode/.agent-docs/debugging/04-phase3-hypothesis.md+0−24
@@ -1,24 +0,0 @@
1-### Phase 3: Hypothesis and Testing
2-
3-**Scientific method:**
4-
5-1. **Form Single Hypothesis**
6- - State clearly: "I think X is the root cause because Y"
7- - Write it down
8- - Be specific, not vague
9-
10-2. **Test Minimally**
11- - Make the SMALLEST possible change to test hypothesis
12- - One variable at a time
13- - Don't fix multiple things at once
14-
15-3. **Verify Before Continuing**
16- - Did it work? Yes → Phase 4
17- - Didn't work? Form NEW hypothesis
18- - DON'T add more fixes on top
19-
20-4. **When You Don't Know**
21- - Say "I don't understand X"
22- - Don't pretend to know
23- - Ask for help
24- - Research more
opencode/.agent-docs/debugging/05-phase4-implementation.md+0−44
@@ -1,44 +0,0 @@
1-### Phase 4: Implementation
2-
3-**Fix the root cause, not the symptom:**
4-
5-1. **Create Failing Test Case**
6- - Simplest possible reproduction
7- - Automated test if possible
8- - One-off test script if no framework
9- - MUST have before fixing
10- - Use the `superpowers:test-driven-development` skill for writing proper failing tests
11-
12-2. **Implement Single Fix**
13- - Address the root cause identified
14- - ONE change at a time
15- - No "while I'm here" improvements
16- - No bundled refactoring
17-
18-3. **Verify Fix**
19- - Test passes now?
20- - No other tests broken?
21- - Issue actually resolved?
22-
23-4. **If Fix Doesn't Work**
24- - STOP
25- - Count: How many fixes have you tried?
26- - If < 3: Return to Phase 1, re-analyze with new information
27- - **If ≥ 3: STOP and question the architecture (step 5 below)**
28- - DON'T attempt Fix #4 without architectural discussion
29-
30-5. **If 3+ Fixes Failed: Question Architecture**
31-
32- **Pattern indicating architectural problem:**
33- - Each fix reveals new shared state/coupling/problem in different place
34- - Fixes require "massive refactoring" to implement
35- - Each fix creates new symptoms elsewhere
36-
37- **STOP and question fundamentals:**
38- - Is this pattern fundamentally sound?
39- - Are we "sticking with it through sheer inertia"?
40- - Should we refactor architecture vs. continue fixing symptoms?
41-
42- **Discuss with your human partner before attempting more fixes**
43-
44- This is NOT a failed hypothesis - this is a wrong architecture.
opencode/.agent-docs/debugging/06-red-flags.md+0−29
@@ -1,29 +0,0 @@
1-## Red Flags - STOP and Follow Process
2-
3-If you catch yourself thinking:
4-- "Quick fix for now, investigate later"
5-- "Just try changing X and see if it works"
6-- "Add multiple changes, run tests"
7-- "Skip the test, I'll manually verify"
8-- "It's probably X, let me fix that"
9-- "I don't fully understand but this might work"
10-- "Pattern says X but I'll adapt it differently"
11-- "Here are the main problems: [lists fixes without investigation]"
12-- Proposing solutions before tracing data flow
13-- **"One more fix attempt" (when already tried 2+)**
14-- **Each fix reveals new problem in different place**
15-
16-**ALL of these mean: STOP. Return to Phase 1.**
17-
18-**If 3+ fixes failed:** Question the architecture (see Phase 4.5)
19-
20-## your human partner's Signals You're Doing It Wrong
21-
22-**Watch for these redirections:**
23-- "Is that not happening?" - You assumed without verifying
24-- "Will it show us...?" - You should have added evidence gathering
25-- "Stop guessing" - You're proposing fixes without understanding
26-- "Ultrathink this" - Question fundamentals, not just symptoms
27-- "We're stuck?" (frustrated) - Your approach isn't working
28-
29-**When you see these:** STOP. Return to Phase 1.
opencode/.agent-docs/debugging/07-common-rationalizations.md+0−12
@@ -1,12 +0,0 @@
1-## Common Rationalizations
2-
3-| Excuse | Reality |
4-|--------|---------|
5-| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
6-| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
7-| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
8-| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
9-| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
10-| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
11-| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
12-| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
opencode/.agent-docs/debugging/08-quick-reference.md+0−8
@@ -1,8 +0,0 @@
1-## Quick Reference
2-
3-| Phase | Key Activities | Success Criteria |
4-|-------|---------------|------------------|
5-| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
6-| **2. Pattern** | Find working examples, compare | Identify differences |
7-| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
8-| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |
opencode/.agent-docs/debugging/09-no-root-cause.md+0−10
@@ -1,10 +0,0 @@
1-## When Process Reveals "No Root Cause"
2-
3-If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
4-
5-1. You've completed the process
6-2. Document what you investigated
7-3. Implement appropriate handling (retry, timeout, error message)
8-4. Add monitoring/logging for future investigation
9-
10-**But:** 95% of "no root cause" cases are incomplete investigation.
opencode/.agent-docs/debugging/10-supporting-techniques.md+0−11
@@ -1,11 +0,0 @@
1-## Supporting Techniques
2-
3-These techniques are part of systematic debugging and available in this directory:
4-
5-- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
6-- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
7-- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
8-
9-**Related skills:**
10-- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1)
11-- **superpowers:verification-before-completion** - Verify fix worked before claiming success
opencode/.agent-docs/debugging/11-real-world-impact.md+0−7
@@ -1,7 +0,0 @@
1-## Real-World Impact
2-
3-From debugging sessions:
4-- Systematic approach: 15-30 minutes to fix
5-- Random fixes approach: 2-3 hours of thrashing
6-- First-time fix rate: 95% vs 40%
7-- New bugs introduced: Near zero vs common
opencode/.agent-docs/debugging/CREATION-LOG.md+0−119
@@ -1,119 +0,0 @@
1-# Creation Log: Systematic Debugging Skill
2-
3-Reference example of extracting, structuring, and bulletproofing a critical skill.
4-
5-## Source Material
6-
7-Extracted debugging framework from `/Users/jesse/.claude/CLAUDE.md`:
8-- 4-phase systematic process (Investigation → Pattern Analysis → Hypothesis → Implementation)
9-- Core mandate: ALWAYS find root cause, NEVER fix symptoms
10-- Rules designed to resist time pressure and rationalization
11-
12-## Extraction Decisions
13-
14-**What to include:**
15-- Complete 4-phase framework with all rules
16-- Anti-shortcuts ("NEVER fix symptom", "STOP and re-analyze")
17-- Pressure-resistant language ("even if faster", "even if I seem in a hurry")
18-- Concrete steps for each phase
19-
20-**What to leave out:**
21-- Project-specific context
22-- Repetitive variations of same rule
23-- Narrative explanations (condensed to principles)
24-
25-## Structure Following skill-creation/SKILL.md
26-
27-1. **Rich when_to_use** - Included symptoms and anti-patterns
28-2. **Type: technique** - Concrete process with steps
29-3. **Keywords** - "root cause", "symptom", "workaround", "debugging", "investigation"
30-4. **Flowchart** - Decision point for "fix failed" → re-analyze vs add more fixes
31-5. **Phase-by-phase breakdown** - Scannable checklist format
32-6. **Anti-patterns section** - What NOT to do (critical for this skill)
33-
34-## Bulletproofing Elements
35-
36-Framework designed to resist rationalization under pressure:
37-
38-### Language Choices
39-- "ALWAYS" / "NEVER" (not "should" / "try to")
40-- "even if faster" / "even if I seem in a hurry"
41-- "STOP and re-analyze" (explicit pause)
42-- "Don't skip past" (catches the actual behavior)
43-
44-### Structural Defenses
45-- **Phase 1 required** - Can't skip to implementation
46-- **Single hypothesis rule** - Forces thinking, prevents shotgun fixes
47-- **Explicit failure mode** - "IF your first fix doesn't work" with mandatory action
48-- **Anti-patterns section** - Shows exactly what shortcuts look like
49-
50-### Redundancy
51-- Root cause mandate in overview + when_to_use + Phase 1 + implementation rules
52-- "NEVER fix symptom" appears 4 times in different contexts
53-- Each phase has explicit "don't skip" guidance
54-
55-## Testing Approach
56-
57-Created 4 validation tests following skills/meta/testing-skills-with-subagents:
58-
59-### Test 1: Academic Context (No Pressure)
60-- Simple bug, no time pressure
61-- **Result:** Perfect compliance, complete investigation
62-
63-### Test 2: Time Pressure + Obvious Quick Fix
64-- User "in a hurry", symptom fix looks easy
65-- **Result:** Resisted shortcut, followed full process, found real root cause
66-
67-### Test 3: Complex System + Uncertainty
68-- Multi-layer failure, unclear if can find root cause
69-- **Result:** Systematic investigation, traced through all layers, found source
70-
71-### Test 4: Failed First Fix
72-- Hypothesis doesn't work, temptation to add more fixes
73-- **Result:** Stopped, re-analyzed, formed new hypothesis (no shotgun)
74-
75-**All tests passed.** No rationalizations found.
76-
77-## Iterations
78-
79-### Initial Version
80-- Complete 4-phase framework
81-- Anti-patterns section
82-- Flowchart for "fix failed" decision
83-
84-### Enhancement 1: TDD Reference
85-- Added link to skills/testing/test-driven-development
86-- Note explaining TDD's "simplest code" ≠ debugging's "root cause"
87-- Prevents confusion between methodologies
88-
89-## Final Outcome
90-
91-Bulletproof skill that:
92-- ✅ Clearly mandates root cause investigation
93-- ✅ Resists time pressure rationalization
94-- ✅ Provides concrete steps for each phase
95-- ✅ Shows anti-patterns explicitly
96-- ✅ Tested under multiple pressure scenarios
97-- ✅ Clarifies relationship to TDD
98-- ✅ Ready for use
99-
100-## Key Insight
101-
102-**Most important bulletproofing:** Anti-patterns section showing exact shortcuts that feel justified in the moment. When Claude thinks "I'll just add this one quick fix", seeing that exact pattern listed as wrong creates cognitive friction.
103-
104-## Usage Example
105-
106-When encountering a bug:
107-1. Load skill: skills/debugging/systematic-debugging
108-2. Read overview (10 sec) - reminded of mandate
109-3. Follow Phase 1 checklist - forced investigation
110-4. If tempted to skip - see anti-pattern, stop
111-5. Complete all phases - root cause found
112-
113-**Time investment:** 5-10 minutes
114-**Time saved:** Hours of symptom-whack-a-mole
115-
116----
117-
118-*Created: 2025-10-03*
119-*Purpose: Reference example for skill extraction and bulletproofing*
opencode/.agent-docs/debugging/condition-based-waiting-example.ts+0−158
@@ -1,158 +0,0 @@
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
opencode/.agent-docs/debugging/condition-based-waiting.md+0−115
@@ -1,115 +0,0 @@
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-See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
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
opencode/.agent-docs/debugging/defense-in-depth.md+0−122
@@ -1,122 +0,0 @@
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.
opencode/.agent-docs/debugging/find-polluter.sh+0−63
@@ -1,63 +0,0 @@
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
opencode/.agent-docs/debugging/root-cause-tracing.md+0−169
@@ -1,169 +0,0 @@
1-# Root Cause Tracing
2-
3-## Overview
4-
5-Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.
6-
7-**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source.
8-
9-## When to Use
10-
11-```dot
12-digraph when_to_use {
13- "Bug appears deep in stack?" [shape=diamond];
14- "Can trace backwards?" [shape=diamond];
15- "Fix at symptom point" [shape=box];
16- "Trace to original trigger" [shape=box];
17- "BETTER: Also add defense-in-depth" [shape=box];
18-
19- "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"];
20- "Can trace backwards?" -> "Trace to original trigger" [label="yes"];
21- "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"];
22- "Trace to original trigger" -> "BETTER: Also add defense-in-depth";
23-}
24-```
25-
26-**Use when:**
27-- Error happens deep in execution (not at entry point)
28-- Stack trace shows long call chain
29-- Unclear where invalid data originated
30-- Need to find which test/code triggers the problem
31-
32-## The Tracing Process
33-
34-### 1. Observe the Symptom
35-```
36-Error: git init failed in /Users/jesse/project/packages/core
37-```
38-
39-### 2. Find Immediate Cause
40-**What code directly causes this?**
41-```typescript
42-await execFileAsync('git', ['init'], { cwd: projectDir });
43-```
44-
45-### 3. Ask: What Called This?
46-```typescript
47-WorktreeManager.createSessionWorktree(projectDir, sessionId)
48- → called by Session.initializeWorkspace()
49- → called by Session.create()
50- → called by test at Project.create()
51-```
52-
53-### 4. Keep Tracing Up
54-**What value was passed?**
55-- `projectDir = ''` (empty string!)
56-- Empty string as `cwd` resolves to `process.cwd()`
57-- That's the source code directory!
58-
59-### 5. Find Original Trigger
60-**Where did empty string come from?**
61-```typescript
62-const context = setupCoreTest(); // Returns { tempDir: '' }
63-Project.create('name', context.tempDir); // Accessed before beforeEach!
64-```
65-
66-## Adding Stack Traces
67-
68-When you can't trace manually, add instrumentation:
69-
70-```typescript
71-// Before the problematic operation
72-async function gitInit(directory: string) {
73- const stack = new Error().stack;
74- console.error('DEBUG git init:', {
75- directory,
76- cwd: process.cwd(),
77- nodeEnv: process.env.NODE_ENV,
78- stack,
79- });
80-
81- await execFileAsync('git', ['init'], { cwd: directory });
82-}
83-```
84-
85-**Critical:** Use `console.error()` in tests (not logger - may not show)
86-
87-**Run and capture:**
88-```bash
89-npm test 2>&1 | grep 'DEBUG git init'
90-```
91-
92-**Analyze stack traces:**
93-- Look for test file names
94-- Find the line number triggering the call
95-- Identify the pattern (same test? same parameter?)
96-
97-## Finding Which Test Causes Pollution
98-
99-If something appears during tests but you don't know which test:
100-
101-Use the bisection script `find-polluter.sh` in this directory:
102-
103-```bash
104-./find-polluter.sh '.git' 'src/**/*.test.ts'
105-```
106-
107-Runs tests one-by-one, stops at first polluter. See script for usage.
108-
109-## Real Example: Empty projectDir
110-
111-**Symptom:** `.git` created in `packages/core/` (source code)
112-
113-**Trace chain:**
114-1. `git init` runs in `process.cwd()` ← empty cwd parameter
115-2. WorktreeManager called with empty projectDir
116-3. Session.create() passed empty string
117-4. Test accessed `context.tempDir` before beforeEach
118-5. setupCoreTest() returns `{ tempDir: '' }` initially
119-
120-**Root cause:** Top-level variable initialization accessing empty value
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/debugging/test-academic.md+0−14
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/debugging/test-pressure-1.md+0−58
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/debugging/test-pressure-2.md+0−68
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/debugging/test-pressure-3.md+0−69
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/programming/01-kiss.md+0−10
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/programming/02-dry.md+0−11
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/programming/03-yagni.md+0−11
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/programming/04-feature-creep-overengineering.md+0−21
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/programming/05-solid.md+0−15
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/programming/06-applying-principles.md+0−6
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/writing/01-writing-essentials.md+0−25
Cut short: this commit's diff is over 1000 lines.
opencode/.agent-docs/writing/02-ai-patterns-avoid.md+0−11
Cut short: this commit's diff is over 1000 lines.
opencode/AGENTS.md+3−39
Cut short: this commit's diff is over 1000 lines.
opencode/agents/plan.md+1−1
Cut short: this commit's diff is over 1000 lines.
opencode/opencode.json+0−8
Cut short: this commit's diff is over 1000 lines.