@rune-kit/rune 2.6.0 → 2.8.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 (42) hide show
  1. package/README.md +22 -6
  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__/parser.test.js +201 -147
  7. package/compiler/__tests__/skill-index.test.js +218 -218
  8. package/compiler/__tests__/status.test.js +336 -0
  9. package/compiler/__tests__/templates.test.js +245 -0
  10. package/compiler/__tests__/visualizer.test.js +325 -0
  11. package/compiler/adapters/antigravity.js +71 -71
  12. package/compiler/bin/rune.js +444 -355
  13. package/compiler/doctor.js +272 -1
  14. package/compiler/emitter.js +939 -678
  15. package/compiler/parser.js +498 -267
  16. package/compiler/status.js +342 -0
  17. package/compiler/visualizer.js +622 -0
  18. package/package.json +1 -1
  19. package/skills/autopsy/SKILL.md +48 -1
  20. package/skills/completion-gate/SKILL.md +51 -3
  21. package/skills/context-engine/SKILL.md +141 -2
  22. package/skills/cook/SKILL.md +177 -4
  23. package/skills/debug/SKILL.md +50 -1
  24. package/skills/docs/SKILL.md +28 -3
  25. package/skills/fix/SKILL.md +26 -1
  26. package/skills/mcp-builder/SKILL.md +53 -1
  27. package/skills/onboard/SKILL.md +51 -1
  28. package/skills/perf/SKILL.md +34 -1
  29. package/skills/plan/SKILL.md +27 -1
  30. package/skills/preflight/SKILL.md +35 -1
  31. package/skills/research/SKILL.md +24 -1
  32. package/skills/retro/SKILL.md +95 -1
  33. package/skills/review/SKILL.md +45 -1
  34. package/skills/scope-guard/SKILL.md +1 -0
  35. package/skills/scout/SKILL.md +22 -1
  36. package/skills/sentinel/SKILL.md +35 -1
  37. package/skills/sentinel/references/policy-driven-constraints.md +424 -0
  38. package/skills/sentinel-env/SKILL.md +0 -2
  39. package/skills/session-bridge/SKILL.md +57 -2
  40. package/skills/session-bridge/references/evolutionary-memory-patterns.md +312 -0
  41. package/skills/team/SKILL.md +15 -1
  42. package/skills/verification/SKILL.md +0 -2
@@ -4,7 +4,7 @@ description: "Validates agent claims against evidence trail. Catches 'done' with
4
4
  user-invocable: false
5
5
  metadata:
6
6
  author: runedev
7
- version: "1.6.0"
7
+ version: "1.8.0"
8
8
  layer: L3
9
9
  model: haiku
10
10
  group: validation
@@ -91,6 +91,30 @@ Why: Self-Validation catches domain-specific quality issues that generic claim m
91
91
  If a skill has Self-Validation and ANY check is UNCONFIRMED or CONTRADICTED → overall verdict cannot be CONFIRMED, even if all explicit claims pass.
92
92
  </HARD-GATE>
93
93
 
94
+ ### Step 1d — Execution Loop Audit
95
+
96
+ Before validating claims, audit the agent's tool call pattern for execution loops that indicate the agent was stuck but didn't report it:
97
+
98
+ **Classify the agent's tool calls** from this workflow into two categories:
99
+
100
+ | Category | Tools | Expected in Phase 4 |
101
+ |----------|-------|---------------------|
102
+ | **Observation** | Read, Grep, Glob, Bash(grep/ls/cat) | <40% of calls |
103
+ | **Effect** | Write, Edit, Bash(build/test/npm) | >60% of calls |
104
+
105
+ **Loop patterns to detect**:
106
+
107
+ | Pattern | Detection | Verdict Impact |
108
+ |---------|-----------|----------------|
109
+ | **Observation chain**: 6+ consecutive observation tools in Phase 4 | Count longest observation-only streak | Add WARN: "Agent had {N}-call observation streak during implementation — possible analysis paralysis" |
110
+ | **Low effect ratio**: <20% effect calls during Phase 4 | `effect_calls / total_calls` | Add WARN: "Only {X}% of Phase 4 calls were writes — agent may have been stuck" |
111
+ | **Repeating tool pattern**: Same tool+args called 3+ times | Hash tool+args, count duplicates | Add WARN: "Agent called {tool}({args}) {N} times — possible loop" |
112
+ | **Budget overrun**: Phase 4 exceeded 50 tool calls for a single-file task | Count Phase 4 calls vs files changed | Add WARN: "50+ tool calls for {N} files changed — disproportionate effort" |
113
+
114
+ **Scoring impact**: Loop warnings don't change individual claim verdicts but ARE included in the Completion Gate Report under a new `### Execution Efficiency` section. This gives the calling orchestrator signal about whether the agent's process was healthy, not just whether the output was correct.
115
+
116
+ **Skip if**: Nano/Fast rigor — not enough tool calls to meaningfully analyze.
117
+
94
118
  ### Step 2 — Match Evidence
95
119
 
96
120
  For each claim, look for corresponding evidence in the conversation context:
@@ -167,8 +191,6 @@ UNCONFIRMED — 1 claim lacks evidence, 1 contradicted. Cannot proceed to commit
167
191
 
168
192
  ### Step 4.5 — Cross-Phase Integration Check
169
193
 
