@rune-kit/rune 2.2.3 → 2.2.6

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.
@@ -1,16 +1,16 @@
1
1
  ---
2
2
  name: "billing-integration"
3
3
  pack: "@rune/saas"
4
- description: "Billing integration — Stripe and LemonSqueezy (Stripe alternative for Vietnam/non-US sellers). Subscription lifecycle, webhook handling, usage-based billing, dunning management, and tax handling."
4
+ description: "Billing integration — Stripe, LemonSqueezy, and Polar. Subscription lifecycle, one-time checkout, webhook handling, Standard Webhooks verification, usage-based billing, dunning management, digital product delivery, and tax handling."
5
5
  model: sonnet
6
6
  tools: [Read, Edit, Write, Grep, Glob, Bash]
7
7
  ---
8
8
 
9
9
  # billing-integration
10
10
 
11
- Billing integration — Stripe and LemonSqueezy (Stripe alternative for Vietnam/non-US sellers). Subscription lifecycle, webhook handling, usage-based billing, dunning management, and tax handling.
11
+ Billing integration — Stripe, LemonSqueezy, and Polar. Subscription lifecycle, one-time payment checkout, webhook handling, Standard Webhooks signature verification, usage-based billing, dunning management, digital product delivery, and tax handling.
12
12
 
13
- > **Vietnam note**: Stripe requires a US/EU entity and is unavailable for direct signup from Vietnam. LemonSqueezy acts as Merchant of Record — handles VAT, tax compliance, and payouts globally. Prefer LemonSqueezy for solo founders and small teams in Vietnam/Southeast Asia.
13
+ > **Provider selection**: Stripe requires a US/EU entity. LemonSqueezy and Polar act as Merchant of Record — handle VAT, tax compliance, and payouts globally. Prefer LemonSqueezy or Polar for solo founders in Vietnam/Southeast Asia. Polar is optimized for developer tools and digital products (open source monetization, one-time purchases, CLI tools).
14
14
 
15
15
  #### Workflow
16
16
 
@@ -29,6 +29,15 @@ For products where billing scales with usage (API calls, seats, storage): create
29
29
  **Step 5 — Dunning management flow**
30
30
  When `invoice.payment_failed` fires: Day 0 — notify customer, retry in 3 days. Day 3 — retry + second email. Day 7 — retry + urgent email + in-app warning banner. Day 14 — suspend account (read-only mode), email with payment link. Day 21 — cancel subscription, archive data with 30-day recovery window. Never hard-delete on cancellation.
31
31
 
32
+ **Step 6 — Hosted checkout flow (one-time + subscription)**
33
+ For products sold as one-time purchases (lifetime deals, digital products, CLI tools): create a checkout session server-side with product ID + metadata (user identifier, tier), redirect user to provider's hosted checkout page, listen for `order.paid` webhook to fulfill. This pattern works across all providers — only the API shape differs. Always pass fulfillment context (user ID, GitHub username, email) in checkout metadata so the webhook handler can deliver without a second lookup.
34
+
35
+ **Step 7 — Standard Webhooks signature verification**
36
+ Polar (and any provider using the Standard Webhooks spec via Svix) sends three headers: `webhook-id`, `webhook-timestamp`, `webhook-signature`. Verify with HMAC-SHA256: `sign(base64decode(secret), "{webhook-id}.{timestamp}.{rawBody}")`. Compare against all signatures in the header (space-separated `v1,{base64}`). Also check timestamp is within 5 minutes to prevent replay attacks. This is different from Stripe's `constructEvent` or LemonSqueezy's `x-signature` — detect which spec the provider uses.
37
+
38
+ **Step 8 — Digital product delivery**
39
+ After payment confirmation, deliver the product automatically. Three common patterns: (a) **Repo access** — call GitHub/GitLab API to add user as collaborator with `pull` permission. Pass username in checkout metadata. Handle 201 (invited) and 204 (already collaborator). (b) **License key** — generate unique key, store in DB with expiry + tier + features, email to customer. Provide public verification endpoint for the product to call at startup. (c) **Download link** — generate signed URL with expiry (S3 presigned, R2 signed). Email link + store for re-download. For all patterns: store delivery result alongside order, implement retry for partial failures, sync to central dashboard for tracking.
40
+
32
41
  #### Example
33
42
 
