@rune-kit/rune 2.4.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +47 -17
  2. package/compiler/__tests__/executive-dashboards.test.js +285 -0
  3. package/compiler/__tests__/inject.test.js +128 -0
  4. package/compiler/__tests__/orchestrators.test.js +151 -0
  5. package/compiler/__tests__/org-templates.test.js +447 -0
  6. package/compiler/__tests__/pack-split.test.js +141 -1
  7. package/compiler/__tests__/parser.test.js +147 -1
  8. package/compiler/__tests__/scripts-bundling.test.js +10 -11
  9. package/compiler/__tests__/skill-index.test.js +218 -0
  10. package/compiler/__tests__/status.test.js +336 -0
  11. package/compiler/__tests__/templates.test.js +245 -0
  12. package/compiler/__tests__/visualizer.test.js +325 -0
  13. package/compiler/adapters/antigravity.js +18 -4
  14. package/compiler/bin/rune.js +90 -1
  15. package/compiler/doctor.js +283 -2
  16. package/compiler/emitter.js +490 -17
  17. package/compiler/parser.js +255 -4
  18. package/compiler/status.js +342 -0
  19. package/compiler/visualizer.js +622 -0
  20. package/hooks/hooks.json +12 -0
  21. package/hooks/intent-router/index.cjs +108 -0
  22. package/hooks/pre-tool-guard/index.cjs +177 -68
  23. package/package.json +63 -63
  24. package/skills/autopsy/SKILL.md +48 -1
  25. package/skills/brainstorm/SKILL.md +2 -0
  26. package/skills/completion-gate/SKILL.md +26 -1
  27. package/skills/context-engine/SKILL.md +93 -2
  28. package/skills/cook/SKILL.md +794 -648
  29. package/skills/debug/SKILL.md +409 -392
  30. package/skills/deploy/SKILL.md +2 -0
  31. package/skills/docs/SKILL.md +28 -3
  32. package/skills/fix/SKILL.md +284 -281
  33. package/skills/mcp-builder/SKILL.md +53 -1
  34. package/skills/onboard/SKILL.md +58 -1
  35. package/skills/perf/SKILL.md +34 -1
  36. package/skills/plan/SKILL.md +372 -342
  37. package/skills/preflight/SKILL.md +396 -360
  38. package/skills/retro/SKILL.md +95 -1
  39. package/skills/review/SKILL.md +535 -489
  40. package/skills/scope-guard/SKILL.md +1 -0
  41. package/skills/scout/SKILL.md +1 -0
  42. package/skills/sentinel/SKILL.md +353 -299
  43. package/skills/sentinel/references/policy-driven-constraints.md +424 -0
  44. package/skills/session-bridge/SKILL.md +58 -2
  45. package/skills/session-bridge/references/evolutionary-memory-patterns.md +312 -0
  46. package/skills/team/SKILL.md +16 -1
  47. package/skills/test/SKILL.md +587 -585
  48. package/skills/verification/SKILL.md +1 -0
  49. package/skills/watchdog/SKILL.md +2 -0
