@rune-kit/rune 2.10.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +65 -6
  3. package/commands/rune.md +168 -168
  4. package/compiler/__tests__/detect-invariants.test.js +136 -0
  5. package/compiler/__tests__/doctor-mesh.test.js +229 -0
  6. package/compiler/__tests__/hook-dispatch.test.js +91 -0
  7. package/compiler/__tests__/hooks-antigravity.test.js +118 -0
  8. package/compiler/__tests__/hooks-cursor.test.js +139 -0
  9. package/compiler/__tests__/hooks-install.test.js +305 -0
  10. package/compiler/__tests__/hooks-merge.test.js +204 -0
  11. package/compiler/__tests__/hooks-tiers.test.js +519 -0
  12. package/compiler/__tests__/hooks-windsurf.test.js +115 -0
  13. package/compiler/__tests__/inject-claude-md.test.js +152 -0
  14. package/compiler/__tests__/load-invariants.test.js +408 -0
  15. package/compiler/__tests__/onboard-invariants.test.js +240 -0
  16. package/compiler/adapters/hooks/antigravity.js +140 -0
  17. package/compiler/adapters/hooks/claude.js +166 -0
  18. package/compiler/adapters/hooks/cursor.js +191 -0
  19. package/compiler/adapters/hooks/index.js +82 -0
  20. package/compiler/adapters/hooks/tier-emitter.js +182 -0
  21. package/compiler/adapters/hooks/windsurf.js +202 -0
  22. package/compiler/bin/rune.js +196 -6
  23. package/compiler/commands/hook-dispatch.js +87 -0
  24. package/compiler/commands/hooks/install.js +120 -0
  25. package/compiler/commands/hooks/merge.js +211 -0
  26. package/compiler/commands/hooks/presets.js +116 -0
  27. package/compiler/commands/hooks/status.js +112 -0
  28. package/compiler/commands/hooks/tiers.js +221 -0
  29. package/compiler/commands/hooks/uninstall.js +94 -0
  30. package/compiler/doctor.js +236 -0
  31. package/contexts/dev.md +34 -34
  32. package/contexts/research.md +43 -43
  33. package/contexts/review.md +55 -55
  34. package/extensions/ai-ml/PACK.md +88 -88
  35. package/extensions/ai-ml/skills/ai-agents.md +172 -172
  36. package/extensions/ai-ml/skills/code-sandbox.md +187 -187
  37. package/extensions/ai-ml/skills/deep-research.md +146 -146
  38. package/extensions/ai-ml/skills/embedding-search.md +66 -66
  39. package/extensions/ai-ml/skills/fine-tuning-guide.md +74 -74
  40. package/extensions/ai-ml/skills/llm-architect.md +125 -125
  41. package/extensions/ai-ml/skills/llm-integration.md +64 -64
  42. package/extensions/ai-ml/skills/prompt-patterns.md +72 -72
  43. package/extensions/ai-ml/skills/rag-patterns.md +66 -66
  44. package/extensions/ai-ml/skills/web-extraction.md +114 -114
  45. package/extensions/analytics/PACK.md +92 -92
  46. package/extensions/analytics/skills/ab-testing.md +72 -72
  47. package/extensions/analytics/skills/dashboard-patterns.md +83 -83
  48. package/extensions/analytics/skills/data-validation.md +68 -68
  49. package/extensions/analytics/skills/funnel-analysis.md +81 -81
  50. package/extensions/analytics/skills/sql-patterns.md +57 -57
  51. package/extensions/analytics/skills/statistical-analysis.md +79 -79
  52. package/extensions/analytics/skills/tracking-setup.md +71 -71
  53. package/extensions/backend/PACK.md +104 -104
  54. package/extensions/backend/skills/api-patterns.md +84 -84
  55. package/extensions/backend/skills/async-pipeline.md +193 -193
  56. package/extensions/backend/skills/auth-patterns.md +97 -97
  57. package/extensions/backend/skills/background-jobs.md +133 -133
  58. package/extensions/backend/skills/caching-patterns.md +108 -108
  59. package/extensions/backend/skills/cli-generation.md +133 -133
  60. package/extensions/backend/skills/database-patterns.md +87 -87
  61. package/extensions/backend/skills/middleware-patterns.md +104 -104
  62. package/extensions/chrome-ext/PACK.md +93 -93
  63. package/extensions/chrome-ext/skills/cws-preflight.md +143 -143
  64. package/extensions/chrome-ext/skills/cws-publish.md +104 -104
  65. package/extensions/chrome-ext/skills/ext-ai-integration.md +251 -251
  66. package/extensions/chrome-ext/skills/ext-messaging.md +139 -139
  67. package/extensions/chrome-ext/skills/ext-storage.md +133 -133
  68. package/extensions/chrome-ext/skills/mv3-scaffold.md +164 -164
  69. package/extensions/content/PACK.md +96 -96
  70. package/extensions/content/skills/blog-patterns.md +88 -88
  71. package/extensions/content/skills/cms-integration.md +131 -131
  72. package/extensions/content/skills/content-scoring.md +107 -107
  73. package/extensions/content/skills/i18n.md +83 -83
  74. package/extensions/content/skills/mdx-authoring.md +137 -137
  75. package/extensions/content/skills/reference.md +1014 -1014
  76. package/extensions/content/skills/seo-patterns.md +67 -67
  77. package/extensions/content/skills/video-repurpose.md +153 -153
  78. package/extensions/devops/PACK.md +101 -101
  79. package/extensions/devops/skills/chaos-testing.md +67 -67
  80. package/extensions/devops/skills/ci-cd.md +75 -75
  81. package/extensions/devops/skills/docker.md +58 -58
  82. package/extensions/devops/skills/edge-serverless.md +163 -163
  83. package/extensions/devops/skills/infra-as-code.md +158 -158
  84. package/extensions/devops/skills/kubernetes.md +110 -110
  85. package/extensions/devops/skills/monitoring.md +57 -57
  86. package/extensions/devops/skills/server-setup.md +64 -64
  87. package/extensions/devops/skills/ssl-domain.md +42 -42
  88. package/extensions/ecommerce/PACK.md +116 -116
  89. package/extensions/ecommerce/skills/cart-system.md +79 -79
  90. package/extensions/ecommerce/skills/inventory-mgmt.md +102 -102
  91. package/extensions/ecommerce/skills/order-management.md +126 -126
  92. package/extensions/ecommerce/skills/payment-integration.md +472 -472
  93. package/extensions/ecommerce/skills/shopify-dev.md +69 -69
  94. package/extensions/ecommerce/skills/subscription-billing.md +93 -93
  95. package/extensions/ecommerce/skills/tax-compliance.md +117 -117
  96. package/extensions/gamedev/PACK.md +142 -142
  97. package/extensions/gamedev/skills/asset-pipeline.md +74 -74
  98. package/extensions/gamedev/skills/audio-system.md +129 -129
  99. package/extensions/gamedev/skills/camera-system.md +87 -87
  100. package/extensions/gamedev/skills/ecs.md +98 -98
  101. package/extensions/gamedev/skills/game-loops.md +72 -72
  102. package/extensions/gamedev/skills/input-system.md +199 -199
  103. package/extensions/gamedev/skills/multiplayer.md +180 -180
  104. package/extensions/gamedev/skills/particles.md +105 -105
  105. package/extensions/gamedev/skills/physics-engine.md +89 -89
  106. package/extensions/gamedev/skills/scene-management.md +146 -146
  107. package/extensions/gamedev/skills/threejs-patterns.md +90 -90
  108. package/extensions/gamedev/skills/webgl.md +71 -71
  109. package/extensions/mobile/PACK.md +106 -106
  110. package/extensions/mobile/skills/app-store-connect.md +152 -152
  111. package/extensions/mobile/skills/app-store-prep.md +66 -66
  112. package/extensions/mobile/skills/deep-linking.md +109 -109
  113. package/extensions/mobile/skills/flutter.md +60 -60
  114. package/extensions/mobile/skills/ios-build-pipeline.md +142 -142
  115. package/extensions/mobile/skills/native-bridge.md +66 -66
  116. package/extensions/mobile/skills/ota-updates.md +97 -97
  117. package/extensions/mobile/skills/push-notifications.md +111 -111
  118. package/extensions/mobile/skills/react-native.md +82 -82
  119. package/extensions/saas/PACK.md +116 -116
  120. package/extensions/saas/skills/billing-integration.md +200 -200
  121. package/extensions/saas/skills/feature-flags.md +130 -130
  122. package/extensions/saas/skills/multi-tenant.md +103 -103
  123. package/extensions/saas/skills/onboarding-flow.md +139 -139
  124. package/extensions/saas/skills/subscription-flow.md +95 -95
  125. package/extensions/saas/skills/team-management.md +144 -144
  126. package/extensions/security/PACK.md +99 -99
  127. package/extensions/security/skills/api-security.md +140 -140
  128. package/extensions/security/skills/compliance.md +68 -68
  129. package/extensions/security/skills/owasp-audit.md +64 -64
  130. package/extensions/security/skills/pentest-patterns.md +77 -77
  131. package/extensions/security/skills/secret-mgmt.md +65 -65
  132. package/extensions/security/skills/supply-chain.md +65 -65
  133. package/extensions/trading/PACK.md +80 -80
  134. package/extensions/trading/skills/chart-components.md +55 -55
  135. package/extensions/trading/skills/experiment-loop.md +125 -125
  136. package/extensions/trading/skills/fintech-patterns.md +47 -47
  137. package/extensions/trading/skills/indicator-library.md +58 -58
  138. package/extensions/trading/skills/quant-analysis.md +111 -111
  139. package/extensions/trading/skills/realtime-data.md +58 -58
  140. package/extensions/trading/skills/trade-logic.md +104 -104
  141. package/extensions/ui/PACK.md +130 -130
  142. package/extensions/ui/skills/a11y-audit.md +91 -91
  143. package/extensions/ui/skills/animation-patterns.md +127 -127
  144. package/extensions/ui/skills/component-patterns.md +100 -100
  145. package/extensions/ui/skills/design-decision.md +108 -108
  146. package/extensions/ui/skills/design-system.md +68 -68
  147. package/extensions/ui/skills/landing-patterns.md +155 -155
  148. package/extensions/ui/skills/palette-picker.md +173 -173
  149. package/extensions/ui/skills/react-health.md +90 -90
  150. package/extensions/ui/skills/type-system.md +125 -125
  151. package/extensions/ui/skills/web-vitals.md +153 -153
  152. package/extensions/zalo/PACK.md +145 -145
  153. package/extensions/zalo/skills/zalo-oa-mcp.md +317 -317
  154. package/extensions/zalo/skills/zalo-oa-messaging.md +429 -429
  155. package/extensions/zalo/skills/zalo-oa-setup.md +236 -236
  156. package/extensions/zalo/skills/zalo-oa-webhook.md +189 -189
  157. package/extensions/zalo/skills/zalo-personal-messaging.md +194 -194
  158. package/extensions/zalo/skills/zalo-personal-setup.md +153 -153
  159. package/extensions/zalo/skills/zalo-rate-guard.md +219 -219
  160. package/hooks/auto-format/index.cjs +48 -48
  161. package/hooks/hooks.json +111 -111
  162. package/hooks/post-session-reflect/index.cjs +189 -189
  163. package/hooks/pre-compact/index.cjs +95 -95
  164. package/hooks/run-hook.cmd +1 -1
  165. package/hooks/secrets-scan/index.cjs +100 -100
  166. package/hooks/session-start/index.cjs +71 -71
  167. package/hooks/typecheck/index.cjs +65 -65
  168. package/package.json +63 -63
  169. package/references/ui-pro-max-data/LICENSE-UI-PRO-MAX +21 -21
  170. package/references/ui-pro-max-data/charts.csv +26 -26
  171. package/references/ui-pro-max-data/colors.csv +161 -161
  172. package/references/ui-pro-max-data/styles.csv +68 -68
  173. package/references/ui-pro-max-data/typography.csv +74 -74
  174. package/references/ui-pro-max-data/ui-reasoning.csv +162 -162
  175. package/references/ui-pro-max-data/ux-guidelines.csv +99 -99
  176. package/skills/adversary/SKILL.md +283 -283
  177. package/skills/asset-creator/SKILL.md +157 -157
  178. package/skills/audit/SKILL.md +147 -2
  179. package/skills/autopsy/SKILL.md +335 -335
  180. package/skills/ba/SKILL.md +85 -1
  181. package/skills/brainstorm/SKILL.md +380 -342
  182. package/skills/browser-pilot/SKILL.md +169 -168
  183. package/skills/constraint-check/SKILL.md +165 -165
  184. package/skills/context-engine/SKILL.md +408 -404
  185. package/skills/cook/SKILL.md +917 -863
  186. package/skills/db/SKILL.md +273 -273
  187. package/skills/debug/SKILL.md +465 -465
  188. package/skills/dependency-doctor/SKILL.md +265 -235
  189. package/skills/deploy/SKILL.md +274 -231
  190. package/skills/design/DESIGN-REFERENCE.md +365 -365
  191. package/skills/design/SKILL.md +590 -589
  192. package/skills/doc-processor/SKILL.md +254 -254
  193. package/skills/docs/SKILL.md +374 -374
  194. package/skills/docs-seeker/SKILL.md +178 -177
  195. package/skills/fix/SKILL.md +332 -330
  196. package/skills/git/SKILL.md +339 -339
  197. package/skills/hallucination-guard/SKILL.md +220 -219
  198. package/skills/incident/SKILL.md +254 -253
  199. package/skills/integrity-check/SKILL.md +169 -169
  200. package/skills/journal/SKILL.md +241 -240
  201. package/skills/launch/SKILL.md +344 -344
  202. package/skills/logic-guardian/SKILL.md +269 -251
  203. package/skills/marketing/SKILL.md +351 -289
  204. package/skills/mcp-builder/SKILL.md +425 -425
  205. package/skills/neural-memory/SKILL.md +359 -362
  206. package/skills/onboard/SKILL.md +432 -403
  207. package/skills/onboard/references/invariants-template.md +76 -0
  208. package/skills/onboard/scripts/detect-invariants.js +439 -0
  209. package/skills/onboard/scripts/inject-claude-md.js +150 -0
  210. package/skills/onboard/scripts/onboard-invariants.js +194 -0
  211. package/skills/perf/SKILL.md +347 -346
  212. package/skills/plan/SKILL.md +435 -428
  213. package/skills/preflight/SKILL.md +415 -415
  214. package/skills/problem-solver/SKILL.md +380 -284
  215. package/skills/rescue/SKILL.md +474 -474
  216. package/skills/research/SKILL.md +4 -0
  217. package/skills/retro/SKILL.md +3 -1
  218. package/skills/review/SKILL.md +614 -588
  219. package/skills/review-intake/SKILL.md +249 -249
  220. package/skills/safeguard/SKILL.md +200 -200
  221. package/skills/sast/SKILL.md +190 -190
  222. package/skills/scaffold/SKILL.md +328 -287
  223. package/skills/scope-guard/SKILL.md +183 -180
  224. package/skills/scout/SKILL.md +269 -263
  225. package/skills/sentinel/SKILL.md +384 -381
  226. package/skills/sentinel-env/SKILL.md +254 -254
  227. package/skills/sequential-thinking/SKILL.md +234 -234
  228. package/skills/session-bridge/SKILL.md +595 -543
  229. package/skills/session-bridge/scripts/load-invariants.js +397 -0
  230. package/skills/skill-forge/SKILL.md +581 -581
  231. package/skills/skill-router/SKILL.md +3 -0
  232. package/skills/slides/SKILL.md +19 -0
  233. package/skills/surgeon/SKILL.md +215 -215
  234. package/skills/team/SKILL.md +557 -537
  235. package/skills/test/SKILL.md +620 -614
  236. package/skills/trend-scout/SKILL.md +145 -145
  237. package/skills/verification/SKILL.md +334 -326
  238. package/skills/video-creator/SKILL.md +201 -201
  239. package/skills/watchdog/SKILL.md +168 -168
  240. package/skills/worktree/SKILL.md +140 -140