34
43
  ```typescript
@@ -94,6 +103,76 @@ app.post('/billing/webhook/lemonsqueezy', express.raw({ type: 'application/json'
94
103
  res.json({ received: true });
95
104
  });
96
105
 
106
+ // Polar — hosted checkout for one-time purchases (developer tools, digital products)
107
+ // Create checkout session server-side, redirect client to checkout.url
108
+ app.post('/checkout/create', async (req, res) => {
109
+ const { productId, githubUsername, email } = req.body;
110
+
111
+ const checkout = await fetch('https://api.polar.sh/v1/checkouts/', {
112
+ method: 'POST',
113
+ headers: {
114
+ Authorization: `Bearer ${process.env.POLAR_ACCESS_TOKEN}`,
115
+ 'Content-Type': 'application/json',
116
+ },
117
+ body: JSON.stringify({
118
+ products: [productId],
119
+ success_url: `${process.env.APP_URL}/checkout/success?checkout_id={CHECKOUT_ID}`,
120
+ ...(email ? { customer_email: email } : {}),
121
+ metadata: { github_username: githubUsername, tier: 'pro' }, // fulfillment context
122
+ }),
123
+ }).then(r => r.json());
124
+
125
+ res.json({ url: checkout.url }); // redirect client to this URL
126
+ });
127
+
128
+ // Polar webhook — Standard Webhooks spec (also used by Svix, Resend, Clerk)
129
+ app.post('/billing/webhook/polar', express.raw({ type: 'application/json' }), async (req, res) => {
130
+ const webhookId = req.headers['webhook-id'] as string;
131
+ const timestamp = req.headers['webhook-timestamp'] as string;
132
+ const signature = req.headers['webhook-signature'] as string;
133
+
134
+ // Verify: HMAC-SHA256(base64decode(secret), "{id}.{timestamp}.{body}")
135
+ const secret = Buffer.from(process.env.POLAR_WEBHOOK_SECRET!.replace(/^whsec_/, ''), 'base64');
136
+ const content = `${webhookId}.${timestamp}.${req.body.toString()}`;
137
+ const expected = crypto.createHmac('sha256', secret).update(content).digest('base64');
138
+
139
+ const valid = signature.split(' ').some(s => {
140
+ const parts = s.split(',');
141
+ return parts.length === 2 && parts[1] === expected;
142
+ });
143
+ if (!valid) return res.status(403).json({ error: 'Invalid signature' });
144
+
145
+ // Replay protection: reject timestamps older than 5 minutes
146
+ if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) {
147
+ return res.status(403).json({ error: 'Timestamp too old' });
148
+ }
149
+
150
+ const event = JSON.parse(req.body.toString());
151
+ if (event.type !== 'order.paid') return res.json({ received: true });
152
+
153
+ const { metadata } = event.data;
154
+ // Deliver based on product type using metadata set during checkout
155
+ if (metadata.github_username) {
156
+ await inviteToRepo(metadata.github_username, 'org/private-repo', 'pull');
157
+ }
158
+
159
+ res.json({ received: true });
160
+ });
161
+
162
+ // Digital product delivery — GitHub repo invite
163
+ const inviteToRepo = async (username: string, repo: string, permission: string) => {
164
+ const res = await fetch(`https://api.github.com/repos/${repo}/collaborators/${username}`, {
165
+ method: 'PUT',
166
+ headers: {
167
+ Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
168
+ Accept: 'application/vnd.github+json',
169
+ },
170
+ body: JSON.stringify({ permission }),
171
+ });
172
+ // 201 = invited, 204 = already collaborator — both are success
173
+ return { success: res.status === 201 || res.status === 204, status: res.status };
174
+ };
175
+
97
176
  // Usage-based billing — report metered usage to Stripe
