@rune-kit/rune 2.4.0 → 2.7.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 (49) hide show
  1. package/README.md +47 -17
  2. package/compiler/__tests__/executive-dashboards.test.js +285 -0
  3. package/compiler/__tests__/inject.test.js +128 -0
  4. package/compiler/__tests__/orchestrators.test.js +151 -0
  5. package/compiler/__tests__/org-templates.test.js +447 -0
  6. package/compiler/__tests__/pack-split.test.js +141 -1
  7. package/compiler/__tests__/parser.test.js +147 -1
  8. package/compiler/__tests__/scripts-bundling.test.js +10 -11
  9. package/compiler/__tests__/skill-index.test.js +218 -0
  10. package/compiler/__tests__/status.test.js +336 -0
  11. package/compiler/__tests__/templates.test.js +245 -0
  12. package/compiler/__tests__/visualizer.test.js +325 -0
  13. package/compiler/adapters/antigravity.js +18 -4
  14. package/compiler/bin/rune.js +90 -1
  15. package/compiler/doctor.js +283 -2
  16. package/compiler/emitter.js +490 -17
  17. package/compiler/parser.js +255 -4
  18. package/compiler/status.js +342 -0
  19. package/compiler/visualizer.js +622 -0
  20. package/hooks/hooks.json +12 -0
  21. package/hooks/intent-router/index.cjs +108 -0
  22. package/hooks/pre-tool-guard/index.cjs +177 -68
  23. package/package.json +63 -63
  24. package/skills/autopsy/SKILL.md +48 -1
  25. package/skills/brainstorm/SKILL.md +2 -0
  26. package/skills/completion-gate/SKILL.md +26 -1
  27. package/skills/context-engine/SKILL.md +93 -2
  28. package/skills/cook/SKILL.md +794 -648
  29. package/skills/debug/SKILL.md +409 -392
  30. package/skills/deploy/SKILL.md +2 -0
  31. package/skills/docs/SKILL.md +28 -3
  32. package/skills/fix/SKILL.md +284 -281
  33. package/skills/mcp-builder/SKILL.md +53 -1
  34. package/skills/onboard/SKILL.md +58 -1
  35. package/skills/perf/SKILL.md +34 -1
  36. package/skills/plan/SKILL.md +372 -342
  37. package/skills/preflight/SKILL.md +396 -360
  38. package/skills/retro/SKILL.md +95 -1
  39. package/skills/review/SKILL.md +535 -489
  40. package/skills/scope-guard/SKILL.md +1 -0
  41. package/skills/scout/SKILL.md +1 -0
  42. package/skills/sentinel/SKILL.md +353 -299
  43. package/skills/sentinel/references/policy-driven-constraints.md +424 -0
  44. package/skills/session-bridge/SKILL.md +58 -2
  45. package/skills/session-bridge/references/evolutionary-memory-patterns.md +312 -0
  46. package/skills/team/SKILL.md +16 -1
  47. package/skills/test/SKILL.md +587 -585
  48. package/skills/verification/SKILL.md +1 -0
  49. package/skills/watchdog/SKILL.md +2 -0
