@rune-kit/rune 2.2.4 → 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.4",
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.3.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
  ```
@@ -200,6 +232,9 @@ Completion Gate Report with status (CONFIRMED/UNCONFIRMED/CONTRADICTED), claim v
200
232
  | Existence Theater — agent creates files but they're stubs | HIGH | Step 1b stub detection: grep for Placeholder/TODO/NotImplementedError in new files |
201
233
  | Cross-phase integration gaps — exports exist but wrong signature | HIGH | Step 4.5: verify exports match Code Contracts from phase file |
202
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 |
203
238
 
204
239
  ## Done When
205
240
 
@@ -5,7 +5,7 @@ context: fork
5
5
  agent: general-purpose
6
6
  metadata:
7
7
  author: runedev
8
- version: "0.9.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.
@@ -346,6 +395,8 @@ If the coder model needs info from other phases, it's in the Cross-Phase Context
346
395
  - Prefer `asyncio.gather()` for parallel I/O operations
347
396
  - Use `asyncio.TaskGroup` (Python 3.11+) for structured concurrency
348
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)
349
400
  5. **Re-plan check** — before proceeding to Phase 5, evaluate:
350
401
  - Did debug-fix loops hit max (3) for any area? → trigger re-plan
351
402
  - Were files modified outside the approved plan scope? → trigger re-plan
@@ -583,6 +634,34 @@ When cook must pause mid-phase (context limit, user break, session end before ph
583
634
 
584
635
  This is more granular than Phase 0's plan-level resume — it resumes within a phase, not just between phases.
585
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
+
586
665
  ### Exit Conditions (Mandatory for Autonomous Runs)
587
666
 
588
667
  Every cook invocation inside `team` or autonomous workflows MUST have exit conditions:
@@ -592,6 +671,8 @@ MAX_DEBUG_LOOPS: 3 per error area (already enforced)
592
671
  MAX_QUALITY_LOOPS: 2 re-runs of Phase 5 (fix→recheck cycle)
593
672
  MAX_REPLAN: 1 re-plan per cook session (Phase 4 re-plan check)
594
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
595
676
  TIMEOUT_SIGNAL: If context-watch reports ORANGE, wrap up current phase and checkpoint
596
677
  ```
597
678
 
@@ -699,6 +780,26 @@ Do NOT ask user until repair budget is spent.
699
780
  - `worktree` (L3): Phase 4 — worktree isolation for parallel implementation
700
781
  - L4 extension packs: Phase 1.5 — domain-specific patterns when stack matches (see Phase 1.5 mapping table)
701
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
+
702
803
  ## Analysis Paralysis Guard
703
804
 
704
805
  <HARD-GATE>
@@ -717,6 +818,38 @@ Stuck patterns (all banned):
717
818
  A wrong first attempt that produces feedback beats perfect understanding that never ships.
718
819
  </HARD-GATE>
719
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
+
720
853
  ## Constraints
721
854
 
722
855
  1. MUST run scout before planning — no plan based on assumptions alone
@@ -791,6 +924,22 @@ Known failure modes for this skill. Check these before declaring done.
791
924
  | Fast mode on security-relevant code | HIGH | Fast mode auto-excludes auth/crypto/payments — never fast-track security code |
792
925
  | Loading all phase files at once into context | HIGH | Phase File Gate: load ONLY the active phase file — one phase per session |
