@rune-kit/rune 2.2.4 → 2.3.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 (78) hide show
  1. package/README.md +1 -1
  2. package/compiler/adapters/openclaw.js +63 -0
  3. package/compiler/emitter.js +10 -0
  4. package/docs/EXTENSION-TEMPLATE.md +18 -0
  5. package/docs/SKILL-TEMPLATE.md +46 -0
  6. package/docs/guides/index.html +84 -21
  7. package/docs/index.html +303 -37
  8. package/docs/script.js +236 -18
  9. package/docs/style.css +417 -59
  10. package/extensions/saas/PACK.md +13 -8
  11. package/extensions/saas/skills/billing-integration.md +82 -3
  12. package/package.json +7 -5
  13. package/skills/adversary/SKILL.md +12 -0
  14. package/skills/audit/SKILL.md +64 -1
  15. package/skills/autopsy/SKILL.md +12 -0
  16. package/skills/ba/SKILL.md +63 -1
  17. package/skills/brainstorm/SKILL.md +11 -0
  18. package/skills/completion-gate/SKILL.md +51 -2
  19. package/skills/context-engine/SKILL.md +83 -1
  20. package/skills/context-pack/SKILL.md +160 -0
  21. package/skills/cook/SKILL.md +657 -808
  22. package/skills/cook/references/deviation-rules.md +19 -0
  23. package/skills/cook/references/error-recovery.md +37 -0
  24. package/skills/cook/references/exit-conditions.md +31 -0
  25. package/skills/cook/references/loop-detection.md +39 -0
  26. package/skills/cook/references/mid-run-signals.md +31 -0
  27. package/skills/cook/references/output-format.md +40 -0
  28. package/skills/cook/references/pack-detection.md +82 -0
  29. package/skills/cook/references/pause-resume-template.md +38 -0
  30. package/skills/cook/references/rfc-template.md +52 -0
  31. package/skills/cook/references/sharp-edges.md +24 -0
  32. package/skills/cook/references/subagent-status.md +38 -0
  33. package/skills/db/SKILL.md +12 -0
  34. package/skills/debug/SKILL.md +81 -2
  35. package/skills/deploy/SKILL.md +56 -1
  36. package/skills/design/SKILL.md +9 -0
  37. package/skills/docs/SKILL.md +12 -0
  38. package/skills/docs-seeker/SKILL.md +11 -0
  39. package/skills/fix/SKILL.md +63 -3
  40. package/skills/git/SKILL.md +55 -1
  41. package/skills/incident/SKILL.md +10 -0
  42. package/skills/journal/SKILL.md +51 -3
  43. package/skills/launch/SKILL.md +12 -0
  44. package/skills/logic-guardian/SKILL.md +11 -0
  45. package/skills/marketing/SKILL.md +13 -0
  46. package/skills/mcp-builder/SKILL.md +13 -0
  47. package/skills/onboard/SKILL.md +54 -2
  48. package/skills/perf/SKILL.md +11 -0
  49. package/skills/plan/SKILL.md +342 -629
  50. package/skills/plan/references/completeness-scoring.md +37 -0
  51. package/skills/plan/references/outcome-block.md +41 -0
  52. package/skills/plan/references/plan-templates.md +193 -0
  53. package/skills/plan/references/wave-planning.md +44 -0
  54. package/skills/plan/references/workflow-registry.md +53 -0
  55. package/skills/preflight/SKILL.md +135 -1
  56. package/skills/rescue/SKILL.md +10 -0
  57. package/skills/research/SKILL.md +36 -8
  58. package/skills/retro/SKILL.md +325 -0
  59. package/skills/review/SKILL.md +100 -1
  60. package/skills/review-intake/SKILL.md +11 -0
  61. package/skills/safeguard/SKILL.md +12 -0
  62. package/skills/scaffold/SKILL.md +10 -0
  63. package/skills/scope-guard/SKILL.md +11 -0
  64. package/skills/scout/SKILL.md +9 -0
  65. package/skills/sentinel/SKILL.md +307 -320
  66. package/skills/sentinel/references/config-protection.md +52 -0
  67. package/skills/sentinel/references/destructive-commands.md +40 -0
  68. package/skills/sentinel/references/domain-hooks.md +73 -0
  69. package/skills/sentinel/references/framework-patterns.md +46 -0
  70. package/skills/sentinel/references/owasp-patterns.md +69 -0
  71. package/skills/sentinel/references/secret-patterns.md +40 -0
  72. package/skills/sentinel/references/skill-content-guard.md +55 -0
  73. package/skills/session-bridge/SKILL.md +60 -2
  74. package/skills/skill-forge/SKILL.md +131 -4
  75. package/skills/skill-router/SKILL.md +33 -1
  76. package/skills/surgeon/SKILL.md +12 -0
  77. package/skills/team/SKILL.md +35 -1
  78. package/skills/test/SKILL.md +211 -7