98
177
  const reportUsage = async (tenantId: string, quantity: number) => {
99
178
  const subscription = await db.subscription.findUnique({ where: { tenantId } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rune-kit/rune",
3
- "version": "2.2.3",
3
+ "version": "2.2.6",
4
4
  "description": "58-skill mesh for AI coding assistants — 5-layer architecture, 200+ connections, 8 platforms (Claude Code, Cursor, Windsurf, Antigravity, Codex, OpenCode, OpenClaw, Generic)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -32,6 +32,7 @@ Comprehensive project health audit across 8 dimensions (7 project + 1 mesh analy
32
32
  - `journal` (L3): record audit date, overall score, and verdict
33
33
  - `constraint-check` (L3): audit HARD-GATE compliance across project skills
34
34
  - `sast` (L3): Phase 2 — deep static analysis (Semgrep, Bandit, ESLint security rules)
35
+ - `retro` (L2): Phase 6 — engineering velocity and health dimension (rune:retro)
35
36
 
36
37
  ## Called By (inbound)
37
38
 
@@ -3,7 +3,7 @@ name: ba
3
3
  description: Business Analyst agent. Deeply understands user requirements before any planning or coding begins. Asks probing questions, identifies hidden requirements, maps stakeholders, defines scope boundaries, and produces a structured Requirements Document that plan and cook consume.
4
4
  metadata:
5
5
  author: runedev
6
- version: "0.2.0"
6
+ version: "0.4.0"
7
7
  layer: L2
8
8
  model: opus
9
9
  group: creation
@@ -85,6 +85,32 @@ Each question must be asked separately, wait for answer before next.
85
85
  Exception: if user provides a detailed spec/PRD → extract answers from it, confirm with user.
86
86
  </HARD-GATE>
87
87
 
88
+ #### Structured Elicitation Frameworks
89
+
90
+ Choose the framework that fits the requirement type. Use it to STRUCTURE the 5 Questions above, not replace them.
91
+
92
+ | Framework | When to Use | Structure |
93
+ |-----------|------------|-----------|
94
+ | **PICO** | Clinical, research, data-driven, or A/B testing features | **P**opulation (who), **I**ntervention (what change), **C**omparison (vs what), **O**utcome (measurable result) |
95
+ | **INVEST** | User stories for sprint-sized features | **I**ndependent, **N**egotiable, **V**aluable, **E**stimable, **S**mall, **T**estable |
96
+ | **Jobs-to-be-Done** | Product features, user workflows | "When [situation], I want to [motivation] so I can [expected outcome]" |
97
+
98
+ > Source: K-Dense claude-scientific-skills (literature-review PICO pattern), adapted for software BA.
99
+
100
+ **PICO Example (data feature):**
101
+ ```
102
+ P: Dashboard users monitoring real-time metrics
103
+ I: Add anomaly detection alerts
104
+ C: vs. current manual threshold setting
105
+ O: 30% faster incident detection (measurable KPI)
106
+ ```
107
+
108
+ **When to apply which:**
109
+ - Feature Request → INVEST (ensures stories are sprint-ready)
110
+ - Data/Analytics/Research feature → PICO (forces measurable outcome definition)
111
+ - Product/UX feature → Jobs-to-be-Done (keeps focus on user motivation)
112
+ - Integration → 5 Questions only (frameworks add noise for plumbing tasks)
113
+
88
114
  ### Step 3 — Hidden Requirement Discovery
89
115
 
90
116
  After the 5 questions, analyze for requirements the user DIDN'T mention:
@@ -108,6 +134,32 @@ After the 5 questions, analyze for requirements the user DIDN'T mention:
108
134
 
109
135
  Present discovered hidden requirements to user: "I found N additional requirements you may not have considered: [list]. Which are relevant?"
110
136
 
137
+ ### Step 3.5 — Completeness Scoring (Options & Alternatives)
138
+
139
+ When presenting options, alternatives, or scope decisions to the user, rate each with a **Completeness score (X/10)**:
140
+
141
+ | Score | Meaning | Guidance |
142
+ |-------|---------|----------|
143
+ | 9-10 | Complete — all edge cases, full coverage, production-ready | Always recommend |
144
+ | 7-8 | Covers happy path, skips some edges | Acceptable for MVP |
145
+ | 4-6 | Shortcut — defers significant work to later | Flag trade-off explicitly |
146
+ | 1-3 | Minimal viable, technical debt guaranteed | Only for time-critical emergencies |
147
+
148
+ **Always recommend the higher-completeness option** unless the delta is truly expensive. With AI-assisted coding, the marginal cost of completeness is near-zero:
149
+
150
+ | Task Type | Human Team | AI-Assisted | Compression |
151
+ |-----------|-----------|-------------|-------------|
152
+ | Boilerplate / scaffolding | 2 days | 15 min | ~100x |
153
+ | Test writing | 1 day | 15 min | ~50x |
154
+ | Feature implementation | 1 week | 30 min | ~30x |
155
+ | Bug fix + regression test | 4 hours | 15 min | ~20x |
156
+
157
+ **When showing effort estimates**, always show both scales: `(human: ~X / AI: ~Y)`. The compression ratio reframes "too expensive" into "15 minutes more."
158
+
159
+ **Anti-pattern**: "Choose B — it covers 90% of the value with less code." → If A is only 70 lines more, choose A. The last 10% is where production bugs hide.
160
+
161
+ > Source: garrytan/gstack v0.9.0 — "Boil the Lake" principle. Completeness is cheap when AI makes the marginal cost near-zero.
162
+
111
163
  ### Step 4 — Scope Definition
112
164
 
113
165
  Based on all gathered information, produce:
@@ -272,6 +324,7 @@ Known failure modes for this skill. Check these before declaring done.
272
324
  | Missing hidden requirements (auth, error handling, edge cases) | HIGH | Step 3 checklist is mandatory scan |
273
325
  | Requirements doc too verbose (>500 lines) | MEDIUM | Max 200 lines — concise, actionable, testable |
274
326
  | Skipping BA for "simple" features that turn out complex | HIGH | Let cook's complexity detection trigger BA, not user judgment |
327
+ | Recommending shortcuts without Completeness Score | MEDIUM | Step 3.5: every option needs X/10 score + dual effort estimate (human vs AI). "90% coverage" is a red flag when 100% costs 15 min more |
275
328
 
276
329
  ## Done When
277
330
 
@@ -4,7 +4,7 @@ description: "Validates agent claims against evidence trail. Catches 'done' with
4
4
  user-invocable: false
5
5
  metadata:
6
6
  author: runedev
7
- version: "1.2.0"
7
+ version: "1.5.0"
8
8
  layer: L3
9
9
  model: haiku
10
10
  group: validation
@@ -73,6 +73,24 @@ If ANY stub detected:
73
73
  - Add synthetic claim: "implemented [filename]" → CONTRADICTED (file is a stub)
74
74
  - This catches agents that create files but don't implement them
75
75
 
76
+ ### Step 1c — Self-Validation Check
77
+
78
+ If the skill that just ran has a `## Self-Validation` section, extract its checklist and treat each item as an implicit claim:
79
+
80
+ ```
81
+ For each Self-Validation check in the skill's SKILL.md:
82
+ 1. Read the check (e.g., "at least one assertion per test")
83
+ 2. Look for evidence in tool output that this check was satisfied
84
+ 3. If evidence found → add as CONFIRMED claim
85
+ 4. If no evidence → add as UNCONFIRMED claim ("Self-Validation: [check] — no evidence")
86
+ ```
87
+
88
+ Why: Self-Validation catches domain-specific quality issues that generic claim matching (Step 2) cannot detect. A test skill knows "no assertions = useless test" but completion-gate doesn't — unless the skill's Self-Validation tells it to check.
89
+
90
+ <HARD-GATE>
91
+ If a skill has Self-Validation and ANY check is UNCONFIRMED or CONTRADICTED → overall verdict cannot be CONFIRMED, even if all explicit claims pass.
92
+ </HARD-GATE>
93
+
76
94
  ### Step 2 — Match Evidence
77
95
 
78
96
  For each claim, look for corresponding evidence in the conversation context:
@@ -87,7 +105,15 @@ For each claim, look for corresponding evidence in the conversation context:
87
105
  | "no security issues" | Sentinel report with PASS verdict | Sentinel skill output |
88
106
  | "coverage ≥ X%" | Coverage tool output with actual percentage | Test runner with coverage flag |
89
107
 
90
- ### Step 3 — Validate Each Claim
108
+ ### Step 3 — Validate Each Claim (Default-FAIL Mindset)
109
+
110
+ <HARD-GATE>
111
+ Default posture is FAIL, not PASS. Actively seek 3-5 issues per review.
112
+ Zero issues found = red flag — look harder, not a sign of quality.
113
+ This prevents rubber-stamping where the gate confirms everything without scrutiny.
114
+ </HARD-GATE>
115
+
116
+ > Source: msitarzewski/agency-agents (50.8k★) — "Default to finding 3-5 issues. Zero issues = red flag, look harder."
91
117
 
92
118
  For each claim + evidence pair:
93
119
 
@@ -100,6 +126,12 @@ IF no evidence found:
100
126
  → UNCONFIRMED (agent may be right but didn't prove it)
101
127
  ```
102
128
 
129
+ **Adversarial validation checklist** (run AFTER initial verdicts):
130
+ 1. Re-read each CONFIRMED claim — is the evidence actually proving THIS claim, or a different one?
131
+ 2. Check for **partial completion** — did the agent do 80% but claim 100%? (e.g., "implemented feature" but only the happy path)
132
+ 3. Check for **scope mismatch** — does the evidence prove the SPECIFIC claim or a broader/narrower version?
133
+ 4. If all claims are CONFIRMED on first pass, apply **skeptic sweep**: re-examine the weakest 2 claims with heightened scrutiny
134
+
103
135
  ### Step 4 — Report
104
136
 
105
137
  ```
@@ -123,6 +155,34 @@ IF no evidence found:
123
155
  UNCONFIRMED — 1 claim lacks evidence, 1 contradicted. Cannot proceed to commit.
124
156
  ```
125
157
 
158
+ ### Step 4.5 — Cross-Phase Integration Check
159
+
160
+ > From GSD (gsd-build/get-shit-done, 30.8k★): "Phase boundaries are where integration bugs hide."
161
+
162
+ When validating a completed phase in a multi-phase plan, check for integration gaps between phases:
163
+
164
+ 1. **Orphaned exports** — files/functions created in this phase that claim to be used by future phases (see `## Cross-Phase Context → Exports`) but are not yet importable:
165
+ ```
166
+ Grep for the export name in the current codebase:
167
+ - If export exists AND is importable → CONFIRMED
168
+ - If export exists but has wrong signature vs phase file contract → CONTRADICTED
169
+ - Expected export missing entirely → UNCONFIRMED ("Phase N claims to export X but X not found")
170
+ ```
171
+
172
+ 2. **Uncalled routes** — API endpoints added in this phase but not wired to any frontend/consumer yet:
173
+ - This is OK if a future phase handles wiring (check master plan)
174
+ - Flag as WARN if no future phase mentions consuming this route
175
+
176
+ 3. **Auth gaps** — new endpoints or pages without authentication/authorization:
177
+ - `Grep` for route handlers without auth middleware
178
+ - Flag as WARN (may be intentional for public endpoints, but worth checking)
179
+
180
+ 4. **E2E flow trace** — for the primary user flow this phase enables:
181
+ - Trace: entry point → business logic → data layer → response
182
+ - If any step in the chain is missing or stubbed → CONTRADICTED
183
+
184
+ **This step is OPTIONAL for single-phase tasks and MANDATORY for multi-phase master plans.**
185
+
126
186
  ### Step 5 — Evidence Quality Gate
127
187
 
128
188
  Before emitting verdict, verify evidence quality:
@@ -170,6 +230,11 @@ Completion Gate Report with status (CONFIRMED/UNCONFIRMED/CONTRADICTED), claim v
170
230
  | Agent pre-generates evidence by running commands proactively | LOW | This is actually GOOD behavior — we want agents to provide evidence |
171
231
  | Completion-gate itself claims "all confirmed" without evidence | CRITICAL | Gate report MUST include the evidence table — no table = report is invalid |
172
232
  | Existence Theater — agent creates files but they're stubs | HIGH | Step 1b stub detection: grep for Placeholder/TODO/NotImplementedError in new files |
233
+ | Cross-phase integration gaps — exports exist but wrong signature | HIGH | Step 4.5: verify exports match Code Contracts from phase file |
234
+ | Phase complete but E2E flow broken — missing link in the chain | MEDIUM | Step 4.5 E2E flow trace: entry → logic → data → response must all be connected |
235
+ | Rubber-stamping — all CONFIRMED without scrutiny | HIGH | Default-FAIL mindset: actively seek 3-5 issues. Zero issues = red flag, apply skeptic sweep on weakest 2 claims |
236
+ | Partial completion claimed as full — 80% done but "implemented" | HIGH | Adversarial checklist: check for partial completion, scope mismatch, evidence-claim alignment |
237
+ | Self-Validation skipped — skill has checks but gate ignores them | HIGH | Step 1c: extract Self-Validation from skill's SKILL.md, treat each as implicit claim. Missing = UNCONFIRMED |
173
238
 
174
239
  ## Done When
175
240
 
@@ -5,7 +5,7 @@ context: fork
5
5
  agent: general-purpose
6
6
  metadata:
7
7
  author: runedev
8
- version: "0.7.0"
8
+ version: "1.3.0"
9
9
  layer: L1
10
10
  model: sonnet
11
11
  group: orchestrator
@@ -248,6 +248,55 @@ This phase is lightweight — a Read + pattern match, not a full scan. It does N
248
248
 
249
249
  **Gate**: User MUST approve the plan before proceeding. Do NOT skip this.
250
250
 
251
+ ### Phase 2.5: RFC GATE (Breaking Changes Only)
252
+
253
+ **Goal**: Formal change management for breaking changes. Prevents unreviewed breaking changes from reaching production.
254
+
255
+ **Auto-trigger conditions** (ANY triggers this gate):
256
+ - Plan includes `BREAKING CHANGE` annotation
257
+ - Plan modifies a public API signature (added/removed/changed parameters)
258
+ - Plan alters database schema (migration required)
259
+ - Plan removes or renames an exported function/type used by other modules
260
+ - Plan changes authentication/authorization flow
261
+
262
+ **Skip conditions**: Non-breaking changes, internal refactors, new features with no API surface change.
263
+
264
+ **RFC Artifact** (`.rune/rfc/RFC-<NNN>-<slug>.md`):
265
+
266
+ ```markdown
267
+ # RFC-<NNN>: <Title>
268
+
269
+ **Date**: [YYYY-MM-DD]
270
+ **Author**: [agent or user]
271
+ **Status**: Proposed | Approved | Rejected
272
+ **Impact**: [list affected consumers — modules, services, users]
273
+
274
+ ## What Changes
275
+ [Specific breaking change — old behavior → new behavior]
276
+
277
+ ## Why
278
+ [Business/technical justification — why breaking is necessary]
279
+
280
+ ## Migration Path
281
+ [Step-by-step guide for consumers to adapt]
282
+ [Include code examples: before → after]
283
+
284
+ ## Rollback Plan
285
+ [How to revert if the change causes issues]
286
+
287
+ ## Affected Systems
288
+ | System | Impact | Migration Effort |
289
+ |--------|--------|-----------------|
290
+ | [module/service] | [description] | [low/medium/high] |
291
+ ```
292
+
293
+ **Gate**: RFC MUST be written and presented to user for approval. User responds: "approved" → proceed. "rejected" → revise plan. "deferred" → skip breaking change, implement non-breaking alternative.
294
+
295
+ <HARD-GATE>
296
+ Breaking change without RFC = BLOCKED. No exceptions.
297
+ "It's just a small change" is the #1 excuse for production incidents from unreviewed breaking changes.
298
+ </HARD-GATE>
299
+
251
300
  ## Phase 2.5: ADVERSARY (Red-Team Challenge)
252
301
 
253
302
  **Goal**: Stress-test the approved plan BEFORE writing code — catch flaws at plan time, not implementation time.
@@ -322,6 +371,11 @@ If the coder model needs info from other phases, it's in the Cross-Phase Context
322
371
  1. Mark Phase 4 as `in_progress`
323
372
  2. **Phase-file execution** — if working from a master plan + phase file:
324
373
  - Execute tasks listed in the phase file (the `## Tasks` section)
374
+ - **Wave-based execution**: if tasks are organized into waves (see `plan` skill), execute wave-by-wave:
375
+ - Wave 1 tasks first (no dependencies — can run in parallel if inside `team`)
376
+ - Wave 2 tasks only after ALL Wave 1 tasks complete
377
+ - Within a wave: `team` dispatches as parallel subagents; solo cook runs sequentially
378
+ - If a task in Wave N fails → do NOT start Wave N+1. Fix or DECOMPOSE the failed task first
325
379
  - Follow code contracts from `## Code Contracts` section
326
380
  - Respect rejection criteria from `## Rejection Criteria` section
327
381
  - Handle failure scenarios from `## Failure Scenarios` section
@@ -341,6 +395,8 @@ If the coder model needs info from other phases, it's in the Cross-Phase Context
341
395
  - Prefer `asyncio.gather()` for parallel I/O operations
342
396
  - Use `asyncio.TaskGroup` (Python 3.11+) for structured concurrency
343
397
  4. If stuck on unexpected errors → invoke `rune:debug` (max 3 debug↔fix loops)
398
+ - Debug will scope-lock to the affected directory (Step 1.5) — fix recommendations stay within boundary
399
+ - If debug recommends changes outside plan scope → treat as R4 deviation (ASK user first)
344
400
  5. **Re-plan check** — before proceeding to Phase 5, evaluate:
345
401
  - Did debug-fix loops hit max (3) for any area? → trigger re-plan
346
402
  - Were files modified outside the approved plan scope? → trigger re-plan
@@ -419,6 +475,7 @@ PARALLEL EXECUTION:
419
475
  **REQUIRED SUB-SKILL**: Use `rune:completion-gate`
420
476
  - Validate that agent claims match evidence trail
421
477
  - Check: tests actually ran (stdout captured), files actually changed (git diff), build actually passed
478
+ - Check: no truncated code files (`// ...`, `// rest of code`, bare ellipsis) — agent MUST complete all output
422
479
  - Any UNCONFIRMED claim → BLOCK with specific gap identified
423
480
 
424
481
  **Gate**: If sentinel finds CRITICAL security issue → STOP, fix it, re-run. Non-negotiable.
@@ -577,6 +634,34 @@ When cook must pause mid-phase (context limit, user break, session end before ph
577
634
 
578
635
  This is more granular than Phase 0's plan-level resume — it resumes within a phase, not just between phases.
579
636
 
637
+ ### Mid-Run Signal Detection (Two-Stage Intent Classification)
638
+
639
+ When user sends a message DURING cook execution (mid-phase), classify intent before acting:
640
+
641
+ **Stage 1 — Keyword Fast-Path** (no LLM reasoning needed, <60 chars):
642
+
643
+ | Pattern | Intent | Action |
644
+ |---------|--------|--------|
645
+ | "stop", "cancel", "dừng", "abort" | `Cancel` | Save progress → emit Cook Report with status BLOCKED → stop |
646
+ | "status", "tiến độ", "progress", "where are you" | `StatusQuery` | Reply with current phase + task + % estimate → resume |
647
+ | "wait", "pause", "đợi" | `Pause` | Create `.rune/.continue-here.md` → WIP commit → stop |
648
+ | "skip this", "bỏ qua", "next" | `Steer` | Skip current task → proceed to next task/phase |
649
+
650
+ **Stage 2 — Context Classification** (if no keyword match AND message >60 chars):
651
+
652
+ | Intent | Signal | Action |
653
+ |--------|--------|--------|
654
+ | `Steer` | Modifies scope but keeps goal ("actually use Redis instead of Memcached") | Update plan inline, note deviation in Cook Report |
655
+ | `NewTask` | Unrelated to current work ("also fix the login page") | Log to `.rune/backlog.md`, continue current task. Announce: "Noted for later — staying on current task." |
656
+ | `Clarification` | Answers a question cook asked, or provides missing context | Absorb into current phase context, resume |
657
+
658
+ > Source: goclaw (832★) — two-stage intent classification prevents expensive LLM calls for simple signals like "stop" or "status".
659
+
660
+ <HARD-GATE>
661
+ NEVER treat a Cancel/Pause signal as a Steer or NewTask. User safety signals take absolute priority.
662
+ If ambiguous between Cancel and Steer → ask user: "Did you mean stop, or change approach?"
663
+ </HARD-GATE>
664
+
580
665
  ### Exit Conditions (Mandatory for Autonomous Runs)
581
666
 
582
667
  Every cook invocation inside `team` or autonomous workflows MUST have exit conditions:
@@ -586,6 +671,8 @@ MAX_DEBUG_LOOPS: 3 per error area (already enforced)
586
671
  MAX_QUALITY_LOOPS: 2 re-runs of Phase 5 (fix→recheck cycle)
587
672
  MAX_REPLAN: 1 re-plan per cook session (Phase 4 re-plan check)
588
673
  MAX_PIVOT: 1 approach pivot per cook session (Approach Pivot Gate)
674
+ MAX_FIXES: 30 per session (hard cap — fix's WTF-likelihood self-regulation)
675
+ WTF_THRESHOLD: 20% quality decay risk → STOP fixing, commit progress, re-assess
589
676
  TIMEOUT_SIGNAL: If context-watch reports ORANGE, wrap up current phase and checkpoint
590
677
  ```
591
678
 
@@ -693,6 +780,26 @@ Do NOT ask user until repair budget is spent.
693
780
  - `worktree` (L3): Phase 4 — worktree isolation for parallel implementation
694
781
  - L4 extension packs: Phase 1.5 — domain-specific patterns when stack matches (see Phase 1.5 mapping table)
695
782
 
783
+ ## Data Flow
784
+
785
+ ### Feeds Into →
786
+
787
+ - `journal` (L3): architectural decisions made during cook → ADR entries for future sessions
788
+ - `session-bridge` (L3): cook's context (plan, decisions, progress) → .rune/ state files for next session
789
+ - `neural-memory` (external): learnings from this cook run → persistent cross-session memory
790
+
791
+ ### Fed By ←
792
+
793
+ - `ba` (L2): Requirements Document → cook's Phase 1 UNDERSTAND input
794
+ - `plan` (L2): master plan + phase files → cook's Phase 2-4 execution roadmap
795
+ - `session-bridge` (L3): .rune/.continue-here.md → cook's Phase 0 resume context
796
+ - `neural-memory` (external): past project decisions → cook's Phase 0 context recall
797
+
798
+ ### Feedback Loops ↻
799
+
800
+ - `cook` ↔ `debug`: cook encounters bug during Phase 4 → debug diagnoses → cook resumes with fix. Debug may discover the plan is wrong → cook triggers Approach Pivot
801
+ - `cook` ↔ `test`: cook writes tests in Phase 3 (RED), implements in Phase 4 (GREEN), runs tests again → failures loop back to Phase 4 fix
802
+
696
803
  ## Analysis Paralysis Guard
697
804
 
698
805
  <HARD-GATE>
@@ -711,6 +818,38 @@ Stuck patterns (all banned):
711
818
  A wrong first attempt that produces feedback beats perfect understanding that never ships.
712
819
  </HARD-GATE>
713
820
 
821
+ ### Hash-Based Tool Loop Detection (Content-Aware)
822
+
823
+ The 5-read counter above catches obvious paralysis. This catches **same-input-same-output loops** — where the agent keeps calling the same tool with the same arguments and getting the same result, making zero progress.
824
+
825
+ **Detection logic** (conceptual — tracked mentally, not via actual SHA256):
826
+
827
+ ```
828
+ For each tool call, track:
829
+ argsHash = fingerprint(tool_name + arguments)
830
+ resultHash = fingerprint(result content)
831
+
832
+ IF same argsHash AND same resultHash seen before:
833
+ consecutive_identical += 1
834
+ ELSE:
835
+ consecutive_identical = 0
836
+
837
+ Thresholds:
838
+ 3 identical calls → WARN: "Loop detected — same tool, same args, same result 3x. Change approach."
839
+ 5 identical calls → FORCE STOP: "True stuck loop. Must try different tool or different arguments."
840
+ ```
841
+
842
+ **Key distinction**: retry-with-different-result is NOT a loop (e.g., re-running tests after a fix). Only same-input-AND-same-output counts.
843
+
844
+ > Source: goclaw (832★) — SHA256-based loop detection distinguishes true stuck loops from productive retries.
845
+
846
+ **Common loop patterns to catch**:
847
+ | Pattern | Looks Like | Actually |
848
+ |---------|-----------|----------|
849
+ | Re-reading same file after failed edit | `Read(file.ts)` → same content 3x | Agent forgot what it read — act on existing knowledge |
850
+ | Re-running same failing test without code change | `Bash(npm test)` → same failure 3x | No code was changed between runs — fix first, then test |
851
+ | Grepping same pattern across different paths | `Grep("pattern", src/)` → `Grep("pattern", lib/)` → same 0 results | Pattern doesn't exist — change search terms |
852
+
714
853
  ## Constraints
715
854
 
716
855
  1. MUST run scout before planning — no plan based on assumptions alone
@@ -739,13 +878,23 @@ A wrong first attempt that produces feedback beats perfect understanding that ne
739
878
 
740
879
  ```
741
880
  ## Cook Report: [Task Name]
742
- - **Status**: complete | partial | blocked
881
+ - **Status**: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED
743
882
  - **Phases**: [list of completed phases]
744
883
  - **Files Changed**: [count] ([list])
745
884
  - **Tests**: [passed]/[total] ([coverage]%)
746
885
  - **Quality**: preflight [PASS/WARN] | sentinel [PASS/WARN] | review [PASS/WARN]
747
886
  - **Commit**: [hash] — [message]
748
887
 
888
+ ### Deliverables (NEXUS response — when invoked by team)
889
+ | # | Deliverable | Status | Evidence |
890
+ |---|-------------|--------|----------|
891
+ | 1 | [from handoff] | DELIVERED | [file path or test output quote] |
892
+ | 2 | [from handoff] | DELIVERED | [file path or test output quote] |
893
+ | 3 | [from handoff] | PARTIAL | [what's missing and why] |
894
+
895
+ ### Concerns (if DONE_WITH_CONCERNS)
896
+ - [concern]: [impact assessment] — [suggested remediation]
897
+
749
898
  ### Decisions Made
750
899
  - [decision]: [rationale]
751
900
 
@@ -754,6 +903,8 @@ A wrong first attempt that produces feedback beats perfect understanding that ne
754
903
  - Saved to .rune/progress.md
755
904
  ```
756
905
 
906
+ > When cook is invoked standalone (not by team), the Deliverables table is optional. When invoked by team with a NEXUS Handoff, the Deliverables table is MANDATORY — team uses it to track acceptance criteria across streams.
907
+
757
908
  ## Sharp Edges
758
909
 
759
910
  Known failure modes for this skill. Check these before declaring done.
@@ -773,6 +924,22 @@ Known failure modes for this skill. Check these before declaring done.
773
924
  | Fast mode on security-relevant code | HIGH | Fast mode auto-excludes auth/crypto/payments — never fast-track security code |
774
925
  | Loading all phase files at once into context | HIGH | Phase File Gate: load ONLY the active phase file — one phase per session |
775
926
  | Resuming without checking master plan | MEDIUM | Phase 0 (RESUME CHECK) runs before Phase 1 — detects existing plans |
927
+ | Treating user "stop"/"cancel" as scope change | CRITICAL | Mid-Run Signal Detection: Cancel/Pause are safety signals with absolute priority — never reinterpret as Steer or NewTask |
928
+ | Same tool+args+result called 3+ times without progress | HIGH | Hash-Based Loop Detection: 3x warn, 5x force stop. Only same-input-AND-same-output counts — retries with different results are fine |
929
+ | Ignoring mid-run user messages during autonomous execution | HIGH | Two-stage intent classification: keyword fast-path for simple signals, context classification for longer messages. Never queue user messages — process immediately |
930
+ | Breaking change shipped without RFC review | CRITICAL | Phase 2.5 RFC Gate: any breaking change MUST have RFC artifact + user approval before implementation |
931
+ | Runaway fix loop — fix introduces more bugs than it resolves | HIGH | fix v0.5.0 WTF-likelihood self-regulation: >20% decay = STOP. Hard cap 30 fixes/session via MAX_FIXES exit condition. Regressions +15%, blast radius +5%/file |
932
+
933
+ ## Self-Validation
934
+
935
+ ```
936
+ SELF-VALIDATION (run before emitting Cook Report):
937
+ - [ ] Every phase in Phase Skip Rules was either executed or explicitly skipped with reason
938
+ - [ ] Plan approval gate was not bypassed — user said "go" (check conversation history)
939
+ - [ ] No Phase 4 code was written before Phase 3 tests (TDD order preserved)
940
+ - [ ] All Phase 5 quality gates (preflight, sentinel, review) ran — not just claimed
941
+ - [ ] Cook Report contains actual commit hash, not placeholder
942
+ ```
776
943
 
777
944
  ## Done When
778
945
 
@@ -784,6 +951,7 @@ Known failure modes for this skill. Check these before declaring done.
784
951
  - Commit created with semantic message
785
952
  - Cook Report emitted with commit hash and phase list
786
953
  - Session state saved to .rune/ via session-bridge
954
+ - Self-Validation: all checks passed
787
955
 
788
956
  ## Cost Profile
789
957