793
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
+ ```
794
943
 
795
944
  ## Done When
796
945
 
@@ -802,6 +951,7 @@ Known failure modes for this skill. Check these before declaring done.
802
951
  - Commit created with semantic message
803
952
  - Cook Report emitted with commit hash and phase list
804
953
  - Session state saved to .rune/ via session-bridge
954
+ - Self-Validation: all checks passed
805
955
 
806
956
  ## Cost Profile
807
957
 
@@ -3,7 +3,7 @@ name: debug
3
3
  description: Root cause analysis for bugs and unexpected behavior. Traces errors through code, uses structured reasoning, and hands off to fix when cause is found. Core of the debug↔fix mesh.
4
4
  metadata:
5
5
  author: runedev
6
- version: "0.5.0"
6
+ version: "0.7.0"
7
7
  layer: L2
8
8
  model: sonnet
9
9
  group: development
@@ -67,6 +67,24 @@ Understand and confirm the error described in the request.
67
67
  - Confirm the error is consistent and reproducible before proceeding
68
68
  - If no reproduction steps provided, ask for them or attempt the most likely path
69
69
 
70
+ ### Step 1.5: Scope Lock (Edit Boundary)
71
+
72
+ After reproducing the error, **lock edits to the narrowest affected directory** to prevent debug-driven scope creep — the #1 source of "while I'm here, let me also fix..." violations.
73
+
74
+ 1. Identify the narrowest directory containing the affected files (from stack trace or error location)
75
+ 2. Announce to user: "Debug scope locked to `<dir>/`. Changes will be restricted to this area."
76
+ 3. Any fix recommendation in the Debug Report MUST reference only files within this boundary
77
+ 4. If root cause traces outside the boundary → expand scope with user confirmation first
78
+
79
+ **Skip conditions** (do NOT lock):
80
+ - Bug spans the entire repo (3+ unrelated directories in stack trace)
81
+ - Cannot determine affected area from initial evidence
82
+ - User explicitly says "investigate everything"
83
+
84
+ **Why:** Debugging naturally expands scope as you trace root causes. Without a boundary, rune:fix receives recommendations touching 10+ files across unrelated modules. The scope lock forces discipline: fix at the source, not at every symptom site.
85
+
86
+ > Source: garrytan/gstack v0.9.0 (investigate skill) — auto-freeze to affected module during debug sessions.
87
+
70
88
  ### Step 2: Gather Evidence
71
89
 
72
90
  Use tools to collect facts — do NOT guess yet.
@@ -231,6 +249,30 @@ After Step 4 (Test Hypotheses): if NO hypothesis is confirmed after 3 cycles of
231
249
  Within any single step: 5+ consecutive Read/Grep calls without forming or testing a hypothesis = stuck. Stop reading, form a hypothesis from what you have, and test it. Incomplete hypotheses that get tested are better than perfect hypotheses that never form.
232
250
  </HARD-GATE>
233
251
 
252
+ ### Hash-Based Evidence Loop Detection
253
+
254
+ Beyond counting reads, detect when debug is **re-gathering the same evidence without progress** — the most common debug-specific stuck pattern.
255
+
256
+ **Detection signals** (track mentally across hypothesis cycles):
257
+
258
+ | Signal | Count | Meaning | Action |
259
+ |--------|-------|---------|--------|
260
+ | Reading the same file:line range in different cycles | 2x | Re-examining without new lens | Form hypothesis from existing evidence NOW |
261
+ | Running the same test command with same failure output | 3x | No code changed between runs | STOP — hand off to fix with current diagnosis, even if incomplete |
262
+ | Grepping the same error string after already finding all occurrences | 2x | Hoping for different results | Evidence is complete — move to Step 3 (hypothesize) |
263
+ | Same hypothesis tested with same evidence across cycles | 2x | Circular reasoning | Mark hypothesis INCONCLUSIVE, try a DIFFERENT hypothesis category |
264
+
265
+ **Hypothesis category diversity rule**: If H1 (cycle 1) was "wrong input data" and it was RULED OUT, H1 (cycle 2) MUST be from a DIFFERENT category:
266
+
267
+ | Category | Examples |
268
+ |----------|---------|
269
+ | Data | Wrong value, missing field, type mismatch, encoding |
270
+ | Control Flow | Wrong branch, missing guard, race condition, async ordering |
271
+ | Environment | Wrong config, missing env var, version mismatch, path issue |
272
+ | State | Stale cache, mutation side-effect, leaked reference, dangling connection |
273
+
274
+ > Source: goclaw (832★) — content-aware loop detection adapted for debug hypothesis cycles.
275
+
234
276
  ## Red Flags — STOP and Return to Step 2
235
277
 
236
278
  If you catch yourself thinking any of these, you are GUESSING, not debugging:
@@ -301,6 +343,11 @@ ALL of these mean: STOP. Return to Step 2 (Gather Evidence).
301
343
  | Escalating to plan when the APPROACH is wrong (not the module) | HIGH | If all 3 fixes hit the same category of blocker (API limit, platform gap), the approach needs pivoting via brainstorm(rescue), not re-planning |
302
344
  | Not tracking fix attempt number for recurring bugs | HIGH | Debug Report MUST include Fix Attempt counter — enables escalation gate |
303
345
  | Adding instrumentation without region markers | MEDIUM | All debug logging MUST use `#region agent-debug` — unmarked code gets cleaned up prematurely by fix |
