@rune-kit/rune 2.10.0 → 2.12.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 (240) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +65 -6
  3. package/commands/rune.md +168 -168
  4. package/compiler/__tests__/detect-invariants.test.js +136 -0
  5. package/compiler/__tests__/doctor-mesh.test.js +229 -0
  6. package/compiler/__tests__/hook-dispatch.test.js +91 -0
  7. package/compiler/__tests__/hooks-antigravity.test.js +118 -0
  8. package/compiler/__tests__/hooks-cursor.test.js +139 -0
  9. package/compiler/__tests__/hooks-install.test.js +305 -0
  10. package/compiler/__tests__/hooks-merge.test.js +204 -0
  11. package/compiler/__tests__/hooks-tiers.test.js +519 -0
  12. package/compiler/__tests__/hooks-windsurf.test.js +115 -0
  13. package/compiler/__tests__/inject-claude-md.test.js +152 -0
  14. package/compiler/__tests__/load-invariants.test.js +408 -0
  15. package/compiler/__tests__/onboard-invariants.test.js +240 -0
  16. package/compiler/adapters/hooks/antigravity.js +140 -0
  17. package/compiler/adapters/hooks/claude.js +166 -0
  18. package/compiler/adapters/hooks/cursor.js +191 -0
  19. package/compiler/adapters/hooks/index.js +82 -0
  20. package/compiler/adapters/hooks/tier-emitter.js +182 -0
  21. package/compiler/adapters/hooks/windsurf.js +202 -0
  22. package/compiler/bin/rune.js +196 -6
  23. package/compiler/commands/hook-dispatch.js +87 -0
  24. package/compiler/commands/hooks/install.js +120 -0
  25. package/compiler/commands/hooks/merge.js +211 -0
  26. package/compiler/commands/hooks/presets.js +116 -0
  27. package/compiler/commands/hooks/status.js +112 -0
  28. package/compiler/commands/hooks/tiers.js +221 -0
  29. package/compiler/commands/hooks/uninstall.js +94 -0
  30. package/compiler/doctor.js +236 -0
  31. package/contexts/dev.md +34 -34
  32. package/contexts/research.md +43 -43
  33. package/contexts/review.md +55 -55
  34. package/extensions/ai-ml/PACK.md +88 -88
  35. package/extensions/ai-ml/skills/ai-agents.md +172 -172
  36. package/extensions/ai-ml/skills/code-sandbox.md +187 -187
  37. package/extensions/ai-ml/skills/deep-research.md +146 -146
  38. package/extensions/ai-ml/skills/embedding-search.md +66 -66
  39. package/extensions/ai-ml/skills/fine-tuning-guide.md +74 -74
  40. package/extensions/ai-ml/skills/llm-architect.md +125 -125
  41. package/extensions/ai-ml/skills/llm-integration.md +64 -64
  42. package/extensions/ai-ml/skills/prompt-patterns.md +72 -72
  43. package/extensions/ai-ml/skills/rag-patterns.md +66 -66
  44. package/extensions/ai-ml/skills/web-extraction.md +114 -114
  45. package/extensions/analytics/PACK.md +92 -92
  46. package/extensions/analytics/skills/ab-testing.md +72 -72
  47. package/extensions/analytics/skills/dashboard-patterns.md +83 -83
  48. package/extensions/analytics/skills/data-validation.md +68 -68
  49. package/extensions/analytics/skills/funnel-analysis.md +81 -81
  50. package/extensions/analytics/skills/sql-patterns.md +57 -57
  51. package/extensions/analytics/skills/statistical-analysis.md +79 -79
  52. package/extensions/analytics/skills/tracking-setup.md +71 -71
  53. package/extensions/backend/PACK.md +104 -104
  54. package/extensions/backend/skills/api-patterns.md +84 -84
  55. package/extensions/backend/skills/async-pipeline.md +193 -193
  56. package/extensions/backend/skills/auth-patterns.md +97 -97
  57. package/extensions/backend/skills/background-jobs.md +133 -133
  58. package/extensions/backend/skills/caching-patterns.md +108 -108
  59. package/extensions/backend/skills/cli-generation.md +133 -133
  60. package/extensions/backend/skills/database-patterns.md +87 -87
  61. package/extensions/backend/skills/middleware-patterns.md +104 -104
  62. package/extensions/chrome-ext/PACK.md +93 -93
  63. package/extensions/chrome-ext/skills/cws-preflight.md +143 -143
  64. package/extensions/chrome-ext/skills/cws-publish.md +104 -104
  65. package/extensions/chrome-ext/skills/ext-ai-integration.md +251 -251
  66. package/extensions/chrome-ext/skills/ext-messaging.md +139 -139
  67. package/extensions/chrome-ext/skills/ext-storage.md +133 -133
  68. package/extensions/chrome-ext/skills/mv3-scaffold.md +164 -164
  69. package/extensions/content/PACK.md +96 -96
  70. package/extensions/content/skills/blog-patterns.md +88 -88
  71. package/extensions/content/skills/cms-integration.md +131 -131
  72. package/extensions/content/skills/content-scoring.md +107 -107
  73. package/extensions/content/skills/i18n.md +83 -83
  74. package/extensions/content/skills/mdx-authoring.md +137 -137
  75. package/extensions/content/skills/reference.md +1014 -1014
  76. package/extensions/content/skills/seo-patterns.md +67 -67
  77. package/extensions/content/skills/video-repurpose.md +153 -153
  78. package/extensions/devops/PACK.md +101 -101
  79. package/extensions/devops/skills/chaos-testing.md +67 -67
  80. package/extensions/devops/skills/ci-cd.md +75 -75
  81. package/extensions/devops/skills/docker.md +58 -58
  82. package/extensions/devops/skills/edge-serverless.md +163 -163
  83. package/extensions/devops/skills/infra-as-code.md +158 -158
  84. package/extensions/devops/skills/kubernetes.md +110 -110
  85. package/extensions/devops/skills/monitoring.md +57 -57
  86. package/extensions/devops/skills/server-setup.md +64 -64
  87. package/extensions/devops/skills/ssl-domain.md +42 -42
  88. package/extensions/ecommerce/PACK.md +116 -116
  89. package/extensions/ecommerce/skills/cart-system.md +79 -79
  90. package/extensions/ecommerce/skills/inventory-mgmt.md +102 -102
  91. package/extensions/ecommerce/skills/order-management.md +126 -126
  92. package/extensions/ecommerce/skills/payment-integration.md +472 -472
  93. package/extensions/ecommerce/skills/shopify-dev.md +69 -69
  94. package/extensions/ecommerce/skills/subscription-billing.md +93 -93
  95. package/extensions/ecommerce/skills/tax-compliance.md +117 -117
  96. package/extensions/gamedev/PACK.md +142 -142
  97. package/extensions/gamedev/skills/asset-pipeline.md +74 -74
  98. package/extensions/gamedev/skills/audio-system.md +129 -129
  99. package/extensions/gamedev/skills/camera-system.md +87 -87
  100. package/extensions/gamedev/skills/ecs.md +98 -98
  101. package/extensions/gamedev/skills/game-loops.md +72 -72
  102. package/extensions/gamedev/skills/input-system.md +199 -199
  103. package/extensions/gamedev/skills/multiplayer.md +180 -180
  104. package/extensions/gamedev/skills/particles.md +105 -105
  105. package/extensions/gamedev/skills/physics-engine.md +89 -89
  106. package/extensions/gamedev/skills/scene-management.md +146 -146
  107. package/extensions/gamedev/skills/threejs-patterns.md +90 -90
  108. package/extensions/gamedev/skills/webgl.md +71 -71
  109. package/extensions/mobile/PACK.md +106 -106
  110. package/extensions/mobile/skills/app-store-connect.md +152 -152
  111. package/extensions/mobile/skills/app-store-prep.md +66 -66
  112. package/extensions/mobile/skills/deep-linking.md +109 -109
  113. package/extensions/mobile/skills/flutter.md +60 -60
  114. package/extensions/mobile/skills/ios-build-pipeline.md +142 -142
  115. package/extensions/mobile/skills/native-bridge.md +66 -66
  116. package/extensions/mobile/skills/ota-updates.md +97 -97
  117. package/extensions/mobile/skills/push-notifications.md +111 -111
  118. package/extensions/mobile/skills/react-native.md +82 -82
  119. package/extensions/saas/PACK.md +116 -116
  120. package/extensions/saas/skills/billing-integration.md +200 -200
  121. package/extensions/saas/skills/feature-flags.md +130 -130
  122. package/extensions/saas/skills/multi-tenant.md +103 -103
  123. package/extensions/saas/skills/onboarding-flow.md +139 -139
  124. package/extensions/saas/skills/subscription-flow.md +95 -95
  125. package/extensions/saas/skills/team-management.md +144 -144
  126. package/extensions/security/PACK.md +99 -99
  127. package/extensions/security/skills/api-security.md +140 -140
  128. package/extensions/security/skills/compliance.md +68 -68
  129. package/extensions/security/skills/owasp-audit.md +64 -64
  130. package/extensions/security/skills/pentest-patterns.md +77 -77
  131. package/extensions/security/skills/secret-mgmt.md +65 -65
  132. package/extensions/security/skills/supply-chain.md +65 -65
  133. package/extensions/trading/PACK.md +80 -80
  134. package/extensions/trading/skills/chart-components.md +55 -55
  135. package/extensions/trading/skills/experiment-loop.md +125 -125
  136. package/extensions/trading/skills/fintech-patterns.md +47 -47
  137. package/extensions/trading/skills/indicator-library.md +58 -58
  138. package/extensions/trading/skills/quant-analysis.md +111 -111
  139. package/extensions/trading/skills/realtime-data.md +58 -58
  140. package/extensions/trading/skills/trade-logic.md +104 -104
  141. package/extensions/ui/PACK.md +130 -130
  142. package/extensions/ui/skills/a11y-audit.md +91 -91
  143. package/extensions/ui/skills/animation-patterns.md +127 -127
  144. package/extensions/ui/skills/component-patterns.md +100 -100
  145. package/extensions/ui/skills/design-decision.md +108 -108
  146. package/extensions/ui/skills/design-system.md +68 -68
  147. package/extensions/ui/skills/landing-patterns.md +155 -155
  148. package/extensions/ui/skills/palette-picker.md +173 -173
  149. package/extensions/ui/skills/react-health.md +90 -90
  150. package/extensions/ui/skills/type-system.md +125 -125
  151. package/extensions/ui/skills/web-vitals.md +153 -153
  152. package/extensions/zalo/PACK.md +145 -145
  153. package/extensions/zalo/skills/zalo-oa-mcp.md +317 -317
  154. package/extensions/zalo/skills/zalo-oa-messaging.md +429 -429
  155. package/extensions/zalo/skills/zalo-oa-setup.md +236 -236
  156. package/extensions/zalo/skills/zalo-oa-webhook.md +189 -189
  157. package/extensions/zalo/skills/zalo-personal-messaging.md +194 -194
  158. package/extensions/zalo/skills/zalo-personal-setup.md +153 -153
  159. package/extensions/zalo/skills/zalo-rate-guard.md +219 -219
  160. package/hooks/auto-format/index.cjs +48 -48
  161. package/hooks/hooks.json +111 -111
  162. package/hooks/post-session-reflect/index.cjs +189 -189
  163. package/hooks/pre-compact/index.cjs +95 -95
  164. package/hooks/run-hook.cmd +1 -1
  165. package/hooks/secrets-scan/index.cjs +100 -100
  166. package/hooks/session-start/index.cjs +71 -71
  167. package/hooks/typecheck/index.cjs +65 -65
  168. package/package.json +63 -63
  169. package/references/ui-pro-max-data/LICENSE-UI-PRO-MAX +21 -21
  170. package/references/ui-pro-max-data/charts.csv +26 -26
  171. package/references/ui-pro-max-data/colors.csv +161 -161
  172. package/references/ui-pro-max-data/styles.csv +68 -68
  173. package/references/ui-pro-max-data/typography.csv +74 -74
  174. package/references/ui-pro-max-data/ui-reasoning.csv +162 -162
  175. package/references/ui-pro-max-data/ux-guidelines.csv +99 -99
  176. package/skills/adversary/SKILL.md +283 -283
  177. package/skills/asset-creator/SKILL.md +157 -157
  178. package/skills/audit/SKILL.md +147 -2
  179. package/skills/autopsy/SKILL.md +335 -335
  180. package/skills/ba/SKILL.md +85 -1
  181. package/skills/brainstorm/SKILL.md +380 -342
  182. package/skills/browser-pilot/SKILL.md +169 -168
  183. package/skills/constraint-check/SKILL.md +165 -165
  184. package/skills/context-engine/SKILL.md +408 -404
  185. package/skills/cook/SKILL.md +917 -863
  186. package/skills/db/SKILL.md +273 -273
  187. package/skills/debug/SKILL.md +465 -465
  188. package/skills/dependency-doctor/SKILL.md +265 -235
  189. package/skills/deploy/SKILL.md +274 -231
  190. package/skills/design/DESIGN-REFERENCE.md +365 -365
  191. package/skills/design/SKILL.md +590 -589
  192. package/skills/doc-processor/SKILL.md +254 -254
  193. package/skills/docs/SKILL.md +374 -374
  194. package/skills/docs-seeker/SKILL.md +178 -177
  195. package/skills/fix/SKILL.md +332 -330
  196. package/skills/git/SKILL.md +339 -339
  197. package/skills/hallucination-guard/SKILL.md +220 -219
  198. package/skills/incident/SKILL.md +254 -253
  199. package/skills/integrity-check/SKILL.md +169 -169
  200. package/skills/journal/SKILL.md +241 -240
  201. package/skills/launch/SKILL.md +344 -344
  202. package/skills/logic-guardian/SKILL.md +269 -251
  203. package/skills/marketing/SKILL.md +351 -289
  204. package/skills/mcp-builder/SKILL.md +425 -425
  205. package/skills/neural-memory/SKILL.md +359 -362
  206. package/skills/onboard/SKILL.md +432 -403
  207. package/skills/onboard/references/invariants-template.md +76 -0
  208. package/skills/onboard/scripts/detect-invariants.js +439 -0
  209. package/skills/onboard/scripts/inject-claude-md.js +150 -0
  210. package/skills/onboard/scripts/onboard-invariants.js +194 -0
  211. package/skills/perf/SKILL.md +347 -346
  212. package/skills/plan/SKILL.md +435 -428
  213. package/skills/preflight/SKILL.md +415 -415
  214. package/skills/problem-solver/SKILL.md +380 -284
  215. package/skills/rescue/SKILL.md +474 -474
  216. package/skills/research/SKILL.md +4 -0
  217. package/skills/retro/SKILL.md +3 -1
  218. package/skills/review/SKILL.md +614 -588
  219. package/skills/review-intake/SKILL.md +249 -249
  220. package/skills/safeguard/SKILL.md +200 -200
  221. package/skills/sast/SKILL.md +190 -190
  222. package/skills/scaffold/SKILL.md +328 -287
  223. package/skills/scope-guard/SKILL.md +183 -180
  224. package/skills/scout/SKILL.md +269 -263
  225. package/skills/sentinel/SKILL.md +384 -381
  226. package/skills/sentinel-env/SKILL.md +254 -254
  227. package/skills/sequential-thinking/SKILL.md +234 -234
  228. package/skills/session-bridge/SKILL.md +595 -543
  229. package/skills/session-bridge/scripts/load-invariants.js +397 -0
  230. package/skills/skill-forge/SKILL.md +581 -581
  231. package/skills/skill-router/SKILL.md +3 -0
  232. package/skills/slides/SKILL.md +19 -0
  233. package/skills/surgeon/SKILL.md +215 -215
  234. package/skills/team/SKILL.md +557 -537
  235. package/skills/test/SKILL.md +620 -614
  236. package/skills/trend-scout/SKILL.md +145 -145
  237. package/skills/verification/SKILL.md +334 -326
  238. package/skills/video-creator/SKILL.md +201 -201
  239. package/skills/watchdog/SKILL.md +168 -168
  240. package/skills/worktree/SKILL.md +140 -140
