@rune-kit/rune 2.4.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +47 -17
  2. package/compiler/__tests__/executive-dashboards.test.js +285 -0
  3. package/compiler/__tests__/inject.test.js +128 -0
  4. package/compiler/__tests__/orchestrators.test.js +151 -0
  5. package/compiler/__tests__/org-templates.test.js +447 -0
  6. package/compiler/__tests__/pack-split.test.js +141 -1
  7. package/compiler/__tests__/parser.test.js +147 -1
  8. package/compiler/__tests__/scripts-bundling.test.js +10 -11
  9. package/compiler/__tests__/skill-index.test.js +218 -0
  10. package/compiler/__tests__/status.test.js +336 -0
  11. package/compiler/__tests__/templates.test.js +245 -0
  12. package/compiler/__tests__/visualizer.test.js +325 -0
  13. package/compiler/adapters/antigravity.js +18 -4
  14. package/compiler/bin/rune.js +90 -1
  15. package/compiler/doctor.js +283 -2
  16. package/compiler/emitter.js +490 -17
  17. package/compiler/parser.js +255 -4
  18. package/compiler/status.js +342 -0
  19. package/compiler/visualizer.js +622 -0
  20. package/hooks/hooks.json +12 -0
  21. package/hooks/intent-router/index.cjs +108 -0
  22. package/hooks/pre-tool-guard/index.cjs +177 -68
  23. package/package.json +63 -63
  24. package/skills/autopsy/SKILL.md +48 -1
  25. package/skills/brainstorm/SKILL.md +2 -0
  26. package/skills/completion-gate/SKILL.md +26 -1
  27. package/skills/context-engine/SKILL.md +93 -2
  28. package/skills/cook/SKILL.md +794 -648
  29. package/skills/debug/SKILL.md +409 -392
  30. package/skills/deploy/SKILL.md +2 -0
  31. package/skills/docs/SKILL.md +28 -3
  32. package/skills/fix/SKILL.md +284 -281
  33. package/skills/mcp-builder/SKILL.md +53 -1
  34. package/skills/onboard/SKILL.md +58 -1
  35. package/skills/perf/SKILL.md +34 -1
  36. package/skills/plan/SKILL.md +372 -342
  37. package/skills/preflight/SKILL.md +396 -360
  38. package/skills/retro/SKILL.md +95 -1
  39. package/skills/review/SKILL.md +535 -489
  40. package/skills/scope-guard/SKILL.md +1 -0
  41. package/skills/scout/SKILL.md +1 -0
  42. package/skills/sentinel/SKILL.md +353 -299
  43. package/skills/sentinel/references/policy-driven-constraints.md +424 -0
  44. package/skills/session-bridge/SKILL.md +58 -2
  45. package/skills/session-bridge/references/evolutionary-memory-patterns.md +312 -0
  46. package/skills/team/SKILL.md +16 -1
  47. package/skills/test/SKILL.md +587 -585
  48. package/skills/verification/SKILL.md +1 -0
  49. package/skills/watchdog/SKILL.md +2 -0