@@ -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,7 +1,7 @@
1
1
  {
2
2
  "name": "@rune-kit/rune",
3
- "version": "2.2.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)",
3
+ "version": "2.3.0",
4
+ "description": "59-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": {
7
7
  "rune": "./compiler/bin/rune.js"
@@ -9,11 +9,12 @@
9
9
  "scripts": {
10
10
  "build": "node compiler/bin/rune.js build",
11
11
  "doctor": "node compiler/bin/rune.js doctor && node scripts/version-sync-check.js",
12
- "test": "node --test compiler/__tests__/*.test.js",
12
+ "test": "node --test compiler/__tests__/*.test.js scripts/__tests__/*.test.js",
13
+ "test:coverage": "c8 --reporter=text --reporter=lcov node --test compiler/__tests__/*.test.js scripts/__tests__/*.test.js",
13
14
  "lint": "biome check .",
14
15
  "lint:fix": "biome check --fix .",
15
16
  "format": "biome format --write .",
16
- "ci": "biome check . && node --test compiler/__tests__/*.test.js && node compiler/bin/rune.js doctor",
17
+ "ci": "biome check . && node --test compiler/__tests__/*.test.js scripts/__tests__/*.test.js && node compiler/bin/rune.js doctor",
17
18
  "version-check": "node scripts/version-sync-check.js",
18
19
  "prepublishOnly": "node scripts/version-sync-check.js"
19
20
  },
@@ -57,6 +58,7 @@
57
58
  "url": "https://github.com/rune-kit/rune/issues"
58
59
  },
59
60
  "devDependencies": {
60
- "@biomejs/biome": "^2.4.7"
61
+ "@biomejs/biome": "^2.4.7",
62
+ "c8": "^10.1.3"
61
63
  }
62
64
  }
@@ -266,6 +266,18 @@ Trigger: plan involves auth, crypto, payment, or user data handling.
266
266
  - Findings formatted for consumption by cook Phase 3 (if PROCEED) or plan (if REVISE)
267
267
  - Strength Notes section acknowledges well-designed aspects of the plan
268
268
 
269
+ ## Returns
270
+
271
+ | Artifact | Format | Location |
272
+ |----------|--------|----------|
273
+ | Adversary Report | Markdown | inline (stdout) |
274
+ | Threat findings | Structured list (CRITICAL/HIGH/MEDIUM) | inline |
275
+ | Risk matrix per dimension | Table | inline |
276
+ | Verdict + remediation list | Markdown | inline |
277
+ | Hardened plan notes (if PROCEED) | Text | passed to cook Phase 3 |
278
+
269
279
  ## Cost Profile
270
280
 
271
281
  ~4000-8000 tokens input (plan + codebase context), ~2000-3000 tokens output. Opus model for adversarial depth. Runs once per feature plan — high cost justified by preventing wasted implementation cycles.
282
+
283
+ **Scope guardrail:** adversary reviews THE PLAN only — never audits existing codebase quality or rewrites code.
@@ -3,7 +3,7 @@ name: audit
3
3
  description: Comprehensive project audit — security, dependencies, code quality, architecture, performance, infra, docs, and mesh analytics. Delegates to specialist skills and generates an 8-dimension health score.
4
4
  metadata:
5
5
  author: runedev
6
- version: "0.1.0"
6
+ version: "0.3.0"
7
7
  layer: L2
8
8
  model: sonnet
9
9
  group: quality
@@ -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
 
@@ -55,6 +56,24 @@ Determine:
55
56
 
56
57
  **Output before proceeding:** Brief project profile, stack summary, and which Framework-Specific Checks will be applied.
57
58
 