170
- > From GSD (gsd-build/get-shit-done, 30.8k★): "Phase boundaries are where integration bugs hide."
171
-
172
194
  When validating a completed phase in a multi-phase plan, check for integration gaps between phases:
173
195
 
174
196
  1. **Orphaned exports** — files/functions created in this phase that claim to be used by future phases (see `## Cross-Phase Context → Exports`) but are not yet importable:
@@ -210,6 +232,29 @@ Before emitting verdict, verify evidence quality:
210
232
  | Quote matches claim exactly | CONFIRMED |
211
233
  | Quote contradicts claim | CONTRADICTED |
212
234
 
235
+ ### Step 5.5 — Plan Diff Check
236
+
237
+ When validating a phase within a master plan, diff actual changes against the phase plan file:
238
+
239
+ 1. **Read the active phase plan** — `Glob` for `.rune/plan-*-phase*.md` matching the current phase
240
+ 2. **Extract `## Files Touched`** — build a list of expected files (new/modify/delete)
241
+ 3. **Extract `## Tasks`** — build a list of all `- [ ]` and `- [x]` items
242
+ 4. **Compare against actual changes** — `git diff --name-only` (or file system scan)
243
+ 5. **Report**:
244
+
245
+ | Check | Status |
246
+ |-------|--------|
247
+ | Unchecked task in phase plan (`- [ ]` still exists) | **INCOMPLETE** — task was not done |
248
+ | File in plan's "Files Touched" but not in actual diff | **MISSING** — planned file was never touched |
249
+ | File in actual diff but NOT in plan's "Files Touched" | **UNPLANNED** — scope creep (warn, not block) |
250
+ | All tasks `[x]` AND all planned files touched | **PLAN-ALIGNED** |
251
+
252
+ ```
253
+ Plan Diff: PLAN-ALIGNED | INCOMPLETE (2 unchecked tasks) | MISSING (1 file never touched)
254
+ ```
255
+
256
+ **Skip if**: No active phase plan found (single-task, no master plan). **MANDATORY** for multi-phase master plans.
257
+
213
258
  ## Verdict Rules
214
259
 