@@ -1,360 +1,396 @@
1
- ---
2
- name: preflight
3
- description: Pre-commit quality gate that catches "almost right" code. Goes beyond linting — checks logic correctness, error handling, regressions, and completeness.
4
- metadata:
5
- author: runedev
6
- version: "0.6.0"
7
- layer: L2
8
- model: sonnet
9
- group: quality
10
- tools: "Read, Bash, Glob, Grep"
11
- ---
12
-
13
- # preflight
14
-
15
- ## Purpose
16
-
17
- <HARD-GATE>
18
- Preflight verdict of BLOCK stops the pipeline. The calling skill (cook, deploy, launch) MUST halt until all BLOCK findings are resolved and preflight re-runs clean.
19
- </HARD-GATE>
20
-
21
- Pre-commit quality gate that catches "almost right" code — the kind that compiles and passes linting but has logic errors, missing error handling, or incomplete implementations. Goes beyond static analysis to check data flow, edge cases, async correctness, and regression impact. The last defense before code enters the repository.
22
-
23
- ## Triggers
24
-
25
- - Called automatically by `cook` before commit phase
26
- - Called by `fix` after applying fixes (verify fix quality)
27
- - `/rune preflight` manual quality check
28
- - Auto-trigger: when staged changes exceed 100 LOC
29
-
30
- ## Calls (outbound)
31
-
32
- - `scout` (L2): find code affected by changes (dependency tracing)
33
- - `sentinel` (L2): security sub-check on changed files
34
- - `hallucination-guard` (L3): verify imports and API references exist
35
- - `test` (L2): run test suite as pre-commit check
36
-
37
- ## Called By (inbound)
38
-
39
- - `cook` (L1): before commit phase — mandatory gate
40
-
41
- ## Check Categories
42
-
43
- ```
44
- LOGIC — data flow errors, edge case misses, async bugs
45
- ERROR — missing try/catch, bare catches, unhelpful error messages
46
- REGRESSION untested impact zones, breaking changes to public API
47
- COMPLETE — missing validation, missing loading states, missing tests
48
- SECURITY delegated to sentinel
49
- IMPORTS delegated to hallucination-guard
50
- ```
51
-
52
- ## Executable Steps
53
-
54
- ### Stage A — Spec Compliance (Plan vs Diff)
55
-
56
- Before checking code quality, verify the code matches what was planned.
57
-
58
- Use `Bash` to get the diff: `git diff --cached` (staged) or `git diff HEAD` (all changes).
59
- Use `Read` to load the approved plan from the calling skill (cook passes plan context).
60
-
61
- **Check each plan phase against the diff:**
62
-
63
- | Plan says... | Diff shows... | Verdict |
64
- |---|---|---|
65
- | "Add function X to file Y" | Function X exists in file Y | PASS |
66
- | "Add function X to file Y" | Function X missing | BLOCK — incomplete implementation |
67
- | "Modify function Z" | Function Z untouched | BLOCK planned change not applied |
68
- | Nothing about file W | File W modified | WARNout-of-scope change (scope creep) |
69
-
70
- **Output**: List of plan-vs-diff mismatches. Any missing planned change = BLOCK. Any unplanned change = WARN.
71
-
72
- If no plan is available (manual preflight invocation), skip Stage A and proceed to Step 1.
73
-
74
- ### Step 1 Logic Review
75
- Use `Read` to load each changed file. For every modified function or method:
76
- - Trace the data flow from input to output. Identify where a `null`, `undefined`, empty array, or 0 value would cause a runtime error or wrong result.
77
- - Check async/await: every `async` function that calls an async operation must `await` it. Identify missing `await` that would cause race conditions or unhandled promise rejections.
78
- - Check boundary conditions: off-by-one in loops, array index out of bounds, division by zero.
79
- - Check type coercions: implicit `==` comparisons that could produce wrong results, string-to-number conversions without validation.
80
-
81
- **Common patterns to flag:**
82
-
83
- ```typescript
84
- // BAD — missing await (race condition)
85
- async function processOrder(orderId: string) {
86
- const order = db.orders.findById(orderId); // order is a Promise, not a value
87
- return calculateTotal(order.items); // crashes: order.items is undefined
88
- }
89
- // GOOD
90
- async function processOrder(orderId: string) {
91
- const order = await db.orders.findById(orderId);
92
- return calculateTotal(order.items);
93
- }
94
- ```
95
-
96
- ```typescript
97
- // BAD — sequential independent I/O
98
- const user = await fetchUser(id);
99
- const permissions = await fetchPermissions(id); // waits unnecessarily
100
- // GOOD parallel
101
- const [user, permissions] = await Promise.all([fetchUser(id), fetchPermissions(id)]);
102
- ```
103
-
104
- Flag each issue with: file path, line number, category (null-deref | missing-await | off-by-one | type-coerce), and a one-line description.
105
-
106
- ### Step 2 Error Handling
107
- For every changed file, verify:
108
- - Every `async` function has a `try/catch` block OR the caller explicitly handles the rejected promise.
109
- - No bare `catch(e) {}` or `except: pass` — every catch must log or rethrow with context.
110
- - Every `fetch` / HTTP client call checks the response status before consuming the body.
111
- - Error messages are user-friendly: no raw stack traces, no internal variable names exposed to the client.
112
- - API route handlers return appropriate HTTP status codes (4xx for client errors, 5xx for server errors).
113
-
114
- **Common patterns to flag:**
115
-
116
- ```typescript
117
- // BAD — swallowed exception
118
- try {
119
- await saveUser(data);
120
- } catch (e) {} // silent failure, caller never knows
121
-
122
- // BAD leaks internals to client
123
- app.use((err, req, res, next) => {
124
- res.status(500).json({ error: err.stack }); // exposes stack trace
125
- });
126
- // GOOD log internally, generic message to client
127
- app.use((err, req, res, next) => {
128
- logger.error(err);
129
- res.status(500).json({ error: 'Internal server error' });
130
- });
131
- ```
132
-
133
- Flag each violation with: file path, line number, category (bare-catch | missing-status-check | raw-error-exposure), and description.
134
-
135
- ### Step 3 Regression Check
136
- Use `rune:scout` to identify all files that import or depend on the changed files/functions.
137
- For each dependent file:
138
- - Check if the changed function signature is still compatible (parameter count, types, return type).
139
- - Check if the dependent file has tests that cover the interaction with the changed code.
140
- - Flag untested impact zones: dependents with zero test coverage of the affected code path.
141
-
142
- Flag each regression risk with: dependent file path, what changed, whether tests exist, severity (breaking | degraded | untested).
143
-
144
- ### Step 4 Completeness Check
145
- Verify that new code ships complete:
146
- - New API endpoint has input validation schema (Zod, Pydantic, Joi, etc.)
147
- - New React/Svelte component has loading state AND error state
148
- - New feature → has at least one test file
149
- - New configuration option → has documentation (inline comment or docs file)
150
- - New database query → has corresponding migration file if schema changed
151
-
152
- **Framework-specific completeness (apply only if detected):**
153
- - React component with async data → must have `loading` state AND `error` state
154
- - Next.js Server Action must have `try/catch` and return typed result
155
- - FastAPI endpoint → must have Pydantic request/response models
156
- - Django ViewSet → must have explicit `permission_classes`
157
- - Express route → must have input validation middleware before handler
158
-
159
- If any completeness item is missing, flag as **WARN** with: what is missing, which file needs it.
160
-
161
- ### Step 4.2 Coherence Check
162
-
163
- Verify that new code is **consistent with existing project patterns** not just correct, but coherent with the codebase it lives in.
164
-
165
- | Check | What To Look For | Severity |
166
- |-------|------------------|----------|
167
- | Naming conventions | New functions/variables follow project's existing naming style (camelCase, snake_case, etc.) | WARN |
168
- | File organization | New files placed in correct directory per project structure (e.g., utils/ not lib/, components/ not ui/) | WARN |
169
- | Import patterns | Uses project's established import style (absolute vs relative, barrel exports vs direct) | WARN |
170
- | Error handling style | Matches project's existing pattern (Result type, try/catch, error codes) | WARN |
171
- | State management | Uses same state approach as rest of project (Zustand, context, stores) | BLOCK if different paradigm |
172
- | API patterns | Follows existing response format, middleware chain, auth pattern | BLOCK if diverges |
173
- | Design system usage | Uses existing design tokens/components, not inline overrides | WARN |
174
-
175
- **Detection**: Read 2-3 existing files in the same directory as the change. Compare patterns. Flag divergences.
176
-
177
- **Skip if**: Project has no established patterns (greenfield, <5 files), or CLAUDE.md/conventions.md explicitly says "no conventions yet."
178
-
179
- ### Step 4.3 Eval Verification
180
-
181
- If `.rune/evals/` directory exists with eval definition files, verify eval results as part of the quality gate.
182
-
183
- | Check | Action | Severity |
184
- |-------|--------|----------|
185
- | Capability eval defined but not run | Feature has `.rune/evals/<feature>.md` with CAP-* entries but no results | WARN: "Capability evals defined but not executed" |
186
- | Regression eval failing | Any REG-* eval with status=fail | BLOCK: "Regression detected — existing behavior broken" |
187
- | Capability eval below threshold | CAP-* eval pass@k below defined threshold | WARN: "Capability eval below threshold (X% vs Y% required)" |
188
- | No eval file for new feature | New feature added (detected by new test files + new source files) but no `.rune/evals/` entry | INFO: "Consider defining capability evals for new feature" |
189
-
190
- **Skip if**: No `.rune/evals/` directory exists (project hasn't adopted eval-driven development).
191
-
192
- ### Step 4.5 Domain Quality Hooks
193
-
194
- Apply domain-specific quality checks based on detected file types in the diff. These extend the generic completeness checks in Step 4 with deeper domain validation.
195
-
196
- <HARD-GATE>
197
- Domain hooks are additive — they add checks, never remove generic ones from Steps 1-4.
198
- If a domain hook flags BLOCK, the overall preflight verdict is BLOCK regardless of other steps.
199
- </HARD-GATE>
200
-
201
- #### Hook Selection (auto-detect from diff)
202
-
203
- | Detected Pattern | Domain Hook | Key Checks |
204
- |-----------------|-------------|------------|
205
- | `migrations/*.sql`, `*.migration.*` | Database | Rollback script present, no bare DROP/DELETE, migration tested |
206
- | `openapi.*`, `*.graphql`, `*.proto` | API Contract | Breaking changes flagged, version bumped, deprecated fields documented |
207
- | `docs/policies/*`, `PRIVACY*`, `TERMS*` | Legal/Compliance | No placeholder text, review date current, practice matches policy |
208
- | `**/billing*`, `**/payment*`, `**/invoice*` | Financial | Decimal precision correct, currency locale-aware, no hardcoded rates |
209
- | `skills/*/SKILL.md`, `extensions/*/PACK.md` | Rune Skill | Frontmatter valid, all required sections present, word count within layer budget |
210
- | `*.test.*`, `*.spec.*`, `__tests__/*` | Test Quality | No `.skip`/`.only` left in, assertions present (not empty tests), no hardcoded timeouts |
211
-
212
- #### Domain Hook Execution
213
-
214
- For each detected domain, run its checks on the relevant files in the diff:
215
-
216
- 1. **Identify** which domain hooks apply based on changed file patterns
217
- 2. **Load** domain-specific check rules (inline above, or from pack reference files if a pack is installed)
218
- 3. **Scan** each relevant file for domain violations
219
- 4. **Classify** findings: BLOCK (data loss risk, breaking contract) or WARN (best practice, incomplete)
220
- 5. **Append** to preflight report under `### Domain Quality` section
221
-
222
- #### Pack Integration
223
-
224
- When a domain pack is installed (e.g., `@rune-pro/finance`, `@rune-pro/legal`), preflight checks the pack's **Hard-Stop Thresholds** table and applies matching rules to staged files. This means:
225
- - Installing `@rune-pro/finance` automatically adds financial quality gates to preflight
226
- - Installing `@rune-pro/legal` automatically adds compliance checks to preflight
227
- - No manual configuration needed pack presence = hooks active
228
-
229
- #### Output Section
230
-
231
- ```
232
- ### Domain Quality
233
- - **Domains detected**: [Database, Financial]
234
- - `migrations/003-add-billing.sql` — BLOCK: DROP TABLE without rollback script
235
- - `src/billing/invoice.ts:42` WARN: price calculation uses `toFixed(2)` instead of `Intl.NumberFormat`
236
- ```
237
-
238
- ### Step 4.8 — Preflight Composite Score
239
-
240
- After all domain hooks (Step 4.5) and completeness checks (Step 4) complete, compute a **Preflight Health Score** to make the verdict numeric and comparable across runs.
241
-
242
- ### Formula
243
-
244
- ```
245
- Preflight Score = (Logic × 0.30) + (Error Handling × 0.20) + (Completeness × 0.20) + (Coherence × 0.15) + (Regression Risk × 0.15)
246
- ```
247
-
248
- **5 verification axes** (Completeness + Correctness via Logic + Coherence — 3D verification model):
249
-
250
- Each dimension is scored per staged files:
251
- - 0 BLOCK findings in dimension 100
252
- - 1 BLOCK dimension capped at 30
253
- - 1 WARN dimension capped at 75
254
- - Each additional WARN subtract 10 (floor: 40)
255
-
256
- ### Grade Thresholds
257
-
258
- | Score | Grade | Verdict |
259
- |-------|-------|---------|
260
- | 90–100 | Excellent | PASS |
261
- | 75–89 | Good | PASS with notes |
262
- | 60–74 | Fair | WARN |
263
- | 40–59 | Poor | WARN (escalate to developer) |
264
- | 0–39 | Critical | BLOCK |
265
-
266
- Score is appended to the Preflight Report footer. Useful for tracking quality trend across sprints when cook logs preflight scores to `.rune/metrics/`.
267
-
268
-
269
- ### Step 5 Security Sub-Check
270
- Invoke `rune:sentinel` on the changed files. Attach sentinel's output verbatim under the "Security" section of the preflight report. If sentinel returns BLOCK, preflight verdict is also BLOCK.
271
-
272
- ### Step 6 Generate Verdict
273
- Aggregate all findings:
274
- - Any BLOCK from sentinel OR a logic issue that would cause data corruption or security bypass → overall **BLOCK**
275
- - Any missing error handling, regression risk with no tests, or incomplete feature → **WARN**
276
- - Only style or best-practice suggestions **PASS**
277
-
278
- Report PASS, WARN, or BLOCK. For WARN, list each item the developer must acknowledge. For BLOCK, list each item that must be fixed before proceeding.
279
-
280
- ## Output Format
281
-
282
- ```
283
- ## Preflight Report
284
- - **Status**: PASS | WARN | BLOCK
285
- - **Files Checked**: [count]
286
- - **Changes**: +[added] -[removed] lines across [files] files
287
-
288
- ### Logic Issues
289
- - `path/to/file.ts:42` null-deref: `user.name` accessed without null check
290
- - `path/to/api.ts:85` missing-await: async database call not awaited
291
-
292
- ### Error Handling
293
- - `path/to/handler.ts:20` — bare-catch: error swallowed silently
294
-
295
- ### Regression Risk
296
- - `utils/format.ts` changed function used by 5 modules, 2 have tests, 3 untested (WARN)
297
-
298
- ### Completeness
299
- - `api/users.ts` new POST endpoint missing input validation schema
300
- - `components/Form.tsx` no loading state during submission
301
-
302
- ### Coherence
303
- - `api/users.ts` — uses `res.json()` but project convention is `sendResponse()` wrapper
304
- - `utils/newHelper.ts` — placed in utils/ but project uses helpers/ directory
305
-
306
- ### Security (from sentinel)
307
- - [sentinel findings if any]
308
-
309
- ### Composite Score
310
- - Logic: [score] | Error: [score] | Completeness: [score] | Coherence: [score] | Regression: [score]
311
- - **Preflight Score**: [weighted value]Grade: [Excellent/Good/Fair/Poor/Critical]
312
-
313
- ### Verdict
314
- WARN 3 issues found (0 blocking, 3 must-acknowledge). Resolve before commit or explicitly acknowledge each WARN.
315
- ```
316
-
317
- ## Constraints
318
-
319
- 1. MUST check: logic errors, error handling, edge cases, type safety, naming conventions
320
- 2. MUST reference specific file:line for every finding
321
- 3. MUST NOT skip edge case analysis — "happy path works" is insufficient
322
- 4. MUST verify error messages are user-friendly and don't leak internal details
323
- 5. MUST check that async operations have proper error handling and cleanup
324
-
325
- ## Returns
326
-
327
- | Artifact | Format | Location |
328
- |----------|--------|----------|
329
- | Preflight report | Markdown | inline (chat output) |
330
- | Issue list (BLOCK/WARN by category) | Markdown list | inline |
331
- | Preflight health score | Markdown table | inline (footer of report) |
332
- | Spec compliance verdict | Markdown table | inline |
333
- | Domain quality findings | Markdown section | inline |
334
-
335
- ## Sharp Edges
336
-
337
- | Failure Mode | Severity | Mitigation |
338
- |---|---|---|
339
- | Stopping at first BLOCK finding without checking remaining files | HIGH | Aggregate all findings first developer needs the complete list, not just the first blocker |
340
- | "Happy path works" accepted as sufficient | HIGH | CONSTRAINT blocks this edge case analysis is mandatory on every function |
341
- | Calling verification directly instead of the test skill | MEDIUM | Preflight calls rune:test for test suite execution; rune:verification for lint/type/build checks |
342
- | Skipping sentinel sub-check because "this file doesn't look security-relevant" | HIGH | MUST invoke sentinel — security relevance is sentinel's job to determine, not preflight's |
343
- | Skipping Stage A (spec compliance) when plan is available | HIGH | If cook provides an approved plan, Stage A is mandatory — catches incomplete implementations |
344
- | Agent modified files not in plan without flagging | MEDIUM | Stage A flags unplanned file changes as WARN — scope creep detection |
345
- | Domain hooks not triggered when pack is installed | HIGH | Step 4.5 auto-detects file patterns — if pack is installed but hooks don't fire, check file pattern matching |
346
- | Domain hooks overriding generic checks | HIGH | HARD-GATE: domain hooks are ADDITIVE — they never replace Steps 1-4 |
347
- | Pack Hard-Stop Thresholds ignored in preflight | MEDIUM | Step 4.5 Pack Integration must read installed pack thresholds — test with each new pack |
348
-
349
- ## Done When
350
-
351
- - Every changed function traced for null-deref, missing-await, and off-by-one
352
- - Error handling verified on all async functions and HTTP calls
353
- - Regression impact assessed — dependent files identified via scout
354
- - Completeness checklist passed (validation schema, loading/error states, test file)
355
- - Sentinel invoked and its output attached in Security section
356
- - Structured report emitted with PASS / WARN / BLOCK verdict and file:line for every finding
357
-
358
- ## Cost Profile
359
-
360
- ~2000-4000 tokens input, ~500-1500 tokens output. Sonnet for logic analysis quality.
1
+ ---
2
+ name: preflight
3
+ description: Pre-commit quality gate that catches "almost right" code. Goes beyond linting — checks logic correctness, error handling, regressions, and completeness.
4
+ metadata:
5
+ author: runedev
6
+ version: "0.7.0"
7
+ layer: L2
8
+ model: sonnet
9
+ group: quality
10
+ tools: "Read, Bash, Glob, Grep"
11
+ emit: preflight.passed, preflight.blocked
12
+ listen: code.changed
13
+ ---
14
+
15
+ # preflight
16
+
17
+ ## Purpose
18
+
19
+ <HARD-GATE>
20
+ Preflight verdict of BLOCK stops the pipeline. The calling skill (cook, deploy, launch) MUST halt until all BLOCK findings are resolved and preflight re-runs clean.
21
+ </HARD-GATE>
22
+
23
+ Pre-commit quality gate that catches "almost right" code — the kind that compiles and passes linting but has logic errors, missing error handling, or incomplete implementations. Goes beyond static analysis to check data flow, edge cases, async correctness, and regression impact. The last defense before code enters the repository.
24
+
25
+ ## Triggers
26
+
27
+ - Called automatically by `cook` before commit phase
28
+ - Called by `fix` after applying fixes (verify fix quality)
29
+ - `/rune preflight` — manual quality check
30
+ - Auto-trigger: when staged changes exceed 100 LOC
31
+
32
+ ## Calls (outbound)
33
+
34
+ - `scout` (L2): find code affected by changes (dependency tracing)
35
+ - `sentinel` (L2): security sub-check on changed files
36
+ - `hallucination-guard` (L3): verify imports and API references exist
37
+ - `test` (L2): run test suite as pre-commit check
38
+
39
+ ## Called By (inbound)
40
+
41
+ - `cook` (L1): before commit phase — mandatory gate
42
+
43
+ ## Check Categories
44
+
45
+ ```
46
+ LOGIC data flow errors, edge case misses, async bugs
47
+ ERROR — missing try/catch, bare catches, unhelpful error messages
48
+ REGRESSION untested impact zones, breaking changes to public API
49
+ COMPLETE missing validation, missing loading states, missing tests
50
+ SECURITY — delegated to sentinel
51
+ IMPORTS — delegated to hallucination-guard
52
+ ```
53
+
54
+ ## Executable Steps
55
+
56
+ ### Stage A Spec Compliance (Plan vs Diff)
57
+
58
+ Before checking code quality, verify the code matches what was planned.
59
+
60
+ Use `Bash` to get the diff: `git diff --cached` (staged) or `git diff HEAD` (all changes).
61
+ Use `Read` to load the approved plan from the calling skill (cook passes plan context).
62
+
63
+ **Check each plan phase against the diff:**
64
+
65
+ | Plan says... | Diff shows... | Verdict |
66
+ |---|---|---|
67
+ | "Add function X to file Y" | Function X exists in file Y | PASS |
68
+ | "Add function X to file Y" | Function X missing | BLOCKincomplete implementation |
69
+ | "Modify function Z" | Function Z untouched | BLOCK — planned change not applied |
70
+ | Nothing about file W | File W modified | WARN out-of-scope change (scope creep) |
71
+
72
+ **Output**: List of plan-vs-diff mismatches. Any missing planned change = BLOCK. Any unplanned change = WARN.
73
+
74
+ If no plan is available (manual preflight invocation), skip Stage A and proceed to Step 1.
75
+
76
+ ### Step 1 Logic Review
77
+ Use `Read` to load each changed file. For every modified function or method:
78
+ - Trace the data flow from input to output. Identify where a `null`, `undefined`, empty array, or 0 value would cause a runtime error or wrong result.
79
+ - Check async/await: every `async` function that calls an async operation must `await` it. Identify missing `await` that would cause race conditions or unhandled promise rejections.
80
+ - Check boundary conditions: off-by-one in loops, array index out of bounds, division by zero.
81
+ - Check type coercions: implicit `==` comparisons that could produce wrong results, string-to-number conversions without validation.
82
+
83
+ **Common patterns to flag:**
84
+
85
+ ```typescript
86
+ // BAD missing await (race condition)
87
+ async function processOrder(orderId: string) {
88
+ const order = db.orders.findById(orderId); // order is a Promise, not a value
89
+ return calculateTotal(order.items); // crashes: order.items is undefined
90
+ }
91
+ // GOOD
92
+ async function processOrder(orderId: string) {
93
+ const order = await db.orders.findById(orderId);
94
+ return calculateTotal(order.items);
95
+ }
96
+ ```
97
+
98
+ ```typescript
99
+ // BAD sequential independent I/O
100
+ const user = await fetchUser(id);
101
+ const permissions = await fetchPermissions(id); // waits unnecessarily
102
+ // GOOD — parallel
103
+ const [user, permissions] = await Promise.all([fetchUser(id), fetchPermissions(id)]);
104
+ ```
105
+
106
+ Flag each issue with: file path, line number, category (null-deref | missing-await | off-by-one | type-coerce), and a one-line description.
107
+
108
+ ### Step 2 Error Handling
109
+ For every changed file, verify:
110
+ - Every `async` function has a `try/catch` block OR the caller explicitly handles the rejected promise.
111
+ - No bare `catch(e) {}` or `except: pass` every catch must log or rethrow with context.
112
+ - Every `fetch` / HTTP client call checks the response status before consuming the body.
113
+ - Error messages are user-friendly: no raw stack traces, no internal variable names exposed to the client.
114
+ - API route handlers return appropriate HTTP status codes (4xx for client errors, 5xx for server errors).
115
+
116
+ **Common patterns to flag:**
117
+
118
+ ```typescript
119
+ // BAD — swallowed exception
120
+ try {
121
+ await saveUser(data);
122
+ } catch (e) {} // silent failure, caller never knows
123
+
124
+ // BAD leaks internals to client
125
+ app.use((err, req, res, next) => {
126
+ res.status(500).json({ error: err.stack }); // exposes stack trace
127
+ });
128
+ // GOOD — log internally, generic message to client
129
+ app.use((err, req, res, next) => {
130
+ logger.error(err);
131
+ res.status(500).json({ error: 'Internal server error' });
132
+ });
133
+ ```
134
+
135
+ Flag each violation with: file path, line number, category (bare-catch | missing-status-check | raw-error-exposure), and description.
136
+
137
+ ### Step 3 — Regression Check
138
+ Use `rune:scout` to identify all files that import or depend on the changed files/functions.
139
+ For each dependent file:
140
+ - Check if the changed function signature is still compatible (parameter count, types, return type).
141
+ - Check if the dependent file has tests that cover the interaction with the changed code.
142
+ - Flag untested impact zones: dependents with zero test coverage of the affected code path.
143
+
144
+ Flag each regression risk with: dependent file path, what changed, whether tests exist, severity (breaking | degraded | untested).
145
+
146
+ ### Step 4 Completeness Check
147
+ Verify that new code ships complete:
148
+ - New API endpoint → has input validation schema (Zod, Pydantic, Joi, etc.)
149
+ - New React/Svelte component → has loading state AND error state
150
+ - New feature → has at least one test file
151
+ - New configuration option → has documentation (inline comment or docs file)
152
+ - New database query → has corresponding migration file if schema changed
153
+
154
+ **Framework-specific completeness (apply only if detected):**
155
+ - React component with async data → must have `loading` state AND `error` state
156
+ - Next.js Server Action → must have `try/catch` and return typed result
157
+ - FastAPI endpoint → must have Pydantic request/response models
158
+ - Django ViewSet → must have explicit `permission_classes`
159
+ - Express route must have input validation middleware before handler
160
+
161
+ If any completeness item is missing, flag as **WARN** with: what is missing, which file needs it.
162
+
163
+ ### Step 4.2Coherence Check
164
+
165
+ Verify that new code is **consistent with existing project patterns** — not just correct, but coherent with the codebase it lives in.
166
+
167
+ | Check | What To Look For | Severity |
168
+ |-------|------------------|----------|
169
+ | Naming conventions | New functions/variables follow project's existing naming style (camelCase, snake_case, etc.) | WARN |
170
+ | File organization | New files placed in correct directory per project structure (e.g., utils/ not lib/, components/ not ui/) | WARN |
171
+ | Import patterns | Uses project's established import style (absolute vs relative, barrel exports vs direct) | WARN |
172
+ | Error handling style | Matches project's existing pattern (Result type, try/catch, error codes) | WARN |
173
+ | State management | Uses same state approach as rest of project (Zustand, context, stores) | BLOCK if different paradigm |
174
+ | API patterns | Follows existing response format, middleware chain, auth pattern | BLOCK if diverges |
175
+ | Design system usage | Uses existing design tokens/components, not inline overrides | WARN |
176
+
177
+ **Detection**: Read 2-3 existing files in the same directory as the change. Compare patterns. Flag divergences.
178
+
179
+ **Skip if**: Project has no established patterns (greenfield, <5 files), or CLAUDE.md/conventions.md explicitly says "no conventions yet."
180
+
181
+ ### Step 4.3 Eval Verification
182
+
183
+ If `.rune/evals/` directory exists with eval definition files, verify eval results as part of the quality gate.
184
+
185
+ | Check | Action | Severity |
186
+ |-------|--------|----------|
187
+ | Capability eval defined but not run | Feature has `.rune/evals/<feature>.md` with CAP-* entries but no results | WARN: "Capability evals defined but not executed" |
188
+ | Regression eval failing | Any REG-* eval with status=fail | BLOCK: "Regression detected existing behavior broken" |
189
+ | Capability eval below threshold | CAP-* eval pass@k below defined threshold | WARN: "Capability eval below threshold (X% vs Y% required)" |
190
+ | No eval file for new feature | New feature added (detected by new test files + new source files) but no `.rune/evals/` entry | INFO: "Consider defining capability evals for new feature" |
191
+
192
+ **Skip if**: No `.rune/evals/` directory exists (project hasn't adopted eval-driven development).
193
+
194
+ ### Step 4.5 Domain Quality Hooks
195
+
196
+ Apply domain-specific quality checks based on detected file types in the diff. These extend the generic completeness checks in Step 4 with deeper domain validation.
197
+
198
+ <HARD-GATE>
199
+ Domain hooks are additive — they add checks, never remove generic ones from Steps 1-4.
200
+ If a domain hook flags BLOCK, the overall preflight verdict is BLOCK regardless of other steps.
201
+ </HARD-GATE>
202
+
203
+ #### Hook Selection (auto-detect from diff)
204
+
205
+ | Detected Pattern | Domain Hook | Key Checks |
206
+ |-----------------|-------------|------------|
207
+ | `migrations/*.sql`, `*.migration.*` | Database | Rollback script present, no bare DROP/DELETE, migration tested |
208
+ | `openapi.*`, `*.graphql`, `*.proto` | API Contract | Breaking changes flagged, version bumped, deprecated fields documented |
209
+ | `docs/policies/*`, `PRIVACY*`, `TERMS*` | Legal/Compliance | No placeholder text, review date current, practice matches policy |
210
+ | `**/billing*`, `**/payment*`, `**/invoice*` | Financial | Decimal precision correct, currency locale-aware, no hardcoded rates |
211
+ | `skills/*/SKILL.md`, `extensions/*/PACK.md` | Rune Skill | Frontmatter valid, all required sections present, word count within layer budget |
212
+ | `*.test.*`, `*.spec.*`, `__tests__/*` | Test Quality | No `.skip`/`.only` left in, assertions present (not empty tests), no hardcoded timeouts |
213
+
214
+ #### Domain Hook Execution
215
+
216
+ For each detected domain, run its checks on the relevant files in the diff:
217
+
218
+ 1. **Identify** which domain hooks apply based on changed file patterns
219
+ 2. **Load** domain-specific check rules (inline above, or from pack reference files if a pack is installed)
220
+ 3. **Scan** each relevant file for domain violations
221
+ 4. **Classify** findings: BLOCK (data loss risk, breaking contract) or WARN (best practice, incomplete)
222
+ 5. **Append** to preflight report under `### Domain Quality` section
223
+
224
+ #### Pack Integration
225
+
226
+ When a domain pack is installed (e.g., `@rune-pro/finance`, `@rune-pro/legal`), preflight checks the pack's **Hard-Stop Thresholds** table and applies matching rules to staged files. This means:
227
+ - Installing `@rune-pro/finance` automatically adds financial quality gates to preflight
228
+ - Installing `@rune-pro/legal` automatically adds compliance checks to preflight
229
+ - No manual configuration needed — pack presence = hooks active
230
+
231
+ #### Output Section
232
+
233
+ ```
234
+ ### Domain Quality
235
+ - **Domains detected**: [Database, Financial]
236
+ - `migrations/003-add-billing.sql` — BLOCK: DROP TABLE without rollback script
237
+ - `src/billing/invoice.ts:42` — WARN: price calculation uses `toFixed(2)` instead of `Intl.NumberFormat`
238
+ ```
239
+
240
+ ### Step 4.6 Organization Approval Requirements (Business)
241
+
242
+ If `.rune/org/org.md` exists, load organization approval workflows and enforce them as additional quality gates.
243
+
244
+ 1. `Read` `.rune/org/org.md` and extract `## Policies`, `## Approval Flows`, and `## Governance Level`
245
+ 2. Apply organization-level quality requirements:
246
+
247
+ | Org Policy | Preflight Check | Severity |
248
+ |------------|----------------|----------|
249
+ | `minimum_reviewers` | Verify PR has required reviewer count before merge | WARN: "Org requires {N} reviewers" |
250
+ | `self-merge_allowed` | If "Never" or "No", flag self-merge attempts | BLOCK if org prohibits |
251
+ | `required_checks` | Verify all org-required checks (tests, security scan, type check, lint) are passing | BLOCK if missing |
252
+ | `staging_required` | If "Yes", verify staging deployment exists before production | WARN if no staging step |
253
+ | `feature_flags` | If "Required for user-facing changes", flag new UI without feature flag | WARN |
254
+ | `cross-domain_changes` | If changes span multiple team domains, require reviewer from each | WARN |
255
+
256
+ 3. Load `## Approval Flows > ### Feature Launch` and display the required approval chain:
257
+ - Output: "Org approval chain: {flow}" so developer knows the full pipeline
258
+ - If governance level is "Maximum", flag any attempt to skip gates
259
+
260
+ 4. Append org findings under `### Organization Requirements` section:
261
+
262
+ ```
263
+ ### Organization Requirements
264
+ - **Org template**: [startup|mid-size|enterprise]
265
+ - **Governance level**: [Minimal|Moderate|Maximum]
266
+ - **Minimum reviewers**: 2 (1 must be director+)
267
+ - **Required checks**: tests (≥80% coverage), security scan, type check, lint
268
+ - **Approval chain**: contributor proposes → lead reviews → vp approves → deploy
269
+ - WARN: Self-merge not allowed per org policy
270
+ ```
271
+
272
+ If `.rune/org/org.md` does not exist, skip and log INFO: "no org config, organization requirements check skipped".
273
+
274
+ ### Step 4.8 Preflight Composite Score
275
+
276
+ After all domain hooks (Step 4.5) and completeness checks (Step 4) complete, compute a **Preflight Health Score** to make the verdict numeric and comparable across runs.
277
+
278
+ ### Formula
279
+
280
+ ```
281
+ Preflight Score = (Logic × 0.30) + (Error Handling × 0.20) + (Completeness × 0.20) + (Coherence × 0.15) + (Regression Risk × 0.15)
282
+ ```
283
+
284
+ **5 verification axes** (Completeness + Correctness via Logic + Coherence — 3D verification model):
285
+
286
+ Each dimension is scored per staged files:
287
+ - 0 BLOCK findings in dimension → 100
288
+ - 1 BLOCK → dimension capped at 30
289
+ - 1 WARN dimension capped at 75
290
+ - Each additional WARN subtract 10 (floor: 40)
291
+
292
+ ### Grade Thresholds
293
+
294
+ | Score | Grade | Verdict |
295
+ |-------|-------|---------|
296
+ | 90–100 | Excellent | PASS |
297
+ | 75–89 | Good | PASS with notes |
298
+ | 60–74 | Fair | WARN |
299
+ | 40–59 | Poor | WARN (escalate to developer) |
300
+ | 0–39 | Critical | BLOCK |
301
+
302
+ Score is appended to the Preflight Report footer. Useful for tracking quality trend across sprints when cook logs preflight scores to `.rune/metrics/`.
303
+
304
+
305
+ ### Step 5 — Security Sub-Check
306
+ Invoke `rune:sentinel` on the changed files. Attach sentinel's output verbatim under the "Security" section of the preflight report. If sentinel returns BLOCK, preflight verdict is also BLOCK.
307
+
308
+ ### Step 6 — Generate Verdict
309
+ Aggregate all findings:
310
+ - Any BLOCK from sentinel OR a logic issue that would cause data corruption or security bypass → overall **BLOCK**
311
+ - Any missing error handling, regression risk with no tests, or incomplete feature **WARN**
312
+ - Only style or best-practice suggestions → **PASS**
313
+
314
+ Report PASS, WARN, or BLOCK. For WARN, list each item the developer must acknowledge. For BLOCK, list each item that must be fixed before proceeding.
315
+
316
+ ## Output Format
317
+
318
+ ```
319
+ ## Preflight Report
320
+ - **Status**: PASS | WARN | BLOCK
321
+ - **Files Checked**: [count]
322
+ - **Changes**: +[added] -[removed] lines across [files] files
323
+
324
+ ### Logic Issues
325
+ - `path/to/file.ts:42` — null-deref: `user.name` accessed without null check
326
+ - `path/to/api.ts:85` — missing-await: async database call not awaited
327
+
328
+ ### Error Handling
329
+ - `path/to/handler.ts:20` bare-catch: error swallowed silently
330
+
331
+ ### Regression Risk
332
+ - `utils/format.ts` changed function used by 5 modules, 2 have tests, 3 untested (WARN)
333
+
334
+ ### Completeness
335
+ - `api/users.ts` — new POST endpoint missing input validation schema
336
+ - `components/Form.tsx` — no loading state during submission
337
+
338
+ ### Coherence
339
+ - `api/users.ts`uses `res.json()` but project convention is `sendResponse()` wrapper
340
+ - `utils/newHelper.ts`placed in utils/ but project uses helpers/ directory
341
+
342
+ ### Security (from sentinel)
343
+ - [sentinel findings if any]
344
+
345
+ ### Composite Score
346
+ - Logic: [score] | Error: [score] | Completeness: [score] | Coherence: [score] | Regression: [score]
347
+ - **Preflight Score**: [weighted value] Grade: [Excellent/Good/Fair/Poor/Critical]
348
+
349
+ ### Verdict
350
+ WARN — 3 issues found (0 blocking, 3 must-acknowledge). Resolve before commit or explicitly acknowledge each WARN.
351
+ ```
352
+
353
+ ## Constraints
354
+
355
+ 1. MUST check: logic errors, error handling, edge cases, type safety, naming conventions
356
+ 2. MUST reference specific file:line for every finding
357
+ 3. MUST NOT skip edge case analysis — "happy path works" is insufficient
358
+ 4. MUST verify error messages are user-friendly and don't leak internal details
359
+ 5. MUST check that async operations have proper error handling and cleanup
360
+
361
+ ## Returns
362
+
363
+ | Artifact | Format | Location |
364
+ |----------|--------|----------|
365
+ | Preflight report | Markdown | inline (chat output) |
366
+ | Issue list (BLOCK/WARN by category) | Markdown list | inline |
367
+ | Preflight health score | Markdown table | inline (footer of report) |
368
+ | Spec compliance verdict | Markdown table | inline |
369
+ | Domain quality findings | Markdown section | inline |
370
+
371
+ ## Sharp Edges
372
+
373
+ | Failure Mode | Severity | Mitigation |
374
+ |---|---|---|
375
+ | Stopping at first BLOCK finding without checking remaining files | HIGH | Aggregate all findings first — developer needs the complete list, not just the first blocker |
376
+ | "Happy path works" accepted as sufficient | HIGH | CONSTRAINT blocks this — edge case analysis is mandatory on every function |
377
+ | Calling verification directly instead of the test skill | MEDIUM | Preflight calls rune:test for test suite execution; rune:verification for lint/type/build checks |
378
+ | Skipping sentinel sub-check because "this file doesn't look security-relevant" | HIGH | MUST invoke sentinel — security relevance is sentinel's job to determine, not preflight's |
379
+ | Skipping Stage A (spec compliance) when plan is available | HIGH | If cook provides an approved plan, Stage A is mandatory — catches incomplete implementations |
380
+ | Agent modified files not in plan without flagging | MEDIUM | Stage A flags unplanned file changes as WARN — scope creep detection |
381
+ | Domain hooks not triggered when pack is installed | HIGH | Step 4.5 auto-detects file patterns — if pack is installed but hooks don't fire, check file pattern matching |
382
+ | Domain hooks overriding generic checks | HIGH | HARD-GATE: domain hooks are ADDITIVE — they never replace Steps 1-4 |
383
+ | Pack Hard-Stop Thresholds ignored in preflight | MEDIUM | Step 4.5 Pack Integration must read installed pack thresholds — test with each new pack |
384
+
385
+ ## Done When
386
+
387
+ - Every changed function traced for null-deref, missing-await, and off-by-one
388
+ - Error handling verified on all async functions and HTTP calls
389
+ - Regression impact assessed — dependent files identified via scout
390
+ - Completeness checklist passed (validation schema, loading/error states, test file)
391
+ - Sentinel invoked and its output attached in Security section
392
+ - Structured report emitted with PASS / WARN / BLOCK verdict and file:line for every finding
393
+
394
+ ## Cost Profile
395
+
396
+ ~2000-4000 tokens input, ~500-1500 tokens output. Sonnet for logic analysis quality.