59
+ ### Phase 0.5: Context-Building (Pure Understanding)
60
+
61
+ <HARD-GATE>
62
+ This phase is FORBIDDEN from producing findings. No BLOCKs, no WARNs, no issues. Context-building only.
63
+ Rushed context = hallucinated vulnerabilities. Slow is fast.
64
+ </HARD-GATE>
65
+
66
+ For each critical module (entry points, auth, data layer, core business logic):
67
+ 1. Read line-by-line. Note at minimum:
68
+ - **3 invariants**: What MUST always be true for this code to work? (e.g., "user is authenticated before reaching this handler")
69
+ - **5 assumptions**: What does this code assume about its inputs, environment, and callers?
70
+ - **3 risks**: What could break if assumptions are violated?
71
+ 2. Record findings as context notes — these feed into Phases 1-7, NOT into the final report directly
72
+
73
+ **Why**: Without this phase, the auditor pattern-matches against known vulnerability lists and hallucinates findings that don't exist in THIS specific codebase. The invariants + assumptions ground all later analysis in reality.
74
+
75
+ > Source: trailofbits/skills (3.7k★) — mandatory pure context phase before findings.
76
+
58
77
  ---
59
78
 
60
79
  ### Phase 1: Dependency Audit
@@ -363,6 +382,36 @@ Use `Write` to save `AUDIT-REPORT.md` to the project root with the full findings
363
382
 
364
383
  Call `rune:journal` to record: audit date, overall health score, verdict, and CRITICAL count.
365
384
 
385
+ ## Weighted Composite Scoring
386
+
387
+ Each dimension score feeds into a weighted composite formula that produces a single comparable health score. Use this formula to compute **Overall Health** — not a simple average.
388
+
389
+ ### Scoring Formula
390
+
391
+ ```
392
+ Overall = (Security × 0.25) + (Code Quality × 0.20) + (Architecture × 0.15)
393
+ + (Dependencies × 0.15) + (Performance × 0.10) + (Infrastructure × 0.08)
394
+ + (Documentation × 0.07)
395
+ ```
396
+
397
+ Mesh Analytics (Phase 8) is advisory — it contributes 0 to the weighted score but informs the verdict narrative.
398
+
399
+ ### Grade Thresholds
400
+
401
+ | Score Range | Grade | Verdict | Action |
402
+ |-------------|-------|---------|--------|
403
+ | 90–100 | Excellent | PASS | Routine audit in 3 months |
404
+ | 75–89 | Good | PASS | Address MEDIUM items next sprint |
405
+ | 60–74 | Fair | WARNING | Fix HIGH items within 2 weeks |
406
+ | 40–59 | Poor | FAIL | Fix CRITICAL + HIGH within 1 week |
407
+ | 0–39 | Critical | FAIL | Emergency response — CRITICAL items block all new work |
408
+
409
+ ### Why Weighted (not average)
410
+
411
+ Security issues cause exponential blast — a 3/10 security score with all other dimensions at 9/10 = overall 72 (Fair), not 8.1 (Good). The formula ensures security and code quality dominate the verdict. Comparable across runs: if Overall moves from 68 → 74 after fixes, the project measurably improved.
412
+
413
+ > Source: zubair-trabzada/geo-seo-claude (2.7k★) — explicit weighted formula with 5-tier grade thresholds.
414
+
366
415
  ## Severity Levels
367
416
 