215
260
  ```
@@ -245,6 +290,8 @@ Completion Gate Report with status (CONFIRMED/UNCONFIRMED/CONTRADICTED), claim v
245
290
  | Rubber-stamping — all CONFIRMED without scrutiny | HIGH | Default-FAIL mindset: actively seek 3-5 issues. Zero issues = red flag, apply skeptic sweep on weakest 2 claims |
246
291
  | Partial completion claimed as full — 80% done but "implemented" | HIGH | Adversarial checklist: check for partial completion, scope mismatch, evidence-claim alignment |
247
292
  | Self-Validation skipped — skill has checks but gate ignores them | HIGH | Step 1c: extract Self-Validation from skill's SKILL.md, treat each as implicit claim. Missing = UNCONFIRMED |
293
+ | Plan says done but phase file has unchecked tasks | HIGH | Step 5.5: diff changed files vs phase plan's Files Touched + Tasks sections |
294
+ | Agent stuck in observation loop but claims "implemented" | HIGH | Step 1d: Execution Loop Audit detects low effect ratio and observation chains — flags in report even if claims pass |
248
295
 
249
296
  ## Done When
250
297
 
@@ -252,6 +299,7 @@ Completion Gate Report with status (CONFIRMED/UNCONFIRMED/CONTRADICTED), claim v
252
299
  - Each claim matched against tool output evidence
253
300
  - Verdict table emitted with claim/evidence/verdict for each item
254
301
  - All 3 verification axes (Completeness/Correctness/Coherence) have at least one claim checked
302
+ - Plan diff check passed (if multi-phase): all tasks checked, all planned files touched
255
303
  - Overall verdict: CONFIRMED / UNCONFIRMED / CONTRADICTED
256
304
  - If not CONFIRMED: specific gaps listed with remediation steps
257
305
 
@@ -4,7 +4,7 @@ description: "Context window management. Auto-triggered when context is filling
4
4
  user-invocable: false
5
5
  metadata:
6
6
  author: runedev
7
- version: "0.6.0"
7
+ version: "0.9.0"
8
8
  layer: L3
9
9
  model: haiku
10
10
  group: state
@@ -145,6 +145,127 @@ When loading context for a task (Phase 1 of cook, or onboard), use a 4-phase ret
145
145
 
146
146
  **Key rule**: Stop at 3 high-relevance files, not 10 mediocre ones. Quality > quantity for context loading.
147
147
 
148
+ ## Compaction Technique: Structured Summary with Continuation Point
149
+
150
+ When compaction is triggered (RED or approved ORANGE), generate a **structured summary** that replaces the full conversation history while preserving therapeutic continuity — the ability to resume exactly where work left off.
151
+
152
+ ### Summary Structure
153
+
154
+ The compaction summary MUST include these sections in order:
155
+
156
+ ```markdown
157
+ ## Compaction Summary (generated at [tool call count])
158
+
159
+ ### Topics Covered
160
+ - [bullet list of distinct topics/tasks worked on this session]
161
+
162
+ ### Key Decisions Made
163
+ - [decision]: [rationale] — affects [files/modules]
164
+
165
+ ### Active Threads
166
+ - [what was being worked on when compaction triggered — the "where we are now" anchor]
167
+ - Current file: [path], current function/section: [name]
168
+ - Partial progress: [what's done vs what remains in the immediate task]
169
+
170
+ ### Emotional/Priority Context
171
+ - [user urgency level, blocking issues, deadlines mentioned]
172
+ - [any user frustrations or preferences expressed this session]
173
+
174
+ ### Continuation Point
175
+ > Resume: [exact next action to take — not vague "continue working" but specific "implement the validation logic in src/auth/validate.ts:47 using the Zod schema defined in Step 2"]
176
+ ```
177
+
178
+ ### Why This Structure
179
+
180
+ Most compaction loses the **continuation point** — the agent knows WHAT was discussed but not WHERE to resume. The "Active Threads" and "Continuation Point" sections solve this by preserving:
181
+ 1. The exact file and function being edited
182
+ 2. What's done vs remaining in the current micro-task
183
+ 3. The specific next action (not a summary of the plan, but the next concrete step)
184
+
185
+ ### Rules
186
+
187
+ - Summary MUST be <500 tokens — if longer, you're summarizing too much detail
188
+ - "Active Threads" section is the most critical — get this wrong and the agent restarts from scratch
189
+ - Never include full file contents in the summary — only paths and line references
190
+ - Include user tone/urgency signals — these are lost in pure technical summaries
191
+
192
+ ## Incremental Stream Processing
193
+
194
+ When processing streaming LLM output (e.g., in skills that invoke AI calls or process tool output incrementally), use **sentence-level buffering** instead of waiting for the full response:
195
+
196
+ ### Pattern: Buffer → Detect Boundary → Act
197
+
198
+ ```
199
+ 1. ACCUMULATE: Feed incoming chunks into a text buffer
200
+ 2. DETECT: Check for sentence boundaries:
201
+ - Primary: 40+ chars ending in . ! ? ; :
202
+ - Secondary: paragraph break (\n\n) with 15+ chars accumulated
203
+ - Never split mid-word or mid-code-block
204
+ 3. EXTRACT: Remove the complete sentence from the buffer
205
+ 4. ACT: Process the extracted sentence immediately (e.g., queue for TTS, parse for structured data, update progress display)
206
+ 5. CONTINUE: Keep accumulating the next sentence while processing the current one
207
+ ```
208
+
209
+ ### When to Use
210
+
211
+ - **Skills that stream AI responses to the user**: process and display incrementally instead of waiting for the full response
212
+ - **Background note-taking**: extract key points from streaming output as they arrive
213
+ - **Progress reporting**: detect milestone keywords in streaming output to update progress
214
+
215
+ ### When NOT to Use
216
+
217
+ - **Code generation**: wait for the full code block — partial code is useless
218
+ - **JSON output**: accumulate until the closing brace — partial JSON can't be parsed
219
+ - **Short responses** (<100 chars expected): overhead of boundary detection exceeds benefit
220
+
221
+ ## Artifact Folding (Large Output Management)
222
+
223
+ When tool results are excessively large, they consume disproportionate context without proportionate value. **Artifact folding** saves the full output to a file and replaces it in context with a compact preview.
224
+
225
+ ### When to Fold
226
+
227
+ | Condition | Action |
228
+ |-----------|--------|
229
+ | Tool output > 4000 characters | Fold to artifact |
230
+ | Tool output > 120 lines | Fold to artifact |
231
+ | Multiple tool outputs from the same command class (e.g., 5+ Grep results) | Fold all into single artifact |
232
+ | Code block output > 200 lines | Fold to artifact |
233
+
234
+ ### Folding Procedure
235
+
236
+ 1. **Save full output** to `.rune/artifacts/artifact-{timestamp}-{tool}.md`:
237
+ ```markdown
238
+ # Artifact: {tool_name} output
239
+ Generated: {timestamp}
240
+ Command: {tool_call_summary}
241
+
242
+ {full_output}
243
+ ```
244
+
245
+ 2. **Replace in context** with a compact preview:
246
+ ```
247
+ [FOLDED: {tool_name} output — {line_count} lines, {char_count} chars]
248
+ Preview (first 10 lines):
249
+ {first_10_lines}
250
+ ...
251
+ Full output: .rune/artifacts/artifact-{timestamp}-{tool}.md
252
+ Use Read to access the full artifact if needed.
253
+ ```
254
+
255
+ 3. **On compaction**: Artifact files survive compaction — the continuation summary references them by path. This means large outputs are preserved across compaction boundaries without consuming context.
256
+
257
+ ### Rules
258
+
259
+ - **Never fold user messages** — only tool outputs
260
+ - **Never fold error outputs** — errors need full visibility for debugging
261
+ - **Never fold outputs < 1000 chars** — folding overhead exceeds savings
262
+ - **Fold preemptively in YELLOW/ORANGE** — don't wait for RED to start managing output size
263
+ - **Clean up artifacts** at session end: artifacts older than the current session can be deleted (they're already in git history or irrelevant)
264
+
265
+ ### Why
266
+
267
+ A single `Grep` across a large codebase can return 3000+ lines. Without folding, this consumes ~4000 tokens of context — often more than the rest of the conversation combined. Folding preserves the information (accessible via Read) while keeping context lean. Combined with the Structured Summary compaction technique, artifact folding enables much longer productive sessions.
268
+
148
269
  ## Context Health Levels
149
270
 
150
271
  ```
@@ -182,7 +303,7 @@ When ORANGE or RED is reached, use this table to determine whether compaction is
182
303
  | Research → Planning | YES | Research findings summarize well; key decisions survive |
183
304
  | Planning → Implementation | YES | Plan is in files (.rune/plan-*.md); context can reload from artifacts |
184
305
  | Debug → Next feature | YES | Debug findings are in Debug Report; fix has the diagnosis |
185
- | Mid-implementation (Phase 4) | **NO** | Losing file paths, partial changes, and test state is catastrophic |
306
+ | Mid-implementation (Phase 4) | **CONDITIONAL** | Safe ONLY at task boundaries within Phase 4 (after a file is fully written + tested). Never mid-file-edit. See Mid-Loop Compaction below |
186
307
  | After failed approach → Pivot | YES | Failed approach should be discarded; fresh context helps |
187
308
  | Quality (Phase 5) → Verify | **NO** | Quality findings reference specific file:line in current context |
188
309
  | After commit (Phase 7) | YES | Work is persisted in git; safe boundary |
@@ -190,6 +311,22 @@ When ORANGE or RED is reached, use this table to determine whether compaction is
190
311
  **What survives compaction**: Task description, file paths mentioned, key decisions, plan reference, current phase.
191
312
  **What is lost**: Full file contents read, intermediate reasoning, exact error messages, tool output details.
192
313
 
314
+ ### Mid-Loop Compaction (Phase 4 Emergency)
315
+
316
+ > From goclaw (nextlevelbuilder/goclaw, 832★): "Compact during run, not just at session boundary."
317
+
318
+ When context hits RED during Phase 4 (implementation), compaction IS possible at **clean split points**:
319
+
320
+ 1. **Find a clean boundary**: completed task within the phase (file fully written + tests pass for that file)
321
+ 2. **Flush state first**: call `session-bridge` to save progress, then call `neural-memory` to capture decisions
322
+ 3. **Split 70/30**: preserve 70% of remaining context for continuation, summarize 30% of completed work
323
+ 4. **Never break tool pairs**: compaction MUST NOT split a `tool_use` from its `tool_result` — always keep pairs together
324
+ 5. **Inject continuation marker**: after compaction, include: "Resuming Phase 4. Tasks [1-3] complete. Currently on task 4. Plan file: `.rune/plan-X-phaseN.md`"
325
+
326
+ **Timeout fallback**: If clean boundary can't be found within 30 seconds, create `.rune/.continue-here.md` and pause instead.
327
+
328
+ **Skip if**: Context is ORANGE (not RED), or fewer than 3 tasks remain in the phase.
329
+
193
330
  ## Context Budget Audit (Baseline Cost Awareness)
194
331
 
195
332
  MCP tool schemas and agent descriptions consume significant baseline context before any work begins. This section helps identify and reduce invisible context waste.
@@ -251,6 +388,8 @@ Known failure modes for this skill. Check these before declaring done.
251
388
  | Injecting stale context from previous session without marking it historical | HIGH | Constraint 3: all loaded context must include session date marker |
252
389
  | Premature compaction from over-estimated utilization | MEDIUM | Tool count is directional only — sessions with heavy Read calls may need lower thresholds; only block at confirmed RED |
253
390
  | Not activating large-file adjustment on Python/Java codebases | MEDIUM | Track Read calls returning >500 lines; if ≥3 occur, switch to adjusted (0.8x) thresholds for the session |
391
+ | Mid-loop compaction breaks tool_use/tool_result pair | CRITICAL | Always keep tool pairs together — splitting causes orphaned results and context corruption |
392
+ | Mid-loop compaction without flushing state first | HIGH | session-bridge + neural-memory MUST run before compaction — losing unsaved decisions is worse than hitting context limit |
254
393
 
255
394
  ## Done When
256
395
 
@@ -5,7 +5,7 @@ context: fork
5
5
  agent: general-purpose
6
6
  metadata:
7
7
  author: runedev
8
- version: "1.7.0"
8
+ version: "2.1.0"
9
9
  layer: L1
10
10
  model: sonnet
11
11
  group: orchestrator
@@ -39,14 +39,41 @@ Cook supports predefined workflow chains for common task types. Use these as sho
39
39
  /rune cook security → Full pipeline + sentinel@opus + sast (all phases, security-escalated)
40
40
  /rune cook hotfix → Minimal: fix → verify → commit (Phase 4 → 6 → 7, skip scout if user provides context)
41
41
  /rune cook nano → Trivial: do → verify → done (no phases, ≤3 steps)
42
+ /rune cook --template <name> → Load pre-built workflow template from installed Pro/Business packs
42
43
  ```
43
44
 
45
+ ### Template Workflows (Pro/Business)
46
+
47
+ When `--template <name>` is provided, cook loads a pre-built workflow template instead of auto-detecting:
48
+
49
+ ```
50
+ /rune cook --template product-discovery → Pro: stakeholder interviews → problem framing → competitive → spec → validation
51
+ /rune cook --template product-launch → Pro: spec lock → implement → quality gates → staged rollout → announcement
52
+ /rune cook --template product-iteration → Pro: metrics review → feedback synthesis → re-prioritize → implement → measure
53
+ /rune cook --template data-exploration → Pro: data profiling → hypotheses → statistical testing → visualization → report
54
+ /rune cook --template data-pipeline → Pro: schema design → ETL → quality gates → deploy → monitoring
55
+ /rune cook --template sales-outreach-campaign → Pro: prospect research → messaging → sequence → A/B test → launch
56
+ /rune cook --template sales-deal-review → Pro: account deep-dive → risk assessment → competitive strategy → action plan
57
+ /rune cook --template support-incident-response → Pro: triage → diagnose → fix → verify → postmortem → KB update
58
+ /rune cook --template support-kb-refresh → Pro: audit → gap analysis → draft → review → publish
59
+ ```
60
+
61
+ **Template resolution**: Templates are `.md` files in `extensions/pro-*/templates/` or `extensions/business-*/templates/`. Each template defines: phases, skill connections, mesh signals, and acceptance criteria. The compiler includes templates in pack output during build.
62
+
63
+ **When --template is used**:
64
+ 1. Skip Phase 1.5 (auto-detection) — template pre-selects domain and pack
65
+ 2. Skip Phase 1.7 (workflow matching) — template IS the workflow
66
+ 3. Load template phases as the master plan (Phase 2 becomes "review template plan" not "create plan")
67
+ 4. Execute each template phase in order, invoking declared skills
68
+ 5. Emit template's declared signals on completion
69
+
44
70
  **Chain selection**: If user invokes `/rune cook` without a chain type, auto-detect from the task description:
45
71
  - Contains "bug", "fix", "broken", "error" → `bugfix`
46
72
  - Contains "refactor", "clean", "restructure" → `refactor`
47
73
  - Contains "security", "auth", "vulnerability", "CVE" → `security`
48
74
  - Contains "urgent", "hotfix", "production" → `hotfix`
49
75
  - Contains "quick", "just", "chỉ cần", "copy", "move", "rename", "bump" → `nano`
76
+ - Contains `--template` → load template workflow (see above)
50
77
  - Default → `feature`
51
78
 
52
79
  ## Phase Skip Rules
@@ -177,7 +204,11 @@ Skip if: bug fix with clear repro steps | user said "just do it" | fast mode + <
177
204
  5. Invoke scout to scan the codebase (Glob + Grep + Read on relevant files)
178
205
  6. Summarize: what exists, project conventions, files likely to change, active decision constraints
179
206
  7. **Python async detection**: if Python project detected, `Grep` for async indicators (`async def`, `await`, `aiosqlite`, `aiohttp`, `asyncio.run`). If ≥3 matches → flag as **"async-first Python"** — new code defaults to `async def`
180
- 8. Mark Phase 1 as `completed`
207
+ 8. **Explore-Before-Commit**: If scout reveals multiple viable approaches (e.g., 2+ libraries, 2+ architectural patterns), do NOT commit to an approach yet. Instead:
208
+ - List alternatives with 1-line trade-off each
209
+ - Flag to Phase 2 (plan) for formal comparison
210
+ - Separating "thinking" (Phase 1) from "committing" (Phase 2) prevents premature lock-in
211
+ 9. Mark Phase 1 as `completed`
181
212
 
182
213
  **Gate**: If scout finds the feature already exists → STOP and inform user.
183
214
 
@@ -212,7 +243,15 @@ After scout completes, check if the detected tech stack or task description matc
212
243
 
213
244
  ## Phase 0: RESUME CHECK (Before Phase 1)
214
245
 
215
- **Goal**: Detect if a master plan already exists for this task. If so, skip Phase 1-2 and resume from the current phase.
246
+ **Goal**: Detect if a master plan already exists for this task, or if a `--template` was specified. If so, skip Phase 1-2 and resume/load the workflow.
247
+
248
+ **Step 0.4 — Template Detection**: If user passed `--template <name>`:
249
+ 1. Search installed pack templates for the name: `Glob` for `extensions/*/templates/<name>.md` and `extensions/pro-*/templates/<name>.md`
250
+ 2. If found: `Read` the template file → parse phases, signals, connections, acceptance criteria
251
+ 3. Generate a master plan from the template: each template phase becomes a plan phase
252
+ 4. Write plan files to `.rune/plan-<template-name>.md` + `.rune/plan-<template-name>-phaseN.md`
253
+ 5. Announce "Loading template: <name> (<pack>)" → skip Phase 1, 1.5, 1.7, 2 → proceed to Phase 4 with Phase 1 of the template
254
+ 6. If template not found: warn user and fall through to normal workflow
216
255
 
217
256
  **Step 0.5 — Cross-Project Recall**: Call `neural-memory` (Recall Mode) with 3-5 topics relevant to the current task. Always prefix queries with the project name (e.g., `"ProjectName auth pattern"` not `"auth pattern"`).
218
257
 
@@ -427,7 +466,15 @@ Before entering ANY Phase N+1, assert: Phase N `completed` in TodoWrite | gate c
427
466
  2. Save to `.rune/decisions.md` (approach + trade-offs), `.rune/progress.md` (task complete), `.rune/conventions.md` (new patterns)
428
467
  3. **Skill metrics** → `.rune/metrics/skills.json`: increment phase run/skip counts, quality gate results, debug loop counts under `cook` key
429
468
  4. **Routing overrides** (H3): if Phase 4 hit max loops for an error pattern → write rule to `.rune/metrics/routing-overrides.json`. Max 10 active rules.
430
- 5. **Step 8.5 — Capture Learnings**: `neural-memory` (Capture Mode) — 2-5 memories: architecture decisions, patterns, error root-causes, trade-offs. Cognitive language (causal/decisional/comparative). Tags: `[project, tech, topic]`. Priority 5 routine / 7-8 decisions / 9-10 critical errors.
469
+ 5. **Step 8.5 — Cross-Cutting Sweep**: After commit, check if this phase changed stats (skill count, test count, signal count, pack count, layer counts). If ANY stat changed:
470
+ - [ ] `README.md` — stats, badges, feature list
471
+ - [ ] `docs/index.html` (landing page) — meta tags, hero badge, install section, mesh stats, footer
472
+ - [ ] `dashboard.html` (if local) — KPI cards, test count, skill tabs, layer counts
473
+ - [ ] `CLAUDE.md` — commands, test count, skill list
474
+ - [ ] `MEMORY.md` — milestones, version info
475
+
476
+ **Skip if**: No stats changed (pure refactor, docs-only, style change). **MANDATORY** if any numeric stat in README differs from actual.
477
+ 6. **Step 8.6 — Capture Learnings**: `neural-memory` (Capture Mode) — 2-5 memories: architecture decisions, patterns, error root-causes, trade-offs. Cognitive language (causal/decisional/comparative). Tags: `[project, tech, topic]`. Priority 5 routine / 7-8 decisions / 9-10 critical errors.
431
478
  6. Mark Phase 8 as `completed`
432
479
 
433
480
  ## Autonomous Loop Patterns
@@ -487,6 +534,56 @@ If ambiguous between Cancel and Steer → ask user: "Did you mean stop, or chang
487
534
  Hard caps: MAX_DEBUG_LOOPS=3, MAX_QUALITY_LOOPS=2, MAX_REPLAN=1, MAX_PIVOT=1, MAX_FIXES=30, WTF_THRESHOLD=20%.
488
535
  Escalation chain: debug-fix (3x) → re-plan (1x) → brainstorm rescue (1x) → THEN escalate to user.
489
536
 
537
+ ### Structured Escalation Report
538
+
539
+ > From agency-agents (msitarzewski/agency-agents, 50.8k★): "After 3 retry failures, structured escalation prevents cargo-cult retrying."
540
+
541
+ When escalation chain exhausts (all retries hit) or cook returns `BLOCKED`, produce a Structured Escalation Report instead of a vague "I can't do this":
542
+
543
+ ```markdown
544
+ ## Escalation Report
545
+ - **Task**: [original task description]
546
+ - **Status**: BLOCKED
547
+ - **Attempts**: [count] across [N] phases
548
+
549
+ ### Failure History
550
+ | # | Approach | Phase | Outcome | Root Cause |
551
+ |---|---------|-------|---------|------------|
552
+ | 1 | Direct fix | Phase 4 | Tests fail — null ref in auth.ts:42 | Missing user context |
553
+ | 2 | Re-plan with guard clause | Phase 4 | Build fails — circular import | Guard approach introduces cycle |
554
+ | 3 | Brainstorm rescue → adapter pattern | Phase 4 | Tests pass but perf regression 3x | Adapter adds indirection overhead |
555
+
556
+ ### Root Cause Analysis
557
+ [1-2 sentences: why ALL approaches failed — is it architectural, environmental, or requirements-level?]
558
+
559
+ ### Recommended Resolutions (pick one)
560
+ 1. **Reassign** — different skill/agent with fresh context
561
+ 2. **Decompose** — break into smaller sub-tasks that CAN succeed independently
562
+ 3. **Revise requirements** — relax constraint X to unblock (specify which)
563
+ 4. **Accept partial** — ship what works, defer blocked portion
564
+ 5. **Defer** — park this task, work on something else first
565
+
566
+ ### Impact Assessment
567
+ - **Blocked by this**: [downstream tasks/phases that depend on this]
568
+ - **Not blocked**: [independent work that can continue]
569
+ ```
570
+
571
+ <HARD-GATE>
572
+ "Bad work is worse than no work." Cook MUST produce this report rather than attempting a 4th variant of a failing approach. Escalating is not failure — shipping broken code is.
573
+ </HARD-GATE>
574
+
575
+ ### Subagent Question Gate
576
+
577
+ > From superpowers (obra/superpowers, 84k★): "Subagents that start work without asking questions produce the wrong thing 40% of the time."
578
+
579
+ Before dispatching a sub-skill (fix, test, review) for a non-trivial task (3+ files OR ambiguous scope):
580
+
581
+ 1. **Invite questions**: Include in the handoff: "Before starting, ask up to 3 clarifying questions if anything is unclear."
582
+ 2. **Answer before work**: If the sub-skill returns questions → answer them, THEN re-dispatch with answers included.
583
+ 3. **Skip if**: Fast/Nano rigor, single-file fix, or sub-skill is haiku-tier (too cheap to gate).
584
+
585
+ This prevents the #1 parallel work failure: sub-skill assumes wrong interpretation, builds 500 LOC, then gets rejected in review.
586
+
490
587
  ### Subagent Status Protocol
491
588
 
492
589
  <MUST-READ path="references/subagent-status.md" trigger="when cook or any sub-skill needs to return a status"/>
@@ -537,6 +634,46 @@ Stuck patterns (all banned):
537
634
  A wrong first attempt that produces feedback beats perfect understanding that never ships.
538
635
  </HARD-GATE>
539
636
 
637
+ ### Observation/Effect Ratio Tracking
638
+
639
+ Track every tool call during Phase 4 (IMPLEMENT) as either **observation** (read-only) or **effect** (modifies state):
640
+
641
+ | Category | Tool Examples |
642
+ |----------|--------------|
643
+ | **Observation** | Read, Grep, Glob, Bash(grep/ls/cat/git log) |
644
+ | **Effect** | Write, Edit, Bash(npm/build/test/mkdir) |
645
+
646
+ **Detection rules** (check every 8 tool calls during Phase 4):
647
+
648
+ | Pattern | Threshold | Signal | Action |
649
+ |---------|-----------|--------|--------|
650
+ | **Observation chain** | 6+ consecutive observation tools with zero effects | Agent is stuck reading, not building | Inject: "OBSERVATION LOOP — 6 reads without writing. Act on what you know or report BLOCKED." |
651
+ | **Low effect ratio** | In last 10 calls, effects < 15% | Agent is in analysis mode, not implementation | Inject: "Effect ratio below 15%. Phase 4 is IMPLEMENT — write code, don't just read it." |
652
+ | **Diminishing returns** | Last 3 observations found <2 new relevant facts combined | Searching is no longer productive | Inject: "Diminishing returns — last 3 reads added nothing new. Synthesize and act." |
653
+ | **Repeating sequences** | A-B-A-B or A-B-C-A-B-C pattern across 6+ calls | Circular behavior | Inject: "REPEATING SEQUENCE detected. Break the cycle — try a different approach or report BLOCKED." |
654
+
655
+ **Important**: These are injected as advisor messages, not hard blocks. The agent can continue if it has good reason, but the message forces conscious acknowledgment of the pattern.
656
+
657
+ **Skip if**: Phase 1 (UNDERSTAND) — observation-heavy is expected during research. Only track during Phase 4+ where effects should dominate.
658
+
659
+ ### Budget-Aware Phase Progression
660
+
661
+ Beyond the existing Exit Conditions (MAX_DEBUG_LOOPS, MAX_QUALITY_LOOPS, etc.), track **cumulative budget** across the entire cook session:
662
+
663
+ | Budget | Limit | What Happens at Limit |
664
+ |--------|-------|----------------------|
665
+ | **Phase 4 react budget** | 15 tool calls per task within Phase 4 | Force: move to next task or report partial completion |
666
+ | **Global replan budget** | 2 replans per session (Phase 4 Step 6) | Force: proceed with current plan or escalate to user |
667
+ | **Quality retry budget** | 3 total quality re-runs across 5a-5d | Force: ship with known issues documented, don't loop |
668
+ | **Total session tool calls** | 150 calls | Force: save state via session-bridge, compact or pause |
669
+
670
+ **Hard override rules**:
671
+ - If react budget exhausted for a task but task is IN_PROGRESS → force CONTINUE to next task (don't re-attempt)
672
+ - If replan budget exhausted but plan still failing → force escalation (don't attempt 3rd replan)
673
+ - If quality retry budget exhausted → emit concerns in Cook Report, proceed to commit with documented caveats
674
+
675
+ **Why**: Without hard budgets, agents get trapped in local optimization loops — retrying the same failing approach indefinitely. Budget constraints force escalation or acceptance of partial results, which is always better than an infinite loop.
676
+
540
677
  ### Hash-Based Tool Loop Detection
541
678
 
542
679
  <MUST-READ path="references/loop-detection.md" trigger="when same tool+args+result appears to be repeating"/>
@@ -615,6 +752,42 @@ Mentally track tool call fingerprints. 3 identical calls → WARN. 5 identical c
615
752
  | Quality Gate | preflight + sentinel + review before Phase 7 | Fix findings, re-run |
616
753
  | Verification Gate | lint + types + tests + build green before commit | Fix, re-run |
617
754
 
755
+ ## Structured Output Contract (Prompt-as-API Pattern)
756
+
757
+ When cook invokes sub-skills that produce structured output (e.g., `ba` for requirements, `plan` for implementation plans, `test` for test specs), use the **Prompt-as-API-Contract** pattern: specify the exact output schema in the invocation prompt so the sub-skill returns machine-parseable results, not free-form prose.
758
+
759
+ ### Pattern
760
+
761
+ ```
762
+ INVOCATION: "Analyze [X] and return results as JSON matching this schema:
763
+ {
764
+ "insights": [{ "id": string, "category": string, "description": string, "actionable": string }],
765
+ "confidence": number,
766
+ "next_steps": string[]
767
+ }
768
+ Do NOT include explanatory text outside the JSON block."
769
+ ```
770
+
771
+ ### When to Apply
772
+
773
+ | Phase | Sub-skill | Output Contract |
774
+ |-------|-----------|----------------|
775
+ | Phase 1 | `ba` | `{ requirements: [{id, priority, description, acceptance_criteria}], ambiguities: string[] }` |
776
+ | Phase 2 | `plan` | `{ phases: [{name, tasks: [{description, files, effort}], dependencies}] }` |
777
+ | Phase 3 | `test` | `{ test_cases: [{name, type, file, assertion}], coverage_targets: string[] }` |
778
+ | Phase 5 | `review` | `{ findings: [{severity, file, line, description, fix}], verdict: "PASS"|"WARN"|"BLOCK" }` |
779
+
780
+ ### Rules
781
+
782
+ - Include 1-2 concrete examples in the prompt — examples are worth more than schema descriptions
783
+ - Always specify "Do NOT include explanatory text outside the JSON/markdown block" — LLMs default to wrapping structured output in prose
784
+ - When the output will be consumed by another skill (not displayed to user), ALWAYS use this pattern
785
+ - When the output will be displayed to the user, use markdown format instead — humans don't read JSON
786
+
787
+ ### Why
788
+
789
+ Free-form sub-skill output forces the calling skill to parse natural language — fragile and lossy. Structured contracts make skill-to-skill communication reliable, enable automated validation, and reduce the tokens wasted on parsing instructions.
790
+
618
791
  ## Output Format
619
792
 
620
793
  <MUST-READ path="references/output-format.md" trigger="before emitting the Cook Report at end of any session"/>
@@ -3,7 +3,7 @@ name: debug
3
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
4
  metadata:
5
5
  author: runedev
6
- version: "0.8.0"
6
+ version: "1.0.0"
7
7
  layer: L2
8
8
  model: sonnet
9
9
  group: development
@@ -178,6 +178,38 @@ After successful root cause identification (Step 5), append entry:
178
178
 
179
179
  This prevents re-debugging the same issue across sessions.
180
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
+
181
213
  ### Step 3: Form Hypotheses
182
214
 
183
215
  List exactly 2-3 possible root causes — no more, no fewer.
@@ -232,6 +264,21 @@ Track fix attempts in the Debug Report. If this is attempt N>1 for the same symp
232
264
  - Explain why the previous fix didn't hold
233
265
  - If N=3: trigger the escalation gate above — classify and route accordingly
234
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
+
235
282
  ### Step 7: Report
236
283
 
237
284
  Produce structured output and hand off to rune:fix.
@@ -375,6 +422,8 @@ Debug returns one of four statuses to its caller (cook, fix, test, surgeon). The
375
422
  | 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 |
376
423
  | 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 |
377
424
  | 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 |
425
+ | Re-investigating known error patterns from scratch | MEDIUM | Step 2d: match error against Known Error Pattern Catalog first — skip hypothesis cycling for recognized patterns |
426
+ | Same error fingerprint across cycles treated as different errors | MEDIUM | Step 2d: normalize line numbers, paths, variable names before comparison — same fingerprint = same error |
378
427
 
379
428
  ## Done When
380
429
 
@@ -3,7 +3,7 @@ name: docs
3
3
  description: Auto-generate and maintain project documentation. Creates README, API docs, architecture docs, changelogs, and keeps them in sync with code changes. The "docs are never outdated" skill.
4
4
  metadata:
5
5
  author: runedev
6
- version: "0.2.0"
6
+ version: "0.3.0"
7
7
  layer: L2
8
8
  model: sonnet
9
9
  group: delivery
@@ -174,9 +174,32 @@ Never silently remove doc content. If code was deleted, mark the doc section as
174
174
 
175
175
  Delegate to `rune:git changelog` to produce a changelog entry from commits since last docs update.
176
176
 
177
- #### Step 4 — Report
177
+ #### Step 4 — Cross-Doc Consistency Pass
178
178
 
179
- Show user: what was updated, what was added, what was flagged for review.
179
+ > From gstack (garrytan/gstack, 50.9k★): "Cross-document consistency prevents the #2 docs problem: docs that exist but contradict each other."
180
+
181
+ After updating any doc, verify consistency across all project documentation:
182
+
183
+ | Check | Files | What to Compare |
184
+ |-------|-------|----------------|
185
+ | **Version numbers** | README, CLAUDE.md, package.json, CHANGELOG | Must all match current version |
186
+ | **Feature lists** | README, landing page, CLAUDE.md | Same features listed (may differ in detail level) |
187
+ | **Stats** | README, CLAUDE.md, landing page, dashboard | Skill count, test count, signal count must match |
188
+ | **Commands** | README, CLAUDE.md, docs/ | Same commands with same flags |
189
+ | **Tech stack** | README, ARCHITECTURE.md, CLAUDE.md | Consistent framework/library references |
190
+
191
+ ```
192
+ Cross-Doc Consistency:
193
+ - [x] README.md ↔ CLAUDE.md: versions match, commands match
194
+ - [x] README.md ↔ docs/index.html: stats match, features match
195
+ - [ ] README.md says "61 skills" but CLAUDE.md says "59" → FIX CLAUDE.md
196
+ ```
197
+
198
+ **Fix inconsistencies immediately** — don't just report them. Update the stale doc to match the source of truth (usually the code or the most recently updated doc).
199
+
200
+ #### Step 5 — Report
201
+
202
+ Show user: what was updated, what was added, what was flagged for review. Include Cross-Doc Consistency results.
180
203
 
181
204
  ### API Mode
182
205
 
@@ -316,6 +339,8 @@ Docs Update Report:
316
339
  | API docs with wrong request/response shapes | HIGH | Extract from Zod/Pydantic/TypeScript types, not from memory |
317
340
  | Missing Quick Start section | MEDIUM | Constraint 4: every README has Quick Start |
318
341
  | Changelog with orphan PR links | LOW | Validate PR numbers exist before linking |
342
+ | Cross-document inconsistency (README says X, CLAUDE.md says Y) | HIGH | Step 7: Cross-Doc Consistency Pass — verify stats, versions, and feature lists match across all docs |
343
+ | Updating one doc but not others (stats drift) | HIGH | After any doc update, sweep all related docs for stale stats — especially README ↔ CLAUDE.md ↔ landing page |
319
344
 
320
345
  ## Done When
321
346