@@ -1,465 +1,465 @@
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: "1.1.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 exists → search 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 2d: Known Error Pattern Matching
182
-
183
- Before forming hypotheses, match the error against common **error archetypes**. If a match is found, skip directly to the known fix approach — no hypothesis cycling needed.
184
-
185
- **Error Pattern Catalog**:
186
-
187
- | Pattern ID | Detection (Error Type + Keywords) | Root Cause | Recovery Hint |
188
- |------------|----------------------------------|------------|---------------|
189
- | `STATELESS_LOSS` | `NameError` / `ReferenceError` + variable defined in previous step | Execution context doesn't persist between tool calls | "Combine all variable definitions and usage in a single code block" |
190
- | `MODULE_NOT_FOUND` | `ModuleNotFoundError` / `Cannot find module` | Dependency not installed or wrong import path | "Check package.json/requirements.txt. Install missing dep, then retry" |
191
- | `TYPE_MISMATCH` | `TypeError` + "undefined is not a function" / "has no attribute" | Wrong type passed through chain — object where primitive expected or vice versa | "Trace the value backward: where was it created? What type was intended?" |
192
- | `ASYNC_DEADLOCK` | `TimeoutError` / `Promise` + hang / `await` missing | Async/await misuse — missing await, blocking in async, unresolved promise | "Check: missing await? Blocking call in async context? Unresolved promise chain?" |
193
- | `PATH_MISMATCH` | `ENOENT` / `FileNotFoundError` + path string in error | Relative vs absolute path, or CWD differs from expected | "Print resolved path. Check CWD. Use path.resolve() or Path.resolve()" |
194
- | `ENCODING_ISSUE` | `UnicodeDecodeError` / `SyntaxError` + quotes/special chars | Non-ASCII characters in code or data (curly quotes, BOM, etc.) | "Check for smart quotes, BOM markers, or non-ASCII in the file. Use `file` command to check encoding" |
195
- | `ENV_MISSING` | `KeyError` / "undefined" + env var name | Environment variable not set or .env not loaded | "Check .env file exists and is loaded. Verify var name matches exactly (case-sensitive)" |
196
- | `CIRCULAR_IMPORT` | `ImportError` + "partially initialized" / "circular" | Module A imports B imports A | "Restructure: move shared types to a third module, or use lazy imports" |
197
-
198
- **Matching rules**:
199
- - Match on error type + 2+ keywords from the Detection column
200
- - If matched: report the pattern ID and recovery hint in the Debug Report, then proceed to test the known fix approach as H1 (highest priority hypothesis)
201
- - If NOT matched: proceed to Step 3 (form hypotheses from scratch)
202
-
203
- **Error fingerprinting**: When comparing errors across hypothesis cycles, normalize these elements before comparison:
204
- - Line numbers → `<LINE>`
205
- - File paths → `<PATH>`
206
- - Variable/function names → `<IDENT>`
207
- - Timestamps → `<TIME>`
208
-
209
- Two errors with the same fingerprint after normalization are the SAME error — don't re-investigate, the previous hypothesis result still applies.
210
-
211
- **Catalog growth**: After each successful debug (Step 5), check: does this error pattern match any existing catalog entry? If not, and the root cause is generalizable (not project-specific), suggest adding it to the catalog via a note in the Debug Report: "New pattern candidate: [pattern] — consider adding to error catalog."
212
-
213
- ### Step 3: Form Hypotheses
214
-
215
- List exactly 2-3 possible root causes — no more, no fewer.
216
-
217
- - Each hypothesis must be specific (name the file, function, or line if possible)
218
- - Order by likelihood (most likely first)
219
- - Format:
220
- - H1: [specific hypothesis — file/function/pattern]
221
- - H2: [specific hypothesis]
222
- - H3: [specific hypothesis]
223
-
224
- ### Step 4: Test Hypotheses
225
-
226
- Test each hypothesis systematically using tools.
227
-
228
- - Use `Read` to inspect the suspected file/function for each hypothesis
229
- - Use `Bash` to run targeted tests: a single failing test, a type check, a linter on the file
230
- - Use `rune:browser-pilot` for UI hypotheses (inspect DOM, network, console)
231
- - For each hypothesis: mark CONFIRMED / RULED OUT with evidence
232
- - If all 3 hypotheses are ruled out → go back to Step 2 to gather more evidence
233
- - Maximum 3 hypothesis cycles. If still unresolved after 3 cycles → escalate (see Hard-Gate)
234
-
235
- ### Step 5: Identify Root Cause
236
-
237
- Narrow to the single actual cause.
238
-
239
- - State the confirmed hypothesis and the exact evidence that proves it
240
- - Identify the specific file, line number, and code construct responsible
241
- - Note any contributing factors (environment, data, timing, config)
242
-
243
- ### Step 5b: Capture Error Pattern
244
-
245
- Call `neural-memory` (Capture Mode) to save the error pattern: root cause, symptoms, and fix approach. Tag with [project-name, error, technology].
246
-
247
- ### Step 6: 3-Fix Escalation Rule
248
-
249
- <HARD-GATE>
250
- If the SAME bug has been "fixed" 3 times and keeps returning:
251
- 1. STOP fixing. The bug is not the problem — the ARCHITECTURE is.
252
- 2. **Classify the failure**:
253
- - **Same category of blocker each time** (e.g., API doesn't support X, platform limitation) → the APPROACH is wrong, not just the code
254
- - **Different bugs each time** (e.g., race condition, then null pointer, then type error) → the MODULE needs redesign
255
- 3. **Route based on classification**:
256
- - Approach is wrong → Escalate to `rune:brainstorm(mode="rescue")` for category-diverse alternatives
257
- - Module needs redesign → Escalate to `rune:plan` for redesign of the affected module
258
- 4. Report all 3 fix attempts and why each failed in the escalation.
259
- "Try a 4th fix" is NOT acceptable. After 3 failures, question the design OR the approach.
260
- </HARD-GATE>
261
-
262
- Track fix attempts in the Debug Report. If this is attempt N>1 for the same symptom:
263
- - Reference previous fix attempts and their outcomes
264
- - Explain why the previous fix didn't hold
265
- - If N=3: trigger the escalation gate above — classify and route accordingly
266
-
267
- ### 3+ Fixes as Architectural Signal
268
-
269
- > From superpowers (obra/superpowers, 84k★): "Each fix revealing new problems elsewhere = structural issue, not a bug hunt."
270
-
271
- When 3+ **distinct** fixes fail (not retries of the same fix), STOP treating it as a bug:
272
-
273
- | Signal | Interpretation | Next Step |
274
- |--------|---------------|-----------|
275
- | Same blocker each time (API limit, platform gap) | Wrong approach | `brainstorm(mode="rescue")` — need fundamentally different path |
276
- | Different bugs each fix (null → race → type) | Wrong architecture | `plan` redesign — module has structural problems |
277
- | Each fix creates a new bug elsewhere | Tight coupling | The module boundary is wrong — need to redraw boundaries before fixing |
278
- | Fix works locally but fails in integration | Missing contract | Cross-module interface is undefined — add explicit contracts first |
279
-
280
- **Key insight**: After 3 failures, question the DESIGN, not the CODE. "Try harder" is never the right answer at this point.
281
-
282
- ### Step 7: Report
283
-
284
- Produce structured output and hand off to rune:fix.
285
-
286
- - Write the Debug Report (see Output Format below)
287
- - Call `rune:fix` with the full report if fix is needed
288
- - Do NOT apply any code changes — report only
289
-
290
- ## Analysis Paralysis Guard
291
-
292
- <HARD-GATE>
293
- Debug is read-heavy by nature — but there are limits.
294
-
295
- 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.
296
-
297
- 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.
298
- </HARD-GATE>
299
-
300
- ### Hash-Based Evidence Loop Detection
301
-
302
- Beyond counting reads, detect when debug is **re-gathering the same evidence without progress** — the most common debug-specific stuck pattern.
303
-
304
- **Detection signals** (track mentally across hypothesis cycles):
305
-
306
- | Signal | Count | Meaning | Action |
307
- |--------|-------|---------|--------|
308
- | Reading the same file:line range in different cycles | 2x | Re-examining without new lens | Form hypothesis from existing evidence NOW |
309
- | 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 |
310
- | Grepping the same error string after already finding all occurrences | 2x | Hoping for different results | Evidence is complete — move to Step 3 (hypothesize) |
311
- | Same hypothesis tested with same evidence across cycles | 2x | Circular reasoning | Mark hypothesis INCONCLUSIVE, try a DIFFERENT hypothesis category |
312
-
313
- **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:
314
-
315
- | Category | Examples |
316
- |----------|---------|
317
- | Data | Wrong value, missing field, type mismatch, encoding |
318
- | Control Flow | Wrong branch, missing guard, race condition, async ordering |
319
- | Environment | Wrong config, missing env var, version mismatch, path issue |
320
- | State | Stale cache, mutation side-effect, leaked reference, dangling connection |
321
-
322
-
323
- ## Red Flags — STOP and Return to Step 2
324
-
325
- If you catch yourself thinking any of these, you are GUESSING, not debugging:
326
-
327
- - "Quick fix for now, investigate later"
328
- - "Just try changing X and see if it works"
329
- - "It's probably X, let me fix that"
330
- - "I don't fully understand but this might work"
331
- - "Here are the main problems: [lists fixes without investigation]"
332
- - Proposing solutions before tracing data flow
333
- - "One more fix attempt" (when already tried 2+)
334
- - "Let me read one more file before forming a hypothesis" (after 5+ reads)
335
-
336
- ALL of these mean: STOP. Return to Step 2 (Gather Evidence).
337
-
338
- ## Constraints
339
-
340
- 1. MUST NOT apply any code changes — debug investigates only, fix applies
341
- 2. MUST reproduce the error before forming hypotheses — no guessing from error messages alone
342
- 3. MUST gather evidence (file reads, grep, stack traces) before hypothesizing
343
- 4. MUST form exactly 2-3 hypotheses, ordered by likelihood — no more, no fewer
344
- 5. MUST mark each hypothesis CONFIRMED or RULED OUT with specific evidence
345
- 6. MUST NOT exceed 3 hypothesis cycles — escalate to problem-solver or sequential-thinking
346
- 7. MUST NOT say "I know what's wrong" without citing file:line evidence
347
- 8. For deep stack errors: MUST use backward tracing (Step 2) — never fix at the crash site
348
- 9. For multi-component systems: MUST instrument boundaries before hypothesizing
349
-
350
- ## Output Format
351
-
352
- ```
353
- ## Debug Report
354
- - **Error**: [error message]
355
- - **Status**: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED
356
- - **Severity**: critical | high | medium | low
357
- - **Confidence**: high | medium | low
358
- - **Fix Attempt**: [1/2/3 — track recurring bugs]
359
-
360
- ### Root Cause
361
- [Detailed explanation of what's causing the error]
362
-
363
- ### Location
364
- - `path/to/file.ts:42` — [description of the problematic code]
365
-
366
- ### Evidence
367
- 1. [observation supporting diagnosis]
368
- 2. [observation supporting diagnosis]
369
-
370
- ### Previous Fix Attempts (if any)
371
- - Attempt 1: [what was tried] → [why it didn't hold]
372
- - Attempt 2: [what was tried] → [why it didn't hold]
373
-
374
- ### Concerns (if DONE_WITH_CONCERNS)
375
- - [concern]: [impact assessment] — [suggested remediation]
376
-
377
- ### Context Needed (if NEEDS_CONTEXT)
378
- - [what is unknown]: [why it blocks diagnosis] — [two most likely answers]
379
-
380
- ### Suggested Fix
381
- [Description of what needs to change — no code, just direction]
382
- [If attempt 3: "ESCALATION: 3-fix rule triggered. Recommending redesign via rune:plan."]
383
-
384
- ### Related Code
385
- - `path/to/related.ts` — [why it's relevant]
386
- ```
387
-
388
- ### Status Protocol (Subagent Contract)
389
-
390
- Debug returns one of four statuses to its caller (cook, fix, test, surgeon). The caller uses this to route next actions.
391
-
392
- | Status | When | Example |
393
- |--------|------|---------|
394
- | `DONE` | Root cause identified with high confidence, ready for fix | Clear diagnosis with file:line evidence |
395
- | `DONE_WITH_CONCERNS` | Root cause found but diagnosis has caveats | "Likely race condition but cannot reproduce consistently — fix may need retry logic" |
396
- | `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" |
397
- | `BLOCKED` | Exhausted 3 hypothesis cycles, escalation triggered | "3 cycles completed, no confirmed root cause — escalating to problem-solver" |
398
-
399
- ## Returns
400
-
401
- | Artifact | Format | Location |
402
- |----------|--------|----------|
403
- | Debug Report | Markdown (inline) | Emitted to calling skill (cook, fix, test, surgeon) |
404
- | Root cause + location | Inline (Debug Report) | Specific file:line with evidence |
405
- | Fix recommendation | Inline (Debug Report) | Direction only — no code changes |
406
- | Debug knowledge base entry | Markdown | `.rune/debug/knowledge-base.md` (appended on success) |
407
-
408
- ## Chain Metadata
409
-
410
- Append to Debug Report when invoked standalone. Suppress when called as sub-skill inside an L1 orchestrator (cook, team, etc.) — the orchestrator emits a consolidated block. See `docs/references/chain-metadata.md`.
411
-
412
- ```yaml
413
- chain_metadata:
414
- skill: "rune:debug"
415
- version: "1.1.0"
416
- status: "[DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED]"
417
- domain: "[area debugged]"
418
- files_changed: [] # debug never changes files
419
- exports:
420
- root_cause: { file: "[path]", line: [N], explanation: "[cause]" }
421
- severity: "[critical | high | medium | low]"
422
- confidence: "[high | medium | low]"
423
- fix_recommendation: "[direction for fix skill]"
424
- suggested_next:
425
- - skill: "rune:fix"
426
- reason: "[grounded in root cause — e.g., 'Critical race condition found in auth.ts:42']"
427
- consumes: ["root_cause", "fix_recommendation"]
428
- ```
429
-
430
- ## Sharp Edges
431
-
432
- | Failure Mode | Severity | Mitigation |
433
- |---|---|---|
434
- | Forming hypothesis from error message alone without evidence | HIGH | Evidence-first rule: read files and grep logs BEFORE hypothesizing |
435
- | Modifying code while "investigating" | CRITICAL | HARD-GATE: any code change during debug = out of scope — hand off to fix |
436
- | Marking hypothesis CONFIRMED without file:line proof | HIGH | CONFIRMED requires specific evidence cited — "it makes sense" is not evidence |
437
- | Exceeding 3 hypothesis cycles without escalation | MEDIUM | After 3 cycles: escalate to rune:problem-solver or rune:sequential-thinking |
438
- | Same bug "fixed" 3+ times without questioning architecture | CRITICAL | 3-Fix Escalation Rule: classify failure → same blocker category = brainstorm(rescue), different bugs = plan redesign |
439
- | 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 |
440
- | Not tracking fix attempt number for recurring bugs | HIGH | Debug Report MUST include Fix Attempt counter — enables escalation gate |
441
- | Adding instrumentation without region markers | MEDIUM | All debug logging MUST use `#region agent-debug` — unmarked code gets cleaned up prematurely by fix |
442
- | 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 |
443
- | 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" |
444
- | 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 |
445
- | 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 |
446
- | 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 |
447
- | Re-investigating known error patterns from scratch | MEDIUM | Step 2d: match error against Known Error Pattern Catalog first — skip hypothesis cycling for recognized patterns |
448
- | Same error fingerprint across cycles treated as different errors | MEDIUM | Step 2d: normalize line numbers, paths, variable names before comparison — same fingerprint = same error |
449
-
450
- ## Done When
451
-
452
- - Error reproduced (not assumed) with specific reproduction steps documented
453
- - 2-3 hypotheses formed, each marked CONFIRMED or RULED OUT with file:line evidence
454
- - Root cause identified at specific file:line
455
- - Structured Debug Report emitted with 4-state status
456
- - If `DONE_WITH_CONCERNS`: caveats documented with impact assessment
457
- - If `NEEDS_CONTEXT`: specific questions + two likely answers provided
458
- - If `BLOCKED`: all 3 hypothesis cycles documented + escalation target identified
459
- - No code changes made — rune:fix called with the report if fix is needed
460
-
461
- ## Cost Profile
462
-
463
- ~2000-5000 tokens input, ~500-1500 tokens output. Sonnet for code analysis quality. May escalate to opus for deeply complex bugs.
464
-
465
- **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: "1.1.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 exists → search 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 2d: Known Error Pattern Matching
182
+
183
+ Before forming hypotheses, match the error against common **error archetypes**. If a match is found, skip directly to the known fix approach — no hypothesis cycling needed.
184
+
185
+ **Error Pattern Catalog**:
186
+
187
+ | Pattern ID | Detection (Error Type + Keywords) | Root Cause | Recovery Hint |
188
+ |------------|----------------------------------|------------|---------------|
189
+ | `STATELESS_LOSS` | `NameError` / `ReferenceError` + variable defined in previous step | Execution context doesn't persist between tool calls | "Combine all variable definitions and usage in a single code block" |
190
+ | `MODULE_NOT_FOUND` | `ModuleNotFoundError` / `Cannot find module` | Dependency not installed or wrong import path | "Check package.json/requirements.txt. Install missing dep, then retry" |
191
+ | `TYPE_MISMATCH` | `TypeError` + "undefined is not a function" / "has no attribute" | Wrong type passed through chain — object where primitive expected or vice versa | "Trace the value backward: where was it created? What type was intended?" |
192
+ | `ASYNC_DEADLOCK` | `TimeoutError` / `Promise` + hang / `await` missing | Async/await misuse — missing await, blocking in async, unresolved promise | "Check: missing await? Blocking call in async context? Unresolved promise chain?" |
193
+ | `PATH_MISMATCH` | `ENOENT` / `FileNotFoundError` + path string in error | Relative vs absolute path, or CWD differs from expected | "Print resolved path. Check CWD. Use path.resolve() or Path.resolve()" |
194
+ | `ENCODING_ISSUE` | `UnicodeDecodeError` / `SyntaxError` + quotes/special chars | Non-ASCII characters in code or data (curly quotes, BOM, etc.) | "Check for smart quotes, BOM markers, or non-ASCII in the file. Use `file` command to check encoding" |
195
+ | `ENV_MISSING` | `KeyError` / "undefined" + env var name | Environment variable not set or .env not loaded | "Check .env file exists and is loaded. Verify var name matches exactly (case-sensitive)" |
196
+ | `CIRCULAR_IMPORT` | `ImportError` + "partially initialized" / "circular" | Module A imports B imports A | "Restructure: move shared types to a third module, or use lazy imports" |
197
+
198
+ **Matching rules**:
199
+ - Match on error type + 2+ keywords from the Detection column
200
+ - If matched: report the pattern ID and recovery hint in the Debug Report, then proceed to test the known fix approach as H1 (highest priority hypothesis)
201
+ - If NOT matched: proceed to Step 3 (form hypotheses from scratch)
202
+
203
+ **Error fingerprinting**: When comparing errors across hypothesis cycles, normalize these elements before comparison:
204
+ - Line numbers → `<LINE>`
205
+ - File paths → `<PATH>`
206
+ - Variable/function names → `<IDENT>`
207
+ - Timestamps → `<TIME>`
208
+
209
+ Two errors with the same fingerprint after normalization are the SAME error — don't re-investigate, the previous hypothesis result still applies.
210
+
211
+ **Catalog growth**: After each successful debug (Step 5), check: does this error pattern match any existing catalog entry? If not, and the root cause is generalizable (not project-specific), suggest adding it to the catalog via a note in the Debug Report: "New pattern candidate: [pattern] — consider adding to error catalog."
212
+
213
+ ### Step 3: Form Hypotheses
214
+
215
+ List exactly 2-3 possible root causes — no more, no fewer.
216
+
217
+ - Each hypothesis must be specific (name the file, function, or line if possible)
218
+ - Order by likelihood (most likely first)
219
+ - Format:
220
+ - H1: [specific hypothesis — file/function/pattern]
221
+ - H2: [specific hypothesis]
222
+ - H3: [specific hypothesis]
223
+
224
+ ### Step 4: Test Hypotheses
225
+
226
+ Test each hypothesis systematically using tools.
227
+
228
+ - Use `Read` to inspect the suspected file/function for each hypothesis
229
+ - Use `Bash` to run targeted tests: a single failing test, a type check, a linter on the file
230
+ - Use `rune:browser-pilot` for UI hypotheses (inspect DOM, network, console)
231
+ - For each hypothesis: mark CONFIRMED / RULED OUT with evidence
232
+ - If all 3 hypotheses are ruled out → go back to Step 2 to gather more evidence
233
+ - Maximum 3 hypothesis cycles. If still unresolved after 3 cycles → escalate (see Hard-Gate)
234
+
235
+ ### Step 5: Identify Root Cause
236
+
237
+ Narrow to the single actual cause.
238
+
239
+ - State the confirmed hypothesis and the exact evidence that proves it
240
+ - Identify the specific file, line number, and code construct responsible
241
+ - Note any contributing factors (environment, data, timing, config)
242
+
243
+ ### Step 5b: Capture Error Pattern
244
+
245
+ Call `neural-memory` (Capture Mode) to save the error pattern: root cause, symptoms, and fix approach. Tag with [project-name, error, technology].
246
+
247
+ ### Step 6: 3-Fix Escalation Rule
248
+
249
+ <HARD-GATE>
250
+ If the SAME bug has been "fixed" 3 times and keeps returning:
251
+ 1. STOP fixing. The bug is not the problem — the ARCHITECTURE is.
252
+ 2. **Classify the failure**:
253
+ - **Same category of blocker each time** (e.g., API doesn't support X, platform limitation) → the APPROACH is wrong, not just the code
254
+ - **Different bugs each time** (e.g., race condition, then null pointer, then type error) → the MODULE needs redesign
255
+ 3. **Route based on classification**:
256
+ - Approach is wrong → Escalate to `rune:brainstorm(mode="rescue")` for category-diverse alternatives
257
+ - Module needs redesign → Escalate to `rune:plan` for redesign of the affected module
258
+ 4. Report all 3 fix attempts and why each failed in the escalation.
259
+ "Try a 4th fix" is NOT acceptable. After 3 failures, question the design OR the approach.
260
+ </HARD-GATE>
261
+
262
+ Track fix attempts in the Debug Report. If this is attempt N>1 for the same symptom:
263
+ - Reference previous fix attempts and their outcomes
264
+ - Explain why the previous fix didn't hold
265
+ - If N=3: trigger the escalation gate above — classify and route accordingly
266
+
267
+ ### 3+ Fixes as Architectural Signal
268
+
269
+ > From superpowers (obra/superpowers, 84k★): "Each fix revealing new problems elsewhere = structural issue, not a bug hunt."
270
+
271
+ When 3+ **distinct** fixes fail (not retries of the same fix), STOP treating it as a bug:
272
+
273
+ | Signal | Interpretation | Next Step |
274
+ |--------|---------------|-----------|
275
+ | Same blocker each time (API limit, platform gap) | Wrong approach | `brainstorm(mode="rescue")` — need fundamentally different path |
276
+ | Different bugs each fix (null → race → type) | Wrong architecture | `plan` redesign — module has structural problems |
277
+ | Each fix creates a new bug elsewhere | Tight coupling | The module boundary is wrong — need to redraw boundaries before fixing |
278
+ | Fix works locally but fails in integration | Missing contract | Cross-module interface is undefined — add explicit contracts first |
279
+
280
+ **Key insight**: After 3 failures, question the DESIGN, not the CODE. "Try harder" is never the right answer at this point.
281
+
282
+ ### Step 7: Report
283
+
284
+ Produce structured output and hand off to rune:fix.
285
+
286
+ - Write the Debug Report (see Output Format below)
287
+ - Call `rune:fix` with the full report if fix is needed
288
+ - Do NOT apply any code changes — report only
289
+
290
+ ## Analysis Paralysis Guard
291
+
292
+ <HARD-GATE>
293
+ Debug is read-heavy by nature — but there are limits.
294
+
295
+ 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.
296
+
297
+ 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.
298
+ </HARD-GATE>
299
+
300
+ ### Hash-Based Evidence Loop Detection
301
+
302
+ Beyond counting reads, detect when debug is **re-gathering the same evidence without progress** — the most common debug-specific stuck pattern.
303
+
304
+ **Detection signals** (track mentally across hypothesis cycles):
305
+
306
+ | Signal | Count | Meaning | Action |
307
+ |--------|-------|---------|--------|
308
+ | Reading the same file:line range in different cycles | 2x | Re-examining without new lens | Form hypothesis from existing evidence NOW |
309
+ | 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 |
310
+ | Grepping the same error string after already finding all occurrences | 2x | Hoping for different results | Evidence is complete — move to Step 3 (hypothesize) |
311
+ | Same hypothesis tested with same evidence across cycles | 2x | Circular reasoning | Mark hypothesis INCONCLUSIVE, try a DIFFERENT hypothesis category |
312
+
313
+ **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:
314
+
315
+ | Category | Examples |
316
+ |----------|---------|
317
+ | Data | Wrong value, missing field, type mismatch, encoding |
318
+ | Control Flow | Wrong branch, missing guard, race condition, async ordering |
319
+ | Environment | Wrong config, missing env var, version mismatch, path issue |
320
+ | State | Stale cache, mutation side-effect, leaked reference, dangling connection |
321
+
322
+
323
+ ## Red Flags — STOP and Return to Step 2
324
+
325
+ If you catch yourself thinking any of these, you are GUESSING, not debugging:
326
+
327
+ - "Quick fix for now, investigate later"
328
+ - "Just try changing X and see if it works"
329
+ - "It's probably X, let me fix that"
330
+ - "I don't fully understand but this might work"
331
+ - "Here are the main problems: [lists fixes without investigation]"
332
+ - Proposing solutions before tracing data flow
333
+ - "One more fix attempt" (when already tried 2+)
334
+ - "Let me read one more file before forming a hypothesis" (after 5+ reads)
335
+
336
+ ALL of these mean: STOP. Return to Step 2 (Gather Evidence).
337
+
338
+ ## Constraints
339
+
340
+ 1. MUST NOT apply any code changes — debug investigates only, fix applies
341
+ 2. MUST reproduce the error before forming hypotheses — no guessing from error messages alone
342
+ 3. MUST gather evidence (file reads, grep, stack traces) before hypothesizing
343
+ 4. MUST form exactly 2-3 hypotheses, ordered by likelihood — no more, no fewer
344
+ 5. MUST mark each hypothesis CONFIRMED or RULED OUT with specific evidence
345
+ 6. MUST NOT exceed 3 hypothesis cycles — escalate to problem-solver or sequential-thinking
346
+ 7. MUST NOT say "I know what's wrong" without citing file:line evidence
347
+ 8. For deep stack errors: MUST use backward tracing (Step 2) — never fix at the crash site
348
+ 9. For multi-component systems: MUST instrument boundaries before hypothesizing
349
+
350
+ ## Output Format
351
+
352
+ ```
353
+ ## Debug Report
354
+ - **Error**: [error message]
355
+ - **Status**: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED
356
+ - **Severity**: critical | high | medium | low
357
+ - **Confidence**: high | medium | low
358
+ - **Fix Attempt**: [1/2/3 — track recurring bugs]
359
+
360
+ ### Root Cause
361
+ [Detailed explanation of what's causing the error]
362
+
363
+ ### Location
364
+ - `path/to/file.ts:42` — [description of the problematic code]
365
+
366
+ ### Evidence
367
+ 1. [observation supporting diagnosis]
368
+ 2. [observation supporting diagnosis]
369
+
370
+ ### Previous Fix Attempts (if any)
371
+ - Attempt 1: [what was tried] → [why it didn't hold]
372
+ - Attempt 2: [what was tried] → [why it didn't hold]
373
+
374
+ ### Concerns (if DONE_WITH_CONCERNS)
375
+ - [concern]: [impact assessment] — [suggested remediation]
376
+
377
+ ### Context Needed (if NEEDS_CONTEXT)
378
+ - [what is unknown]: [why it blocks diagnosis] — [two most likely answers]
379
+
380
+ ### Suggested Fix
381
+ [Description of what needs to change — no code, just direction]
382
+ [If attempt 3: "ESCALATION: 3-fix rule triggered. Recommending redesign via rune:plan."]
383
+
384
+ ### Related Code
385
+ - `path/to/related.ts` — [why it's relevant]
386
+ ```
387
+
388
+ ### Status Protocol (Subagent Contract)
389
+
390
+ Debug returns one of four statuses to its caller (cook, fix, test, surgeon). The caller uses this to route next actions.
391
+
392
+ | Status | When | Example |
393
+ |--------|------|---------|
394
+ | `DONE` | Root cause identified with high confidence, ready for fix | Clear diagnosis with file:line evidence |
395
+ | `DONE_WITH_CONCERNS` | Root cause found but diagnosis has caveats | "Likely race condition but cannot reproduce consistently — fix may need retry logic" |
396
+ | `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" |
397
+ | `BLOCKED` | Exhausted 3 hypothesis cycles, escalation triggered | "3 cycles completed, no confirmed root cause — escalating to problem-solver" |
398
+
399
+ ## Returns
400
+
401
+ | Artifact | Format | Location |
402
+ |----------|--------|----------|
403
+ | Debug Report | Markdown (inline) | Emitted to calling skill (cook, fix, test, surgeon) |
404
+ | Root cause + location | Inline (Debug Report) | Specific file:line with evidence |
405
+ | Fix recommendation | Inline (Debug Report) | Direction only — no code changes |
406
+ | Debug knowledge base entry | Markdown | `.rune/debug/knowledge-base.md` (appended on success) |
407
+
408
+ ## Chain Metadata
409
+
410
+ Append to Debug Report when invoked standalone. Suppress when called as sub-skill inside an L1 orchestrator (cook, team, etc.) — the orchestrator emits a consolidated block. See `docs/references/chain-metadata.md`.
411
+
412
+ ```yaml
413
+ chain_metadata:
414
+ skill: "rune:debug"
415
+ version: "1.1.0"
416
+ status: "[DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED]"
417
+ domain: "[area debugged]"
418
+ files_changed: [] # debug never changes files
419
+ exports:
420
+ root_cause: { file: "[path]", line: [N], explanation: "[cause]" }
421
+ severity: "[critical | high | medium | low]"
422
+ confidence: "[high | medium | low]"
423
+ fix_recommendation: "[direction for fix skill]"
424
+ suggested_next:
425
+ - skill: "rune:fix"
426
+ reason: "[grounded in root cause — e.g., 'Critical race condition found in auth.ts:42']"
427
+ consumes: ["root_cause", "fix_recommendation"]
428
+ ```
429
+
430
+ ## Sharp Edges
431
+
432
+ | Failure Mode | Severity | Mitigation |
433
+ |---|---|---|
434
+ | Forming hypothesis from error message alone without evidence | HIGH | Evidence-first rule: read files and grep logs BEFORE hypothesizing |
435
+ | Modifying code while "investigating" | CRITICAL | HARD-GATE: any code change during debug = out of scope — hand off to fix |
436
+ | Marking hypothesis CONFIRMED without file:line proof | HIGH | CONFIRMED requires specific evidence cited — "it makes sense" is not evidence |
437
+ | Exceeding 3 hypothesis cycles without escalation | MEDIUM | After 3 cycles: escalate to rune:problem-solver or rune:sequential-thinking |
438
+ | Same bug "fixed" 3+ times without questioning architecture | CRITICAL | 3-Fix Escalation Rule: classify failure → same blocker category = brainstorm(rescue), different bugs = plan redesign |
439
+ | 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 |
440
+ | Not tracking fix attempt number for recurring bugs | HIGH | Debug Report MUST include Fix Attempt counter — enables escalation gate |
441
+ | Adding instrumentation without region markers | MEDIUM | All debug logging MUST use `#region agent-debug` — unmarked code gets cleaned up prematurely by fix |
442
+ | 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 |
443
+ | 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" |
444
+ | 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 |
445
+ | 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 |
446
+ | 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 |
447
+ | Re-investigating known error patterns from scratch | MEDIUM | Step 2d: match error against Known Error Pattern Catalog first — skip hypothesis cycling for recognized patterns |
448
+ | Same error fingerprint across cycles treated as different errors | MEDIUM | Step 2d: normalize line numbers, paths, variable names before comparison — same fingerprint = same error |
449
+
450
+ ## Done When
451
+
452
+ - Error reproduced (not assumed) with specific reproduction steps documented
453
+ - 2-3 hypotheses formed, each marked CONFIRMED or RULED OUT with file:line evidence
454
+ - Root cause identified at specific file:line
455
+ - Structured Debug Report emitted with 4-state status
456
+ - If `DONE_WITH_CONCERNS`: caveats documented with impact assessment
457
+ - If `NEEDS_CONTEXT`: specific questions + two likely answers provided
458
+ - If `BLOCKED`: all 3 hypothesis cycles documented + escalation target identified
459
+ - No code changes made — rune:fix called with the report if fix is needed
460
+
461
+ ## Cost Profile
462
+
463
+ ~2000-5000 tokens input, ~500-1500 tokens output. Sonnet for code analysis quality. May escalate to opus for deeply complex bugs.
464
+
465
+ **Scope guardrail**: Do not apply code changes or expand investigation beyond the locked scope directory unless explicitly delegated by the parent agent.