368
417
  ```
@@ -410,6 +459,10 @@ Apply confidence filtering: only report findings with >80% confidence. Consolida
410
459
  | Documentation | [n] |
411
460
  | Mesh Analytics | [n] |
412
461
 
462
+ ### Composite Score
463
+ - **Formula**: (Security×0.25) + (Code Quality×0.20) + (Architecture×0.15) + (Dependencies×0.15) + (Performance×0.10) + (Infrastructure×0.08) + (Documentation×0.07)
464
+ - **Weighted Score**: [computed value] → Grade: [Excellent/Good/Fair/Poor/Critical]
465
+
413
466
  ### Top Priority Actions
414
467
  1. [action] — [file:line] — [why it matters]
415
468
 
@@ -443,6 +496,16 @@ Report saved to: AUDIT-REPORT.md
443
496
  | Deps Gate | dependency-doctor report received before assembling final report | Invoke rune:dependency-doctor — do not skip |
444
497
  | Report Gate | All 8 phases completed before writing AUDIT-REPORT.md | Complete all phases, note skipped ones |
445
498
 
499
+ ## Returns
500
+
501
+ | Artifact | Format | Location |
502
+ |----------|--------|----------|
503
+ | Audit report | Markdown | `AUDIT-REPORT.md` (project root) |
504
+ | 8-dimension health score | Markdown table | `AUDIT-REPORT.md` + inline |
505
+ | Weighted composite score + grade | Markdown | inline + `AUDIT-REPORT.md` |
506
+ | Mesh analytics section | Markdown table | inline + `AUDIT-REPORT.md` |
507
+ | Journal entry | Text | `.rune/adr/` (via `rune:journal`) |
508
+
446
509
  ## Sharp Edges
447
510
 
448
511
  | Failure Mode | Severity | Mitigation |
@@ -195,6 +195,18 @@ Known failure modes for this skill. Check these before declaring done.
195
195
  - journal called with health score and surgery queue
196
196
  - Autopsy Report emitted with overall health tier and top-3 issues
197
197
 
198
+ ## Returns
199
+
200
+ | Artifact | Format | Location |
201
+ |----------|--------|----------|
202
+ | Health score per module | Scored table (0-100) | inline |
203
+ | RESCUE-REPORT.md | Markdown + Mermaid | project root |
204
+ | Surgery queue (priority order) | Ordered list | RESCUE-REPORT.md |
205
+ | Git archaeology findings | Bash output + summary | inline |
206
+ | Journal entry | Text | via `journal` L3 |
207
+
198
208
  ## Cost Profile
199
209
 
200
210
  ~5000-10000 tokens input, ~2000-4000 tokens output. Opus for deep analysis. Most expensive L2 skill but runs once per rescue.
211
+
212
+ **Scope guardrail:** autopsy assesses — it does not refactor. All surgery is delegated to `surgeon` after the report is complete.
@@ -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:
@@ -259,6 +311,15 @@ Saved to `.rune/features/<feature-name>/requirements.md`
259
311
  6. MUST ask ONE question at a time — don't overwhelm user with 5 questions at once
260
312
  7. MUST NOT skip BA for non-trivial tasks — "just build it" gets redirected to Question 1
261
313
 
314
+ ## Returns
315
+
316
+ | Artifact | Format | Location |
317
+ |----------|--------|----------|
318
+ | Requirements document | Markdown | `.rune/features/<feature-name>/requirements.md` |
319
+ | User stories with acceptance criteria | Markdown (GIVEN/WHEN/THEN) | inline + requirements.md |
320
+ | Scope definition (in/out/assumptions) | Markdown sections | requirements.md |
321
+ | Non-functional requirements table | Markdown table | requirements.md |
322
+
262
323
  ## Sharp Edges
263
324
 
264
325
  Known failure modes for this skill. Check these before declaring done.
@@ -272,6 +333,7 @@ Known failure modes for this skill. Check these before declaring done.
272
333
  | Missing hidden requirements (auth, error handling, edge cases) | HIGH | Step 3 checklist is mandatory scan |
273
334
  | Requirements doc too verbose (>500 lines) | MEDIUM | Max 200 lines — concise, actionable, testable |
274
335
  | Skipping BA for "simple" features that turn out complex | HIGH | Let cook's complexity detection trigger BA, not user judgment |
336
+ | 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
337
 
276
338
  ## Done When
277
339
 
@@ -299,6 +299,15 @@ Choose Option B if [specific hedge condition].
299
299
  Proceeding to rune:plan with Option A. Constraints to honor: [list].
300
300
  ```
301
301
 
302
+ ## Returns
303
+
304
+ | Artifact | Format | Location |
305
+ |----------|--------|----------|
306
+ | Option matrix (2-3 Discovery / 3-5 Rescue) | Markdown sections | inline (chat output) |
307
+ | Trade-off analysis per option | Markdown (pros/cons/effort/risk) | inline |
308
+ | Single recommendation with hedge condition | Markdown | inline |
309
+ | Approved design document | Markdown | `docs/plans/<feature>.md` |
310
+
302
311
  ## Sharp Edges
303
312
 
304
313
  Known failure modes for this skill. Check these before declaring done.
@@ -326,3 +335,5 @@ Known failure modes for this skill. Check these before declaring done.
326
335
  ## Cost Profile
327
336
 
328
337
  ~2000-5000 tokens input, ~1000-2500 tokens output. Opus for creative reasoning depth. Runs infrequently — only when creative exploration is needed.