@@ -1,863 +1,917 @@
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.3.0"
9
- layer: L1
10
- model: sonnet
11
- group: orchestrator
12
- tools: "Read, Write, Edit, Bash, Glob, Grep"
13
- emit: phase.complete, checkpoint.request
14
- listen: plan.ready, review.complete, ideas.ready, preflight.passed, verification.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 → implement → quality (Phase 1 → 2 → 4 → 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 67, 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-iterationPro: metrics review feedback synthesis re-prioritize implement → measure
53
- /rune cook --template data-explorationPro: data profiling hypotheses statistical testing → visualization → report
54
- /rune cook --template data-pipelinePro: 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-refreshPro: 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
-
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 "graft", "port from", "copy from repo", "clone feature from" **delegate to `rune:graft`** (not a cook chain — hand off entirely)
77
- - Contains `--template`load template workflow (see above)
78
- - Default`feature`
79
-
80
- ## Phase Skip Rules
81
-
82
- Not every task needs every phase:
83
-
84
- ```
85
- Nano task: DO → VERIFY → DONE (no phases, auto-detected)
86
- Simple bug fix: Phase 1 4 6 7
87
- Small refactor: Phase 1 → 4 → 5 → 6 → 7
88
- New feature: Phase 1 → 1.5 → 2 → 3 → 4 → 5 → 6 → 7 → 8
89
- Complex feature: All phases + brainstorm in Phase 2
90
- Security-sensitive: All phases + sentinel escalated to opus
91
- Fast mode: Phase 1 4 6 7 (auto-detected, see below)
92
- Multi-session: Phase 0 (resume) → 3 → 4 5 6 7 (one plan phase per session)
93
- ```
94
-
95
- Determine complexity BEFORE starting using the Rigor Assessment below. Create TodoWrite with applicable phases.
96
-
97
- ### Rigor Assessment (Progressive Scaling)
98
-
99
- 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.
100
-
101
- | Risk Signal | Weight | Detection |
102
- |-------------|--------|-----------|
103
- | Files affected: 1 | 0 | Estimate from task description + scout |
104
- | Files affected: 2-3 | +1 | |
105
- | Files affected: 4+ | +3 | |
106
- | Cross-module impact (changes span 2+ directories) | +2 | scout identifies touch points across boundaries |
107
- | Security-sensitive code (auth, crypto, payments, secrets) | +3 | Keyword match in file paths or task description |
108
- | Public API change (exports, routes, schema) | +2 | Task modifies interfaces consumed by external code |
109
- | Database schema change | +2 | Task mentions migration, schema, ALTER, column |
110
- | New dependency added | +1 | Task requires `npm install` or equivalent |
111
- | Code will be imported by other modules | +1 | New exports or modifications to shared utilities |
112
-
113
- **Rigor level mapping:**
114
-
115
- | Score | Level | Maps To | Phases |
116
- |-------|-------|---------|--------|
117
- | 0 | Nano | `nano` chain | DOVERIFYDONE |
118
- | 1-2 | Fast | `fast` mode | Phase 1 → 4 → 6 → 7 |
119
- | 3-5 | Standard | `bugfix` / `refactor` | Phase 1 → 2 → 4 → 5 → 6 → 7 |
120
- | 6-8 | Full | `feature` | Phase 1 → 1.5 2 3 → 4 → 5 → 6 → 7 → 8 |
121
- | 9+ | Critical | `security` / full + adversary | All phases + sentinel@opus + adversary |
122
-
123
- **Rules:**
124
- - Security signal (+3) automatically floors rigor at Standard NEVER nano/fast for security code
125
- - User can override: "full pipeline" forces Full, "just do it" forces Nano
126
- - 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."
127
- - Announce chosen level: "Rigor: Fast (score 2 — single file, no security)"
128
-
129
- ## Nano Mode (Auto-Detect)
130
-
131
- For trivial tasks that don't need any pipeline at all:
132
-
133
- ```
134
- IF all of these are true:
135
- - Task is ≤3 discrete steps (e.g., run command, edit 1 file, commit)
136
- - Task description < 60 chars OR user prefixes with "quick:", "just", "chỉ cần"
137
- - No code logic changes (copy files, config edits, version bumps, git ops, run scripts)
138
- - No new functions/classes/components created
139
- THEN: Nano Mode activated
140
- - Execute directly: DO VERIFY DONE
141
- - No phases. No plan. No test. No review.
142
- - Still verify output (check exit codes, confirm file exists, etc.)
143
- - Still use semantic commit message if committing
144
- ```
145
-
146
- **Announce**: "Nano mode: trivial task, executing directly."
147
- **Override**: User can say "full pipeline" or "cook feature" to force phases.
148
- **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.
149
-
150
- <HARD-GATE>
151
- Nano mode MUST NOT be used for:
152
- - Any code that will be imported/called by other code
153
- - Security-relevant files (auth, crypto, payments, .env, secrets)
154
- - Database schema changes
155
- - Public API changes
156
- If any of these are detected mid-task, STOP and upgrade to Fast/Full mode.
157
- </HARD-GATE>
158
-
159
- ## Fast Mode (Auto-Detect)
160
-
161
- Cook auto-detects small changes and streamlines the pipeline:
162
-
163
- ```
164
- IF all of these are true:
165
- - Total estimated change < 30 LOC
166
- - Single file affected
167
- - No security-relevant code (auth, crypto, payments, .env)
168
- - No public API changes
169
- - No database schema changes
170
- THEN: Fast Mode activated
171
- - Skip Phase 2 (PLAN) change is too small for a formal plan
172
- - Skip Phase 3 (TEST) unless existing tests cover the area
173
- - Skip Phase 5b (SENTINEL)non-security code
174
- - Skip Phase 8 (BRIDGE) — not worth persisting
175
- - KEEP Phase 5a (PREFLIGHT) and Phase 6 (VERIFY) — always run quality checks
176
- ```
177
-
178
- **Announce fast mode**: "Fast mode: small change detected (<30 LOC, single file, non-security). Streamlined pipeline."
179
- **Override**: User can say "full pipeline" to force all phases even on small changes.
180
-
181
- ## Phase 0.5: ENVIRONMENT CHECK (First Run Only)
182
-
183
- **SUB-SKILL**: Use `rune:sentinel-env` — verify the environment can run the project before planning.
184
-
185
- 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`.
186
-
187
- ## Phase 1: UNDERSTAND
188
-
189
- **Goal**: Know what exists before changing anything.
190
-
191
- **REQUIRED SUB-SKILLS**: Use `rune:scout`. For non-trivial tasks, use `rune:ba`.
192
-
193
- 1. Create TodoWrite with all applicable phases for this task
194
- 2. Mark Phase 1 as `in_progress`
195
- 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.
196
- 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.
197
- 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.
198
-
199
- ### Phase 1 Step 3.5 Clarification Gate
200
-
201
- Ask **2 questions** before planning: (1) "What does success look like?" (2) "What should NOT change?"
202
-
203
- 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`.
204
-
205
- 5. Invoke scout to scan the codebase (Glob + Grep + Read on relevant files)
206
- 6. Summarize: what exists, project conventions, files likely to change, active decision constraints
207
- 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`
208
- 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:
209
- - List alternatives with 1-line trade-off each
210
- - Flag to Phase 2 (plan) for formal comparison
211
- - Separating "thinking" (Phase 1) from "committing" (Phase 2) prevents premature lock-in
212
- 9. Mark Phase 1 as `completed`
213
-
214
- **Gate**: If scout finds the feature already exists STOP and inform user.
215
-
216
- ## Phase 1.5: DOMAIN CONTEXT (L4 Pack Detection)
217
-
218
- **Goal**: Detect if domain-specific L4 extension packs apply to this task.
219
-
220
- <MUST-READ path="references/pack-detection.md" trigger="Phase 1.5 before checking L4 pack mapping"/>
221
-
222
- 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.
223
-
224
- ## Phase 1.7: WORKFLOW ORCHESTRATION (Multi-Skill Sequences)
225
-
226
- **Goal**: If Phase 1.5 detected a pack AND the task maps to a named workflow, orchestrate the multi-skill sequence.
227
-
228
- **Trigger**: Only runs if Phase 1.5 found a pack match AND the pack's Workflows table has a matching command.
229
-
230
- <MUST-READ path="references/pack-detection.md" trigger="Phase 1.7 workflow command detection section"/>
231
-
232
- 1. Read the matched PACK.md's Workflows section
233
- 2. Identify the workflow name and skill sequence
234
- 3. For each skill in sequence:
235
- a. Load the skill file from the pack's `skills/` directory
236
- b. Execute the skill's workflow steps
237
- c. Write output artifact to `.rune/<domain>/` (e.g., `.rune/hr/jd-[role]-[date].md`)
238
- d. The next skill reads the previous artifact as input context
239
- 4. After all skills complete: summarize the workflow results to the user
240
-
241
- **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.
242
-
243
- **Skip if**: No workflow match found in Phase 1.5. Single-skill tasks proceed directly to Phase 2 (PLAN) as normal.
244
-
245
- ## Phase 0: RESUME CHECK (Before Phase 1)
246
-
247
- **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.
248
-
249
- **Step 0.4 Template Detection**: If user passed `--template <name>`:
250
- 1. Search installed pack templates for the name: `Glob` for `extensions/*/templates/<name>.md` and `extensions/pro-*/templates/<name>.md`
251
- 2. If found: `Read` the template file parse phases, signals, connections, acceptance criteria
252
- 3. Generate a master plan from the template: each template phase becomes a plan phase
253
- 4. Write plan files to `.rune/plan-<template-name>.md` + `.rune/plan-<template-name>-phaseN.md`
254
- 5. Announce "Loading template: <name> (<pack>)" → skip Phase 1, 1.5, 1.7, 2 → proceed to Phase 4 with Phase 1 of the template
255
- 6. If template not found: warn user and fall through to normal workflow
256
-
257
- **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"`).
258
-
259
- 1. Use `Glob` to check for `.rune/plan-*.md` files
260
- 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
261
- 3. If no master plan exists → proceed to Phase 1 as normal
262
-
263
- **Step 0.6 Contract Load**: Use `Glob` to check for `.rune/contract.md`. If it exists:
264
- 1. `Read` the contract file and parse each `## section` as a named rule set
265
- 2. Hold contract rules in context — they apply as **hard gates** throughout all phases
266
- 3. Any code change that violates a contract rule STOP and inform user before proceeding
267
- 4. If no contract exists → proceed normally (contract is optional)
268
-
269
- <HARD-GATE>
270
- 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.
271
- </HARD-GATE>
272
-
273
- **This enables multi-session workflows**: Opus plans once → each session picks up the next phase.
274
-
275
- ## Phase 2: PLAN
276
-
277
- **Goal**: Break the task into concrete implementation steps before writing code.
278
-
279
- **REQUIRED SUB-SKILL**: Use `rune:plan`
280
-
281
- 1. Mark Phase 2 as `in_progress`
282
- 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.
283
- 3. Create implementation plan: exact files to create/modify, change order, dependencies, active decision constraints
284
- 4. If multiple valid approaches exist → invoke `rune:brainstorm` for trade-off analysis
285
- 5. Present plan to user for approval
286
- 6. If feature workspace was created, write approved plan to `.rune/features/<name>/plan.md`
287
- 7. Mark Phase 2 as `completed`
288
-
289
- **Gate**: User MUST approve the plan before proceeding. Do NOT skip this.
290
-
291
- ### Phase 2.5: RFC GATE (Breaking Changes Only)
292
-
293
- **Goal**: Formal change management for breaking changes. Prevents unreviewed breaking changes from reaching production.
294
-
295
- <MUST-READ path="references/rfc-template.md" trigger="Phase 2.5 any time a breaking change is detected in the plan"/>
296
-
297
- <HARD-GATE>
298
- Breaking change without RFC = BLOCKED. No exceptions.
299
- "It's just a small change" is the #1 excuse for production incidents from unreviewed breaking changes.
300
- </HARD-GATE>
301
-
302
- ### Phase 2.5: ADVERSARY (Red-Team Challenge)
303
-
304
- **Goal**: Stress-test the approved plan BEFORE writing code — catch flaws at plan time, not implementation time.
305
-
306
- **REQUIRED SUB-SKILL**: Use `rune:adversary`
307
-
308
- 1. **Skip conditions**: bug fixes, hotfixes, simple refactors (< 3 files, no new logic), fast mode
309
- 2. **Run adversary** Full Red-Team mode for new features/architectural changes; Quick Challenge mode for smaller plans
310
- 3. **Handle verdict**:
311
- - **REVISE** return to Phase 2 with adversary findings as constraints; user must re-approve
312
- - **HARDEN** present remediations, update plan inline, then proceed to Phase 3
313
- - **PROCEED** → pass findings as implementation notes to Phase 3
314
- 4. **Max 1 REVISE loop** per cook session — if revised plan also gets REVISE, ask user to decide
315
-
316
- ### Phase-Aware Execution (Master Plan + Phase Files)
317
-
318
- When `rune:plan` produces a **master plan + phase files** (non-trivial tasks):
319
-
320
- 1. After plan approval: load ONLY Phase 1's file do NOT load all phase files
321
- 2. Execute through cook Phase 3-6 (test → implement → quality → verify)
322
- 3. After phase complete: mark tasks done, update master plan status `⬚ → ✅`, announce "Phase N complete. Phase N+1 ready for next session."
323
- 4. Next session: Phase 0 detects master plan → loads next phase → executes
324
-
325
- <HARD-GATE>
326
- NEVER load multiple phase files at once. One phase per session = small context = better code.
327
- If the coder model needs info from other phases, it's in the Cross-Phase Context section of the current phase file.
328
- </HARD-GATE>
329
-
330
- ## Phase 3: TEST (TDD Red)
331
-
332
- **Goal**: Define expected behavior with failing tests BEFORE writing implementation.
333
-
334
- **REQUIRED SUB-SKILL**: Use `rune:test`
335
-
336
- 1. Mark Phase 3 as `in_progress`
337
- 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.
338
- 3. Write test files based on the plan cover primary use case + edge cases; tests MUST be runnable
339
- 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
340
- 5. Run tests to verify they FAIL — expected: RED because implementation doesn't exist yet
341
- 6. Mark Phase 3 as `completed`
342
-
343
- **Gate**: Tests MUST exist and MUST fail. If tests pass without implementation → tests are wrong, rewrite them.
344
-
345
- ## Phase 4: IMPLEMENT (TDD Green)
346
-
347
- **Goal**: Write the minimum code to make tests pass.
348
-
349
- **REQUIRED SUB-SKILL**: Use `rune:fix`
350
-
351
- 1. Mark Phase 4 as `in_progress`
352
- 2. **Phase-file execution** if working from a master plan + phase file:
353
- - Execute tasks from `## Tasks` section wave-by-wave
354
- - Wave N only starts after ALL Wave N-1 tasks complete
355
- - Follow Code Contracts, Rejection Criteria, Failure Scenarios from the phase file
356
- - Mark each task `[x]` as completed
357
- 3. Implement the feature following the plan (Write for new files, Edit for existing)
358
- 4. Run tests after each significant change — if fail → debug and fix
359
- - **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
360
- 5. If stuck → invoke `rune:debug` (max 3 debug↔fix loops). Fixes outside plan scope require user approval (R4).
361
- 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.
362
- 7. **Approach Pivot Gate** — if re-plan ALSO fails:
363
-
364
- <HARD-GATE>
365
- Do NOT surrender. Do NOT tell user "no solution exists."
366
- Do NOT try a 4th variant of the same approach.
367
- MUST invoke brainstorm(mode="rescue") before giving up.
368
- </HARD-GATE>
369
-
370
- Invoke `rune:brainstorm(mode="rescue")` with `failed_approach`, `failure_evidence[]`, `original_goal`. Returns 3-5 alternatives → user picks → **restart from Phase 2**.
371
-
372
- 8. All tests MUST pass before proceeding
373
- 9. Mark Phase 4 as `completed`
374
-
375
- **Gate**: ALL tests from Phase 3 MUST pass. Do NOT proceed with failing tests.
376
-
377
- ## Phase 5: QUALITY (Staged)
378
-
379
- **Goal**: Catch issues before they reach production.
380
-
381
- 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.
382
-
383
- **Signal dispatch ordering**: When `fix` emits `code.changed`, 4 listeners react (preflight, sentinel, test, review). Cook coordinates dispatch order do NOT let all 4 fire simultaneously:
384
- - **Stage 1**: preflight + sentinel (parallelindependent checks)
385
- - **Stage 2**: test (after Stage 1 passes no point testing non-compliant code)
386
- - **Stage 3**: review (after test passes review verified code only)
387
-
388
- ```
389
- STAGE 1 (parallel):
390
- Launch 5a (preflight) + 5b (sentinel) simultaneously.
391
- Wait for BOTH to complete.
392
- If 5a returns BLOCK fix spec gaps, re-run 5a. Code review CANNOT start on non-compliant code.
393
- If 5b returns BLOCK → fix security issue, re-run 5b.
394
-
395
- STAGE 2 (after Stage 1 passes):
396
- Launch 5c (review) + 5d (completion-gate) simultaneously.
397
- If any returns BLOCK fix findings, re-run the blocking check only.
398
- ```
399
-
400
- ### 5a. Preflight (Spec Compliance + Logic) STAGE 1
401
- **REQUIRED SUB-SKILL**: Use `rune:preflight`
402
- - Spec compliance: compare approved plan vs actual diff
403
- - Logic review, error handling, completeness
404
- - **Must pass before 5c (review) can start** — no point reviewing code quality if it doesn't match the spec
405
-
406
- ### 5b. SecuritySTAGE 1
407
- **REQUIRED SUB-SKILL**: Use `rune:sentinel`
408
- - Secret scan, OWASP check (no injection/XSS/CSRF), dependency audit
409
-
410
- ### 5c. Code ReviewSTAGE 2
411
- **REQUIRED SUB-SKILL**: Use `rune:review`
412
- - Pattern compliance, code quality, performance bottlenecks
413
- - Reviewer reads code independently — does NOT rely on implementer's claims
414
- - **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.
415
-
416
- ### 5d. Completion Gate — STAGE 2
417
- **REQUIRED SUB-SKILL**: Use `rune:completion-gate`
418
- - Validate agent claims match evidence trail (tests ran, files changed, build passed)
419
- - No truncated code files (`// ...`, `// rest of code`, bare ellipsis) — agent MUST complete all output
420
- - Any UNCONFIRMED claim BLOCK
421
-
422
- **Gate**: If sentinel finds CRITICAL security issue STOP, fix it, re-run. Non-negotiable.
423
- **Gate**: If completion-gate finds UNCONFIRMED claim → STOP, re-verify. Non-negotiable.
424
-
425
- ## Per-Phase Rules (Project-Specific)
426
-
427
- 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.
428
-
429
- ```markdown
430
- # .rune/phase-rules.md (example)
431
-
432
- ## Phase 2: PLAN
433
- - All API endpoints must follow REST naming convention /api/v1/<resource>
434
- - Database changes require a rollback migration
435
-
436
- ## Phase 3: TEST
437
- - Enforce TDD format: describe → it → arrange → act → assert
438
- - Minimum 3 edge cases per public function
439
-
440
- ## Phase 5: QUALITY
441
- - Review must check for N+1 queries on any ORM code
442
- - Sentinel must verify CORS configuration on new routes
443
- ```
444
-
445
- **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.
446
-
447
- ## Checkpoint Protocol (Opt-In)
448
-
449
- 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.
450
-
451
- ## Phase Transition Protocol (MANDATORY)
452
-
453
- 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.
454
-
455
- **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.
456
-
457
- ## Phase 6: VERIFY
458
-
459
- **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.
460
-
461
- ## Phase 7: COMMIT
462
-
463
- **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."
464
-
465
- ## Phase 8: BRIDGE
466
-
467
- **Goal**: Save context for future sessions and record metrics for mesh analytics.
468
-
469
- **REQUIRED SUB-SKILL**: Use `rune:session-bridge`
470
-
471
- 1. Mark Phase 8 as `in_progress`
472
- 2. Save to `.rune/decisions.md` (approach + trade-offs), `.rune/progress.md` (task complete), `.rune/conventions.md` (new patterns)
473
- 3. **Skill metrics** → `.rune/metrics/skills.json`: increment phase run/skip counts, quality gate results, debug loop counts under `cook` key
474
- 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.
475
- 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:
476
- - [ ] `README.md` — stats, badges, feature list
477
- - [ ] `docs/index.html` (landing page) — meta tags, hero badge, install section, mesh stats, footer
478
- - [ ] `dashboard.html` (if local) — KPI cards, test count, skill tabs, layer counts
479
- - [ ] `CLAUDE.md` — commands, test count, skill list
480
- - [ ] `MEMORY.md` — milestones, version info
481
-
482
- **Skip if**: No stats changed (pure refactor, docs-only, style change). **MANDATORY** if any numeric stat in README differs from actual.
483
- 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.
484
- 6. Mark Phase 8 as `completed`
485
-
486
- ## Autonomous Loop Patterns
487
-
488
- When cook runs inside `team` (L1) or autonomous workflows, these patterns apply.
489
-
490
- ### De-Sloppify Pass
491
-
492
- 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.
493
-
494
- **Trigger**: Implementation touched 3+ files OR 100+ LOC changed. Skip for nano/fast rigor.
495
-
496
- **Slop targets** (check every modified file):
497
-
498
- | Slop Type | Detection | Fix |
499
- |-----------|-----------|-----|
500
- | Leftover debug | `console.log`, `print()`, `debugger`, `TODO: remove` | Delete |
501
- | Over-defensive checks | Null checks on values guaranteed non-null by TypeScript/framework | Remove redundant guard |
502
- | Type-test slop | `typeof x === 'string'` when x is already typed as string | Remove — trust the type system |
503
- | Duplicated logic | Same 3+ lines appear in multiple places | Extract utility |
504
- | Framework-behavior tests | Tests asserting that React renders, that Express routes exist, that mocks work | Delete — test YOUR code, not the framework |
505
- | Inconsistent naming | Mixed `camelCase`/`snake_case` in same file | Normalize to project convention |
506
- | Dead imports | Imports no longer used after edits | Remove |
507
-
508
- **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.
509
-
510
- ### Continuous PR Loop (team orchestration only)
511
-
512
- ```
513
- cook instance commit → push → create PR → wait CI
514
- IF CI passes → mark workstream complete
515
- IF CI fails read CI output fix push → wait CI (max 3 retries)
516
- IF 3 retries fail → escalate to user with CI logs
517
- ```
518
-
519
- ### Formal Pause/Resume (`.continue-here.md`)
520
-
521
- <MUST-READ path="references/pause-resume-template.md" trigger="when cook must pause mid-phase (context limit, user break, session end)"/>
522
-
523
- 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.
524
-
525
- ### Mid-Run Signal Detection
526
-
527
- <MUST-READ path="references/mid-run-signals.md" trigger="when user sends a message DURING cook execution"/>
528
-
529
- Two-stage intent classification: keyword fast-path for short messages (<60 chars), context classification for longer ones. Never queue user messages — process immediately.
530
-
531
- <HARD-GATE>
532
- NEVER treat a Cancel/Pause signal as a Steer or NewTask. User safety signals take absolute priority.
533
- If ambiguous between Cancel and Steer → ask user: "Did you mean stop, or change approach?"
534
- </HARD-GATE>
535
-
536
- ### Exit Conditions (Mandatory for Autonomous Runs)
537
-
538
- <MUST-READ path="references/exit-conditions.md" trigger="cook running inside team or any autonomous workflow"/>
539
-
540
- Hard caps: MAX_DEBUG_LOOPS=3, MAX_QUALITY_LOOPS=2, MAX_REPLAN=1, MAX_PIVOT=1, MAX_FIXES=30, WTF_THRESHOLD=20%.
541
- Escalation chain: debug-fix (3x) → re-plan (1x) → brainstorm rescue (1x) → THEN escalate to user.
542
-
543
- ### Structured Escalation Report
544
-
545
- > From agency-agents (msitarzewski/agency-agents, 50.8k★): "After 3 retry failures, structured escalation prevents cargo-cult retrying."
546
-
547
- 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":
548
-
549
- ```markdown
550
- ## Escalation Report
551
- - **Task**: [original task description]
552
- - **Status**: BLOCKED
553
- - **Attempts**: [count] across [N] phases
554
-
555
- ### Failure History
556
- | # | Approach | Phase | Outcome | Root Cause |
557
- |---|---------|-------|---------|------------|
558
- | 1 | Direct fix | Phase 4 | Tests fail — null ref in auth.ts:42 | Missing user context |
559
- | 2 | Re-plan with guard clause | Phase 4 | Build fails — circular import | Guard approach introduces cycle |
560
- | 3 | Brainstorm rescue → adapter pattern | Phase 4 | Tests pass but perf regression 3x | Adapter adds indirection overhead |
561
-
562
- ### Root Cause Analysis
563
- [1-2 sentences: why ALL approaches failed is it architectural, environmental, or requirements-level?]
564
-
565
- ### Recommended Resolutions (pick one)
566
- 1. **Reassign** — different skill/agent with fresh context
567
- 2. **Decompose** break into smaller sub-tasks that CAN succeed independently
568
- 3. **Revise requirements** — relax constraint X to unblock (specify which)
569
- 4. **Accept partial** ship what works, defer blocked portion
570
- 5. **Defer** — park this task, work on something else first
571
-
572
- ### Impact Assessment
573
- - **Blocked by this**: [downstream tasks/phases that depend on this]
574
- - **Not blocked**: [independent work that can continue]
575
- ```
576
-
577
- <HARD-GATE>
578
- "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.
579
- </HARD-GATE>
580
-
581
- ### Subagent Question Gate
582
-
583
- > From superpowers (obra/superpowers, 84k★): "Subagents that start work without asking questions produce the wrong thing 40% of the time."
584
-
585
- Before dispatching a sub-skill (fix, test, review) for a non-trivial task (3+ files OR ambiguous scope):
586
-
587
- 1. **Invite questions**: Include in the handoff: "Before starting, ask up to 3 clarifying questions if anything is unclear."
588
- 2. **Answer before work**: If the sub-skill returns questions → answer them, THEN re-dispatch with answers included.
589
- 3. **Skip if**: Fast/Nano rigor, single-file fix, or sub-skill is haiku-tier (too cheap to gate).
590
-
591
- This prevents the #1 parallel work failure: sub-skill assumes wrong interpretation, builds 500 LOC, then gets rejected in review.
592
-
593
- ### Subagent Status Protocol
594
-
595
- <MUST-READ path="references/subagent-status.md" trigger="when cook or any sub-skill needs to return a status"/>
596
-
597
- Cook and all sub-skills return: `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED`.
598
-
599
- ### Subagent Context Isolation
600
-
601
- When invoking sub-skills (fix, debug, test, review, etc.), **craft exactly the context they need** — never pass the full orchestrator session context.
602
-
603
- | Pass To Sub-Skill | DO NOT Pass |
604
- |-------------------|-------------|
605
- | Task description + specific goal | Full conversation history |
606
- | Relevant file paths from scout | Unrelated files from other phases |
607
- | Project conventions (naming, test framework) | Other sub-skill outputs |
608
- | Plan excerpt for THIS phase only | Full master plan |
609
- | Error/stack trace (for debug/fix) | Previous debug attempts from other bugs |
610
-
611
- **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.
612
-
613
- ## Deviation Rules
614
-
615
- <MUST-READ path="references/deviation-rules.md" trigger="when implementation diverges from the approved plan"/>
616
-
617
- R1-R3 (bug/security/blocking fix): auto-fix, continue. R4 (architectural change): ASK user first.
618
-
619
- ## Error Recovery
620
-
621
- <MUST-READ path="references/error-recovery.md" trigger="when any phase fails or a task hits repeated errors"/>
622
-
623
- Includes phase-by-phase failure handling and repair operators (RETRY → DECOMPOSE → PRUNE) with a 2-attempt budget before escalation.
624
-
625
- ## Analysis Paralysis Guard
626
-
627
- <HARD-GATE>
628
- 5+ consecutive read-only tool calls (Read, Grep, Glob) without a single write action (Edit, Write, Bash) = STUCK.
629
-
630
- You MUST either:
631
- 1. **Act** write code, run a command, create a file
632
- 2. **Report BLOCKED** — state the specific missing piece: "Cannot proceed because [X]"
633
-
634
- Stuck patterns (all banned):
635
- - Reading 10+ files to "fully understand" before acting
636
- - Grepping every variation of a string across the entire repo
637
- - Reading the same file twice in one investigation
638
- - "Let me check one more thing" — repeated after 5 reads
639
-
640
- A wrong first attempt that produces feedback beats perfect understanding that never ships.
641
- </HARD-GATE>
642
-
643
- ### Observation/Effect Ratio Tracking
644
-
645
- Track every tool call during Phase 4 (IMPLEMENT) as either **observation** (read-only) or **effect** (modifies state):
646
-
647
- | Category | Tool Examples |
648
- |----------|--------------|
649
- | **Observation** | Read, Grep, Glob, Bash(grep/ls/cat/git log) |
650
- | **Effect** | Write, Edit, Bash(npm/build/test/mkdir) |
651
-
652
- **Detection rules** (check every 8 tool calls during Phase 4):
653
-
654
- | Pattern | Threshold | Signal | Action |
655
- |---------|-----------|--------|--------|
656
- | **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." |
657
- | **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." |
658
- | **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." |
659
- | **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." |
660
-
661
- **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.
662
-
663
- **Skip if**: Phase 1 (UNDERSTAND) — observation-heavy is expected during research. Only track during Phase 4+ where effects should dominate.
664
-
665
- ### Budget-Aware Phase Progression
666
-
667
- Beyond the existing Exit Conditions (MAX_DEBUG_LOOPS, MAX_QUALITY_LOOPS, etc.), track **cumulative budget** across the entire cook session:
668
-
669
- | Budget | Limit | What Happens at Limit |
670
- |--------|-------|----------------------|
671
- | **Phase 4 react budget** | 15 tool calls per task within Phase 4 | Force: move to next task or report partial completion |
672
- | **Global replan budget** | 2 replans per session (Phase 4 Step 6) | Force: proceed with current plan or escalate to user |
673
- | **Quality retry budget** | 3 total quality re-runs across 5a-5d | Force: ship with known issues documented, don't loop |
674
- | **Total session tool calls** | 150 calls | Force: save state via session-bridge, compact or pause |
675
-
676
- **Hard override rules**:
677
- - If react budget exhausted for a task but task is IN_PROGRESS → force CONTINUE to next task (don't re-attempt)
678
- - If replan budget exhausted but plan still failing → force escalation (don't attempt 3rd replan)
679
- - If quality retry budget exhausted emit concerns in Cook Report, proceed to commit with documented caveats
680
-
681
- **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.
682
-
683
- ### Hash-Based Tool Loop Detection
684
-
685
- <MUST-READ path="references/loop-detection.md" trigger="when same tool+args+result appears to be repeating"/>
686
-
687
- Mentally track tool call fingerprints. 3 identical calls → WARN. 5 identical calls → FORCE STOP. Only same-input-AND-same-output counts as a loop.
688
-
689
- ## Called By (inbound)
690
-
691
- - User: `/rune cook` direct invocation — primary entry point
692
- - `team` (L1): parallel workstream execution (meta-orchestration)
693
-
694
- ## Calls (outbound)
695
-
696
- | Phase | Sub-skill | Layer | Purpose |
697
- |-------|-----------|-------|---------|
698
- | 0 / 8 | `neural-memory` | ext | Recall context at start; capture learnings at end |
699
- | 0.5 | `sentinel-env` | L3 | Environment pre-flight (first run only) |
700
- | 1 | `scout` | L2 | Scan codebase before planning |
701
- | 1 | `onboard` | L2 | Initialize project context if no CLAUDE.md |
702
- | 1 | `ba` | L2 | Requirement elicitation for features |
703
- | 2 | `plan` | L2 | Create implementation plan |
704
- | 2 | `brainstorm` | L2 | Trade-off analysis / rescue mode |
705
- | 2 | `design` | L2 | UI/design phase for frontend features |
706
- | 2.5 | `adversary` | L2 | Red-team challenge on approved plan |
707
- | 3 | `test` | L2 | Write failing tests (RED phase) |
708
- | 4 | `fix` | L2 | Implement code changes (GREEN phase) |
709
- | 4 | `debug` | L2 | Unexpected errors (max 3 loops) |
710
- | 4 | `db` | L2 | Schema changes detected in diff |
711
- | 4 | `worktree` | L3 | Worktree isolation for parallel implementation |
712
- | 5a | `preflight` | L2 | Spec compliance + logic review |
713
- | 5b | `sentinel` | L2 | Security scan |
714
- | 5c | `review` | L2 | Code quality review |
715
- | 5 | `perf` | L2 | Performance regression check (optional) |
716
- | 5 | `audit` | L2 | Project health audit when scope warrants |
717
- | 5 | `review-intake` | L2 | Structured review intake for complex PRs |
718
- | 5 | `sast` | L3 | Static analysis security testing |
719
- | 5d | `completion-gate` | L3 | Validate agent claims against evidence trail |
720
- | 5 | `constraint-check` | L3 | Audit HARD-GATE compliance across workflow |
721
- | 6 | `verification` | L3 | Lint + types + tests + build |
722
- | 6 | `hallucination-guard` | L3 | Verify imports and API calls are real |
723
- | 7 | `journal` | L3 | Record architectural decisions |
724
- | 8 | `session-bridge` | L3 | Save context for future sessions |
725
- | any | `context-pack` | L3 | create structured handoff briefings before spawning subagents |
726
- | any | `skill-forge` | L2 | When new skill creation detected during cook |
727
- | 1.5 | L4 extension packs | L4 | Domain-specific patterns when stack matches |
728
-
729
- ## Data Flow
730
-
731
- **Feeds Into →** `journal` (decisions → ADRs) | `session-bridge` (context .rune/ state) | `neural-memory` (learnings → cross-session)
732
-
733
- **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)
734
-
735
- **Feedback Loops ↻** cook↔debug (Phase 4 bug debug fix resume; if plan wrong Approach Pivot) | cook↔test (RED GREEN → failures loop back)
736
-
737
- ## Constraints
738
-
739
- 1. MUST run scout before planning
740
- 2. MUST get user plan approval before writing code
741
- 3. MUST write failing tests before implementation (TDD) unless explicitly skipped
742
- 4. MUST NOT commit with failing tests
743
- 5. MUST NOT modify files outside approved plan scope without user confirmation
744
- 6. MUST run verification (lint + type-check + tests + build) before commit
745
- 7. MUST NOT say "all tests pass" without showing actual test output
746
- 8. MUST NOT contradict `.rune/decisions.md` without explicit user override
747
-
748
- ## Mesh Gates
749
-
750
- | Gate | Requires | If Missing |
751
- |------|----------|------------|
752
- | Resume Gate | Phase 0 checks for master plan before starting | Proceed to Phase 1 |
753
- | Scout Gate | scout output before Phase 2 | Invoke rune:scout first |
754
- | Plan Gate | User-approved plan before Phase 3 | Cannot proceed |
755
- | Adversary Gate | adversary verdict before Phase 3 for features | Skip for bugfix/hotfix/refactor |
756
- | Phase File Gate | Active phase file only (multi-session) | Load only active phase |
757
- | Test-First Gate | Failing tests before Phase 4 | Write tests or get explicit skip |
758
- | Quality Gate | preflight + sentinel + review before Phase 7 | Fix findings, re-run |
759
- | Verification Gate | lint + types + tests + build green before commit | Fix, re-run |
760
-
761
- ## Structured Output Contract (Prompt-as-API Pattern)
762
-
763
- 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.
764
-
765
- ### Pattern
766
-
767
- ```
768
- INVOCATION: "Analyze [X] and return results as JSON matching this schema:
769
- {
770
- "insights": [{ "id": string, "category": string, "description": string, "actionable": string }],
771
- "confidence": number,
772
- "next_steps": string[]
773
- }
774
- Do NOT include explanatory text outside the JSON block."
775
- ```
776
-
777
- ### When to Apply
778
-
779
- | Phase | Sub-skill | Output Contract |
780
- |-------|-----------|----------------|
781
- | Phase 1 | `ba` | `{ requirements: [{id, priority, description, acceptance_criteria}], ambiguities: string[] }` |
782
- | Phase 2 | `plan` | `{ phases: [{name, tasks: [{description, files, effort}], dependencies}] }` |
783
- | Phase 3 | `test` | `{ test_cases: [{name, type, file, assertion}], coverage_targets: string[] }` |
784
- | Phase 5 | `review` | `{ findings: [{severity, file, line, description, fix}], verdict: "PASS"|"WARN"|"BLOCK" }` |
785
-
786
- ### Rules
787
-
788
- - Include 1-2 concrete examples in the prompt — examples are worth more than schema descriptions
789
- - Always specify "Do NOT include explanatory text outside the JSON/markdown block" — LLMs default to wrapping structured output in prose
790
- - When the output will be consumed by another skill (not displayed to user), ALWAYS use this pattern
791
- - When the output will be displayed to the user, use markdown format instead — humans don't read JSON
792
-
793
- ### Why
794
-
795
- 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.
796
-
797
- ## Output Format
798
-
799
- <MUST-READ path="references/output-format.md" trigger="before emitting the Cook Report at end of any session"/>
800
-
801
- Emit a Cook Report with: Status, Phases, Files Changed, Tests, Quality results, Commit hash.
802
- When invoked by `team` with a NEXUS Handoff, include the Deliverables table MANDATORY.
803
-
804
- ## Returns
805
-
806
- | Artifact | Format | Location |
807
- |----------|--------|----------|
808
- | Plan files (master + phase) | Markdown | `.rune/plan-<feature>.md`, `.rune/plan-<feature>-phase<N>.md` |
809
- | Implementation code | Source files | Per plan file paths |
810
- | Test files | Source files | Co-located or `__tests__/` per project convention |
811
- | Verification results | Inline stdout | Shown in Cook Report |
812
- | Cook Report | Markdown (inline) | Emitted at end of session |
813
- | Session state | Markdown | `.rune/decisions.md`, `.rune/progress.md`, `.rune/conventions.md` |
814
-
815
- ## Document Ownership
816
-
817
- | Scope | Access | Files |
818
- |-------|--------|-------|
819
- | **Owns** (read + write) | `.rune/plan-*.md`, `.rune/progress.md`, `.rune/decisions.md`, `.rune/conventions.md`, source files per approved plan |
820
- | **Reads** (never writes) | `CLAUDE.md`, `SKILL.md` (any), `.rune/contract.md`, `.rune/checkpoint.md` |
821
- | **Never modifies** | `compiler/**`, `extensions/**`, `PACK.md`, other skills' `SKILL.md`, `.rune/learnings.jsonl` |
822
-
823
- When delegating to sub-skills (scout, plan, test, review), each sub-skill owns its own output. Cook coordinates but does not overwrite sub-skill artifacts.
824
-
825
- ## Anti-Patterns
826
-
827
- Common multi-agent failures to explicitly avoid. These are NOT edge cases — they are the most frequent cook failures in production.
828
-
829
- | Anti-Pattern | Why It Fails | Correct Approach |
830
- |---|---|---|
831
- | **Bypass hierarchy** — skipping scout/plan and jumping to Phase 4 code | Builds wrong thing. Most "wasted work" traces back to missing Phase 1-2 | Follow phase gates. Even "obvious" tasks benefit from 30s of scout |
832
- | **Shadow decisions** making architectural choices without logging to decisions.md | Next session repeats the same debate. Team agents contradict each other | Log every non-trivial choice via `decisions.md` or `journal` |
833
- | **Gold-plating** adding "nice-to-have" features not in the approved plan | Scope creep, delayed delivery, untested code paths | Build ONLY what's in the plan. Log extras as follow-up tasks |
834
- | **Test-after** writing tests after implementation instead of before (TDD violation) | Tests validate implementation bugs, not requirements. Coverage looks good but misses edge cases | Phase 3 (RED) before Phase 4 (GREEN). Always |
835
- | **Monolithic commit** — one giant commit with all changes | Impossible to revert partially. Review is overwhelming | Commit per phase or per logical unit. Small, reviewable diffs |
836
- | **Assumption-based implementation** — guessing requirements instead of asking | Builds the wrong thing confidently. User discovers mismatch late | If ambiguous, ask. 30s of clarification saves 30min of rework |
837
-
838
- ## Sharp Edges
839
-
840
- <MUST-READ path="references/sharp-edges.md" trigger="before declaring done review all 18 failure modes"/>
841
-
842
- **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.
843
-
844
- ## Self-Validation
845
-
846
- ```
847
- SELF-VALIDATION (run before emitting Cook Report):
848
- - [ ] Every phase in Phase Skip Rules was either executed or explicitly skipped with reason
849
- - [ ] Plan approval gate was not bypassed user said "go" (check conversation history)
850
- - [ ] No Phase 4 code was written before Phase 3 tests (TDD order preserved)
851
- - [ ] All Phase 5 quality gates (preflight, sentinel, review) ran not just claimed
852
- - [ ] Cook Report contains actual commit hash, not placeholder
853
- ```
854
-
855
- ## Done When
856
-
857
- All applicable phases complete + Self-Validation passed:
858
- - User approved plan | All tests PASS (output shown) | preflight+sentinel+review PASS | build green
859
- - Cook Report emitted with commit hash | Session state saved to .rune/ via session-bridge
860
-
861
- ## Cost Profile
862
-
863
- ~$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.4.0"
9
+ layer: L1
10
+ model: sonnet
11
+ group: orchestrator
12
+ tools: "Read, Write, Edit, Bash, Glob, Grep"
13
+ emit: phase.complete, checkpoint.request
14
+ listen: plan.ready, review.complete, ideas.ready, preflight.passed, verification.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 → implement → quality (Phase 1 → 2 → 4 → 5 → 6 → 7)
39
+ /rune cook security → Full pipeline + sentinel@opus + sast (all phases, security-escalated)
40
+ /rune cook hotfix → Production Hotfix Protocol: contain → fix → verify → deploywatchdogpostmortem (see below)
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
+ ### Production Hotfix Protocol
46
+
47
+ When `hotfix` chain is active AND triggered from a live incident (not a dev-time fix), follow the full orchestrated chain — not just fix → verify → commit.
48
+
49
+ ```
50
+ FULL HOTFIX CHAIN (when incident is active):
51
+
52
+ 1. CONTAIN`rune:incident` (if not already running): triage + contain blast radius first
53
+ 2. BRANCHcreate hotfix branch via worktree (isolate from main)
54
+ 3. FIX`rune:fix` (minimal change only no refactoring, no scope creep)
55
+ 4. VERIFY `rune:verification` (full test suite on hotfix branch)
56
+ 5. SENTINEL `rune:sentinel` (security check fix may introduce new surface)
57
+ 6. DEPLOY `rune:deploy` (deploy hotfix to production)
58
+ 7. WATCHDOG`rune:watchdog` (confirm health check passes post-deploy)
59
+ 8. POSTMORTEM → `rune:journal` + `rune:neural-memory` (capture root cause + fix pattern)
60
+
61
+ HARD-GATES:
62
+ - Do NOT skip CONTAIN if users are actively affected
63
+ - Do NOT skip SENTINEL on hotfix — rushed fixes frequently introduce new vulnerabilities
64
+ - Do NOT merge hotfix to main without VERIFY passing
65
+ - Do NOT skip POSTMORTEMhotfix without learning = same incident next month
66
+ ```
67
+
68
+ **Minimal hotfix chain (non-incident, dev-time):** Phase 4 → 6 → 7 (fix → verify → commit). User provides context, skip scout.
69
+
70
+ ### Template Workflows (Pro/Business)
71
+
72
+ When `--template <name>` is provided, cook loads a pre-built workflow template instead of auto-detecting:
73
+
74
+ ```
75
+ /rune cook --template product-discovery → Pro: stakeholder interviews problem framing competitive spec validation
76
+ /rune cook --template product-launch → Pro: spec lock implementquality gates staged rollout announcement
77
+ /rune cook --template product-iteration Pro: metrics review feedback synthesis → re-prioritize → implement → measure
78
+ /rune cook --template data-exploration → Pro: data profiling hypotheses → statistical testing → visualization → report
79
+ /rune cook --template data-pipeline → Pro: schema design → ETL → quality gates → deploy → monitoring
80
+ /rune cook --template sales-outreach-campaign → Pro: prospect research → messaging → sequence → A/B test → launch
81
+ /rune cook --template sales-deal-review → Pro: account deep-dive → risk assessment → competitive strategy → action plan
82
+ /rune cook --template support-incident-response Pro: triage → diagnose → fix → verify → postmortem → KB update
83
+ /rune cook --template support-kb-refresh → Pro: audit → gap analysis → draft → review → publish
84
+ ```
85
+
86
+ **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.
87
+
88
+ **When --template is used**:
89
+ 1. Skip Phase 1.5 (auto-detection) template pre-selects domain and pack
90
+ 2. Skip Phase 1.7 (workflow matching) — template IS the workflow
91
+ 3. Load template phases as the master plan (Phase 2 becomes "review template plan" not "create plan")
92
+ 4. Execute each template phase in order, invoking declared skills
93
+ 5. Emit template's declared signals on completion
94
+
95
+ **Chain selection**: If user invokes `/rune cook` without a chain type, auto-detect from the task description:
96
+ - Contains "bug", "fix", "broken", "error" → `bugfix`
97
+ - Contains "refactor", "clean", "restructure" → `refactor`
98
+ - Contains "security", "auth", "vulnerability", "CVE" → `security`
99
+ - Contains "urgent", "hotfix", "production" `hotfix`
100
+ - Contains "quick", "just", "chỉ cần", "copy", "move", "rename", "bump" → `nano`
101
+ - Contains "graft", "port from", "copy from repo", "clone feature from" → **delegate to `rune:graft`** (not a cook chain — hand off entirely)
102
+ - Contains `--template` → load template workflow (see above)
103
+ - Default `feature`
104
+
105
+ ## Phase Skip Rules
106
+
107
+ Not every task needs every phase:
108
+
109
+ ```
110
+ Nano task: DO VERIFY DONE (no phases, auto-detected)
111
+ Simple bug fix: Phase 1 4 6 7
112
+ Small refactor: Phase 1 → 4 → 5 → 6 → 7
113
+ New feature: Phase 1 → 1.5 → 2 → 3 → 4 → 5 → 6 → 7 → 8
114
+ Complex feature: All phases + brainstorm in Phase 2
115
+ Security-sensitive: All phases + sentinel escalated to opus
116
+ Fast mode: Phase 1 → 4 → 6 → 7 (auto-detected, see below)
117
+ Multi-session: Phase 0 (resume) 3 4 567 (one plan phase per session)
118
+ ```
119
+
120
+ Determine complexity BEFORE starting using the Rigor Assessment below. Create TodoWrite with applicable phases.
121
+
122
+ ### Rigor Assessment (Progressive Scaling)
123
+
124
+ 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.
125
+
126
+ | Risk Signal | Weight | Detection |
127
+ |-------------|--------|-----------|
128
+ | Files affected: 1 | 0 | Estimate from task description + scout |
129
+ | Files affected: 2-3 | +1 | |
130
+ | Files affected: 4+ | +3 | |
131
+ | Cross-module impact (changes span 2+ directories) | +2 | scout identifies touch points across boundaries |
132
+ | Security-sensitive code (auth, crypto, payments, secrets) | +3 | Keyword match in file paths or task description |
133
+ | Public API change (exports, routes, schema) | +2 | Task modifies interfaces consumed by external code |
134
+ | Database schema change | +2 | Task mentions migration, schema, ALTER, column |
135
+ | New dependency added | +1 | Task requires `npm install` or equivalent |
136
+ | Code will be imported by other modules | +1 | New exports or modifications to shared utilities |
137
+
138
+ **Rigor level mapping:**
139
+
140
+ | Score | Level | Maps To | Phases |
141
+ |-------|-------|---------|--------|
142
+ | 0 | Nano | `nano` chain | DO VERIFY → DONE |
143
+ | 1-2 | Fast | `fast` mode | Phase 1 → 4 → 6 → 7 |
144
+ | 3-5 | Standard | `bugfix` / `refactor` | Phase 1 → 2 → 4 → 5 → 6 → 7 |
145
+ | 6-8 | Full | `feature` | Phase 1 → 1.5 → 2 → 3 → 4 → 5 → 6 → 7 → 8 |
146
+ | 9+ | Critical | `security` / full + adversary | All phases + sentinel@opus + adversary |
147
+
148
+ **Rules:**
149
+ - Security signal (+3) automatically floors rigor at Standard — NEVER nano/fast for security code
150
+ - User can override: "full pipeline" forces Full, "just do it" forces Nano
151
+ - 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."
152
+ - Announce chosen level: "Rigor: Fast (score 2 single file, no security)"
153
+
154
+ ## Nano Mode (Auto-Detect)
155
+
156
+ For trivial tasks that don't need any pipeline at all:
157
+
158
+ ```
159
+ IF all of these are true:
160
+ - Task is ≤3 discrete steps (e.g., run command, edit 1 file, commit)
161
+ - Task description < 60 chars OR user prefixes with "quick:", "just", "chỉ cần"
162
+ - No code logic changes (copy files, config edits, version bumps, git ops, run scripts)
163
+ - No new functions/classes/components created
164
+ THEN: Nano Mode activated
165
+ - Execute directly: DO VERIFY → DONE
166
+ - No phases. No plan. No test. No review.
167
+ - Still verify output (check exit codes, confirm file exists, etc.)
168
+ - Still use semantic commit message if committing
169
+ ```
170
+
171
+ **Announce**: "Nano mode: trivial task, executing directly."
172
+ **Override**: User can say "full pipeline" or "cook feature" to force phases.
173
+ **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.
174
+
175
+ <HARD-GATE>
176
+ Nano mode MUST NOT be used for:
177
+ - Any code that will be imported/called by other code
178
+ - Security-relevant files (auth, crypto, payments, .env, secrets)
179
+ - Database schema changes
180
+ - Public API changes
181
+ If any of these are detected mid-task, STOP and upgrade to Fast/Full mode.
182
+ </HARD-GATE>
183
+
184
+ ## Fast Mode (Auto-Detect)
185
+
186
+ Cook auto-detects small changes and streamlines the pipeline:
187
+
188
+ ```
189
+ IF all of these are true:
190
+ - Total estimated change < 30 LOC
191
+ - Single file affected
192
+ - No security-relevant code (auth, crypto, payments, .env)
193
+ - No public API changes
194
+ - No database schema changes
195
+ THEN: Fast Mode activated
196
+ - Skip Phase 2 (PLAN) change is too small for a formal plan
197
+ - Skip Phase 3 (TEST) unless existing tests cover the area
198
+ - Skip Phase 5b (SENTINEL) — non-security code
199
+ - Skip Phase 8 (BRIDGE)not worth persisting
200
+ - KEEP Phase 5a (PREFLIGHT) and Phase 6 (VERIFY) — always run quality checks
201
+ ```
202
+
203
+ **Announce fast mode**: "Fast mode: small change detected (<30 LOC, single file, non-security). Streamlined pipeline."
204
+ **Override**: User can say "full pipeline" to force all phases even on small changes.
205
+
206
+ ## Phase 0.5: ENVIRONMENT CHECK (First Run Only)
207
+
208
+ **SUB-SKILL**: Use `rune:sentinel-env` verify the environment can run the project before planning.
209
+
210
+ 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`.
211
+
212
+ ## Phase 1: UNDERSTAND
213
+
214
+ **Goal**: Know what exists before changing anything.
215
+
216
+ **REQUIRED SUB-SKILLS**: Use `rune:scout`. For non-trivial tasks, use `rune:ba`.
217
+
218
+ 1. Create TodoWrite with all applicable phases for this task
219
+ 2. Mark Phase 1 as `in_progress`
220
+ 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.
221
+ 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.
222
+ 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.
223
+
224
+ ### Phase 1 Step 3.5 Clarification Gate
225
+
226
+ Ask **2 questions** before planning: (1) "What does success look like?" (2) "What should NOT change?"
227
+
228
+ 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`.
229
+
230
+ 5. Invoke scout to scan the codebase (Glob + Grep + Read on relevant files)
231
+ 6. Summarize: what exists, project conventions, files likely to change, active decision constraints
232
+ 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`
233
+ 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:
234
+ - List alternatives with 1-line trade-off each
235
+ - Flag to Phase 2 (plan) for formal comparison
236
+ - Separating "thinking" (Phase 1) from "committing" (Phase 2) prevents premature lock-in
237
+ 9. Mark Phase 1 as `completed`
238
+
239
+ **Gate**: If scout finds the feature already exists STOP and inform user.
240
+
241
+ ## Phase 1.5: DOMAIN CONTEXT (L4 Pack Detection)
242
+
243
+ **Goal**: Detect if domain-specific L4 extension packs apply to this task.
244
+
245
+ <MUST-READ path="references/pack-detection.md" trigger="Phase 1.5 before checking L4 pack mapping"/>
246
+
247
+ 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.
248
+
249
+ ## Phase 1.7: WORKFLOW ORCHESTRATION (Multi-Skill Sequences)
250
+
251
+ **Goal**: If Phase 1.5 detected a pack AND the task maps to a named workflow, orchestrate the multi-skill sequence.
252
+
253
+ **Trigger**: Only runs if Phase 1.5 found a pack match AND the pack's Workflows table has a matching command.
254
+
255
+ <MUST-READ path="references/pack-detection.md" trigger="Phase 1.7 workflow command detection section"/>
256
+
257
+ 1. Read the matched PACK.md's Workflows section
258
+ 2. Identify the workflow name and skill sequence
259
+ 3. For each skill in sequence:
260
+ a. Load the skill file from the pack's `skills/` directory
261
+ b. Execute the skill's workflow steps
262
+ c. Write output artifact to `.rune/<domain>/` (e.g., `.rune/hr/jd-[role]-[date].md`)
263
+ d. The next skill reads the previous artifact as input context
264
+ 4. After all skills complete: summarize the workflow results to the user
265
+
266
+ **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.
267
+
268
+ **Skip if**: No workflow match found in Phase 1.5. Single-skill tasks proceed directly to Phase 2 (PLAN) as normal.
269
+
270
+ ## Phase 0: RESUME CHECK (Before Phase 1)
271
+
272
+ **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.
273
+
274
+ **Step 0.4 — Template Detection**: If user passed `--template <name>`:
275
+ 1. Search installed pack templates for the name: `Glob` for `extensions/*/templates/<name>.md` and `extensions/pro-*/templates/<name>.md`
276
+ 2. If found: `Read` the template file → parse phases, signals, connections, acceptance criteria
277
+ 3. Generate a master plan from the template: each template phase becomes a plan phase
278
+ 4. Write plan files to `.rune/plan-<template-name>.md` + `.rune/plan-<template-name>-phaseN.md`
279
+ 5. Announce "Loading template: <name> (<pack>)" → skip Phase 1, 1.5, 1.7, 2 → proceed to Phase 4 with Phase 1 of the template
280
+ 6. If template not found: warn user and fall through to normal workflow
281
+
282
+ **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"`).
283
+
284
+ 1. Use `Glob` to check for `.rune/plan-*.md` files
285
+ 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
286
+ 3. If no master plan exists proceed to Phase 1 as normal
287
+
288
+ **Step 0.6 — Contract Load**: Use `Glob` to check for `.rune/contract.md`. If it exists:
289
+ 1. `Read` the contract file and parse each `## section` as a named rule set
290
+ 2. Hold contract rules in context — they apply as **hard gates** throughout all phases
291
+ 3. Any code change that violates a contract rule → STOP and inform user before proceeding
292
+ 4. If no contract exists → proceed normally (contract is optional)
293
+
294
+ <HARD-GATE>
295
+ 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.
296
+ </HARD-GATE>
297
+
298
+ **This enables multi-session workflows**: Opus plans once → each session picks up the next phase.
299
+
300
+ ## Phase 2: PLAN
301
+
302
+ **Goal**: Break the task into concrete implementation steps before writing code.
303
+
304
+ **REQUIRED SUB-SKILL**: Use `rune:plan`
305
+
306
+ 1. Mark Phase 2 as `in_progress`
307
+ 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.
308
+ 3. Create implementation plan: exact files to create/modify, change order, dependencies, active decision constraints
309
+ 4. If multiple valid approaches exist invoke `rune:brainstorm` for trade-off analysis
310
+ 5. Present plan to user for approval
311
+ 6. If feature workspace was created, write approved plan to `.rune/features/<name>/plan.md`
312
+ 7. Mark Phase 2 as `completed`
313
+
314
+ **Gate**: User MUST approve the plan before proceeding. Do NOT skip this.
315
+
316
+ ### Phase 2.5: RFC GATE (Breaking Changes Only)
317
+
318
+ **Goal**: Formal change management for breaking changes. Prevents unreviewed breaking changes from reaching production.
319
+
320
+ <MUST-READ path="references/rfc-template.md" trigger="Phase 2.5 any time a breaking change is detected in the plan"/>
321
+
322
+ <HARD-GATE>
323
+ Breaking change without RFC = BLOCKED. No exceptions.
324
+ "It's just a small change" is the #1 excuse for production incidents from unreviewed breaking changes.
325
+ </HARD-GATE>
326
+
327
+ ### Phase 2.5: ADVERSARY (Red-Team Challenge)
328
+
329
+ **Goal**: Stress-test the approved plan BEFORE writing code — catch flaws at plan time, not implementation time.
330
+
331
+ **REQUIRED SUB-SKILL**: Use `rune:adversary`
332
+
333
+ 1. **Skip conditions**: bug fixes, hotfixes, simple refactors (< 3 files, no new logic), fast mode
334
+ 2. **Run adversary** — Full Red-Team mode for new features/architectural changes; Quick Challenge mode for smaller plans
335
+ 3. **Handle verdict**:
336
+ - **REVISE** → return to Phase 2 with adversary findings as constraints; user must re-approve
337
+ - **HARDEN** present remediations, update plan inline, then proceed to Phase 3
338
+ - **PROCEED** pass findings as implementation notes to Phase 3
339
+ 4. **Max 1 REVISE loop** per cook session if revised plan also gets REVISE, ask user to decide
340
+
341
+ ### Phase-Aware Execution (Master Plan + Phase Files)
342
+
343
+ When `rune:plan` produces a **master plan + phase files** (non-trivial tasks):
344
+
345
+ 1. After plan approval: load ONLY Phase 1's file — do NOT load all phase files
346
+ 2. Execute through cook Phase 3-6 (test → implement → quality → verify)
347
+ 3. After phase complete: mark tasks done, update master plan status `⬚ → ✅`, announce "Phase N complete. Phase N+1 ready for next session."
348
+ 4. Next session: Phase 0 detects master plan → loads next phase → executes
349
+
350
+ <HARD-GATE>
351
+ NEVER load multiple phase files at once. One phase per session = small context = better code.
352
+ If the coder model needs info from other phases, it's in the Cross-Phase Context section of the current phase file.
353
+ </HARD-GATE>
354
+
355
+ ## Phase 3: TEST (TDD Red)
356
+
357
+ **Goal**: Define expected behavior with failing tests BEFORE writing implementation.
358
+
359
+ **REQUIRED SUB-SKILL**: Use `rune:test`
360
+
361
+ 1. Mark Phase 3 as `in_progress`
362
+ 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.
363
+ 3. Write test files based on the plan — cover primary use case + edge cases; tests MUST be runnable
364
+ 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
365
+ 5. Run tests to verify they FAIL expected: RED because implementation doesn't exist yet
366
+ 6. Mark Phase 3 as `completed`
367
+
368
+ **Gate**: Tests MUST exist and MUST fail. If tests pass without implementation → tests are wrong, rewrite them.
369
+
370
+ ## Phase 4: IMPLEMENT (TDD Green)
371
+
372
+ **Goal**: Write the minimum code to make tests pass.
373
+
374
+ **REQUIRED SUB-SKILL**: Use `rune:fix`
375
+
376
+ 1. Mark Phase 4 as `in_progress`
377
+ 2. **Phase-file execution** if working from a master plan + phase file:
378
+ - Execute tasks from `## Tasks` section wave-by-wave
379
+ - Wave N only starts after ALL Wave N-1 tasks complete
380
+ - Follow Code Contracts, Rejection Criteria, Failure Scenarios from the phase file
381
+ - Mark each task `[x]` as completed
382
+ 3. Implement the feature following the plan (Write for new files, Edit for existing)
383
+ 4. Run tests after each significant changeif fail debug and fix
384
+ - **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
385
+ 5. If stuck invoke `rune:debug` (max 3 debug↔fix loops). Fixes outside plan scope require user approval (R4).
386
+ 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.
387
+ 7. **Approach Pivot Gate** — if re-plan ALSO fails:
388
+
389
+ <HARD-GATE>
390
+ Do NOT surrender. Do NOT tell user "no solution exists."
391
+ Do NOT try a 4th variant of the same approach.
392
+ MUST invoke brainstorm(mode="rescue") before giving up.
393
+ </HARD-GATE>
394
+
395
+ Invoke `rune:brainstorm(mode="rescue")` with `failed_approach`, `failure_evidence[]`, `original_goal`. Returns 3-5 alternatives → user picks → **restart from Phase 2**.
396
+
397
+ 8. All tests MUST pass before proceeding
398
+ 9. Mark Phase 4 as `completed`
399
+
400
+ **Gate**: ALL tests from Phase 3 MUST pass. Do NOT proceed with failing tests.
401
+
402
+ ## Phase 5: QUALITY (Staged)
403
+
404
+ **Goal**: Catch issues before they reach production.
405
+
406
+ 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.
407
+
408
+ **Signal dispatch ordering**: When `fix` emits `code.changed`, 4 listeners react (preflight, sentinel, test, review). Cook coordinates dispatch order — do NOT let all 4 fire simultaneously:
409
+ - **Stage 1**: preflight + sentinel (parallel — independent checks)
410
+ - **Stage 2**: test (after Stage 1 passes no point testing non-compliant code)
411
+ - **Stage 3**: review (after test passes — review verified code only)
412
+
413
+ ```
414
+ STAGE 1 (parallel):
415
+ Launch 5a (preflight) + 5b (sentinel) simultaneously.
416
+ Wait for BOTH to complete.
417
+ If 5a returns BLOCK → fix spec gaps, re-run 5a. Code review CANNOT start on non-compliant code.
418
+ If 5b returns BLOCK fix security issue, re-run 5b.
419
+
420
+ STAGE 2 (after Stage 1 passes):
421
+ Launch 5c (review) + 5d (completion-gate) simultaneously.
422
+ If any returns BLOCK → fix findings, re-run the blocking check only.
423
+ ```
424
+
425
+ ### Remediation Cycle Counter
426
+
427
+ Every BLOCK finding gets a cycle counter. Fix re-run still BLOCK? Increment. **Max 3 cycles per gate** before escalation.
428
+
429
+ ```
430
+ Cycle 1: fix finding → re-run gate
431
+ Cycle 2: different fix → re-run gate
432
+ Cycle 3: last attempt → re-run gate
433
+ Cycle 4: STOP. Escalate to user with all 3 failed attempts + evidence.
434
+ ```
435
+
436
+ Track per-gate, not globally — preflight cycle 2 does not count against sentinel cycle 1. If the SAME finding persists across 3 cycles, the fix approach is wrong — do NOT keep trying the same strategy. Cycle 2+ MUST try a different fix than Cycle 1.
437
+
438
+ ### Upstream Inconsistency Protocol
439
+
440
+ During Phase 5 quality checks, if a gate finding traces to an **upstream artifact** (plan was wrong, spec was incomplete, architecture was flawed) rather than an implementation bug:
441
+
442
+ 1. Tag finding as `UPSTREAM:<phase>` (e.g., `UPSTREAM:plan`, `UPSTREAM:spec`)
443
+ 2. STOP current quality gate — fixing code won't resolve an upstream problem
444
+ 3. Re-invoke the upstream skill (`rune:plan` for plan issues, `rune:ba` for spec gaps) with the finding as context
445
+ 4. Get user approval on the corrected upstream artifact
446
+ 5. Resume Phase 5 from the beginning (re-run all gates — upstream change may invalidate prior PASS results)
447
+
448
+ ### 5a. Preflight (Spec Compliance + Logic) — STAGE 1
449
+ **REQUIRED SUB-SKILL**: Use `rune:preflight`
450
+ - Spec compliance: compare approved plan vs actual diff
451
+ - Logic review, error handling, completeness
452
+ - **Must pass before 5c (review) can start** — no point reviewing code quality if it doesn't match the spec
453
+
454
+ ### 5b. Security — STAGE 1
455
+ **REQUIRED SUB-SKILL**: Use `rune:sentinel`
456
+ - Secret scan, OWASP check (no injection/XSS/CSRF), dependency audit
457
+
458
+ ### 5c. Code Review — STAGE 2
459
+ **REQUIRED SUB-SKILL**: Use `rune:review`
460
+ - Pattern compliance, code quality, performance bottlenecks
461
+ - Reviewer reads code independently — does NOT rely on implementer's claims
462
+ - **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.
463
+
464
+ ### 5d. Completion Gate — STAGE 2
465
+ **REQUIRED SUB-SKILL**: Use `rune:completion-gate`
466
+ - Validate agent claims match evidence trail (tests ran, files changed, build passed)
467
+ - No truncated code files (`// ...`, `// rest of code`, bare ellipsis) — agent MUST complete all output
468
+ - Any UNCONFIRMED claim → BLOCK
469
+
470
+ **Gate**: If sentinel finds CRITICAL security issue → STOP, fix it, re-run. Non-negotiable.
471
+ **Gate**: If completion-gate finds UNCONFIRMED claim → STOP, re-verify. Non-negotiable.
472
+
473
+ ## Per-Phase Rules (Project-Specific)
474
+
475
+ 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.
476
+
477
+ ```markdown
478
+ # .rune/phase-rules.md (example)
479
+
480
+ ## Phase 2: PLAN
481
+ - All API endpoints must follow REST naming convention /api/v1/<resource>
482
+ - Database changes require a rollback migration
483
+
484
+ ## Phase 3: TEST
485
+ - Enforce TDD format: describe → it → arrange → act → assert
486
+ - Minimum 3 edge cases per public function
487
+
488
+ ## Phase 5: QUALITY
489
+ - Review must check for N+1 queries on any ORM code
490
+ - Sentinel must verify CORS configuration on new routes
491
+ ```
492
+
493
+ **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.
494
+
495
+ ## Checkpoint Protocol (Opt-In)
496
+
497
+ 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.
498
+
499
+ ## Phase Transition Protocol (MANDATORY)
500
+
501
+ 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.
502
+
503
+ **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.
504
+
505
+ ## Phase 6: VERIFY
506
+
507
+ **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.
508
+
509
+ ## Phase 7: COMMIT
510
+
511
+ **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."
512
+
513
+ ## Phase 8: BRIDGE
514
+
515
+ **Goal**: Save context for future sessions and record metrics for mesh analytics.
516
+
517
+ **REQUIRED SUB-SKILL**: Use `rune:session-bridge`
518
+
519
+ 1. Mark Phase 8 as `in_progress`
520
+ 2. Save to `.rune/decisions.md` (approach + trade-offs), `.rune/progress.md` (task complete), `.rune/conventions.md` (new patterns)
521
+ 3. **Skill metrics** `.rune/metrics/skills.json`: increment phase run/skip counts, quality gate results, debug loop counts under `cook` key
522
+ 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.
523
+ 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:
524
+ - [ ] `README.md` — stats, badges, feature list
525
+ - [ ] `docs/index.html` (landing page) — meta tags, hero badge, install section, mesh stats, footer
526
+ - [ ] `dashboard.html` (if local) — KPI cards, test count, skill tabs, layer counts
527
+ - [ ] `CLAUDE.md` commands, test count, skill list
528
+ - [ ] `MEMORY.md` — milestones, version info
529
+
530
+ **Skip if**: No stats changed (pure refactor, docs-only, style change). **MANDATORY** if any numeric stat in README differs from actual.
531
+ 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.
532
+ 6. Mark Phase 8 as `completed`
533
+
534
+ ## Autonomous Loop Patterns
535
+
536
+ When cook runs inside `team` (L1) or autonomous workflows, these patterns apply.
537
+
538
+ ### De-Sloppify Pass
539
+
540
+ 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.
541
+
542
+ **Trigger**: Implementation touched 3+ files OR 100+ LOC changed. Skip for nano/fast rigor.
543
+
544
+ **Slop targets** (check every modified file):
545
+
546
+ | Slop Type | Detection | Fix |
547
+ |-----------|-----------|-----|
548
+ | Leftover debug | `console.log`, `print()`, `debugger`, `TODO: remove` | Delete |
549
+ | Over-defensive checks | Null checks on values guaranteed non-null by TypeScript/framework | Remove redundant guard |
550
+ | Type-test slop | `typeof x === 'string'` when x is already typed as string | Remove — trust the type system |
551
+ | Duplicated logic | Same 3+ lines appear in multiple places | Extract utility |
552
+ | Framework-behavior tests | Tests asserting that React renders, that Express routes exist, that mocks work | Delete — test YOUR code, not the framework |
553
+ | Inconsistent naming | Mixed `camelCase`/`snake_case` in same file | Normalize to project convention |
554
+ | Dead imports | Imports no longer used after edits | Remove |
555
+
556
+ **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.
557
+
558
+ ### Continuous PR Loop (team orchestration only)
559
+
560
+ ```
561
+ cook instance → commit → push → create PR → wait CI
562
+ IF CI passes → mark workstream complete
563
+ IF CI fails read CI output fix push wait CI (max 3 retries)
564
+ IF 3 retries fail → escalate to user with CI logs
565
+ ```
566
+
567
+ ### Formal Pause/Resume (`.continue-here.md`)
568
+
569
+ <MUST-READ path="references/pause-resume-template.md" trigger="when cook must pause mid-phase (context limit, user break, session end)"/>
570
+
571
+ 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.
572
+
573
+ ### Mid-Run Signal Detection
574
+
575
+ <MUST-READ path="references/mid-run-signals.md" trigger="when user sends a message DURING cook execution"/>
576
+
577
+ Two-stage intent classification: keyword fast-path for short messages (<60 chars), context classification for longer ones. Never queue user messages — process immediately.
578
+
579
+ <HARD-GATE>
580
+ NEVER treat a Cancel/Pause signal as a Steer or NewTask. User safety signals take absolute priority.
581
+ If ambiguous between Cancel and Steer → ask user: "Did you mean stop, or change approach?"
582
+ </HARD-GATE>
583
+
584
+ ### Exit Conditions (Mandatory for Autonomous Runs)
585
+
586
+ <MUST-READ path="references/exit-conditions.md" trigger="cook running inside team or any autonomous workflow"/>
587
+
588
+ Hard caps: MAX_DEBUG_LOOPS=3, MAX_QUALITY_LOOPS=2, MAX_REPLAN=1, MAX_PIVOT=1, MAX_FIXES=30, WTF_THRESHOLD=20%.
589
+ Escalation chain: debug-fix (3x) re-plan (1x) brainstorm rescue (1x) THEN escalate to user.
590
+
591
+ ### Structured Escalation Report
592
+
593
+ > From agency-agents (msitarzewski/agency-agents, 50.8k★): "After 3 retry failures, structured escalation prevents cargo-cult retrying."
594
+
595
+ 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":
596
+
597
+ ```markdown
598
+ ## Escalation Report
599
+ - **Task**: [original task description]
600
+ - **Status**: BLOCKED
601
+ - **Attempts**: [count] across [N] phases
602
+
603
+ ### Failure History
604
+ | # | Approach | Phase | Outcome | Root Cause |
605
+ |---|---------|-------|---------|------------|
606
+ | 1 | Direct fix | Phase 4 | Tests fail null ref in auth.ts:42 | Missing user context |
607
+ | 2 | Re-plan with guard clause | Phase 4 | Build fails — circular import | Guard approach introduces cycle |
608
+ | 3 | Brainstorm rescue adapter pattern | Phase 4 | Tests pass but perf regression 3x | Adapter adds indirection overhead |
609
+
610
+ ### Root Cause Analysis
611
+ [1-2 sentences: why ALL approaches failedis it architectural, environmental, or requirements-level?]
612
+
613
+ ### Recommended Resolutions (pick one)
614
+ 1. **Reassign** — different skill/agent with fresh context
615
+ 2. **Decompose** break into smaller sub-tasks that CAN succeed independently
616
+ 3. **Revise requirements** — relax constraint X to unblock (specify which)
617
+ 4. **Accept partial** ship what works, defer blocked portion
618
+ 5. **Defer** — park this task, work on something else first
619
+
620
+ ### Impact Assessment
621
+ - **Blocked by this**: [downstream tasks/phases that depend on this]
622
+ - **Not blocked**: [independent work that can continue]
623
+ ```
624
+
625
+ <HARD-GATE>
626
+ "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.
627
+ </HARD-GATE>
628
+
629
+ ### Subagent Question Gate
630
+
631
+ > From superpowers (obra/superpowers, 84k★): "Subagents that start work without asking questions produce the wrong thing 40% of the time."
632
+
633
+ Before dispatching a sub-skill (fix, test, review) for a non-trivial task (3+ files OR ambiguous scope):
634
+
635
+ 1. **Invite questions**: Include in the handoff: "Before starting, ask up to 3 clarifying questions if anything is unclear."
636
+ 2. **Answer before work**: If the sub-skill returns questions answer them, THEN re-dispatch with answers included.
637
+ 3. **Skip if**: Fast/Nano rigor, single-file fix, or sub-skill is haiku-tier (too cheap to gate).
638
+
639
+ This prevents the #1 parallel work failure: sub-skill assumes wrong interpretation, builds 500 LOC, then gets rejected in review.
640
+
641
+ ### Subagent Status Protocol
642
+
643
+ <MUST-READ path="references/subagent-status.md" trigger="when cook or any sub-skill needs to return a status"/>
644
+
645
+ Cook and all sub-skills return: `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED`.
646
+
647
+ ### Subagent Context Isolation
648
+
649
+ When invoking sub-skills (fix, debug, test, review, etc.), **craft exactly the context they need** — never pass the full orchestrator session context.
650
+
651
+ | Pass To Sub-Skill | DO NOT Pass |
652
+ |-------------------|-------------|
653
+ | Task description + specific goal | Full conversation history |
654
+ | Relevant file paths from scout | Unrelated files from other phases |
655
+ | Project conventions (naming, test framework) | Other sub-skill outputs |
656
+ | Plan excerpt for THIS phase only | Full master plan |
657
+ | Error/stack trace (for debug/fix) | Previous debug attempts from other bugs |
658
+
659
+ **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.
660
+
661
+ ## Deviation Rules
662
+
663
+ <MUST-READ path="references/deviation-rules.md" trigger="when implementation diverges from the approved plan"/>
664
+
665
+ R1-R3 (bug/security/blocking fix): auto-fix, continue. R4 (architectural change): ASK user first.
666
+
667
+ ## Error Recovery
668
+
669
+ <MUST-READ path="references/error-recovery.md" trigger="when any phase fails or a task hits repeated errors"/>
670
+
671
+ Includes phase-by-phase failure handling and repair operators (RETRY DECOMPOSE PRUNE) with a 2-attempt budget before escalation.
672
+
673
+ ## Analysis Paralysis Guard
674
+
675
+ <HARD-GATE>
676
+ 5+ consecutive read-only tool calls (Read, Grep, Glob) without a single write action (Edit, Write, Bash) = STUCK.
677
+
678
+ You MUST either:
679
+ 1. **Act** write code, run a command, create a file
680
+ 2. **Report BLOCKED** — state the specific missing piece: "Cannot proceed because [X]"
681
+
682
+ Stuck patterns (all banned):
683
+ - Reading 10+ files to "fully understand" before acting
684
+ - Grepping every variation of a string across the entire repo
685
+ - Reading the same file twice in one investigation
686
+ - "Let me check one more thing" — repeated after 5 reads
687
+
688
+ A wrong first attempt that produces feedback beats perfect understanding that never ships.
689
+ </HARD-GATE>
690
+
691
+ ### Observation/Effect Ratio Tracking
692
+
693
+ Track every tool call during Phase 4 (IMPLEMENT) as either **observation** (read-only) or **effect** (modifies state):
694
+
695
+ | Category | Tool Examples |
696
+ |----------|--------------|
697
+ | **Observation** | Read, Grep, Glob, Bash(grep/ls/cat/git log) |
698
+ | **Effect** | Write, Edit, Bash(npm/build/test/mkdir) |
699
+
700
+ **Detection rules** (check every 8 tool calls during Phase 4):
701
+
702
+ | Pattern | Threshold | Signal | Action |
703
+ |---------|-----------|--------|--------|
704
+ | **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." |
705
+ | **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." |
706
+ | **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." |
707
+ | **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." |
708
+
709
+ **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.
710
+
711
+ **Skip if**: Phase 1 (UNDERSTAND) observation-heavy is expected during research. Only track during Phase 4+ where effects should dominate.
712
+
713
+ ### Budget-Aware Phase Progression
714
+
715
+ Beyond the existing Exit Conditions (MAX_DEBUG_LOOPS, MAX_QUALITY_LOOPS, etc.), track **cumulative budget** across the entire cook session:
716
+
717
+ | Budget | Limit | What Happens at Limit |
718
+ |--------|-------|----------------------|
719
+ | **Phase 4 react budget** | 15 tool calls per task within Phase 4 | Force: move to next task or report partial completion |
720
+ | **Global replan budget** | 2 replans per session (Phase 4 Step 6) | Force: proceed with current plan or escalate to user |
721
+ | **Quality retry budget** | 3 total quality re-runs across 5a-5d | Force: ship with known issues documented, don't loop |
722
+ | **Total session tool calls** | 150 calls | Force: save state via session-bridge, compact or pause |
723
+
724
+ **Hard override rules**:
725
+ - If react budget exhausted for a task but task is IN_PROGRESS force CONTINUE to next task (don't re-attempt)
726
+ - If replan budget exhausted but plan still failing force escalation (don't attempt 3rd replan)
727
+ - If quality retry budget exhausted emit concerns in Cook Report, proceed to commit with documented caveats
728
+
729
+ **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.
730
+
731
+ ### Hash-Based Tool Loop Detection
732
+
733
+ <MUST-READ path="references/loop-detection.md" trigger="when same tool+args+result appears to be repeating"/>
734
+
735
+ Mentally track tool call fingerprints. 3 identical callsWARN. 5 identical callsFORCE STOP. Only same-input-AND-same-output counts as a loop.
736
+
737
+ ## Called By (inbound)
738
+
739
+ - User: `/rune cook` direct invocation — primary entry point
740
+ - `team` (L1): parallel workstream execution (meta-orchestration)
741
+
742
+ ## Calls (outbound)
743
+
744
+ | Phase | Sub-skill | Layer | Purpose |
745
+ |-------|-----------|-------|---------|
746
+ | 0 / 8 | `neural-memory` | ext | Recall context at start; capture learnings at end |
747
+ | 0.5 | `sentinel-env` | L3 | Environment pre-flight (first run only) |
748
+ | 1 | `scout` | L2 | Scan codebase before planning |
749
+ | 1 | `onboard` | L2 | Initialize project context if no CLAUDE.md |
750
+ | 1 | `ba` | L2 | Requirement elicitation for features |
751
+ | 1 | `logic-guardian` | L2 | Conditional: when `.rune/logic-manifest.json` exists — protect complex business logic before any edits |
752
+ | 2 | `plan` | L2 | Create implementation plan |
753
+ | 2 | `brainstorm` | L2 | Trade-off analysis / rescue mode |
754
+ | 2 | `design` | L2 | UI/design phase for frontend features |
755
+ | 2.5 | `adversary` | L2 | Red-team challenge on approved plan |
756
+ | 3 | `test` | L2 | Write failing tests (RED phase) |
757
+ | 4 | `fix` | L2 | Implement code changes (GREEN phase) |
758
+ | 4 | `debug` | L2 | Unexpected errors (max 3 loops) |
759
+ | 4 | `db` | L2 | Schema changes detected in diff |
760
+ | 4 | `worktree` | L3 | Worktree isolation for parallel implementation |
761
+ | 5a | `preflight` | L2 | Spec compliance + logic review |
762
+ | 5b | `sentinel` | L2 | Security scan |
763
+ | 5c | `review` | L2 | Code quality review |
764
+ | 5 | `scope-guard` | L3 | Verify changed files match approved plan scope (flag out-of-scope files before commit) |
765
+ | 5 | `perf` | L2 | Performance regression check (optional) |
766
+ | 5 | `audit` | L2 | Project health audit when scope warrants |
767
+ | 5 | `review-intake` | L2 | Structured review intake for complex PRs |
768
+ | 5 | `sast` | L3 | Static analysis security testing |
769
+ | 5d | `completion-gate` | L3 | Validate agent claims against evidence trail |
770
+ | 5 | `constraint-check` | L3 | Audit HARD-GATE compliance across workflow |
771
+ | 6 | `verification` | L3 | Lint + types + tests + build |
772
+ | 6 | `hallucination-guard` | L3 | Verify imports and API calls are real |
773
+ | 7 | `journal` | L3 | Record architectural decisions |
774
+ | 8 | `session-bridge` | L3 | Save context for future sessions |
775
+ | any | `context-pack` | L3 | create structured handoff briefings before spawning subagents |
776
+ | any | `skill-forge` | L2 | When new skill creation detected during cook |
777
+ | 1.5 | L4 extension packs | L4 | Domain-specific patterns when stack matches |
778
+
779
+ ## Data Flow
780
+
781
+ **Feeds Into →** `journal` (decisions → ADRs) | `session-bridge` (context .rune/ state) | `neural-memory` (learnings cross-session)
782
+
783
+ **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)
784
+
785
+ **Feedback Loops ↻** cook↔debug (Phase 4 bug → debug → fix → resume; if plan wrong → Approach Pivot) | cook↔test (RED → GREEN → failures loop back)
786
+
787
+ ## Constraints
788
+
789
+ 1. MUST run scout before planning
790
+ 2. MUST get user plan approval before writing code
791
+ 3. MUST write failing tests before implementation (TDD) unless explicitly skipped
792
+ 4. MUST NOT commit with failing tests
793
+ 5. MUST NOT modify files outside approved plan scope without user confirmation
794
+ 6. MUST run verification (lint + type-check + tests + build) before commit
795
+ 7. MUST NOT say "all tests pass" without showing actual test output
796
+ 8. MUST NOT contradict `.rune/decisions.md` without explicit user override
797
+
798
+ ## Mesh Gates
799
+
800
+ | Gate | Requires | If Missing |
801
+ |------|----------|------------|
802
+ | Resume Gate | Phase 0 checks for master plan before starting | Proceed to Phase 1 |
803
+ | Scout Gate | scout output before Phase 2 | Invoke rune:scout first |
804
+ | Plan Gate | User-approved plan before Phase 3 | Cannot proceed |
805
+ | Adversary Gate | adversary verdict before Phase 3 for features | Skip for bugfix/hotfix/refactor |
806
+ | Phase File Gate | Active phase file only (multi-session) | Load only active phase |
807
+ | Test-First Gate | Failing tests before Phase 4 | Write tests or get explicit skip |
808
+ | Quality Gate | preflight + sentinel + review before Phase 7 | Fix findings, re-run |
809
+ | Verification Gate | lint + types + tests + build green before commit | Fix, re-run |
810
+
811
+ ## Structured Output Contract (Prompt-as-API Pattern)
812
+
813
+ 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.
814
+
815
+ ### Pattern
816
+
817
+ ```
818
+ INVOCATION: "Analyze [X] and return results as JSON matching this schema:
819
+ {
820
+ "insights": [{ "id": string, "category": string, "description": string, "actionable": string }],
821
+ "confidence": number,
822
+ "next_steps": string[]
823
+ }
824
+ Do NOT include explanatory text outside the JSON block."
825
+ ```
826
+
827
+ ### When to Apply
828
+
829
+ | Phase | Sub-skill | Output Contract |
830
+ |-------|-----------|----------------|
831
+ | Phase 1 | `ba` | `{ requirements: [{id, priority, description, acceptance_criteria}], ambiguities: string[] }` |
832
+ | Phase 2 | `plan` | `{ phases: [{name, tasks: [{description, files, effort}], dependencies}] }` |
833
+ | Phase 3 | `test` | `{ test_cases: [{name, type, file, assertion}], coverage_targets: string[] }` |
834
+ | Phase 5 | `review` | `{ findings: [{severity, file, line, description, fix}], verdict: "PASS"|"WARN"|"BLOCK" }` |
835
+
836
+ ### Rules
837
+
838
+ - Include 1-2 concrete examples in the prompt — examples are worth more than schema descriptions
839
+ - Always specify "Do NOT include explanatory text outside the JSON/markdown block" — LLMs default to wrapping structured output in prose
840
+ - When the output will be consumed by another skill (not displayed to user), ALWAYS use this pattern
841
+ - When the output will be displayed to the user, use markdown format instead — humans don't read JSON
842
+
843
+ ### Why
844
+
845
+ 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.
846
+
847
+ ## Output Format
848
+
849
+ <MUST-READ path="references/output-format.md" trigger="before emitting the Cook Report at end of any session"/>
850
+
851
+ Emit a Cook Report with: Status, Phases, Files Changed, Tests, Quality results, Commit hash.
852
+ When invoked by `team` with a NEXUS Handoff, include the Deliverables table — MANDATORY.
853
+
854
+ ## Returns
855
+
856
+ | Artifact | Format | Location |
857
+ |----------|--------|----------|
858
+ | Plan files (master + phase) | Markdown | `.rune/plan-<feature>.md`, `.rune/plan-<feature>-phase<N>.md` |
859
+ | Implementation code | Source files | Per plan file paths |
860
+ | Test files | Source files | Co-located or `__tests__/` per project convention |
861
+ | Verification results | Inline stdout | Shown in Cook Report |
862
+ | Cook Report | Markdown (inline) | Emitted at end of session |
863
+ | Session state | Markdown | `.rune/decisions.md`, `.rune/progress.md`, `.rune/conventions.md` |
864
+
865
+ ## Document Ownership
866
+
867
+ | Scope | Access | Files |
868
+ |-------|--------|-------|
869
+ | **Owns** (read + write) | `.rune/plan-*.md`, `.rune/progress.md`, `.rune/decisions.md`, `.rune/conventions.md`, source files per approved plan |
870
+ | **Reads** (never writes) | `CLAUDE.md`, `SKILL.md` (any), `.rune/contract.md`, `.rune/checkpoint.md` |
871
+ | **Never modifies** | `compiler/**`, `extensions/**`, `PACK.md`, other skills' `SKILL.md`, `.rune/learnings.jsonl` |
872
+
873
+ When delegating to sub-skills (scout, plan, test, review), each sub-skill owns its own output. Cook coordinates but does not overwrite sub-skill artifacts.
874
+
875
+ ## Anti-Patterns
876
+
877
+ Common multi-agent failures to explicitly avoid. These are NOT edge cases — they are the most frequent cook failures in production.
878
+
879
+ | Anti-Pattern | Why It Fails | Correct Approach |
880
+ |---|---|---|
881
+ | **Bypass hierarchy** — skipping scout/plan and jumping to Phase 4 code | Builds wrong thing. Most "wasted work" traces back to missing Phase 1-2 | Follow phase gates. Even "obvious" tasks benefit from 30s of scout |
882
+ | **Shadow decisions** — making architectural choices without logging to decisions.md | Next session repeats the same debate. Team agents contradict each other | Log every non-trivial choice via `decisions.md` or `journal` |
883
+ | **Gold-plating** — adding "nice-to-have" features not in the approved plan | Scope creep, delayed delivery, untested code paths | Build ONLY what's in the plan. Log extras as follow-up tasks |
884
+ | **Test-after** — writing tests after implementation instead of before (TDD violation) | Tests validate implementation bugs, not requirements. Coverage looks good but misses edge cases | Phase 3 (RED) before Phase 4 (GREEN). Always |
885
+ | **Monolithic commit** — one giant commit with all changes | Impossible to revert partially. Review is overwhelming | Commit per phase or per logical unit. Small, reviewable diffs |
886
+ | **Assumption-based implementation** — guessing requirements instead of asking | Builds the wrong thing confidently. User discovers mismatch late | If ambiguous, ask. 30s of clarification saves 30min of rework |
887
+ | **Infinite remediation loop** — fixing the same BLOCK finding 4+ times with the same approach | Wastes tokens, drifts further from solution. If 3 attempts failed, the approach is wrong | Remediation Cycle Counter: max 3 cycles, Cycle 2+ must try different strategy, Cycle 4 escalates to user |
888
+ | **Code fix for upstream problem** — fixing implementation when the plan/spec was wrong | Code "passes" but implements the wrong thing. Bug resurfaces in integration | Upstream Inconsistency Protocol: tag as UPSTREAM, re-invoke upstream skill, get approval, re-run gates |
889
+
890
+ ## Sharp Edges
891
+
892
+ <MUST-READ path="references/sharp-edges.md" trigger="before declaring done — review all 18 failure modes"/>
893
+
894
+ **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.
895
+
896
+ ## Self-Validation
897
+
898
+ ```
899
+ SELF-VALIDATION (run before emitting Cook Report):
900
+ - [ ] Every phase in Phase Skip Rules was either executed or explicitly skipped with reason
901
+ - [ ] Plan approval gate was not bypassed — user said "go" (check conversation history)
902
+ - [ ] No Phase 4 code was written before Phase 3 tests (TDD order preserved)
903
+ - [ ] All Phase 5 quality gates (preflight, sentinel, review) ran — not just claimed
904
+ - [ ] No quality gate exceeded 3 remediation cycles without user escalation
905
+ - [ ] No upstream issue was fixed by code change alone — UPSTREAM findings re-invoked the source skill
906
+ - [ ] Cook Report contains actual commit hash, not placeholder
907
+ ```
908
+
909
+ ## Done When
910
+
911
+ All applicable phases complete + Self-Validation passed:
912
+ - User approved plan | All tests PASS (output shown) | preflight+sentinel+review PASS | build green
913
+ - Cook Report emitted with commit hash | Session state saved to .rune/ via session-bridge
914
+
915
+ ## Cost Profile
916
+
917
+ ~$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).