346
+ | Re-reading same file:line in different hypothesis cycles | HIGH | Hash-based evidence loop: if same evidence gathered 2x, form hypothesis from existing data — don't re-gather |
347
+ | Same hypothesis category across cycles after RULED OUT | HIGH | Hypothesis category diversity: if "data" ruled out in cycle 1, cycle 2 must try "control flow", "environment", or "state" |
348
+ | Running same test 3x with same failure without code change | MEDIUM | True stuck loop — no progress possible. Hand off to fix with current incomplete diagnosis |
349
+ | Scope creep via debug — "while investigating, also fix X" | HIGH | Step 1.5 Scope Lock: lock edits to narrowest affected directory. Fix recommendations MUST stay within boundary. Expand only with user confirmation |
350
+ | Debug report recommends touching 5+ unrelated files | HIGH | Symptom of fixing at crash sites instead of source. Backward trace (Step 2) to find origin. If truly 5+ files → likely architectural issue → escalate via 3-Fix Rule |
304
351
 
305
352
  ## Done When
306
353
 
@@ -4,7 +4,7 @@ description: "Deploy application to target platform. Use when user explicitly sa
4
4
  disable-model-invocation: true
5
5
  metadata:
6
6
  author: runedev
7
- version: "0.3.0"
7
+ version: "0.4.0"
8
8
  layer: L2
9
9
  model: sonnet
10
10
  group: delivery
@@ -64,6 +64,49 @@ If sentinel returns CRITICAL issues → STOP. Do NOT proceed. Report issues.
64
64
 
65
65
  Both gates MUST pass. No exceptions.
66
66
 
67
+ ### Step 1.5 — Release Checklist (Production Deploys Only)
68
+
69
+ **Skip for**: staging, preview, development deploys.
70
+
71
+ Before production deploy, verify ALL items:
72
+
73
+ | # | Check | How | Gate |
74
+ |---|-------|-----|------|
75
+ | 1 | Version bumped | `package.json`/`pyproject.toml` version matches release | BLOCK if unchanged |
76
+ | 2 | Changelog updated | `CHANGELOG.md` has entry for this version | WARN if missing |
77
+ | 3 | Breaking changes documented | RFC artifact exists for each breaking change | BLOCK if RFC missing |
78
+ | 4 | Migration scripts ready | DB migrations tested on staging first | BLOCK if untested migration |
79
+ | 5 | Rollback plan documented | `.rune/deploy/rollback-<version>.md` exists | WARN if missing |
80
+ | 6 | Release notes drafted | Customer-facing notes for release-comms | WARN if missing |
81
+ | 7 | Dependencies locked | Lock file committed, no floating versions | BLOCK if unlocked |
82
+
83
+ **Rollback Plan Template** (`.rune/deploy/rollback-<version>.md`):
84
+
85
+ ```markdown
86
+ # Rollback Plan: v<version>
87
+
88
+ ## Trigger Conditions
89
+ - [When to rollback — e.g., error rate >5%, P0 incident, data corruption]
90
+
91
+ ## Steps
92
+ 1. [Revert command — e.g., `vercel rollback`, `fly releases rollback`]
93
+ 2. [DB rollback — e.g., `npm run migrate:rollback` or "N/A — no migration"]
94
+ 3. [Cache invalidation if needed]
95
+ 4. [Notify stakeholders]
96
+
97
+ ## Verification
98
+ - [ ] Previous version serving traffic
99
+ - [ ] Health check passing
100
+ - [ ] No data loss confirmed
101
+
102
+ ## Post-Rollback
103
+ - [ ] Incident created for root cause analysis
104
+ - [ ] Fix branch created from rolled-back commit
105
+ ```
106
+
107
+ If any BLOCK item fails → STOP deploy. Fix before retrying.
108
+ If WARN items missing → proceed but flag in deploy report.
109
+
67
110
  ### Step 2 — Detect platform
68
111
 
69
112
  Use `Bash` to inspect the project root for platform config files:
@@ -147,6 +190,8 @@ Deploy Report with platform, status (success/failed/rollback), deployed URL, bui
147
190
  3. MUST verify deploy is live and responding before declaring success
148
191
  4. MUST NOT deploy with known CRITICAL security findings
149
192
  5. MUST log deploy metadata (version, timestamp, commit hash)
193
+ 6. MUST complete release checklist for production deploys — version bump, changelog, rollback plan
194
+ 7. MUST create rollback plan artifact before first production deploy of a version
150
195
 
151
196
  ## Sharp Edges
152
197