338
+
339
+ **Scope guardrail:** Brainstorm produces options and a recommendation — never implementation code or an execution plan. All code and planning begins only after user approves an approach and `rune:plan` is invoked.
@@ -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.6.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,25 @@ IF no evidence found:
100
126
  → UNCONFIRMED (agent may be right but didn't prove it)
101
127
  ```
102
128
 
129
+ **3-Axis verification** — categorize each claim into one of three axes, then ensure all axes are covered:
130
+
131
+ | Axis | Question | Example Claims |
132
+ |------|----------|----------------|
133
+ | **Completeness** | Were all planned tasks done? All specs implemented? | "implemented feature X", "all TODO items done", "migration created" |
134
+ | **Correctness** | Does output match spec intent? Do tests verify real behavior? | "tests pass", "build succeeds", "lint clean", "fixed the bug" |
135
+ | **Coherence** | Does it follow project patterns? Consistent with existing code? | "follows conventions", "uses existing patterns", "no new deps needed" |
136
+
137
+ If an axis has ZERO claims → flag as gap: "No [Completeness/Correctness/Coherence] evidence found — agent may have skipped this dimension."
138
+
139
+ > Source: Fission-AI/OpenSpec (32.8k★) — 3-dimensional verification beyond pass/fail.
140
+
141
+ **Adversarial validation checklist** (run AFTER initial verdicts):
142
+ 1. Re-read each CONFIRMED claim — is the evidence actually proving THIS claim, or a different one?
143
+ 2. Check for **partial completion** — did the agent do 80% but claim 100%? (e.g., "implemented feature" but only the happy path)
144
+ 3. Check for **scope mismatch** — does the evidence prove the SPECIFIC claim or a broader/narrower version?
145
+ 4. If all claims are CONFIRMED on first pass, apply **skeptic sweep**: re-examine the weakest 2 claims with heightened scrutiny
146
+ 5. Check **axis coverage** — are all 3 axes (Completeness/Correctness/Coherence) represented? Missing axis = investigation gap
147
+
103
148
  ### Step 4 — Report
104
149
 
105
150
  ```
@@ -200,12 +245,16 @@ Completion Gate Report with status (CONFIRMED/UNCONFIRMED/CONTRADICTED), claim v
200
245
  | Existence Theater — agent creates files but they're stubs | HIGH | Step 1b stub detection: grep for Placeholder/TODO/NotImplementedError in new files |
201
246
  | Cross-phase integration gaps — exports exist but wrong signature | HIGH | Step 4.5: verify exports match Code Contracts from phase file |
202
247
  | 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 |
248
+ | 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 |
249
+ | Partial completion claimed as full — 80% done but "implemented" | HIGH | Adversarial checklist: check for partial completion, scope mismatch, evidence-claim alignment |
250
+ | 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
251
 
204
252
  ## Done When
205
253
 
206
254
  - All completion claims extracted from agent output
207
255
  - Each claim matched against tool output evidence
208
256
  - Verdict table emitted with claim/evidence/verdict for each item
257
+ - All 3 verification axes (Completeness/Correctness/Coherence) have at least one claim checked
209
258
  - Overall verdict: CONFIRMED / UNCONFIRMED / CONTRADICTED
210
259
  - If not CONFIRMED: specific gaps listed with remediation steps
211
260
 
@@ -4,7 +4,7 @@ description: "Context window management. Auto-triggered when context is filling
4
4
  user-invocable: false
5
5
  metadata:
6
6
  author: runedev
7
- version: "0.4.0"
7
+ version: "0.6.0"
8
8
  layer: L3
9
9
  model: haiku
10
10
  group: state
@@ -130,6 +130,23 @@ In addition to tool-call counting, monitor context window percentage when availa
130
130
  Debounce: emit advisory max once per 5 tool calls to avoid noise.
131
131
  Tool-call thresholds (Steps 1-2) remain the primary signal. Percentage advisory is supplementary — use when CLI status bar data is available.
132
132
 
133
+ ## Iterative Retrieval (Context-Loading Strategy)
134
+
135
+ When loading context for a task (Phase 1 of cook, or onboard), use a 4-phase retrieval loop instead of loading everything at once:
136
+
137
+ ```
138
+ 1. DISPATCH (broad): Search with initial task keywords → get 5-10 candidate files
139
+ 2. EVALUATE: Score each file's relevance (0-1). Note codebase-specific terminology discovered
140
+ 3. REFINE: Use discovered terms to search again with better keywords
141
+ 4. LOOP: Repeat max 3 cycles. STOP when 3 high-relevance files found (not 10 mediocre ones)
142
+ ```
143
+
144
+ **Why**: The first search cycle reveals codebase-specific terms (custom class names, project conventions, internal APIs) that produce much better results in cycle 2. Loading 3 deeply relevant files beats loading 10 surface-level matches.
145
+
146
+ **Key rule**: Stop at 3 high-relevance files, not 10 mediocre ones. Quality > quantity for context loading.
147
+
148
+ > Source: affaan-m/everything-claude-code (91.9k★) — 4-phase iterative retrieval.
149
+
133
150
  ## Context Health Levels
134
151
 
135
152
  ```
@@ -158,6 +175,71 @@ Note: These are tool call counts, NOT token percentages. Claude Code does not ex
158
175
  - Blockers: [if any]
159
176
  ```
160
177
 
178
+ ## Strategic Compact Decision Table
179
+
180
+ When ORANGE or RED is reached, use this table to determine whether compaction is safe at the current boundary:
181
+
182
+ | Transition | Compact? | Reason |
183
+ |-----------|----------|--------|
184
+ | Research → Planning | YES | Research findings summarize well; key decisions survive |
185
+ | Planning → Implementation | YES | Plan is in files (.rune/plan-*.md); context can reload from artifacts |
186
+ | Debug → Next feature | YES | Debug findings are in Debug Report; fix has the diagnosis |
187
+ | Mid-implementation (Phase 4) | **NO** | Losing file paths, partial changes, and test state is catastrophic |
188
+ | After failed approach → Pivot | YES | Failed approach should be discarded; fresh context helps |
189
+ | Quality (Phase 5) → Verify | **NO** | Quality findings reference specific file:line in current context |
190
+ | After commit (Phase 7) | YES | Work is persisted in git; safe boundary |
191
+
192
+ **What survives compaction**: Task description, file paths mentioned, key decisions, plan reference, current phase.
193
+ **What is lost**: Full file contents read, intermediate reasoning, exact error messages, tool output details.
194
+
195
+ > Source: affaan-m/everything-claude-code (91.9k★) — strategic compact timing decision table.
196
+
197
+ ## Context Budget Audit (Baseline Cost Awareness)
198
+
199
+ MCP tool schemas and agent descriptions consume significant baseline context before any work begins. This section helps identify and reduce invisible context waste.
200
+
201
+ ### Token Cost Reference
202
+
203
+ | Source | Approx. Cost | Loaded When |
204
+ |--------|-------------|-------------|
205
+ | Each MCP tool schema | ~500 tokens | Session start (always) |
206
+ | Each agent description | ~200-400 tokens | Every `Task()` invocation |
207
+ | CLAUDE.md | ~100-2000 tokens | Session start (always) |
208
+ | Skill SKILL.md (full load) | ~500-3000 tokens | When skill is invoked |
209
+
210
+ ### Budget Rules
211
+
212
+ | Rule | Threshold | Action |
213
+ |------|-----------|--------|
214
+ | Max MCP servers | <10 active | Disable unused MCP servers in settings |
215
+ | Max MCP tools | <80 total | Remove or consolidate bloated MCP servers |
216
+ | Agent descriptions | Only load needed | Use specific `subagent_type` to avoid loading all descriptions |
217
+ | CLAUDE.md size | <150 lines | Move detailed docs to `.rune/` files, keep CLAUDE.md as index |
218
+
219
+ ### Audit Procedure
220
+
221
+ When context health is YELLOW or worse, or when onboard detects >80 MCP tools:
222
+
223
+ 1. Count total MCP tool schemas loaded (from session start messages)
224
+ 2. Count agent descriptions available
225
+ 3. Estimate baseline cost: `(tools × 500) + (agents × 300) + CLAUDE.md tokens`
226
+ 4. If baseline >15% of estimated context window → flag as **Context Budget Warning**
227
+ 5. Rank MCP servers by tool count — suggest disabling servers with most tools and least usage
228
+
229
+ ### Report Addition
230
+
231
+ When Context Budget Warning fires, append to Context Health report:
232
+
233
+ ```
234
+ ### Context Budget
235
+ - **Baseline cost**: ~[N]k tokens ([X]% of estimated window)
236
+ - **MCP tools loaded**: [count] across [N] servers
237
+ - **Top consumers**: [server1] ([N] tools), [server2] ([N] tools)
238
+ - **Recommendation**: Disable [server] to save ~[N]k tokens
239
+ ```
240
+
241
+ > Source: affaan-m/everything-claude-code (91.9k★) — MCP token cost awareness and budget rules.
242
+
161
243
  ## Constraints
162
244
 
163
245
  1. MUST preserve context fidelity — no summarizing away critical details