@@ -1,392 +1,409 @@
1
- ---
2
- name: debug
3
- description: Root cause analysis for bugs and unexpected behavior. Traces errors through code, uses structured reasoning, and hands off to fix when cause is found. Core of the debug↔fix mesh.
4
- metadata:
5
- author: runedev
6
- version: "0.8.0"
7
- layer: L2
8
- model: sonnet
9
- group: development
10
- tools: "Read, Bash, Glob, Grep"
11
- ---
12
-
13
- # debug
14
-
15
- ## Purpose
16
-
17
- Root cause analysis ONLY. Debug investigates — it does NOT fix. It traces errors through code, analyzes stack traces, forms and tests hypotheses, and identifies the exact cause before handing off to rune:fix.
18
-
19
- <HARD-GATE>
20
- Do NOT fix the code. Debug investigates only. Any code change is out of scope.
21
- If root cause cannot be identified after 3 hypothesis cycles:
22
- - Escalate to `rune:problem-solver` for structured 5-Whys or Fishbone analysis
23
- - Or escalate to `rune:sequential-thinking` for multi-variable analysis
24
- - Report escalation in the Debug Report with all evidence gathered so far
25
- </HARD-GATE>
26
-
27
- ## Triggers
28
-
29
- - Called by `cook` when implementation hits unexpected errors
30
- - Called by `test` when a test fails with unclear reason
31
- - Called by `fix` when root cause is unclear before fixing
32
- - `/rune debug <issue>` manual debugging
33
- - Auto-trigger: when error output contains stack trace or error code
34
-
35
- ## Calls (outbound)
36
-
37
- - `scout` (L2): find related code, trace imports, identify affected modules
38
- - `fix` (L2): when root cause found, hand off with diagnosis for fix application
39
- - `brainstorm` (L2): 3-Fix Escalation when root cause is "wrong approach" — invoke with mode="rescue" for category-diverse alternatives
40
- - `plan` (L2): 3-Fix Escalation when root cause is "wrong module design" invoke for redesign
41
- - `docs-seeker` (L3): lookup API docs for unclear errors or deprecated APIs
42
- - `problem-solver` (L3): structured reasoning (5 Whys, Fishbone) for complex bugs
43
- - `browser-pilot` (L3): capture browser console errors, network failures, visual bugs
44
- - `sequential-thinking` (L3): multi-variable root cause analysis
45
- - `neural-memory` (L3): after root cause found capture error pattern for future recognition
46
-
47
- ## Called By (inbound)
48
-
49
- - `cook` (L1): implementation hits bug during Phase 4
50
- - `fix` (L2): root cause unclear, can't fix blindly — needs diagnosis first
51
- - `test` (L2): test fails unexpectedly, unclear why
52
- - `surgeon` (L2): diagnose issues in legacy modules
53
-
54
- ## Cross-Hub Connections
55
-
56
- - `debug` ↔ `fix` — bidirectional: debug finds cause → fix applies, fix can't determine cause → debug investigates
57
- - `debug` ← `test` — test fails → debug investigates
58
-
59
- ## Execution
60
-
61
- ### Step 1: Reproduce
62
-
63
- Understand and confirm the error described in the request.
64
-
65
- - Read the error message, stack trace, and reproduction steps
66
- - Identify which environment it occurs in (dev/prod, browser/server)
67
- - Confirm the error is consistent and reproducible before proceeding
68
- - If no reproduction steps provided, ask for them or attempt the most likely path
69
-
70
- ### Step 1.5: Scope Lock (Edit Boundary)
71
-
72
- After reproducing the error, **lock edits to the narrowest affected directory** to prevent debug-driven scope creep — the #1 source of "while I'm here, let me also fix..." violations.
73
-
74
- 1. Identify the narrowest directory containing the affected files (from stack trace or error location)
75
- 2. Announce to user: "Debug scope locked to `<dir>/`. Changes will be restricted to this area."
76
- 3. Any fix recommendation in the Debug Report MUST reference only files within this boundary
77
- 4. If root cause traces outside the boundary expand scope with user confirmation first
78
-
79
- **Skip conditions** (do NOT lock):
80
- - Bug spans the entire repo (3+ unrelated directories in stack trace)
81
- - Cannot determine affected area from initial evidence
82
- - User explicitly says "investigate everything"
83
-
84
- **Why:** Debugging naturally expands scope as you trace root causes. Without a boundary, rune:fix receives recommendations touching 10+ files across unrelated modules. The scope lock forces discipline: fix at the source, not at every symptom site.
85
-
86
-
87
- ### Step 2: Gather Evidence
88
-
89
- Use tools to collect facts — do NOT guess yet.
90
-
91
- - Use `Grep` to search codebase for the exact error string or related error codes
92
- - Use `Read` to examine stack trace files, log files, or the specific file:line mentioned
93
- - Use `Glob` to find related files (config, types, tests) that may be involved
94
- - Use `rune:browser-pilot` if the issue is UI-related (console errors, network failures, visual bugs)
95
- - Use `rune:scout` to trace imports and identify all modules touched by the affected code path
96
-
97
- #### Backward Tracing (for deep stack errors)
98
-
99
- When the error appears deep in execution (wrong directory, wrong path, wrong value):
100
-
101
- 1. **Observe symptom** what's the exact error and where does it appear?
102
- 2. **Find immediate cause** — what code directly triggers this? Read that file:line
103
- 3. **What called this?** trace one level up. What value was passed? By whom?
104
- 4. **Keep tracing up** — repeat until you find where the bad value ORIGINATES
105
- 5. **Fix at source**the root cause is where invalid data is CREATED, not where it CRASHES
106
-
107
- Rule: NEVER fix where the error appears. Trace back to where invalid data originated.
108
-
109
- #### Instrumentation Tip: Use console.error, Not Loggers
110
- When adding diagnostic instrumentation, use `console.error()` (stderr) — NOT application loggers. Loggers are configured to suppress output based on log level or environment (e.g., `LOG_LEVEL=warn` silences `logger.debug`). `console.error` bypasses all logger configuration and writes directly to stderr. This is counterintuitive but critical — the one time you NEED debug output is exactly when loggers are configured to hide it.
111
-
112
- #### Defense-in-Depth (After Root Cause Found)
113
- When the root cause is invalid data flowing through multiple layers, recommend fixing at ALL layers — not just the source:
114
-
115
- | Layer | Purpose | Example |
116
- |-------|---------|---------|
117
- | Layer 1: Entry Point | Reject invalid input at API/CLI boundary | Validate not empty, exists, correct type |
118
- | Layer 2: Business Logic | Ensure data makes sense for the operation | Validate required params before processing |
119
- | Layer 3: Environment Guards | Prevent dangerous operations in specific contexts | Refuse destructive ops outside allowed dirs |
120
- | Layer 4: Debug Instrumentation | Capture context for forensics | Stack trace logging before dangerous operations |
121
-
122
- All four layers are necessary. During testing, each layer catches bugs the others miss different code paths bypass single validation points. When recommending a fix via `rune:fix`, explicitly call out which layers need validation added.
123
-
124
- #### Multi-Component Instrumentation (for systems with 3+ layers)
125
-
126
- When the system has multiple components (CI build deploy, API → service → DB):
127
-
128
- Before hypothesizing, add diagnostic logging at EACH component boundary:
129
- - Log what data ENTERS each component
130
- - Log what data EXITS each component
131
- - Verify environment/config propagation across boundaries
132
- - Run once analyze logs → identify WHICH boundary fails → THEN hypothesize
133
-
134
- This reveals: "secrets reach workflow ✓, workflow reaches build ✗" pinpoints the failing layer.
135
-
136
- ### Step 2b: Instrument with Preserved Markers
137
-
138
- When adding diagnostic logging or instrumentation during investigation, mark ALL additions with region markers:
139
-
140
- ```
141
- // #region agent-debug — [hypothesis being tested]
142
- console.log('[DEBUG] value at boundary:', data);
143
- // #endregion agent-debug
144
- ```
145
-
146
- Language-appropriate equivalents:
147
- - Python: `# region agent-debug` / `# endregion agent-debug`
148
- - Rust: `// region agent-debug` / `// endregion agent-debug`
149
-
150
- **Why preserved markers matter:**
151
- - `rune:fix` will preserve these markers until the bug is fully resolved and tests pass
152
- - If the bug recurs, markers show exactly what was previously instrumented
153
- - Cleaning up debug traces before the fix is verified prevents learning from failure history
154
- - After fix is verified + tests pass fix will clean up markers in a final pass
155
-
156
- <HARD-GATE>
157
- ALL diagnostic code added during debug MUST be wrapped in `#region agent-debug` markers.
158
- Unmarked instrumentation will be treated as stray code and removed prematurely.
159
- </HARD-GATE>
160
-
161
- ### Step 2c: Check Debug Knowledge Base
162
-
163
- Before forming hypotheses, check `.rune/debug/knowledge-base.md`:
164
- - If file exists → search for matching symptoms/error messages
165
- - If match found → try known fix FIRST, skip hypothesis cycle
166
- - If no matchproceed to Step 3
167
-
168
- After successful root cause identification (Step 5), append entry:
169
- ```
170
- ### [date] [symptom summary]
171
- - **Symptom**: [error message or behavior]
172
- - **Root Cause**: [what was actually wrong]
173
- - **Fix**: [what resolved it]
174
- - **Files**: [affected files]
175
- ```
176
-
177
- This prevents re-debugging the same issue across sessions.
178
-
179
- ### Step 3: Form Hypotheses
180
-
181
- List exactly 2-3 possible root causes — no more, no fewer.
182
-
183
- - Each hypothesis must be specific (name the file, function, or line if possible)
184
- - Order by likelihood (most likely first)
185
- - Format:
186
- - H1: [specific hypothesis file/function/pattern]
187
- - H2: [specific hypothesis]
188
- - H3: [specific hypothesis]
189
-
190
- ### Step 4: Test Hypotheses
191
-
192
- Test each hypothesis systematically using tools.
193
-
194
- - Use `Read` to inspect the suspected file/function for each hypothesis
195
- - Use `Bash` to run targeted tests: a single failing test, a type check, a linter on the file
196
- - Use `rune:browser-pilot` for UI hypotheses (inspect DOM, network, console)
197
- - For each hypothesis: mark CONFIRMED / RULED OUT with evidence
198
- - If all 3 hypotheses are ruled out → go back to Step 2 to gather more evidence
199
- - Maximum 3 hypothesis cycles. If still unresolved after 3 cycles → escalate (see Hard-Gate)
200
-
201
- ### Step 5: Identify Root Cause
202
-
203
- Narrow to the single actual cause.
204
-
205
- - State the confirmed hypothesis and the exact evidence that proves it
206
- - Identify the specific file, line number, and code construct responsible
207
- - Note any contributing factors (environment, data, timing, config)
208
-
209
- ### Step 5b: Capture Error Pattern
210
-
211
- Call `neural-memory` (Capture Mode) to save the error pattern: root cause, symptoms, and fix approach. Tag with [project-name, error, technology].
212
-
213
- ### Step 6: 3-Fix Escalation Rule
214
-
215
- <HARD-GATE>
216
- If the SAME bug has been "fixed" 3 times and keeps returning:
217
- 1. STOP fixing. The bug is not the problem — the ARCHITECTURE is.
218
- 2. **Classify the failure**:
219
- - **Same category of blocker each time** (e.g., API doesn't support X, platform limitation) the APPROACH is wrong, not just the code
220
- - **Different bugs each time** (e.g., race condition, then null pointer, then type error) → the MODULE needs redesign
221
- 3. **Route based on classification**:
222
- - Approach is wrong Escalate to `rune:brainstorm(mode="rescue")` for category-diverse alternatives
223
- - Module needs redesign → Escalate to `rune:plan` for redesign of the affected module
224
- 4. Report all 3 fix attempts and why each failed in the escalation.
225
- "Try a 4th fix" is NOT acceptable. After 3 failures, question the design OR the approach.
226
- </HARD-GATE>
227
-
228
- Track fix attempts in the Debug Report. If this is attempt N>1 for the same symptom:
229
- - Reference previous fix attempts and their outcomes
230
- - Explain why the previous fix didn't hold
231
- - If N=3: trigger the escalation gate above — classify and route accordingly
232
-
233
- ### Step 7: Report
234
-
235
- Produce structured output and hand off to rune:fix.
236
-
237
- - Write the Debug Report (see Output Format below)
238
- - Call `rune:fix` with the full report if fix is needed
239
- - Do NOT apply any code changes report only
240
-
241
- ## Analysis Paralysis Guard
242
-
243
- <HARD-GATE>
244
- Debug is read-heavy by naturebut there are limits.
245
-
246
- After Step 4 (Test Hypotheses): if NO hypothesis is confirmed after 3 cycles of Steps 2-4, you MUST stop and escalate. Do NOT start cycle 4. Report all evidence gathered and escalate to problem-solver or sequential-thinking.
247
-
248
- Within any single step: 5+ consecutive Read/Grep calls without forming or testing a hypothesis = stuck. Stop reading, form a hypothesis from what you have, and test it. Incomplete hypotheses that get tested are better than perfect hypotheses that never form.
249
- </HARD-GATE>
250
-
251
- ### Hash-Based Evidence Loop Detection
252
-
253
- Beyond counting reads, detect when debug is **re-gathering the same evidence without progress** — the most common debug-specific stuck pattern.
254
-
255
- **Detection signals** (track mentally across hypothesis cycles):
256
-
257
- | Signal | Count | Meaning | Action |
258
- |--------|-------|---------|--------|
259
- | Reading the same file:line range in different cycles | 2x | Re-examining without new lens | Form hypothesis from existing evidence NOW |
260
- | Running the same test command with same failure output | 3x | No code changed between runs | STOP — hand off to fix with current diagnosis, even if incomplete |
261
- | Grepping the same error string after already finding all occurrences | 2x | Hoping for different results | Evidence is complete move to Step 3 (hypothesize) |
262
- | Same hypothesis tested with same evidence across cycles | 2x | Circular reasoning | Mark hypothesis INCONCLUSIVE, try a DIFFERENT hypothesis category |
263
-
264
- **Hypothesis category diversity rule**: If H1 (cycle 1) was "wrong input data" and it was RULED OUT, H1 (cycle 2) MUST be from a DIFFERENT category:
265
-
266
- | Category | Examples |
267
- |----------|---------|
268
- | Data | Wrong value, missing field, type mismatch, encoding |
269
- | Control Flow | Wrong branch, missing guard, race condition, async ordering |
270
- | Environment | Wrong config, missing env var, version mismatch, path issue |
271
- | State | Stale cache, mutation side-effect, leaked reference, dangling connection |
272
-
273
-
274
- ## Red Flags STOP and Return to Step 2
275
-
276
- If you catch yourself thinking any of these, you are GUESSING, not debugging:
277
-
278
- - "Quick fix for now, investigate later"
279
- - "Just try changing X and see if it works"
280
- - "It's probably X, let me fix that"
281
- - "I don't fully understand but this might work"
282
- - "Here are the main problems: [lists fixes without investigation]"
283
- - Proposing solutions before tracing data flow
284
- - "One more fix attempt" (when already tried 2+)
285
- - "Let me read one more file before forming a hypothesis" (after 5+ reads)
286
-
287
- ALL of these mean: STOP. Return to Step 2 (Gather Evidence).
288
-
289
- ## Constraints
290
-
291
- 1. MUST NOT apply any code changes debug investigates only, fix applies
292
- 2. MUST reproduce the error before forming hypotheses — no guessing from error messages alone
293
- 3. MUST gather evidence (file reads, grep, stack traces) before hypothesizing
294
- 4. MUST form exactly 2-3 hypotheses, ordered by likelihood — no more, no fewer
295
- 5. MUST mark each hypothesis CONFIRMED or RULED OUT with specific evidence
296
- 6. MUST NOT exceed 3 hypothesis cycles escalate to problem-solver or sequential-thinking
297
- 7. MUST NOT say "I know what's wrong" without citing file:line evidence
298
- 8. For deep stack errors: MUST use backward tracing (Step 2) — never fix at the crash site
299
- 9. For multi-component systems: MUST instrument boundaries before hypothesizing
300
-
301
- ## Output Format
302
-
303
- ```
304
- ## Debug Report
305
- - **Error**: [error message]
306
- - **Status**: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED
307
- - **Severity**: critical | high | medium | low
308
- - **Confidence**: high | medium | low
309
- - **Fix Attempt**: [1/2/3track recurring bugs]
310
-
311
- ### Root Cause
312
- [Detailed explanation of what's causing the error]
313
-
314
- ### Location
315
- - `path/to/file.ts:42`[description of the problematic code]
316
-
317
- ### Evidence
318
- 1. [observation supporting diagnosis]
319
- 2. [observation supporting diagnosis]
320
-
321
- ### Previous Fix Attempts (if any)
322
- - Attempt 1: [what was tried] → [why it didn't hold]
323
- - Attempt 2: [what was tried] [why it didn't hold]
324
-
325
- ### Concerns (if DONE_WITH_CONCERNS)
326
- - [concern]: [impact assessment] [suggested remediation]
327
-
328
- ### Context Needed (if NEEDS_CONTEXT)
329
- - [what is unknown]: [why it blocks diagnosis] — [two most likely answers]
330
-
331
- ### Suggested Fix
332
- [Description of what needs to change no code, just direction]
333
- [If attempt 3: "ESCALATION: 3-fix rule triggered. Recommending redesign via rune:plan."]
334
-
335
- ### Related Code
336
- - `path/to/related.ts` [why it's relevant]
337
- ```
338
-
339
- ### Status Protocol (Subagent Contract)
340
-
341
- Debug returns one of four statuses to its caller (cook, fix, test, surgeon). The caller uses this to route next actions.
342
-
343
- | Status | When | Example |
344
- |--------|------|---------|
345
- | `DONE` | Root cause identified with high confidence, ready for fix | Clear diagnosis with file:line evidence |
346
- | `DONE_WITH_CONCERNS` | Root cause found but diagnosis has caveats | "Likely race condition but cannot reproduce consistently fix may need retry logic" |
347
- | `NEEDS_CONTEXT` | Cannot diagnose without more info — missing repro steps, env details, or access | "Error only occurs in production — need prod logs or env variables to continue" |
348
- | `BLOCKED` | Exhausted 3 hypothesis cycles, escalation triggered | "3 cycles completed, no confirmed root cause — escalating to problem-solver" |
349
-
350
- ## Returns
351
-
352
- | Artifact | Format | Location |
353
- |----------|--------|----------|
354
- | Debug Report | Markdown (inline) | Emitted to calling skill (cook, fix, test, surgeon) |
355
- | Root cause + location | Inline (Debug Report) | Specific file:line with evidence |
356
- | Fix recommendation | Inline (Debug Report) | Direction only — no code changes |
357
- | Debug knowledge base entry | Markdown | `.rune/debug/knowledge-base.md` (appended on success) |
358
-
359
- ## Sharp Edges
360
-
361
- | Failure Mode | Severity | Mitigation |
362
- |---|---|---|
363
- | Forming hypothesis from error message alone without evidence | HIGH | Evidence-first rule: read files and grep logs BEFORE hypothesizing |
364
- | Modifying code while "investigating" | CRITICAL | HARD-GATE: any code change during debug = out of scopehand off to fix |
365
- | Marking hypothesis CONFIRMED without file:line proof | HIGH | CONFIRMED requires specific evidence cited"it makes sense" is not evidence |
366
- | Exceeding 3 hypothesis cycles without escalation | MEDIUM | After 3 cycles: escalate to rune:problem-solver or rune:sequential-thinking |
367
- | Same bug "fixed" 3+ times without questioning architecture | CRITICAL | 3-Fix Escalation Rule: classify failure → same blocker category = brainstorm(rescue), different bugs = plan redesign |
368
- | Escalating to plan when the APPROACH is wrong (not the module) | HIGH | If all 3 fixes hit the same category of blocker (API limit, platform gap), the approach needs pivoting via brainstorm(rescue), not re-planning |
369
- | Not tracking fix attempt number for recurring bugs | HIGH | Debug Report MUST include Fix Attempt counter — enables escalation gate |
370
- | Adding instrumentation without region markers | MEDIUM | All debug logging MUST use `#region agent-debug` — unmarked code gets cleaned up prematurely by fix |
371
- | Re-reading same file:line in different hypothesis cycles | HIGH | Hash-based evidence loop: if same evidence gathered 2x, form hypothesis from existing data — don't re-gather |
372
- | Same hypothesis category across cycles after RULED OUT | HIGH | Hypothesis category diversity: if "data" ruled out in cycle 1, cycle 2 must try "control flow", "environment", or "state" |
373
- | Running same test 3x with same failure without code change | MEDIUM | True stuck loop — no progress possible. Hand off to fix with current incomplete diagnosis |
374
- | Scope creep via debug — "while investigating, also fix X" | HIGH | Step 1.5 Scope Lock: lock edits to narrowest affected directory. Fix recommendations MUST stay within boundary. Expand only with user confirmation |
375
- | Debug report recommends touching 5+ unrelated files | HIGH | Symptom of fixing at crash sites instead of source. Backward trace (Step 2) to find origin. If truly 5+ files → likely architectural issue → escalate via 3-Fix Rule |
376
-
377
- ## Done When
378
-
379
- - Error reproduced (not assumed) with specific reproduction steps documented
380
- - 2-3 hypotheses formed, each marked CONFIRMED or RULED OUT with file:line evidence
381
- - Root cause identified at specific file:line
382
- - Structured Debug Report emitted with 4-state status
383
- - If `DONE_WITH_CONCERNS`: caveats documented with impact assessment
384
- - If `NEEDS_CONTEXT`: specific questions + two likely answers provided
385
- - If `BLOCKED`: all 3 hypothesis cycles documented + escalation target identified
386
- - No code changes made rune:fix called with the report if fix is needed
387
-
388
- ## Cost Profile
389
-
390
- ~2000-5000 tokens input, ~500-1500 tokens output. Sonnet for code analysis quality. May escalate to opus for deeply complex bugs.
391
-
392
- **Scope guardrail**: Do not apply code changes or expand investigation beyond the locked scope directory unless explicitly delegated by the parent agent.
1
+ ---
2
+ name: debug
3
+ description: Root cause analysis for bugs and unexpected behavior. Traces errors through code, uses structured reasoning, and hands off to fix when cause is found. Core of the debug↔fix mesh.
4
+ metadata:
5
+ author: runedev
6
+ version: "0.9.0"
7
+ layer: L2
8
+ model: sonnet
9
+ group: development
10
+ tools: "Read, Bash, Glob, Grep"
11
+ emit: bug.diagnosed
12
+ listen: tests.failed
13
+ ---
14
+
15
+ # debug
16
+
17
+ ## Purpose
18
+
19
+ Root cause analysis ONLY. Debug investigates — it does NOT fix. It traces errors through code, analyzes stack traces, forms and tests hypotheses, and identifies the exact cause before handing off to rune:fix.
20
+
21
+ <HARD-GATE>
22
+ Do NOT fix the code. Debug investigates only. Any code change is out of scope.
23
+ If root cause cannot be identified after 3 hypothesis cycles:
24
+ - Escalate to `rune:problem-solver` for structured 5-Whys or Fishbone analysis
25
+ - Or escalate to `rune:sequential-thinking` for multi-variable analysis
26
+ - Report escalation in the Debug Report with all evidence gathered so far
27
+ </HARD-GATE>
28
+
29
+ ## Triggers
30
+
31
+ - Called by `cook` when implementation hits unexpected errors
32
+ - Called by `test` when a test fails with unclear reason
33
+ - Called by `fix` when root cause is unclear before fixing
34
+ - `/rune debug <issue>` — manual debugging
35
+ - Auto-trigger: when error output contains stack trace or error code
36
+
37
+ ## Calls (outbound)
38
+
39
+ - `scout` (L2): find related code, trace imports, identify affected modules
40
+ - `fix` (L2): when root cause found, hand off with diagnosis for fix application
41
+ - `brainstorm` (L2): 3-Fix Escalation when root cause is "wrong approach" — invoke with mode="rescue" for category-diverse alternatives
42
+ - `plan` (L2): 3-Fix Escalation when root cause is "wrong module design" — invoke for redesign
43
+ - `docs-seeker` (L3): lookup API docs for unclear errors or deprecated APIs
44
+ - `problem-solver` (L3): structured reasoning (5 Whys, Fishbone) for complex bugs
45
+ - `browser-pilot` (L3): capture browser console errors, network failures, visual bugs
46
+ - `sequential-thinking` (L3): multi-variable root cause analysis
47
+ - `neural-memory` (L3): after root cause found — capture error pattern for future recognition
48
+
49
+ ## Called By (inbound)
50
+
51
+ - `cook` (L1): implementation hits bug during Phase 4
52
+ - `fix` (L2): root cause unclear, can't fix blindly — needs diagnosis first
53
+ - `test` (L2): test fails unexpectedly, unclear why
54
+ - `surgeon` (L2): diagnose issues in legacy modules
55
+
56
+ ## Cross-Hub Connections
57
+
58
+ - `debug` ↔ `fix` — bidirectional: debug finds cause → fix applies, fix can't determine cause → debug investigates
59
+ - `debug` ← `test` — test fails → debug investigates
60
+
61
+ ## Execution
62
+
63
+ ### Step 1: Reproduce
64
+
65
+ Understand and confirm the error described in the request.
66
+
67
+ - Read the error message, stack trace, and reproduction steps
68
+ - Identify which environment it occurs in (dev/prod, browser/server)
69
+ - Confirm the error is consistent and reproducible before proceeding
70
+ - If no reproduction steps provided, ask for them or attempt the most likely path
71
+
72
+ ### Step 1.5: Scope Lock (Edit Boundary)
73
+
74
+ After reproducing the error, **lock edits to the narrowest affected directory** to prevent debug-driven scope creep — the #1 source of "while I'm here, let me also fix..." violations.
75
+
76
+ 1. Identify the narrowest directory containing the affected files (from stack trace or error location)
77
+ 2. Announce to user: "Debug scope locked to `<dir>/`. Changes will be restricted to this area."
78
+ 3. Any fix recommendation in the Debug Report MUST reference only files within this boundary
79
+ 4. If root cause traces outside the boundary → expand scope with user confirmation first
80
+
81
+ **Skip conditions** (do NOT lock):
82
+ - Bug spans the entire repo (3+ unrelated directories in stack trace)
83
+ - Cannot determine affected area from initial evidence
84
+ - User explicitly says "investigate everything"
85
+
86
+ **Why:** Debugging naturally expands scope as you trace root causes. Without a boundary, rune:fix receives recommendations touching 10+ files across unrelated modules. The scope lock forces discipline: fix at the source, not at every symptom site.
87
+
88
+
89
+ ### Step 2: Gather Evidence
90
+
91
+ Use tools to collect facts do NOT guess yet.
92
+
93
+ - Use `Grep` to search codebase for the exact error string or related error codes
94
+ - Use `Read` to examine stack trace files, log files, or the specific file:line mentioned
95
+ - Use `Glob` to find related files (config, types, tests) that may be involved
96
+ - Use `rune:browser-pilot` if the issue is UI-related (console errors, network failures, visual bugs)
97
+ - Use `rune:scout` to trace imports and identify all modules touched by the affected code path
98
+
99
+ #### Backward Tracing (for deep stack errors)
100
+
101
+ When the error appears deep in execution (wrong directory, wrong path, wrong value):
102
+
103
+ 1. **Observe symptom**what's the exact error and where does it appear?
104
+ 2. **Find immediate cause** — what code directly triggers this? Read that file:line
105
+ 3. **What called this?**trace one level up. What value was passed? By whom?
106
+ 4. **Keep tracing up** — repeat until you find where the bad value ORIGINATES
107
+ 5. **Fix at source** the root cause is where invalid data is CREATED, not where it CRASHES
108
+
109
+ Rule: NEVER fix where the error appears. Trace back to where invalid data originated.
110
+
111
+ #### Instrumentation Tip: Use console.error, Not Loggers
112
+ When adding diagnostic instrumentation, use `console.error()` (stderr) NOT application loggers. Loggers are configured to suppress output based on log level or environment (e.g., `LOG_LEVEL=warn` silences `logger.debug`). `console.error` bypasses all logger configuration and writes directly to stderr. This is counterintuitive but critical — the one time you NEED debug output is exactly when loggers are configured to hide it.
113
+
114
+ #### Defense-in-Depth (After Root Cause Found)
115
+ When the root cause is invalid data flowing through multiple layers, recommend fixing at ALL layers — not just the source:
116
+
117
+ | Layer | Purpose | Example |
118
+ |-------|---------|---------|
119
+ | Layer 1: Entry Point | Reject invalid input at API/CLI boundary | Validate not empty, exists, correct type |
120
+ | Layer 2: Business Logic | Ensure data makes sense for the operation | Validate required params before processing |
121
+ | Layer 3: Environment Guards | Prevent dangerous operations in specific contexts | Refuse destructive ops outside allowed dirs |
122
+ | Layer 4: Debug Instrumentation | Capture context for forensics | Stack trace logging before dangerous operations |
123
+
124
+ All four layers are necessary. During testing, each layer catches bugs the others miss — different code paths bypass single validation points. When recommending a fix via `rune:fix`, explicitly call out which layers need validation added.
125
+
126
+ #### Multi-Component Instrumentation (for systems with 3+ layers)
127
+
128
+ When the system has multiple components (CI build → deploy, API → service → DB):
129
+
130
+ Before hypothesizing, add diagnostic logging at EACH component boundary:
131
+ - Log what data ENTERS each component
132
+ - Log what data EXITS each component
133
+ - Verify environment/config propagation across boundaries
134
+ - Run once analyze logs identify WHICH boundary fails THEN hypothesize
135
+
136
+ This reveals: "secrets reach workflow ✓, workflow reaches build ✗" — pinpoints the failing layer.
137
+
138
+ ### Step 2b: Instrument with Preserved Markers
139
+
140
+ When adding diagnostic logging or instrumentation during investigation, mark ALL additions with region markers:
141
+
142
+ ```
143
+ // #region agent-debug — [hypothesis being tested]
144
+ console.log('[DEBUG] value at boundary:', data);
145
+ // #endregion agent-debug
146
+ ```
147
+
148
+ Language-appropriate equivalents:
149
+ - Python: `# region agent-debug` / `# endregion agent-debug`
150
+ - Rust: `// region agent-debug` / `// endregion agent-debug`
151
+
152
+ **Why preserved markers matter:**
153
+ - `rune:fix` will preserve these markers until the bug is fully resolved and tests pass
154
+ - If the bug recurs, markers show exactly what was previously instrumented
155
+ - Cleaning up debug traces before the fix is verified prevents learning from failure history
156
+ - After fix is verified + tests pass → fix will clean up markers in a final pass
157
+
158
+ <HARD-GATE>
159
+ ALL diagnostic code added during debug MUST be wrapped in `#region agent-debug` markers.
160
+ Unmarked instrumentation will be treated as stray code and removed prematurely.
161
+ </HARD-GATE>
162
+
163
+ ### Step 2c: Check Debug Knowledge Base
164
+
165
+ Before forming hypotheses, check `.rune/debug/knowledge-base.md`:
166
+ - If file existssearch for matching symptoms/error messages
167
+ - If match found → try known fix FIRST, skip hypothesis cycle
168
+ - If no match proceed to Step 3
169
+
170
+ After successful root cause identification (Step 5), append entry:
171
+ ```
172
+ ### [date] [symptom summary]
173
+ - **Symptom**: [error message or behavior]
174
+ - **Root Cause**: [what was actually wrong]
175
+ - **Fix**: [what resolved it]
176
+ - **Files**: [affected files]
177
+ ```
178
+
179
+ This prevents re-debugging the same issue across sessions.
180
+
181
+ ### Step 3: Form Hypotheses
182
+
183
+ List exactly 2-3 possible root causes no more, no fewer.
184
+
185
+ - Each hypothesis must be specific (name the file, function, or line if possible)
186
+ - Order by likelihood (most likely first)
187
+ - Format:
188
+ - H1: [specific hypothesis — file/function/pattern]
189
+ - H2: [specific hypothesis]
190
+ - H3: [specific hypothesis]
191
+
192
+ ### Step 4: Test Hypotheses
193
+
194
+ Test each hypothesis systematically using tools.
195
+
196
+ - Use `Read` to inspect the suspected file/function for each hypothesis
197
+ - Use `Bash` to run targeted tests: a single failing test, a type check, a linter on the file
198
+ - Use `rune:browser-pilot` for UI hypotheses (inspect DOM, network, console)
199
+ - For each hypothesis: mark CONFIRMED / RULED OUT with evidence
200
+ - If all 3 hypotheses are ruled out → go back to Step 2 to gather more evidence
201
+ - Maximum 3 hypothesis cycles. If still unresolved after 3 cycles → escalate (see Hard-Gate)
202
+
203
+ ### Step 5: Identify Root Cause
204
+
205
+ Narrow to the single actual cause.
206
+
207
+ - State the confirmed hypothesis and the exact evidence that proves it
208
+ - Identify the specific file, line number, and code construct responsible
209
+ - Note any contributing factors (environment, data, timing, config)
210
+
211
+ ### Step 5b: Capture Error Pattern
212
+
213
+ Call `neural-memory` (Capture Mode) to save the error pattern: root cause, symptoms, and fix approach. Tag with [project-name, error, technology].
214
+
215
+ ### Step 6: 3-Fix Escalation Rule
216
+
217
+ <HARD-GATE>
218
+ If the SAME bug has been "fixed" 3 times and keeps returning:
219
+ 1. STOP fixing. The bug is not the problem the ARCHITECTURE is.
220
+ 2. **Classify the failure**:
221
+ - **Same category of blocker each time** (e.g., API doesn't support X, platform limitation) → the APPROACH is wrong, not just the code
222
+ - **Different bugs each time** (e.g., race condition, then null pointer, then type error) the MODULE needs redesign
223
+ 3. **Route based on classification**:
224
+ - Approach is wrong Escalate to `rune:brainstorm(mode="rescue")` for category-diverse alternatives
225
+ - Module needs redesign Escalate to `rune:plan` for redesign of the affected module
226
+ 4. Report all 3 fix attempts and why each failed in the escalation.
227
+ "Try a 4th fix" is NOT acceptable. After 3 failures, question the design OR the approach.
228
+ </HARD-GATE>
229
+
230
+ Track fix attempts in the Debug Report. If this is attempt N>1 for the same symptom:
231
+ - Reference previous fix attempts and their outcomes
232
+ - Explain why the previous fix didn't hold
233
+ - If N=3: trigger the escalation gate above — classify and route accordingly
234
+
235
+ ### 3+ Fixes as Architectural Signal
236
+
237
+ > From superpowers (obra/superpowers, 84k★): "Each fix revealing new problems elsewhere = structural issue, not a bug hunt."
238
+
239
+ When 3+ **distinct** fixes fail (not retries of the same fix), STOP treating it as a bug:
240
+
241
+ | Signal | Interpretation | Next Step |
242
+ |--------|---------------|-----------|
243
+ | Same blocker each time (API limit, platform gap) | Wrong approach | `brainstorm(mode="rescue")` — need fundamentally different path |
244
+ | Different bugs each fix (null → race → type) | Wrong architecture | `plan` redesign module has structural problems |
245
+ | Each fix creates a new bug elsewhere | Tight coupling | The module boundary is wrong — need to redraw boundaries before fixing |
246
+ | Fix works locally but fails in integration | Missing contract | Cross-module interface is undefined add explicit contracts first |
247
+
248
+ **Key insight**: After 3 failures, question the DESIGN, not the CODE. "Try harder" is never the right answer at this point.
249
+
250
+ ### Step 7: Report
251
+
252
+ Produce structured output and hand off to rune:fix.
253
+
254
+ - Write the Debug Report (see Output Format below)
255
+ - Call `rune:fix` with the full report if fix is needed
256
+ - Do NOT apply any code changes — report only
257
+
258
+ ## Analysis Paralysis Guard
259
+
260
+ <HARD-GATE>
261
+ Debug is read-heavy by naturebut there are limits.
262
+
263
+ After Step 4 (Test Hypotheses): if NO hypothesis is confirmed after 3 cycles of Steps 2-4, you MUST stop and escalate. Do NOT start cycle 4. Report all evidence gathered and escalate to problem-solver or sequential-thinking.
264
+
265
+ Within any single step: 5+ consecutive Read/Grep calls without forming or testing a hypothesis = stuck. Stop reading, form a hypothesis from what you have, and test it. Incomplete hypotheses that get tested are better than perfect hypotheses that never form.
266
+ </HARD-GATE>
267
+
268
+ ### Hash-Based Evidence Loop Detection
269
+
270
+ Beyond counting reads, detect when debug is **re-gathering the same evidence without progress** — the most common debug-specific stuck pattern.
271
+
272
+ **Detection signals** (track mentally across hypothesis cycles):
273
+
274
+ | Signal | Count | Meaning | Action |
275
+ |--------|-------|---------|--------|
276
+ | Reading the same file:line range in different cycles | 2x | Re-examining without new lens | Form hypothesis from existing evidence NOW |
277
+ | Running the same test command with same failure output | 3x | No code changed between runs | STOP — hand off to fix with current diagnosis, even if incomplete |
278
+ | Grepping the same error string after already finding all occurrences | 2x | Hoping for different results | Evidence is complete — move to Step 3 (hypothesize) |
279
+ | Same hypothesis tested with same evidence across cycles | 2x | Circular reasoning | Mark hypothesis INCONCLUSIVE, try a DIFFERENT hypothesis category |
280
+
281
+ **Hypothesis category diversity rule**: If H1 (cycle 1) was "wrong input data" and it was RULED OUT, H1 (cycle 2) MUST be from a DIFFERENT category:
282
+
283
+ | Category | Examples |
284
+ |----------|---------|
285
+ | Data | Wrong value, missing field, type mismatch, encoding |
286
+ | Control Flow | Wrong branch, missing guard, race condition, async ordering |
287
+ | Environment | Wrong config, missing env var, version mismatch, path issue |
288
+ | State | Stale cache, mutation side-effect, leaked reference, dangling connection |
289
+
290
+
291
+ ## Red Flags STOP and Return to Step 2
292
+
293
+ If you catch yourself thinking any of these, you are GUESSING, not debugging:
294
+
295
+ - "Quick fix for now, investigate later"
296
+ - "Just try changing X and see if it works"
297
+ - "It's probably X, let me fix that"
298
+ - "I don't fully understand but this might work"
299
+ - "Here are the main problems: [lists fixes without investigation]"
300
+ - Proposing solutions before tracing data flow
301
+ - "One more fix attempt" (when already tried 2+)
302
+ - "Let me read one more file before forming a hypothesis" (after 5+ reads)
303
+
304
+ ALL of these mean: STOP. Return to Step 2 (Gather Evidence).
305
+
306
+ ## Constraints
307
+
308
+ 1. MUST NOT apply any code changes — debug investigates only, fix applies
309
+ 2. MUST reproduce the error before forming hypotheses no guessing from error messages alone
310
+ 3. MUST gather evidence (file reads, grep, stack traces) before hypothesizing
311
+ 4. MUST form exactly 2-3 hypotheses, ordered by likelihood — no more, no fewer
312
+ 5. MUST mark each hypothesis CONFIRMED or RULED OUT with specific evidence
313
+ 6. MUST NOT exceed 3 hypothesis cycles — escalate to problem-solver or sequential-thinking
314
+ 7. MUST NOT say "I know what's wrong" without citing file:line evidence
315
+ 8. For deep stack errors: MUST use backward tracing (Step 2) never fix at the crash site
316
+ 9. For multi-component systems: MUST instrument boundaries before hypothesizing
317
+
318
+ ## Output Format
319
+
320
+ ```
321
+ ## Debug Report
322
+ - **Error**: [error message]
323
+ - **Status**: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED
324
+ - **Severity**: critical | high | medium | low
325
+ - **Confidence**: high | medium | low
326
+ - **Fix Attempt**: [1/2/3track recurring bugs]
327
+
328
+ ### Root Cause
329
+ [Detailed explanation of what's causing the error]
330
+
331
+ ### Location
332
+ - `path/to/file.ts:42` [description of the problematic code]
333
+
334
+ ### Evidence
335
+ 1. [observation supporting diagnosis]
336
+ 2. [observation supporting diagnosis]
337
+
338
+ ### Previous Fix Attempts (if any)
339
+ - Attempt 1: [what was tried] → [why it didn't hold]
340
+ - Attempt 2: [what was tried] → [why it didn't hold]
341
+
342
+ ### Concerns (if DONE_WITH_CONCERNS)
343
+ - [concern]: [impact assessment] [suggested remediation]
344
+
345
+ ### Context Needed (if NEEDS_CONTEXT)
346
+ - [what is unknown]: [why it blocks diagnosis][two most likely answers]
347
+
348
+ ### Suggested Fix
349
+ [Description of what needs to change — no code, just direction]
350
+ [If attempt 3: "ESCALATION: 3-fix rule triggered. Recommending redesign via rune:plan."]
351
+
352
+ ### Related Code
353
+ - `path/to/related.ts` — [why it's relevant]
354
+ ```
355
+
356
+ ### Status Protocol (Subagent Contract)
357
+
358
+ Debug returns one of four statuses to its caller (cook, fix, test, surgeon). The caller uses this to route next actions.
359
+
360
+ | Status | When | Example |
361
+ |--------|------|---------|
362
+ | `DONE` | Root cause identified with high confidence, ready for fix | Clear diagnosis with file:line evidence |
363
+ | `DONE_WITH_CONCERNS` | Root cause found but diagnosis has caveats | "Likely race condition but cannot reproduce consistently fix may need retry logic" |
364
+ | `NEEDS_CONTEXT` | Cannot diagnose without more info missing repro steps, env details, or access | "Error only occurs in production need prod logs or env variables to continue" |
365
+ | `BLOCKED` | Exhausted 3 hypothesis cycles, escalation triggered | "3 cycles completed, no confirmed root cause escalating to problem-solver" |
366
+
367
+ ## Returns
368
+
369
+ | Artifact | Format | Location |
370
+ |----------|--------|----------|
371
+ | Debug Report | Markdown (inline) | Emitted to calling skill (cook, fix, test, surgeon) |
372
+ | Root cause + location | Inline (Debug Report) | Specific file:line with evidence |
373
+ | Fix recommendation | Inline (Debug Report) | Direction only — no code changes |
374
+ | Debug knowledge base entry | Markdown | `.rune/debug/knowledge-base.md` (appended on success) |
375
+
376
+ ## Sharp Edges
377
+
378
+ | Failure Mode | Severity | Mitigation |
379
+ |---|---|---|
380
+ | Forming hypothesis from error message alone without evidence | HIGH | Evidence-first rule: read files and grep logs BEFORE hypothesizing |
381
+ | Modifying code while "investigating" | CRITICAL | HARD-GATE: any code change during debug = out of scope — hand off to fix |
382
+ | Marking hypothesis CONFIRMED without file:line proof | HIGH | CONFIRMED requires specific evidence cited — "it makes sense" is not evidence |
383
+ | Exceeding 3 hypothesis cycles without escalation | MEDIUM | After 3 cycles: escalate to rune:problem-solver or rune:sequential-thinking |
384
+ | Same bug "fixed" 3+ times without questioning architecture | CRITICAL | 3-Fix Escalation Rule: classify failure same blocker category = brainstorm(rescue), different bugs = plan redesign |
385
+ | Escalating to plan when the APPROACH is wrong (not the module) | HIGH | If all 3 fixes hit the same category of blocker (API limit, platform gap), the approach needs pivoting via brainstorm(rescue), not re-planning |
386
+ | Not tracking fix attempt number for recurring bugs | HIGH | Debug Report MUST include Fix Attempt counter — enables escalation gate |
387
+ | Adding instrumentation without region markers | MEDIUM | All debug logging MUST use `#region agent-debug` — unmarked code gets cleaned up prematurely by fix |
388
+ | Re-reading same file:line in different hypothesis cycles | HIGH | Hash-based evidence loop: if same evidence gathered 2x, form hypothesis from existing data — don't re-gather |
389
+ | Same hypothesis category across cycles after RULED OUT | HIGH | Hypothesis category diversity: if "data" ruled out in cycle 1, cycle 2 must try "control flow", "environment", or "state" |
390
+ | Running same test 3x with same failure without code change | MEDIUM | True stuck loop — no progress possible. Hand off to fix with current incomplete diagnosis |
391
+ | Scope creep via debug — "while investigating, also fix X" | HIGH | Step 1.5 Scope Lock: lock edits to narrowest affected directory. Fix recommendations MUST stay within boundary. Expand only with user confirmation |
392
+ | Debug report recommends touching 5+ unrelated files | HIGH | Symptom of fixing at crash sites instead of source. Backward trace (Step 2) to find origin. If truly 5+ files → likely architectural issue → escalate via 3-Fix Rule |
393
+
394
+ ## Done When
395
+
396
+ - Error reproduced (not assumed) with specific reproduction steps documented
397
+ - 2-3 hypotheses formed, each marked CONFIRMED or RULED OUT with file:line evidence
398
+ - Root cause identified at specific file:line
399
+ - Structured Debug Report emitted with 4-state status
400
+ - If `DONE_WITH_CONCERNS`: caveats documented with impact assessment
401
+ - If `NEEDS_CONTEXT`: specific questions + two likely answers provided
402
+ - If `BLOCKED`: all 3 hypothesis cycles documented + escalation target identified
403
+ - No code changes made — rune:fix called with the report if fix is needed
404
+
405
+ ## Cost Profile
406
+
407
+ ~2000-5000 tokens input, ~500-1500 tokens output. Sonnet for code analysis quality. May escalate to opus for deeply complex bugs.
408
+
409
+ **Scope guardrail**: Do not apply code changes or expand investigation beyond the locked scope directory unless explicitly delegated by the parent agent.