@@ -1,648 +1,794 @@
1
- ---
2
- name: cook
3
- description: "Feature implementation orchestrator. ALWAYS use this skill for ANY code change — implement, build, add feature, create, fix bug, or any task that modifies source code. This is the default route for 70% of all requests. Runs full TDD cycle: understand → plan → test → implement → quality → verify → commit."
4
- context: fork
5
- agent: general-purpose
6
- metadata:
7
- author: runedev
8
- version: "1.7.0"
9
- layer: L1
10
- model: sonnet
11
- group: orchestrator
12
- tools: "Read, Write, Edit, Bash, Glob, Grep"
13
- ---
14
-
15
- # cook
16
-
17
- ## Purpose
18
-
19
- The primary orchestrator for feature implementation. Coordinates the entire L2 mesh in a phased TDD workflow. Handles 70% of all user requests — any task that modifies source code routes through cook.
20
-
21
- <HARD-GATE>
22
- Before starting ANY implementation:
23
- 1. You MUST understand the codebase first (Phase 1)
24
- 2. You MUST have a plan before writing code (Phase 2)
25
- 3. You MUST write failing tests before implementation (Phase 3) — unless explicitly skipped
26
- This applies to EVERY feature regardless of perceived simplicity.
27
- </HARD-GATE>
28
-
29
- ## Workflow Chains (Predefined)
30
-
31
- Cook supports predefined workflow chains for common task types. Use these as shortcuts instead of manually determining phases:
32
-
33
- ```
34
- /rune cook feature → Full TDD pipeline (all phases)
35
- /rune cook bugfix → Diagnose → fix → verify (Phase 1 → 4 → 6 → 7)
36
- /rune cook refactor Understand plan → implement → quality (Phase 1 → 2 → 4 → 5 → 6 → 7)
37
- /rune cook security Full pipeline + sentinel@opus + sast (all phases, security-escalated)
38
- /rune cook hotfix Minimal: fixverifycommit (Phase 467, skip scout if user provides context)
39
- /rune cook nano Trivial: do verify done (no phases, ≤3 steps)
40
- ```
41
-
42
- **Chain selection**: If user invokes `/rune cook` without a chain type, auto-detect from the task description:
43
- - Contains "bug", "fix", "broken", "error" → `bugfix`
44
- - Contains "refactor", "clean", "restructure" → `refactor`
45
- - Contains "security", "auth", "vulnerability", "CVE" → `security`
46
- - Contains "urgent", "hotfix", "production" → `hotfix`
47
- - Contains "quick", "just", "chỉ cần", "copy", "move", "rename", "bump" `nano`
48
- - Default → `feature`
49
-
50
- ## Phase Skip Rules
51
-
52
- Not every task needs every phase:
53
-
54
- ```
55
- Nano task: DOVERIFYDONE (no phases, auto-detected)
56
- Simple bug fix: Phase 1467
57
- Small refactor: Phase 14567
58
- New feature: Phase 11.5 2 3 4 567 → 8
59
- Complex feature: All phases + brainstorm in Phase 2
60
- Security-sensitive: All phases + sentinel escalated to opus
61
- Fast mode: Phase 1 4 6 7 (auto-detected, see below)
62
- Multi-session: Phase 0 (resume) → 3 → 4 → 5 → 6 → 7 (one plan phase per session)
63
- ```
64
-
65
- Determine complexity BEFORE starting using the Rigor Assessment below. Create TodoWrite with applicable phases.
66
-
67
- ### Rigor Assessment (Progressive Scaling)
68
-
69
- Before selecting a workflow chain or phase set, compute the task's **rigor level** from risk signals. This prevents over-engineering trivial changes while ensuring full ceremony for critical ones.
70
-
71
- | Risk Signal | Weight | Detection |
72
- |-------------|--------|-----------|
73
- | Files affected: 1 | 0 | Estimate from task description + scout |
74
- | Files affected: 2-3 | +1 | |
75
- | Files affected: 4+ | +3 | |
76
- | Cross-module impact (changes span 2+ directories) | +2 | scout identifies touch points across boundaries |
77
- | Security-sensitive code (auth, crypto, payments, secrets) | +3 | Keyword match in file paths or task description |
78
- | Public API change (exports, routes, schema) | +2 | Task modifies interfaces consumed by external code |
79
- | Database schema change | +2 | Task mentions migration, schema, ALTER, column |
80
- | New dependency added | +1 | Task requires `npm install` or equivalent |
81
- | Code will be imported by other modules | +1 | New exports or modifications to shared utilities |
82
-
83
- **Rigor level mapping:**
84
-
85
- | Score | Level | Maps To | Phases |
86
- |-------|-------|---------|--------|
87
- | 0 | Nano | `nano` chain | DOVERIFYDONE |
88
- | 1-2 | Fast | `fast` mode | Phase 1 → 4 → 6 → 7 |
89
- | 3-5 | Standard | `bugfix` / `refactor` | Phase 1 → 2 → 4 → 5 → 6 → 7 |
90
- | 6-8 | Full | `feature` | Phase 1 → 1.5 → 2 → 3 → 4 → 5 → 6 → 7 8 |
91
- | 9+ | Critical | `security` / full + adversary | All phases + sentinel@opus + adversary |
92
-
93
- **Rules:**
94
- - Security signal (+3) automatically floors rigor at Standard NEVER nano/fast for security code
95
- - User can override: "full pipeline" forces Full, "just do it" forces Nano
96
- - If rigor upgrades mid-task (e.g., scout reveals cross-module impact not obvious from description), announce: "Rigor upgrade: [signal detected] — upgrading from Fast to Standard."
97
- - Announce chosen level: "Rigor: Fast (score 2 — single file, no security)"
98
-
99
- ## Nano Mode (Auto-Detect)
100
-
101
- For trivial tasks that don't need any pipeline at all:
102
-
103
- ```
104
- IF all of these are true:
105
- - Task is ≤3 discrete steps (e.g., run command, edit 1 file, commit)
106
- - Task description < 60 chars OR user prefixes with "quick:", "just", "chỉ cần"
107
- - No code logic changes (copy files, config edits, version bumps, git ops, run scripts)
108
- - No new functions/classes/components created
109
- THEN: Nano Mode activated
110
- - Execute directly: DO VERIFY DONE
111
- - No phases. No plan. No test. No review.
112
- - Still verify output (check exit codes, confirm file exists, etc.)
113
- - Still use semantic commit message if committing
114
- ```
115
-
116
- **Announce**: "Nano mode: trivial task, executing directly."
117
- **Override**: User can say "full pipeline" or "cook feature" to force phases.
118
- **Escape hatch**: If during execution the task turns out more complex than expectedannounce upgrade: "Upgrading to Fast/Full mode task is more complex than detected." Resume from Phase 1.
119
-
120
- <HARD-GATE>
121
- Nano mode MUST NOT be used for:
122
- - Any code that will be imported/called by other code
123
- - Security-relevant files (auth, crypto, payments, .env, secrets)
124
- - Database schema changes
125
- - Public API changes
126
- If any of these are detected mid-task, STOP and upgrade to Fast/Full mode.
127
- </HARD-GATE>
128
-
129
- ## Fast Mode (Auto-Detect)
130
-
131
- Cook auto-detects small changes and streamlines the pipeline:
132
-
133
- ```
134
- IF all of these are true:
135
- - Total estimated change < 30 LOC
136
- - Single file affected
137
- - No security-relevant code (auth, crypto, payments, .env)
138
- - No public API changes
139
- - No database schema changes
140
- THEN: Fast Mode activated
141
- - Skip Phase 2 (PLAN) change is too small for a formal plan
142
- - Skip Phase 3 (TEST) unless existing tests cover the area
143
- - Skip Phase 5b (SENTINEL) — non-security code
144
- - Skip Phase 8 (BRIDGE) — not worth persisting
145
- - KEEP Phase 5a (PREFLIGHT) and Phase 6 (VERIFY) — always run quality checks
146
- ```
147
-
148
- **Announce fast mode**: "Fast mode: small change detected (<30 LOC, single file, non-security). Streamlined pipeline."
149
- **Override**: User can say "full pipeline" to force all phases even on small changes.
150
-
151
- ## Phase 0.5: ENVIRONMENT CHECK (First Run Only)
152
-
153
- **SUB-SKILL**: Use `rune:sentinel-env` — verify the environment can run the project before planning.
154
-
155
- Auto-trigger: no `.rune/` dir (first run) OR build just failed with env-looking errors AND NOT fast mode. Skip silently on subsequent runs. Force with `/rune env-check`.
156
-
157
- ## Phase 1: UNDERSTAND
158
-
159
- **Goal**: Know what exists before changing anything.
160
-
161
- **REQUIRED SUB-SKILLS**: Use `rune:scout`. For non-trivial tasks, use `rune:ba`.
162
-
163
- 1. Create TodoWrite with all applicable phases for this task
164
- 2. Mark Phase 1 as `in_progress`
165
- 3. **BA gate**: Feature Request / Integration / Greenfield → invoke `rune:ba`. Task > 50 words or business terms (users, revenue, workflow) → invoke `rune:ba`. Bug Fix / simple Refactor → skip. BA produces `.rune/features/<name>/requirements.md` for Phase 2.
166
- 4. **Decision enforcement**: `Glob` for `.rune/decisions.md`; if exists, `Read` + extract constraints for Phase 2. Plan MUST NOT contradict active decisions without explicit user override.
167
-
168
- ### Phase 1 Step 3.5 — Clarification Gate
169
-
170
- Ask **2 questions** before planning: (1) "What does success look like?" (2) "What should NOT change?"
171
-
172
- Skip if: bug fix with clear repro steps | user said "just do it" | fast mode + <10 LOC | hotfix chain active. Complexity revealed → escalate to `rune:ba`.
173
-
174
- 5. Invoke scout to scan the codebase (Glob + Grep + Read on relevant files)
175
- 6. Summarize: what exists, project conventions, files likely to change, active decision constraints
176
- 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`
177
- 8. Mark Phase 1 as `completed`
178
-
179
- **Gate**: If scout finds the feature already exists → STOP and inform user.
180
-
181
- ## Phase 1.5: DOMAIN CONTEXT (L4 Pack Detection)
182
-
183
- **Goal**: Detect if domain-specific L4 extension packs apply to this task.
184
-
185
- <MUST-READ path="references/pack-detection.md" trigger="Phase 1.5 — before checking L4 pack mapping"/>
186
-
187
- After scout completes, check if the detected tech stack or task description matches any L4 extension pack. This phase is lightweight — a Read + pattern match. It does NOT replace Phase 1 (scout) or Phase 2 (plan). If 0 packs match: skip silently.
188
-
189
- ## Phase 1.7: WORKFLOW ORCHESTRATION (Multi-Skill Sequences)
190
-
191
- **Goal**: If Phase 1.5 detected a pack AND the task maps to a named workflow, orchestrate the multi-skill sequence.
192
-
193
- **Trigger**: Only runs if Phase 1.5 found a pack match AND the pack's Workflows table has a matching command.
194
-
195
- <MUST-READ path="references/pack-detection.md" trigger="Phase 1.7 workflow command detection section"/>
196
-
197
- 1. Read the matched PACK.md's Workflows section
198
- 2. Identify the workflow name and skill sequence
199
- 3. For each skill in sequence:
200
- a. Load the skill file from the pack's `skills/` directory
201
- b. Execute the skill's workflow steps
202
- c. Write output artifact to `.rune/<domain>/` (e.g., `.rune/hr/jd-[role]-[date].md`)
203
- d. The next skill reads the previous artifact as input context
204
- 4. After all skills complete: summarize the workflow results to the user
205
-
206
- **Threading state**: Each skill in the sequence produces an artifact file. The next skill's Step 1 reads existing artifacts from `.rune/<domain>/`. This is already built into each skill no new plumbing needed.
207
-
208
- **Skip if**: No workflow match found in Phase 1.5. Single-skill tasks proceed directly to Phase 2 (PLAN) as normal.
209
-
210
- ## Phase 0: RESUME CHECK (Before Phase 1)
211
-
212
- **Goal**: Detect if a master plan already exists for this task. If so, skip Phase 1-2 and resume from the current phase.
213
-
214
- **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"`).
215
-
216
- 1. Use `Glob` to check for `.rune/plan-*.md` files
217
- 2. If a master plan exists matching the current task: Read it → find first `⬚ Pending` or `🔄 Active` phase → load ONLY that phase file → announce "Resuming from Phase N" → skip to Phase 4
218
- 3. If no master plan exists → proceed to Phase 1 as normal
219
-
220
- **This enables multi-session workflows**: Opus plans once → each session picks up the next phase.
221
-
222
- ## Phase 2: PLAN
223
-
224
- **Goal**: Break the task into concrete implementation steps before writing code.
225
-
226
- **REQUIRED SUB-SKILL**: Use `rune:plan`
227
-
228
- 1. Mark Phase 2 as `in_progress`
229
- 2. **Feature workspace** (opt-in) — for non-trivial features (3+ phases), suggest creating `.rune/features/<feature-name>/` with `spec.md`, `plan.md`, `decisions.md`, `status.md`. Skip for simple bug fixes, fast mode.
230
- 3. Create implementation plan: exact files to create/modify, change order, dependencies, active decision constraints
231
- 4. If multiple valid approaches exist → invoke `rune:brainstorm` for trade-off analysis
232
- 5. Present plan to user for approval
233
- 6. If feature workspace was created, write approved plan to `.rune/features/<name>/plan.md`
234
- 7. Mark Phase 2 as `completed`
235
-
236
- **Gate**: User MUST approve the plan before proceeding. Do NOT skip this.
237
-
238
- ### Phase 2.5: RFC GATE (Breaking Changes Only)
239
-
240
- **Goal**: Formal change management for breaking changes. Prevents unreviewed breaking changes from reaching production.
241
-
242
- <MUST-READ path="references/rfc-template.md" trigger="Phase 2.5 any time a breaking change is detected in the plan"/>
243
-
244
- <HARD-GATE>
245
- Breaking change without RFC = BLOCKED. No exceptions.
246
- "It's just a small change" is the #1 excuse for production incidents from unreviewed breaking changes.
247
- </HARD-GATE>
248
-
249
- ### Phase 2.5: ADVERSARY (Red-Team Challenge)
250
-
251
- **Goal**: Stress-test the approved plan BEFORE writing code catch flaws at plan time, not implementation time.
252
-
253
- **REQUIRED SUB-SKILL**: Use `rune:adversary`
254
-
255
- 1. **Skip conditions**: bug fixes, hotfixes, simple refactors (< 3 files, no new logic), fast mode
256
- 2. **Run adversary**Full Red-Team mode for new features/architectural changes; Quick Challenge mode for smaller plans
257
- 3. **Handle verdict**:
258
- - **REVISE** return to Phase 2 with adversary findings as constraints; user must re-approve
259
- - **HARDEN**present remediations, update plan inline, then proceed to Phase 3
260
- - **PROCEED** pass findings as implementation notes to Phase 3
261
- 4. **Max 1 REVISE loop** per cook session — if revised plan also gets REVISE, ask user to decide
262
-
263
- ### Phase-Aware Execution (Master Plan + Phase Files)
264
-
265
- When `rune:plan` produces a **master plan + phase files** (non-trivial tasks):
266
-
267
- 1. After plan approval: load ONLY Phase 1's file — do NOT load all phase files
268
- 2. Execute through cook Phase 3-6 (test → implement → quality → verify)
269
- 3. After phase complete: mark tasks done, update master plan status `⬚ ✅`, announce "Phase N complete. Phase N+1 ready for next session."
270
- 4. Next session: Phase 0 detects master plan → loads next phase → executes
271
-
272
- <HARD-GATE>
273
- NEVER load multiple phase files at once. One phase per session = small context = better code.
274
- If the coder model needs info from other phases, it's in the Cross-Phase Context section of the current phase file.
275
- </HARD-GATE>
276
-
277
- ## Phase 3: TEST (TDD Red)
278
-
279
- **Goal**: Define expected behavior with failing tests BEFORE writing implementation.
280
-
281
- **REQUIRED SUB-SKILL**: Use `rune:test`
282
-
283
- 1. Mark Phase 3 as `in_progress`
284
- 2. **Eval definitions** (Full/Critical rigor only): Before writing tests, define capability evals (pass@k) and regression evals (pass^k) in `.rune/evals/<feature>.md`. Capability evals test "can the system do this new thing?" — regression evals test "did we break existing behavior?" Skip for Fast/Standard rigor levels.
285
- 3. Write test files based on the plan cover primary use case + edge cases; tests MUST be runnable
286
- 4. **Python async pre-check** (if async-first Python flagged in Phase 1): verify `pytest-asyncio` is installed and `asyncio_mode = "auto"` is in `pyproject.toml` — if missing, warn user before writing async tests
287
- 5. Run tests to verify they FAIL — expected: RED because implementation doesn't exist yet
288
- 6. Mark Phase 3 as `completed`
289
-
290
- **Gate**: Tests MUST exist and MUST fail. If tests pass without implementation → tests are wrong, rewrite them.
291
-
292
- ## Phase 4: IMPLEMENT (TDD Green)
293
-
294
- **Goal**: Write the minimum code to make tests pass.
295
-
296
- **REQUIRED SUB-SKILL**: Use `rune:fix`
297
-
298
- 1. Mark Phase 4 as `in_progress`
299
- 2. **Phase-file execution** — if working from a master plan + phase file:
300
- - Execute tasks from `## Tasks` section wave-by-wave
301
- - Wave N only starts after ALL Wave N-1 tasks complete
302
- - Follow Code Contracts, Rejection Criteria, Failure Scenarios from the phase file
303
- - Mark each task `[x]` as completed
304
- 3. Implement the feature following the plan (Write for new files, Edit for existing)
305
- 4. Run tests after each significant change — if fail → debug and fix
306
- - **Python async** (if async-first flagged): no blocking calls in async functions — `time.sleep` → `asyncio.sleep`, `requests` → `httpx.AsyncClient`, use `asyncio.gather()` for parallel I/O
307
- 5. If stuck invoke `rune:debug` (max 3 debug↔fix loops). Fixes outside plan scope require user approval (R4).
308
- 6. **Re-plan check** — evaluate before Phase 5: max debug loops hit? out-of-scope files changed? new dep changes approach? user scope change? If any fire → invoke `rune:plan` with delta context, get user approval before resuming.
309
- 7. **Approach Pivot Gate** — if re-plan ALSO fails:
310
-
311
- <HARD-GATE>
312
- Do NOT surrender. Do NOT tell user "no solution exists."
313
- Do NOT try a 4th variant of the same approach.
314
- MUST invoke brainstorm(mode="rescue") before giving up.
315
- </HARD-GATE>
316
-
317
- Invoke `rune:brainstorm(mode="rescue")` with `failed_approach`, `failure_evidence[]`, `original_goal`. Returns 3-5 alternatives → user picks → **restart from Phase 2**.
318
-
319
- 8. All tests MUST pass before proceeding
320
- 9. Mark Phase 4 as `completed`
321
-
322
- **Gate**: ALL tests from Phase 3 MUST pass. Do NOT proceed with failing tests.
323
-
324
- ## Phase 5: QUALITY (Staged)
325
-
326
- **Goal**: Catch issues before they reach production.
327
-
328
- Quality checks run in **two stages** — spec compliance gates code review. Reviewing code quality before verifying it matches the spec wastes effort on code that may need rewriting.
329
-
330
- ```
331
- STAGE 1 (parallel):
332
- Launch 5a (preflight) + 5b (sentinel) simultaneously.
333
- Wait for BOTH to complete.
334
- If 5a returns BLOCK → fix spec gaps, re-run 5a. Code review CANNOT start on non-compliant code.
335
- If 5b returns BLOCK fix security issue, re-run 5b.
336
-
337
- STAGE 2 (after Stage 1 passes):
338
- Launch 5c (review) + 5d (completion-gate) simultaneously.
339
- If any returns BLOCK fix findings, re-run the blocking check only.
340
- ```
341
-
342
- ### 5a. Preflight (Spec Compliance + Logic) STAGE 1
343
- **REQUIRED SUB-SKILL**: Use `rune:preflight`
344
- - Spec compliance: compare approved plan vs actual diff
345
- - Logic review, error handling, completeness
346
- - **Must pass before 5c (review) can start** — no point reviewing code quality if it doesn't match the spec
347
-
348
- ### 5b. Security — STAGE 1
349
- **REQUIRED SUB-SKILL**: Use `rune:sentinel`
350
- - Secret scan, OWASP check (no injection/XSS/CSRF), dependency audit
351
-
352
- ### 5c. Code Review STAGE 2
353
- **REQUIRED SUB-SKILL**: Use `rune:review`
354
- - Pattern compliance, code quality, performance bottlenecks
355
- - Reviewer reads code independently does NOT rely on implementer's claims
356
- - **Reviewer isolation** (when invoked via `team`): The review agent MUST be a separate context window from the implementing agent. Author reasoning contaminates review — the reviewer should never have seen the implementation's reasoning chain. Sonnet implements, a fresh Sonnet reviews.
357
-
358
- ### 5d. Completion GateSTAGE 2
359
- **REQUIRED SUB-SKILL**: Use `rune:completion-gate`
360
- - Validate agent claims match evidence trail (tests ran, files changed, build passed)
361
- - No truncated code files (`// ...`, `// rest of code`, bare ellipsis) agent MUST complete all output
362
- - Any UNCONFIRMED claim → BLOCK
363
-
364
- **Gate**: If sentinel finds CRITICAL security issue STOP, fix it, re-run. Non-negotiable.
365
- **Gate**: If completion-gate finds UNCONFIRMED claim STOP, re-verify. Non-negotiable.
366
-
367
- ## Per-Phase Rules (Project-Specific)
368
-
369
- Projects can define phase-specific rules in `.rune/phase-rules.md` that apply ONLY during specific cook phases. These are additive they enhance skill guidance, not replace it.
370
-
371
- ```markdown
372
- # .rune/phase-rules.md (example)
373
-
374
- ## Phase 2: PLAN
375
- - All API endpoints must follow REST naming convention /api/v1/<resource>
376
- - Database changes require a rollback migration
377
-
378
- ## Phase 3: TEST
379
- - Enforce TDD format: describe → it → arrange → act → assert
380
- - Minimum 3 edge cases per public function
381
-
382
- ## Phase 5: QUALITY
383
- - Review must check for N+1 queries on any ORM code
384
- - Sentinel must verify CORS configuration on new routes
385
- ```
386
-
387
- **Loading**: Cook reads `.rune/phase-rules.md` during Phase 0 (resume check). Rules for each phase are injected into the sub-skill's context when that phase starts. If file doesn't exist → skip silently.
388
-
389
- ## Checkpoint Protocol (Opt-In)
390
-
391
- Invoke `rune:session-bridge` after Phase 2, 4, and 5 to save intermediate state. OPT-IN — activate only if task spans 3+ phases, context-watch is ORANGE, or user explicitly requests checkpoints. Before spawning subagents, invoke `rune:context-pack` to create structured handoff briefings.
392
-
393
- ## Phase Transition Protocol (MANDATORY)
394
-
395
- Before entering ANY Phase N+1, assert: Phase N `completed` in TodoWrite | gate condition met | no BLOCK from sub-skills | no unresolved CRITICAL findings. If any fails → STOP, log "BLOCKED at Phase N→N+1: [assertion]", fix, re-check.
396
-
397
- **Key transitions:** 1→2: scout done | 2→3: plan approved | 3→4: failing tests exist | 4→5: all tests pass | 5→6: no CRITICAL findings | 6→7: lint+types+build green.
398
-
399
- ## Phase 6: VERIFY
400
-
401
- **REQUIRED SUB-SKILL**: Use `rune:verification` — run lint, type check, full test suite, build. Then `rune:hallucination-guard` to verify imports and API signatures. ALL checks MUST pass before commit.
402
-
403
- ## Phase 7: COMMIT
404
-
405
- **RECOMMENDED SUB-SKILL**: Use `rune:git` — stage specific files (`git add <files>`, NOT `git add .`), generate semantic commit message from diff. If working from master plan: update phase status `🔄 → ✅`, announce next phase or "All phases complete."
406
-
407
- ## Phase 8: BRIDGE
408
-
409
- **Goal**: Save context for future sessions and record metrics for mesh analytics.
410
-
411
- **REQUIRED SUB-SKILL**: Use `rune:session-bridge`
412
-
413
- 1. Mark Phase 8 as `in_progress`
414
- 2. Save to `.rune/decisions.md` (approach + trade-offs), `.rune/progress.md` (task complete), `.rune/conventions.md` (new patterns)
415
- 3. **Skill metrics** → `.rune/metrics/skills.json`: increment phase run/skip counts, quality gate results, debug loop counts under `cook` key
416
- 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.
417
- 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.
418
- 6. Mark Phase 8 as `completed`
419
-
420
- ## Autonomous Loop Patterns
421
-
422
- When cook runs inside `team` (L1) or autonomous workflows, these patterns apply.
423
-
424
- ### De-Sloppify Pass
425
-
426
- After Phase 4 completes (all tests green), run a **separate focused cleanup pass** on all modified files. Two focused passes outperform one constrained pass — let the implementer write freely in Phase 4, then clean up here.
427
-
428
- **Trigger**: Implementation touched 3+ files OR 100+ LOC changed. Skip for nano/fast rigor.
429
-
430
- **Slop targets** (check every modified file):
431
-
432
- | Slop Type | Detection | Fix |
433
- |-----------|-----------|-----|
434
- | Leftover debug | `console.log`, `print()`, `debugger`, `TODO: remove` | Delete |
435
- | Over-defensive checks | Null checks on values guaranteed non-null by TypeScript/framework | Remove redundant guard |
436
- | Type-test slop | `typeof x === 'string'` when x is already typed as string | Remove — trust the type system |
437
- | Duplicated logic | Same 3+ lines appear in multiple places | Extract utility |
438
- | Framework-behavior tests | Tests asserting that React renders, that Express routes exist, that mocks work | Delete — test YOUR code, not the framework |
439
- | Inconsistent naming | Mixed `camelCase`/`snake_case` in same file | Normalize to project convention |
440
- | Dead imports | Imports no longer used after edits | Remove |
441
-
442
- **Important**: This is NOT a quality gate — it's a cleanup pass. Don't block the pipeline for cosmetic issues. Fix what you find, move on.
443
-
444
- ### Continuous PR Loop (team orchestration only)
445
-
446
- ```
447
- cook instance commit pushcreate PRwait CI
448
- IF CI passes → mark workstream complete
449
- IF CI failsread CI outputfixpushwait CI (max 3 retries)
450
- IF 3 retries fail → escalate to user with CI logs
451
- ```
452
-
453
- ### Formal Pause/Resume (`.continue-here.md`)
454
-
455
- <MUST-READ path="references/pause-resume-template.md" trigger="when cook must pause mid-phase (context limit, user break, session end)"/>
456
-
457
- When cook must pause mid-phase, create `.rune/.continue-here.md` with structured handoff, then WIP commit. Phase 0 detects it on resume. More granular than plan-level resume resumes within a phase.
458
-
459
- ### Mid-Run Signal Detection
460
-
461
- <MUST-READ path="references/mid-run-signals.md" trigger="when user sends a message DURING cook execution"/>
462
-
463
- Two-stage intent classification: keyword fast-path for short messages (<60 chars), context classification for longer ones. Never queue user messages — process immediately.
464
-
465
- <HARD-GATE>
466
- NEVER treat a Cancel/Pause signal as a Steer or NewTask. User safety signals take absolute priority.
467
- If ambiguous between Cancel and Steer ask user: "Did you mean stop, or change approach?"
468
- </HARD-GATE>
469
-
470
- ### Exit Conditions (Mandatory for Autonomous Runs)
471
-
472
- <MUST-READ path="references/exit-conditions.md" trigger="cook running inside team or any autonomous workflow"/>
473
-
474
- Hard caps: MAX_DEBUG_LOOPS=3, MAX_QUALITY_LOOPS=2, MAX_REPLAN=1, MAX_PIVOT=1, MAX_FIXES=30, WTF_THRESHOLD=20%.
475
- Escalation chain: debug-fix (3x) → re-plan (1x) → brainstorm rescue (1x) → THEN escalate to user.
476
-
477
- ### Subagent Status Protocol
478
-
479
- <MUST-READ path="references/subagent-status.md" trigger="when cook or any sub-skill needs to return a status"/>
480
-
481
- Cook and all sub-skills return: `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED`.
482
-
483
- ### Subagent Context Isolation
484
-
485
- When invoking sub-skills (fix, debug, test, review, etc.), **craft exactly the context they need** — never pass the full orchestrator session context.
486
-
487
- | Pass To Sub-Skill | DO NOT Pass |
488
- |-------------------|-------------|
489
- | Task description + specific goal | Full conversation history |
490
- | Relevant file paths from scout | Unrelated files from other phases |
491
- | Project conventions (naming, test framework) | Other sub-skill outputs |
492
- | Plan excerpt for THIS phase only | Full master plan |
493
- | Error/stack trace (for debug/fix) | Previous debug attempts from other bugs |
494
-
495
- **Why**: Sub-skills that inherit orchestrator context get polluted — they chase false connections, reference stale data, and consume tokens on irrelevant context. A focused sub-skill with 500 tokens of curated context outperforms one with 5000 tokens of inherited noise.
496
-
497
- ## Deviation Rules
498
-
499
- <MUST-READ path="references/deviation-rules.md" trigger="when implementation diverges from the approved plan"/>
500
-
501
- R1-R3 (bug/security/blocking fix): auto-fix, continue. R4 (architectural change): ASK user first.
502
-
503
- ## Error Recovery
504
-
505
- <MUST-READ path="references/error-recovery.md" trigger="when any phase fails or a task hits repeated errors"/>
506
-
507
- Includes phase-by-phase failure handling and repair operators (RETRY DECOMPOSEPRUNE) with a 2-attempt budget before escalation.
508
-
509
- ## Analysis Paralysis Guard
510
-
511
- <HARD-GATE>
512
- 5+ consecutive read-only tool calls (Read, Grep, Glob) without a single write action (Edit, Write, Bash) = STUCK.
513
-
514
- You MUST either:
515
- 1. **Act** write code, run a command, create a file
516
- 2. **Report BLOCKED** — state the specific missing piece: "Cannot proceed because [X]"
517
-
518
- Stuck patterns (all banned):
519
- - Reading 10+ files to "fully understand" before acting
520
- - Grepping every variation of a string across the entire repo
521
- - Reading the same file twice in one investigation
522
- - "Let me check one more thing" — repeated after 5 reads
523
-
524
- A wrong first attempt that produces feedback beats perfect understanding that never ships.
525
- </HARD-GATE>
526
-
527
- ### Hash-Based Tool Loop Detection
528
-
529
- <MUST-READ path="references/loop-detection.md" trigger="when same tool+args+result appears to be repeating"/>
530
-
531
- Mentally track tool call fingerprints. 3 identical calls → WARN. 5 identical calls → FORCE STOP. Only same-input-AND-same-output counts as a loop.
532
-
533
- ## Called By (inbound)
534
-
535
- - User: `/rune cook` direct invocation primary entry point
536
- - `team` (L1): parallel workstream execution (meta-orchestration)
537
-
538
- ## Calls (outbound)
539
-
540
- | Phase | Sub-skill | Layer | Purpose |
541
- |-------|-----------|-------|---------|
542
- | 0 / 8 | `neural-memory` | ext | Recall context at start; capture learnings at end |
543
- | 0.5 | `sentinel-env` | L3 | Environment pre-flight (first run only) |
544
- | 1 | `scout` | L2 | Scan codebase before planning |
545
- | 1 | `onboard` | L2 | Initialize project context if no CLAUDE.md |
546
- | 1 | `ba` | L2 | Requirement elicitation for features |
547
- | 2 | `plan` | L2 | Create implementation plan |
548
- | 2 | `brainstorm` | L2 | Trade-off analysis / rescue mode |
549
- | 2 | `design` | L2 | UI/design phase for frontend features |
550
- | 2.5 | `adversary` | L2 | Red-team challenge on approved plan |
551
- | 3 | `test` | L2 | Write failing tests (RED phase) |
552
- | 4 | `fix` | L2 | Implement code changes (GREEN phase) |
553
- | 4 | `debug` | L2 | Unexpected errors (max 3 loops) |
554
- | 4 | `db` | L2 | Schema changes detected in diff |
555
- | 4 | `worktree` | L3 | Worktree isolation for parallel implementation |
556
- | 5a | `preflight` | L2 | Spec compliance + logic review |
557
- | 5b | `sentinel` | L2 | Security scan |
558
- | 5c | `review` | L2 | Code quality review |
559
- | 5 | `perf` | L2 | Performance regression check (optional) |
560
- | 5 | `audit` | L2 | Project health audit when scope warrants |
561
- | 5 | `review-intake` | L2 | Structured review intake for complex PRs |
562
- | 5 | `sast` | L3 | Static analysis security testing |
563
- | 5d | `completion-gate` | L3 | Validate agent claims against evidence trail |
564
- | 5 | `constraint-check` | L3 | Audit HARD-GATE compliance across workflow |
565
- | 6 | `verification` | L3 | Lint + types + tests + build |
566
- | 6 | `hallucination-guard` | L3 | Verify imports and API calls are real |
567
- | 7 | `journal` | L3 | Record architectural decisions |
568
- | 8 | `session-bridge` | L3 | Save context for future sessions |
569
- | any | `context-pack` | L3 | create structured handoff briefings before spawning subagents |
570
- | any | `skill-forge` | L2 | When new skill creation detected during cook |
571
- | 1.5 | L4 extension packs | L4 | Domain-specific patterns when stack matches |
572
-
573
- ## Data Flow
574
-
575
- **Feeds Into →** `journal` (decisions → ADRs) | `session-bridge` (context → .rune/ state) | `neural-memory` (learnings → cross-session)
576
-
577
- **Fed By ←** `ba` (requirements → Phase 1) | `plan` (master plan Phase 2-4) | `session-bridge` (.continue-here.md Phase 0 resume) | `neural-memory` (past decisions → Phase 0 recall)
578
-
579
- **Feedback Loops ↻** cook↔debug (Phase 4 bug → debug → fix resume; if plan wrong Approach Pivot) | cook↔test (RED GREEN failures loop back)
580
-
581
- ## Constraints
582
-
583
- 1. MUST run scout before planning
584
- 2. MUST get user plan approval before writing code
585
- 3. MUST write failing tests before implementation (TDD) unless explicitly skipped
586
- 4. MUST NOT commit with failing tests
587
- 5. MUST NOT modify files outside approved plan scope without user confirmation
588
- 6. MUST run verification (lint + type-check + tests + build) before commit
589
- 7. MUST NOT say "all tests pass" without showing actual test output
590
- 8. MUST NOT contradict `.rune/decisions.md` without explicit user override
591
-
592
- ## Mesh Gates
593
-
594
- | Gate | Requires | If Missing |
595
- |------|----------|------------|
596
- | Resume Gate | Phase 0 checks for master plan before starting | Proceed to Phase 1 |
597
- | Scout Gate | scout output before Phase 2 | Invoke rune:scout first |
598
- | Plan Gate | User-approved plan before Phase 3 | Cannot proceed |
599
- | Adversary Gate | adversary verdict before Phase 3 for features | Skip for bugfix/hotfix/refactor |
600
- | Phase File Gate | Active phase file only (multi-session) | Load only active phase |
601
- | Test-First Gate | Failing tests before Phase 4 | Write tests or get explicit skip |
602
- | Quality Gate | preflight + sentinel + review before Phase 7 | Fix findings, re-run |
603
- | Verification Gate | lint + types + tests + build green before commit | Fix, re-run |
604
-
605
- ## Output Format
606
-
607
- <MUST-READ path="references/output-format.md" trigger="before emitting the Cook Report at end of any session"/>
608
-
609
- Emit a Cook Report with: Status, Phases, Files Changed, Tests, Quality results, Commit hash.
610
- When invoked by `team` with a NEXUS Handoff, include the Deliverables table — MANDATORY.
611
-
612
- ## Returns
613
-
614
- | Artifact | Format | Location |
615
- |----------|--------|----------|
616
- | Plan files (master + phase) | Markdown | `.rune/plan-<feature>.md`, `.rune/plan-<feature>-phase<N>.md` |
617
- | Implementation code | Source files | Per plan file paths |
618
- | Test files | Source files | Co-located or `__tests__/` per project convention |
619
- | Verification results | Inline stdout | Shown in Cook Report |
620
- | Cook Report | Markdown (inline) | Emitted at end of session |
621
- | Session state | Markdown | `.rune/decisions.md`, `.rune/progress.md`, `.rune/conventions.md` |
622
-
623
- ## Sharp Edges
624
-
625
- <MUST-READ path="references/sharp-edges.md" trigger="before declaring done review all 18 failure modes"/>
626
-
627
- **CRITICAL failures** (always check): skipping scout | writing code without plan approval | "done" without evidence trail | surrendering without Approach Pivot Gate | breaking change without RFC | treating Cancel/Pause as scope change.
628
-
629
- ## Self-Validation
630
-
631
- ```
632
- SELF-VALIDATION (run before emitting Cook Report):
633
- - [ ] Every phase in Phase Skip Rules was either executed or explicitly skipped with reason
634
- - [ ] Plan approval gate was not bypassed user said "go" (check conversation history)
635
- - [ ] No Phase 4 code was written before Phase 3 tests (TDD order preserved)
636
- - [ ] All Phase 5 quality gates (preflight, sentinel, review) ran — not just claimed
637
- - [ ] Cook Report contains actual commit hash, not placeholder
638
- ```
639
-
640
- ## Done When
641
-
642
- All applicable phases complete + Self-Validation passed:
643
- - User approved plan | All tests PASS (output shown) | preflight+sentinel+review PASS | build green
644
- - Cook Report emitted with commit hash | Session state saved to .rune/ via session-bridge
645
-
646
- ## Cost Profile
647
-
648
- ~$0.05-0.15 per feature. Haiku for scanning (Phase 1), sonnet for coding (Phase 3-4), opus for complex planning (Phase 2 when needed).
1
+ ---
2
+ name: cook
3
+ description: "Feature implementation orchestrator. ALWAYS use this skill for ANY code change — implement, build, add feature, create, fix bug, or any task that modifies source code. This is the default route for 70% of all requests. Runs full TDD cycle: understand → plan → test → implement → quality → verify → commit."
4
+ context: fork
5
+ agent: general-purpose
6
+ metadata:
7
+ author: runedev
8
+ version: "2.0.0"
9
+ layer: L1
10
+ model: sonnet
11
+ group: orchestrator
12
+ tools: "Read, Write, Edit, Bash, Glob, Grep"
13
+ emit: phase.complete
14
+ listen: plan.ready, review.complete
15
+ ---
16
+
17
+ # cook
18
+
19
+ ## Purpose
20
+
21
+ The primary orchestrator for feature implementation. Coordinates the entire L2 mesh in a phased TDD workflow. Handles 70% of all user requests — any task that modifies source code routes through cook.
22
+
23
+ <HARD-GATE>
24
+ Before starting ANY implementation:
25
+ 1. You MUST understand the codebase first (Phase 1)
26
+ 2. You MUST have a plan before writing code (Phase 2)
27
+ 3. You MUST write failing tests before implementation (Phase 3) — unless explicitly skipped
28
+ This applies to EVERY feature regardless of perceived simplicity.
29
+ </HARD-GATE>
30
+
31
+ ## Workflow Chains (Predefined)
32
+
33
+ Cook supports predefined workflow chains for common task types. Use these as shortcuts instead of manually determining phases:
34
+
35
+ ```
36
+ /rune cook feature Full TDD pipeline (all phases)
37
+ /rune cook bugfix Diagnose fix verify (Phase 1 → 4 → 6 → 7)
38
+ /rune cook refactor Understand plan implementquality (Phase 124 5 6 7)
39
+ /rune cook security Full pipeline + sentinel@opus + sast (all phases, security-escalated)
40
+ /rune cook hotfix → Minimal: fix → verify → commit (Phase 4 → 6 → 7, skip scout if user provides context)
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
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 messagingsequence 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: triagediagnosefixverifypostmortem → KB update
58
+ /rune cook --template support-kb-refresh Pro: auditgap analysisdraftreviewpublish
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
+
70
+ **Chain selection**: If user invokes `/rune cook` without a chain type, auto-detect from the task description:
71
+ - Contains "bug", "fix", "broken", "error" `bugfix`
72
+ - Contains "refactor", "clean", "restructure" → `refactor`
73
+ - Contains "security", "auth", "vulnerability", "CVE" `security`
74
+ - Contains "urgent", "hotfix", "production" `hotfix`
75
+ - Contains "quick", "just", "chỉ cần", "copy", "move", "rename", "bump" → `nano`
76
+ - Contains `--template` load template workflow (see above)
77
+ - Default `feature`
78
+
79
+ ## Phase Skip Rules
80
+
81
+ Not every task needs every phase:
82
+
83
+ ```
84
+ Nano task: DO → VERIFY → DONE (no phases, auto-detected)
85
+ Simple bug fix: Phase 1 4 6 7
86
+ Small refactor: Phase 1 → 4 → 5 → 6 → 7
87
+ New feature: Phase 1 1.5 2 345 → 6 → 7 → 8
88
+ Complex feature: All phases + brainstorm in Phase 2
89
+ Security-sensitive: All phases + sentinel escalated to opus
90
+ Fast mode: Phase 1 → 4 → 6 → 7 (auto-detected, see below)
91
+ Multi-session: Phase 0 (resume) 3 4 5 6 7 (one plan phase per session)
92
+ ```
93
+
94
+ Determine complexity BEFORE starting using the Rigor Assessment below. Create TodoWrite with applicable phases.
95
+
96
+ ### Rigor Assessment (Progressive Scaling)
97
+
98
+ Before selecting a workflow chain or phase set, compute the task's **rigor level** from risk signals. This prevents over-engineering trivial changes while ensuring full ceremony for critical ones.
99
+
100
+ | Risk Signal | Weight | Detection |
101
+ |-------------|--------|-----------|
102
+ | Files affected: 1 | 0 | Estimate from task description + scout |
103
+ | Files affected: 2-3 | +1 | |
104
+ | Files affected: 4+ | +3 | |
105
+ | Cross-module impact (changes span 2+ directories) | +2 | scout identifies touch points across boundaries |
106
+ | Security-sensitive code (auth, crypto, payments, secrets) | +3 | Keyword match in file paths or task description |
107
+ | Public API change (exports, routes, schema) | +2 | Task modifies interfaces consumed by external code |
108
+ | Database schema change | +2 | Task mentions migration, schema, ALTER, column |
109
+ | New dependency added | +1 | Task requires `npm install` or equivalent |
110
+ | Code will be imported by other modules | +1 | New exports or modifications to shared utilities |
111
+
112
+ **Rigor level mapping:**
113
+
114
+ | Score | Level | Maps To | Phases |
115
+ |-------|-------|---------|--------|
116
+ | 0 | Nano | `nano` chain | DO → VERIFY → DONE |
117
+ | 1-2 | Fast | `fast` mode | Phase 1 4 → 6 → 7 |
118
+ | 3-5 | Standard | `bugfix` / `refactor` | Phase 1 24 5 6 7 |
119
+ | 6-8 | Full | `feature` | Phase 1 → 1.5 → 2 → 3 → 4 → 5 → 6 → 7 → 8 |
120
+ | 9+ | Critical | `security` / full + adversary | All phases + sentinel@opus + adversary |
121
+
122
+ **Rules:**
123
+ - Security signal (+3) automatically floors rigor at Standard — NEVER nano/fast for security code
124
+ - User can override: "full pipeline" forces Full, "just do it" forces Nano
125
+ - If rigor upgrades mid-task (e.g., scout reveals cross-module impact not obvious from description), announce: "Rigor upgrade: [signal detected] — upgrading from Fast to Standard."
126
+ - Announce chosen level: "Rigor: Fast (score 2 single file, no security)"
127
+
128
+ ## Nano Mode (Auto-Detect)
129
+
130
+ For trivial tasks that don't need any pipeline at all:
131
+
132
+ ```
133
+ IF all of these are true:
134
+ - Task is ≤3 discrete steps (e.g., run command, edit 1 file, commit)
135
+ - Task description < 60 chars OR user prefixes with "quick:", "just", "chỉ cần"
136
+ - No code logic changes (copy files, config edits, version bumps, git ops, run scripts)
137
+ - No new functions/classes/components created
138
+ THEN: Nano Mode activated
139
+ - Execute directly: DO → VERIFY → DONE
140
+ - No phases. No plan. No test. No review.
141
+ - Still verify output (check exit codes, confirm file exists, etc.)
142
+ - Still use semantic commit message if committing
143
+ ```
144
+
145
+ **Announce**: "Nano mode: trivial task, executing directly."
146
+ **Override**: User can say "full pipeline" or "cook feature" to force phases.
147
+ **Escape hatch**: If during execution the task turns out more complex than expected → announce upgrade: "Upgrading to Fast/Full mode — task is more complex than detected." Resume from Phase 1.
148
+
149
+ <HARD-GATE>
150
+ Nano mode MUST NOT be used for:
151
+ - Any code that will be imported/called by other code
152
+ - Security-relevant files (auth, crypto, payments, .env, secrets)
153
+ - Database schema changes
154
+ - Public API changes
155
+ If any of these are detected mid-task, STOP and upgrade to Fast/Full mode.
156
+ </HARD-GATE>
157
+
158
+ ## Fast Mode (Auto-Detect)
159
+
160
+ Cook auto-detects small changes and streamlines the pipeline:
161
+
162
+ ```
163
+ IF all of these are true:
164
+ - Total estimated change < 30 LOC
165
+ - Single file affected
166
+ - No security-relevant code (auth, crypto, payments, .env)
167
+ - No public API changes
168
+ - No database schema changes
169
+ THEN: Fast Mode activated
170
+ - Skip Phase 2 (PLAN) change is too small for a formal plan
171
+ - Skip Phase 3 (TEST) — unless existing tests cover the area
172
+ - Skip Phase 5b (SENTINEL) non-security code
173
+ - Skip Phase 8 (BRIDGE) — not worth persisting
174
+ - KEEP Phase 5a (PREFLIGHT) and Phase 6 (VERIFY) always run quality checks
175
+ ```
176
+
177
+ **Announce fast mode**: "Fast mode: small change detected (<30 LOC, single file, non-security). Streamlined pipeline."
178
+ **Override**: User can say "full pipeline" to force all phases even on small changes.
179
+
180
+ ## Phase 0.5: ENVIRONMENT CHECK (First Run Only)
181
+
182
+ **SUB-SKILL**: Use `rune:sentinel-env` — verify the environment can run the project before planning.
183
+
184
+ Auto-trigger: no `.rune/` dir (first run) OR build just failed with env-looking errors AND NOT fast mode. Skip silently on subsequent runs. Force with `/rune env-check`.
185
+
186
+ ## Phase 1: UNDERSTAND
187
+
188
+ **Goal**: Know what exists before changing anything.
189
+
190
+ **REQUIRED SUB-SKILLS**: Use `rune:scout`. For non-trivial tasks, use `rune:ba`.
191
+
192
+ 1. Create TodoWrite with all applicable phases for this task
193
+ 2. Mark Phase 1 as `in_progress`
194
+ 3. **BA gate**: Feature Request / Integration / Greenfield → invoke `rune:ba`. Task > 50 words or business terms (users, revenue, workflow) → invoke `rune:ba`. Bug Fix / simple Refactor → skip. BA produces `.rune/features/<name>/requirements.md` for Phase 2.
195
+ 4. **Decision enforcement**: `Glob` for `.rune/decisions.md`; if exists, `Read` + extract constraints for Phase 2. Plan MUST NOT contradict active decisions without explicit user override.
196
+ 4b. **Contract enforcement**: If `.rune/contract.md` was loaded in Phase 0.6, list applicable contract sections for this task (e.g., `contract.security` for auth work, `contract.data` for database changes). These rules constrain Phase 2 planning and Phase 4 implementation.
197
+
198
+ ### Phase 1 Step 3.5 Clarification Gate
199
+
200
+ Ask **2 questions** before planning: (1) "What does success look like?" (2) "What should NOT change?"
201
+
202
+ Skip if: bug fix with clear repro steps | user said "just do it" | fast mode + <10 LOC | hotfix chain active. Complexity revealed escalate to `rune:ba`.
203
+
204
+ 5. Invoke scout to scan the codebase (Glob + Grep + Read on relevant files)
205
+ 6. Summarize: what exists, project conventions, files likely to change, active decision constraints
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`
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`
212
+
213
+ **Gate**: If scout finds the feature already exists → STOP and inform user.
214
+
215
+ ## Phase 1.5: DOMAIN CONTEXT (L4 Pack Detection)
216
+
217
+ **Goal**: Detect if domain-specific L4 extension packs apply to this task.
218
+
219
+ <MUST-READ path="references/pack-detection.md" trigger="Phase 1.5 — before checking L4 pack mapping"/>
220
+
221
+ After scout completes, check if the detected tech stack or task description matches any L4 extension pack. This phase is lightweight — a Read + pattern match. It does NOT replace Phase 1 (scout) or Phase 2 (plan). If 0 packs match: skip silently.
222
+
223
+ ## Phase 1.7: WORKFLOW ORCHESTRATION (Multi-Skill Sequences)
224
+
225
+ **Goal**: If Phase 1.5 detected a pack AND the task maps to a named workflow, orchestrate the multi-skill sequence.
226
+
227
+ **Trigger**: Only runs if Phase 1.5 found a pack match AND the pack's Workflows table has a matching command.
228
+
229
+ <MUST-READ path="references/pack-detection.md" trigger="Phase 1.7 workflow command detection section"/>
230
+
231
+ 1. Read the matched PACK.md's Workflows section
232
+ 2. Identify the workflow name and skill sequence
233
+ 3. For each skill in sequence:
234
+ a. Load the skill file from the pack's `skills/` directory
235
+ b. Execute the skill's workflow steps
236
+ c. Write output artifact to `.rune/<domain>/` (e.g., `.rune/hr/jd-[role]-[date].md`)
237
+ d. The next skill reads the previous artifact as input context
238
+ 4. After all skills complete: summarize the workflow results to the user
239
+
240
+ **Threading state**: Each skill in the sequence produces an artifact file. The next skill's Step 1 reads existing artifacts from `.rune/<domain>/`. This is already built into each skill — no new plumbing needed.
241
+
242
+ **Skip if**: No workflow match found in Phase 1.5. Single-skill tasks proceed directly to Phase 2 (PLAN) as normal.
243
+
244
+ ## Phase 0: RESUME CHECK (Before Phase 1)
245
+
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
255
+
256
+ **Step 0.5Cross-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"`).
257
+
258
+ 1. Use `Glob` to check for `.rune/plan-*.md` files
259
+ 2. If a master plan exists matching the current task: Read it find first `⬚ Pending` or `🔄 Active` phase → load ONLY that phase file → announce "Resuming from Phase N" → skip to Phase 4
260
+ 3. If no master plan exists proceed to Phase 1 as normal
261
+
262
+ **Step 0.6 — Contract Load**: Use `Glob` to check for `.rune/contract.md`. If it exists:
263
+ 1. `Read` the contract file and parse each `## section` as a named rule set
264
+ 2. Hold contract rules in context — they apply as **hard gates** throughout all phases
265
+ 3. Any code change that violates a contract rule STOP and inform user before proceeding
266
+ 4. If no contract exists → proceed normally (contract is optional)
267
+
268
+ <HARD-GATE>
269
+ Contract violations are NON-NEGOTIABLE. If `.rune/contract.md` exists and a planned or implemented change violates any rule, cook MUST stop and report the violation. The user must explicitly override ("ignore contract rule X") to proceed.
270
+ </HARD-GATE>
271
+
272
+ **This enables multi-session workflows**: Opus plans once → each session picks up the next phase.
273
+
274
+ ## Phase 2: PLAN
275
+
276
+ **Goal**: Break the task into concrete implementation steps before writing code.
277
+
278
+ **REQUIRED SUB-SKILL**: Use `rune:plan`
279
+
280
+ 1. Mark Phase 2 as `in_progress`
281
+ 2. **Feature workspace** (opt-in) for non-trivial features (3+ phases), suggest creating `.rune/features/<feature-name>/` with `spec.md`, `plan.md`, `decisions.md`, `status.md`. Skip for simple bug fixes, fast mode.
282
+ 3. Create implementation plan: exact files to create/modify, change order, dependencies, active decision constraints
283
+ 4. If multiple valid approaches exist → invoke `rune:brainstorm` for trade-off analysis
284
+ 5. Present plan to user for approval
285
+ 6. If feature workspace was created, write approved plan to `.rune/features/<name>/plan.md`
286
+ 7. Mark Phase 2 as `completed`
287
+
288
+ **Gate**: User MUST approve the plan before proceeding. Do NOT skip this.
289
+
290
+ ### Phase 2.5: RFC GATE (Breaking Changes Only)
291
+
292
+ **Goal**: Formal change management for breaking changes. Prevents unreviewed breaking changes from reaching production.
293
+
294
+ <MUST-READ path="references/rfc-template.md" trigger="Phase 2.5 any time a breaking change is detected in the plan"/>
295
+
296
+ <HARD-GATE>
297
+ Breaking change without RFC = BLOCKED. No exceptions.
298
+ "It's just a small change" is the #1 excuse for production incidents from unreviewed breaking changes.
299
+ </HARD-GATE>
300
+
301
+ ### Phase 2.5: ADVERSARY (Red-Team Challenge)
302
+
303
+ **Goal**: Stress-test the approved plan BEFORE writing code — catch flaws at plan time, not implementation time.
304
+
305
+ **REQUIRED SUB-SKILL**: Use `rune:adversary`
306
+
307
+ 1. **Skip conditions**: bug fixes, hotfixes, simple refactors (< 3 files, no new logic), fast mode
308
+ 2. **Run adversary** — Full Red-Team mode for new features/architectural changes; Quick Challenge mode for smaller plans
309
+ 3. **Handle verdict**:
310
+ - **REVISE** → return to Phase 2 with adversary findings as constraints; user must re-approve
311
+ - **HARDEN** → present remediations, update plan inline, then proceed to Phase 3
312
+ - **PROCEED** pass findings as implementation notes to Phase 3
313
+ 4. **Max 1 REVISE loop** per cook session if revised plan also gets REVISE, ask user to decide
314
+
315
+ ### Phase-Aware Execution (Master Plan + Phase Files)
316
+
317
+ When `rune:plan` produces a **master plan + phase files** (non-trivial tasks):
318
+
319
+ 1. After plan approval: load ONLY Phase 1's file — do NOT load all phase files
320
+ 2. Execute through cook Phase 3-6 (test → implement → quality → verify)
321
+ 3. After phase complete: mark tasks done, update master plan status `⬚ → ✅`, announce "Phase N complete. Phase N+1 ready for next session."
322
+ 4. Next session: Phase 0 detects master plan loads next phase → executes
323
+
324
+ <HARD-GATE>
325
+ NEVER load multiple phase files at once. One phase per session = small context = better code.
326
+ If the coder model needs info from other phases, it's in the Cross-Phase Context section of the current phase file.
327
+ </HARD-GATE>
328
+
329
+ ## Phase 3: TEST (TDD Red)
330
+
331
+ **Goal**: Define expected behavior with failing tests BEFORE writing implementation.
332
+
333
+ **REQUIRED SUB-SKILL**: Use `rune:test`
334
+
335
+ 1. Mark Phase 3 as `in_progress`
336
+ 2. **Eval definitions** (Full/Critical rigor only): Before writing tests, define capability evals (pass@k) and regression evals (pass^k) in `.rune/evals/<feature>.md`. Capability evals test "can the system do this new thing?" — regression evals test "did we break existing behavior?" Skip for Fast/Standard rigor levels.
337
+ 3. Write test files based on the plan — cover primary use case + edge cases; tests MUST be runnable
338
+ 4. **Python async pre-check** (if async-first Python flagged in Phase 1): verify `pytest-asyncio` is installed and `asyncio_mode = "auto"` is in `pyproject.toml` — if missing, warn user before writing async tests
339
+ 5. Run tests to verify they FAIL expected: RED because implementation doesn't exist yet
340
+ 6. Mark Phase 3 as `completed`
341
+
342
+ **Gate**: Tests MUST exist and MUST fail. If tests pass without implementation tests are wrong, rewrite them.
343
+
344
+ ## Phase 4: IMPLEMENT (TDD Green)
345
+
346
+ **Goal**: Write the minimum code to make tests pass.
347
+
348
+ **REQUIRED SUB-SKILL**: Use `rune:fix`
349
+
350
+ 1. Mark Phase 4 as `in_progress`
351
+ 2. **Phase-file execution** — if working from a master plan + phase file:
352
+ - Execute tasks from `## Tasks` section wave-by-wave
353
+ - Wave N only starts after ALL Wave N-1 tasks complete
354
+ - Follow Code Contracts, Rejection Criteria, Failure Scenarios from the phase file
355
+ - Mark each task `[x]` as completed
356
+ 3. Implement the feature following the plan (Write for new files, Edit for existing)
357
+ 4. Run tests after each significant change — if fail → debug and fix
358
+ - **Python async** (if async-first flagged): no blocking calls in async functions `time.sleep` → `asyncio.sleep`, `requests` → `httpx.AsyncClient`, use `asyncio.gather()` for parallel I/O
359
+ 5. If stuck → invoke `rune:debug` (max 3 debug↔fix loops). Fixes outside plan scope require user approval (R4).
360
+ 6. **Re-plan check** evaluate before Phase 5: max debug loops hit? out-of-scope files changed? new dep changes approach? user scope change? If any fire → invoke `rune:plan` with delta context, get user approval before resuming.
361
+ 7. **Approach Pivot Gate**if re-plan ALSO fails:
362
+
363
+ <HARD-GATE>
364
+ Do NOT surrender. Do NOT tell user "no solution exists."
365
+ Do NOT try a 4th variant of the same approach.
366
+ MUST invoke brainstorm(mode="rescue") before giving up.
367
+ </HARD-GATE>
368
+
369
+ Invoke `rune:brainstorm(mode="rescue")` with `failed_approach`, `failure_evidence[]`, `original_goal`. Returns 3-5 alternatives user picks **restart from Phase 2**.
370
+
371
+ 8. All tests MUST pass before proceeding
372
+ 9. Mark Phase 4 as `completed`
373
+
374
+ **Gate**: ALL tests from Phase 3 MUST pass. Do NOT proceed with failing tests.
375
+
376
+ ## Phase 5: QUALITY (Staged)
377
+
378
+ **Goal**: Catch issues before they reach production.
379
+
380
+ Quality checks run in **two stages** spec compliance gates code review. Reviewing code quality before verifying it matches the spec wastes effort on code that may need rewriting.
381
+
382
+ ```
383
+ STAGE 1 (parallel):
384
+ Launch 5a (preflight) + 5b (sentinel) simultaneously.
385
+ Wait for BOTH to complete.
386
+ If 5a returns BLOCK → fix spec gaps, re-run 5a. Code review CANNOT start on non-compliant code.
387
+ If 5b returns BLOCK fix security issue, re-run 5b.
388
+
389
+ STAGE 2 (after Stage 1 passes):
390
+ Launch 5c (review) + 5d (completion-gate) simultaneously.
391
+ If any returns BLOCK fix findings, re-run the blocking check only.
392
+ ```
393
+
394
+ ### 5a. Preflight (Spec Compliance + Logic) — STAGE 1
395
+ **REQUIRED SUB-SKILL**: Use `rune:preflight`
396
+ - Spec compliance: compare approved plan vs actual diff
397
+ - Logic review, error handling, completeness
398
+ - **Must pass before 5c (review) can start** — no point reviewing code quality if it doesn't match the spec
399
+
400
+ ### 5b. Security — STAGE 1
401
+ **REQUIRED SUB-SKILL**: Use `rune:sentinel`
402
+ - Secret scan, OWASP check (no injection/XSS/CSRF), dependency audit
403
+
404
+ ### 5c. Code Review — STAGE 2
405
+ **REQUIRED SUB-SKILL**: Use `rune:review`
406
+ - Pattern compliance, code quality, performance bottlenecks
407
+ - Reviewer reads code independently — does NOT rely on implementer's claims
408
+ - **Reviewer isolation** (when invoked via `team`): The review agent MUST be a separate context window from the implementing agent. Author reasoning contaminates review — the reviewer should never have seen the implementation's reasoning chain. Sonnet implements, a fresh Sonnet reviews.
409
+
410
+ ### 5d. Completion Gate — STAGE 2
411
+ **REQUIRED SUB-SKILL**: Use `rune:completion-gate`
412
+ - Validate agent claims match evidence trail (tests ran, files changed, build passed)
413
+ - No truncated code files (`// ...`, `// rest of code`, bare ellipsis) — agent MUST complete all output
414
+ - Any UNCONFIRMED claim BLOCK
415
+
416
+ **Gate**: If sentinel finds CRITICAL security issueSTOP, fix it, re-run. Non-negotiable.
417
+ **Gate**: If completion-gate finds UNCONFIRMED claim STOP, re-verify. Non-negotiable.
418
+
419
+ ## Per-Phase Rules (Project-Specific)
420
+
421
+ Projects can define phase-specific rules in `.rune/phase-rules.md` that apply ONLY during specific cook phases. These are additive — they enhance skill guidance, not replace it.
422
+
423
+ ```markdown
424
+ # .rune/phase-rules.md (example)
425
+
426
+ ## Phase 2: PLAN
427
+ - All API endpoints must follow REST naming convention /api/v1/<resource>
428
+ - Database changes require a rollback migration
429
+
430
+ ## Phase 3: TEST
431
+ - Enforce TDD format: describe → it → arrange → act → assert
432
+ - Minimum 3 edge cases per public function
433
+
434
+ ## Phase 5: QUALITY
435
+ - Review must check for N+1 queries on any ORM code
436
+ - Sentinel must verify CORS configuration on new routes
437
+ ```
438
+
439
+ **Loading**: Cook reads `.rune/phase-rules.md` during Phase 0 (resume check). Rules for each phase are injected into the sub-skill's context when that phase starts. If file doesn't exist skip silently.
440
+
441
+ ## Checkpoint Protocol (Opt-In)
442
+
443
+ Invoke `rune:session-bridge` after Phase 2, 4, and 5 to save intermediate state. OPT-IN — activate only if task spans 3+ phases, context-watch is ORANGE, or user explicitly requests checkpoints. Before spawning subagents, invoke `rune:context-pack` to create structured handoff briefings.
444
+
445
+ ## Phase Transition Protocol (MANDATORY)
446
+
447
+ Before entering ANY Phase N+1, assert: Phase N `completed` in TodoWrite | gate condition met | no BLOCK from sub-skills | no unresolved CRITICAL findings. If any fails STOP, log "BLOCKED at Phase NN+1: [assertion]", fix, re-check.
448
+
449
+ **Key transitions:** 1→2: scout done | 23: plan approved | 34: failing tests exist | 45: all tests pass | 56: no CRITICAL findings | 6→7: lint+types+build green.
450
+
451
+ ## Phase 6: VERIFY
452
+
453
+ **REQUIRED SUB-SKILL**: Use `rune:verification` — run lint, type check, full test suite, build. Then `rune:hallucination-guard` to verify imports and API signatures. ALL checks MUST pass before commit.
454
+
455
+ ## Phase 7: COMMIT
456
+
457
+ **RECOMMENDED SUB-SKILL**: Use `rune:git` stage specific files (`git add <files>`, NOT `git add .`), generate semantic commit message from diff. If working from master plan: update phase status `🔄 ✅`, announce next phase or "All phases complete."
458
+
459
+ ## Phase 8: BRIDGE
460
+
461
+ **Goal**: Save context for future sessions and record metrics for mesh analytics.
462
+
463
+ **REQUIRED SUB-SKILL**: Use `rune:session-bridge`
464
+
465
+ 1. Mark Phase 8 as `in_progress`
466
+ 2. Save to `.rune/decisions.md` (approach + trade-offs), `.rune/progress.md` (task complete), `.rune/conventions.md` (new patterns)
467
+ 3. **Skill metrics** `.rune/metrics/skills.json`: increment phase run/skip counts, quality gate results, debug loop counts under `cook` key
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.
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.
478
+ 6. Mark Phase 8 as `completed`
479
+
480
+ ## Autonomous Loop Patterns
481
+
482
+ When cook runs inside `team` (L1) or autonomous workflows, these patterns apply.
483
+
484
+ ### De-Sloppify Pass
485
+
486
+ After Phase 4 completes (all tests green), run a **separate focused cleanup pass** on all modified files. Two focused passes outperform one constrained pass — let the implementer write freely in Phase 4, then clean up here.
487
+
488
+ **Trigger**: Implementation touched 3+ files OR 100+ LOC changed. Skip for nano/fast rigor.
489
+
490
+ **Slop targets** (check every modified file):
491
+
492
+ | Slop Type | Detection | Fix |
493
+ |-----------|-----------|-----|
494
+ | Leftover debug | `console.log`, `print()`, `debugger`, `TODO: remove` | Delete |
495
+ | Over-defensive checks | Null checks on values guaranteed non-null by TypeScript/framework | Remove redundant guard |
496
+ | Type-test slop | `typeof x === 'string'` when x is already typed as string | Remove — trust the type system |
497
+ | Duplicated logic | Same 3+ lines appear in multiple places | Extract utility |
498
+ | Framework-behavior tests | Tests asserting that React renders, that Express routes exist, that mocks work | Delete — test YOUR code, not the framework |
499
+ | Inconsistent naming | Mixed `camelCase`/`snake_case` in same file | Normalize to project convention |
500
+ | Dead imports | Imports no longer used after edits | Remove |
501
+
502
+ **Important**: This is NOT a quality gate — it's a cleanup pass. Don't block the pipeline for cosmetic issues. Fix what you find, move on.
503
+
504
+ ### Continuous PR Loop (team orchestration only)
505
+
506
+ ```
507
+ cook instance commitpushcreate PR wait CI
508
+ IF CI passes → mark workstream complete
509
+ IF CI fails → read CI output → fix → push → wait CI (max 3 retries)
510
+ IF 3 retries fail → escalate to user with CI logs
511
+ ```
512
+
513
+ ### Formal Pause/Resume (`.continue-here.md`)
514
+
515
+ <MUST-READ path="references/pause-resume-template.md" trigger="when cook must pause mid-phase (context limit, user break, session end)"/>
516
+
517
+ When cook must pause mid-phase, create `.rune/.continue-here.md` with structured handoff, then WIP commit. Phase 0 detects it on resume. More granular than plan-level resume — resumes within a phase.
518
+
519
+ ### Mid-Run Signal Detection
520
+
521
+ <MUST-READ path="references/mid-run-signals.md" trigger="when user sends a message DURING cook execution"/>
522
+
523
+ Two-stage intent classification: keyword fast-path for short messages (<60 chars), context classification for longer ones. Never queue user messages — process immediately.
524
+
525
+ <HARD-GATE>
526
+ NEVER treat a Cancel/Pause signal as a Steer or NewTask. User safety signals take absolute priority.
527
+ If ambiguous between Cancel and Steer → ask user: "Did you mean stop, or change approach?"
528
+ </HARD-GATE>
529
+
530
+ ### Exit Conditions (Mandatory for Autonomous Runs)
531
+
532
+ <MUST-READ path="references/exit-conditions.md" trigger="cook running inside team or any autonomous workflow"/>
533
+
534
+ Hard caps: MAX_DEBUG_LOOPS=3, MAX_QUALITY_LOOPS=2, MAX_REPLAN=1, MAX_PIVOT=1, MAX_FIXES=30, WTF_THRESHOLD=20%.
535
+ Escalation chain: debug-fix (3x) re-plan (1x) brainstorm rescue (1x) → THEN escalate to user.
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
+
587
+ ### Subagent Status Protocol
588
+
589
+ <MUST-READ path="references/subagent-status.md" trigger="when cook or any sub-skill needs to return a status"/>
590
+
591
+ Cook and all sub-skills return: `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED`.
592
+
593
+ ### Subagent Context Isolation
594
+
595
+ When invoking sub-skills (fix, debug, test, review, etc.), **craft exactly the context they need** — never pass the full orchestrator session context.
596
+
597
+ | Pass To Sub-Skill | DO NOT Pass |
598
+ |-------------------|-------------|
599
+ | Task description + specific goal | Full conversation history |
600
+ | Relevant file paths from scout | Unrelated files from other phases |
601
+ | Project conventions (naming, test framework) | Other sub-skill outputs |
602
+ | Plan excerpt for THIS phase only | Full master plan |
603
+ | Error/stack trace (for debug/fix) | Previous debug attempts from other bugs |
604
+
605
+ **Why**: Sub-skills that inherit orchestrator context get polluted — they chase false connections, reference stale data, and consume tokens on irrelevant context. A focused sub-skill with 500 tokens of curated context outperforms one with 5000 tokens of inherited noise.
606
+
607
+ ## Deviation Rules
608
+
609
+ <MUST-READ path="references/deviation-rules.md" trigger="when implementation diverges from the approved plan"/>
610
+
611
+ R1-R3 (bug/security/blocking fix): auto-fix, continue. R4 (architectural change): ASK user first.
612
+
613
+ ## Error Recovery
614
+
615
+ <MUST-READ path="references/error-recovery.md" trigger="when any phase fails or a task hits repeated errors"/>
616
+
617
+ Includes phase-by-phase failure handling and repair operators (RETRY DECOMPOSE PRUNE) with a 2-attempt budget before escalation.
618
+
619
+ ## Analysis Paralysis Guard
620
+
621
+ <HARD-GATE>
622
+ 5+ consecutive read-only tool calls (Read, Grep, Glob) without a single write action (Edit, Write, Bash) = STUCK.
623
+
624
+ You MUST either:
625
+ 1. **Act** write code, run a command, create a file
626
+ 2. **Report BLOCKED** — state the specific missing piece: "Cannot proceed because [X]"
627
+
628
+ Stuck patterns (all banned):
629
+ - Reading 10+ files to "fully understand" before acting
630
+ - Grepping every variation of a string across the entire repo
631
+ - Reading the same file twice in one investigation
632
+ - "Let me check one more thing" — repeated after 5 reads
633
+
634
+ A wrong first attempt that produces feedback beats perfect understanding that never ships.
635
+ </HARD-GATE>
636
+
637
+ ### Hash-Based Tool Loop Detection
638
+
639
+ <MUST-READ path="references/loop-detection.md" trigger="when same tool+args+result appears to be repeating"/>
640
+
641
+ Mentally track tool call fingerprints. 3 identical calls → WARN. 5 identical calls → FORCE STOP. Only same-input-AND-same-output counts as a loop.
642
+
643
+ ## Called By (inbound)
644
+
645
+ - User: `/rune cook` direct invocation — primary entry point
646
+ - `team` (L1): parallel workstream execution (meta-orchestration)
647
+
648
+ ## Calls (outbound)
649
+
650
+ | Phase | Sub-skill | Layer | Purpose |
651
+ |-------|-----------|-------|---------|
652
+ | 0 / 8 | `neural-memory` | ext | Recall context at start; capture learnings at end |
653
+ | 0.5 | `sentinel-env` | L3 | Environment pre-flight (first run only) |
654
+ | 1 | `scout` | L2 | Scan codebase before planning |
655
+ | 1 | `onboard` | L2 | Initialize project context if no CLAUDE.md |
656
+ | 1 | `ba` | L2 | Requirement elicitation for features |
657
+ | 2 | `plan` | L2 | Create implementation plan |
658
+ | 2 | `brainstorm` | L2 | Trade-off analysis / rescue mode |
659
+ | 2 | `design` | L2 | UI/design phase for frontend features |
660
+ | 2.5 | `adversary` | L2 | Red-team challenge on approved plan |
661
+ | 3 | `test` | L2 | Write failing tests (RED phase) |
662
+ | 4 | `fix` | L2 | Implement code changes (GREEN phase) |
663
+ | 4 | `debug` | L2 | Unexpected errors (max 3 loops) |
664
+ | 4 | `db` | L2 | Schema changes detected in diff |
665
+ | 4 | `worktree` | L3 | Worktree isolation for parallel implementation |
666
+ | 5a | `preflight` | L2 | Spec compliance + logic review |
667
+ | 5b | `sentinel` | L2 | Security scan |
668
+ | 5c | `review` | L2 | Code quality review |
669
+ | 5 | `perf` | L2 | Performance regression check (optional) |
670
+ | 5 | `audit` | L2 | Project health audit when scope warrants |
671
+ | 5 | `review-intake` | L2 | Structured review intake for complex PRs |
672
+ | 5 | `sast` | L3 | Static analysis security testing |
673
+ | 5d | `completion-gate` | L3 | Validate agent claims against evidence trail |
674
+ | 5 | `constraint-check` | L3 | Audit HARD-GATE compliance across workflow |
675
+ | 6 | `verification` | L3 | Lint + types + tests + build |
676
+ | 6 | `hallucination-guard` | L3 | Verify imports and API calls are real |
677
+ | 7 | `journal` | L3 | Record architectural decisions |
678
+ | 8 | `session-bridge` | L3 | Save context for future sessions |
679
+ | any | `context-pack` | L3 | create structured handoff briefings before spawning subagents |
680
+ | any | `skill-forge` | L2 | When new skill creation detected during cook |
681
+ | 1.5 | L4 extension packs | L4 | Domain-specific patterns when stack matches |
682
+
683
+ ## Data Flow
684
+
685
+ **Feeds Into →** `journal` (decisions → ADRs) | `session-bridge` (context → .rune/ state) | `neural-memory` (learnings → cross-session)
686
+
687
+ **Fed By ←** `ba` (requirements → Phase 1) | `plan` (master plan → Phase 2-4) | `session-bridge` (.continue-here.md → Phase 0 resume) | `neural-memory` (past decisions → Phase 0 recall)
688
+
689
+ **Feedback Loops ↻** cook↔debug (Phase 4 bug → debug → fix → resume; if plan wrong → Approach Pivot) | cook↔test (RED → GREEN → failures loop back)
690
+
691
+ ## Constraints
692
+
693
+ 1. MUST run scout before planning
694
+ 2. MUST get user plan approval before writing code
695
+ 3. MUST write failing tests before implementation (TDD) unless explicitly skipped
696
+ 4. MUST NOT commit with failing tests
697
+ 5. MUST NOT modify files outside approved plan scope without user confirmation
698
+ 6. MUST run verification (lint + type-check + tests + build) before commit
699
+ 7. MUST NOT say "all tests pass" without showing actual test output
700
+ 8. MUST NOT contradict `.rune/decisions.md` without explicit user override
701
+
702
+ ## Mesh Gates
703
+
704
+ | Gate | Requires | If Missing |
705
+ |------|----------|------------|
706
+ | Resume Gate | Phase 0 checks for master plan before starting | Proceed to Phase 1 |
707
+ | Scout Gate | scout output before Phase 2 | Invoke rune:scout first |
708
+ | Plan Gate | User-approved plan before Phase 3 | Cannot proceed |
709
+ | Adversary Gate | adversary verdict before Phase 3 for features | Skip for bugfix/hotfix/refactor |
710
+ | Phase File Gate | Active phase file only (multi-session) | Load only active phase |
711
+ | Test-First Gate | Failing tests before Phase 4 | Write tests or get explicit skip |
712
+ | Quality Gate | preflight + sentinel + review before Phase 7 | Fix findings, re-run |
713
+ | Verification Gate | lint + types + tests + build green before commit | Fix, re-run |
714
+
715
+ ## Structured Output Contract (Prompt-as-API Pattern)
716
+
717
+ 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.
718
+
719
+ ### Pattern
720
+
721
+ ```
722
+ INVOCATION: "Analyze [X] and return results as JSON matching this schema:
723
+ {
724
+ "insights": [{ "id": string, "category": string, "description": string, "actionable": string }],
725
+ "confidence": number,
726
+ "next_steps": string[]
727
+ }
728
+ Do NOT include explanatory text outside the JSON block."
729
+ ```
730
+
731
+ ### When to Apply
732
+
733
+ | Phase | Sub-skill | Output Contract |
734
+ |-------|-----------|----------------|
735
+ | Phase 1 | `ba` | `{ requirements: [{id, priority, description, acceptance_criteria}], ambiguities: string[] }` |
736
+ | Phase 2 | `plan` | `{ phases: [{name, tasks: [{description, files, effort}], dependencies}] }` |
737
+ | Phase 3 | `test` | `{ test_cases: [{name, type, file, assertion}], coverage_targets: string[] }` |
738
+ | Phase 5 | `review` | `{ findings: [{severity, file, line, description, fix}], verdict: "PASS"|"WARN"|"BLOCK" }` |
739
+
740
+ ### Rules
741
+
742
+ - Include 1-2 concrete examples in the prompt — examples are worth more than schema descriptions
743
+ - Always specify "Do NOT include explanatory text outside the JSON/markdown block" — LLMs default to wrapping structured output in prose
744
+ - When the output will be consumed by another skill (not displayed to user), ALWAYS use this pattern
745
+ - When the output will be displayed to the user, use markdown format instead — humans don't read JSON
746
+
747
+ ### Why
748
+
749
+ 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.
750
+
751
+ ## Output Format
752
+
753
+ <MUST-READ path="references/output-format.md" trigger="before emitting the Cook Report at end of any session"/>
754
+
755
+ Emit a Cook Report with: Status, Phases, Files Changed, Tests, Quality results, Commit hash.
756
+ When invoked by `team` with a NEXUS Handoff, include the Deliverables table — MANDATORY.
757
+
758
+ ## Returns
759
+
760
+ | Artifact | Format | Location |
761
+ |----------|--------|----------|
762
+ | Plan files (master + phase) | Markdown | `.rune/plan-<feature>.md`, `.rune/plan-<feature>-phase<N>.md` |
763
+ | Implementation code | Source files | Per plan file paths |
764
+ | Test files | Source files | Co-located or `__tests__/` per project convention |
765
+ | Verification results | Inline stdout | Shown in Cook Report |
766
+ | Cook Report | Markdown (inline) | Emitted at end of session |
767
+ | Session state | Markdown | `.rune/decisions.md`, `.rune/progress.md`, `.rune/conventions.md` |
768
+
769
+ ## Sharp Edges
770
+
771
+ <MUST-READ path="references/sharp-edges.md" trigger="before declaring done — review all 18 failure modes"/>
772
+
773
+ **CRITICAL failures** (always check): skipping scout | writing code without plan approval | "done" without evidence trail | surrendering without Approach Pivot Gate | breaking change without RFC | treating Cancel/Pause as scope change.
774
+
775
+ ## Self-Validation
776
+
777
+ ```
778
+ SELF-VALIDATION (run before emitting Cook Report):
779
+ - [ ] Every phase in Phase Skip Rules was either executed or explicitly skipped with reason
780
+ - [ ] Plan approval gate was not bypassed — user said "go" (check conversation history)
781
+ - [ ] No Phase 4 code was written before Phase 3 tests (TDD order preserved)
782
+ - [ ] All Phase 5 quality gates (preflight, sentinel, review) ran — not just claimed
783
+ - [ ] Cook Report contains actual commit hash, not placeholder
784
+ ```
785
+
786
+ ## Done When
787
+
788
+ All applicable phases complete + Self-Validation passed:
789
+ - User approved plan | All tests PASS (output shown) | preflight+sentinel+review PASS | build green
790
+ - Cook Report emitted with commit hash | Session state saved to .rune/ via session-bridge
791
+
792
+ ## Cost Profile
793
+
794
+ ~$0.05-0.15 per feature. Haiku for scanning (Phase 1), sonnet for coding (Phase 3-4), opus for complex planning (Phase 2 when needed).