pi-spine 2.29.0 → 2.30.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.
@@ -111,7 +111,12 @@ export function stripBatchFlagValueTokens(args) {
111
111
  export function formatLifecycleHuman(result, json = false) {
112
112
  if (json) return `${JSON.stringify(result, null, 2)}\n`;
113
113
 
114
- const lines = ["", result.ok ? "Batch lifecycle" : "Batch lifecycle failed", "", ` ${result.headline}`];
114
+ const lines = [
115
+ "",
116
+ result.ok ? "Batch lifecycle" : result.pending ? "Batch lifecycle pending" : "Batch lifecycle failed",
117
+ "",
118
+ ` ${result.headline}`,
119
+ ];
115
120
 
116
121
  if (result.error) {
117
122
  lines.push("", ` Error: ${result.error}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.29.0",
3
+ "version": "2.30.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -72,14 +72,17 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^1.0.1",
75
+ "@earendil-works/pi-coding-agent": "^1.4.0",
76
76
  "@types/node": "^22.20.4",
77
- "eslint": "^10.11.0",
78
- "globals": "^17.12.0",
77
+ "eslint": "^10.14.0",
78
+ "globals": "^17.14.0",
79
79
  "typebox": "1.3.34",
80
80
  "typescript": "6.0.3"
81
81
  },
82
82
  "license": "MIT",
83
+ "overrides": {
84
+ "undici": "^8.12.2"
85
+ },
83
86
  "dependencies": {
84
87
  "picomatch": "^4.0.7"
85
88
  }
@@ -413,7 +413,7 @@ Individual steps can override the task-level review:
413
413
  | **1** | PROMPT.md + STATUS.md | Always |
414
414
  | **2** | `{tasksRoot}/CONTEXT.md` | When listed in "Context to Read First" |
415
415
  | **3** | Specific reference docs | Only what the task needs |
416
- | **4** | Cursor rules (when `.cursor/rules/` exists) | **Workers:** auto-selected per task via profile `worker.*`, PROMPT File Scope globs, `config.standards` append (FR-WORK-05). **Reviewers:** separate `profile.reviewer.*` selection with review-type scope — plan uses File Scope, code uses git diff paths, final uses always-only rules; 16 KiB cap, no `referenceDocs` (FR-REV-08) |
416
+ | **4** | Cursor rules (when `.cursor/rules/` exists) | **Workers:** auto-selected per task via profile `worker.*`, PROMPT File Scope globs, `config.standards` append (FR-WORK-05). **Reviewers:** separate `profile.reviewer.*` selection with review-type scope — plan uses File Scope; code uses git diff paths with File Scope fallback on empty diff or git error; final uses baseline diff paths with File Scope fallback; 16 KiB cap, no `referenceDocs` (FR-REV-08) |
417
417
 
418
418
  Populate "Context to Read First" from `referenceDocs` in spine config. Never list docs in `neverLoad`.
419
419
 
@@ -486,7 +486,7 @@ When decomposing a PRD, assign non-overlapping file scopes to tasks that should
486
486
 
487
487
  **Worker rules:** File Scope also drives **glob-matched Cursor rules** injected into batch workers (FR-WORK-05). Tasks touching `**/*.{js,mjs}` activate JS standards; Swift/Python tasks need scope paths that match those rule globs. Keep scope precise — wide scope pulls more rules and increases prompt byte usage.
488
488
 
489
- **Reviewer rules (FR-REV-08):** Plan reviews use the same File Scope for glob matching; code reviews use changed paths from `git diff`. Final reviews load always-on rules only. Worker-only packs (`taskplane-worker-cursor.mdc`) are excluded from reviewer context by default.
489
+ **Reviewer rules (FR-REV-08):** Plan reviews use the same File Scope for glob matching; code reviews use changed paths from `git diff`, falling back to the File Scope when the diff is empty or git fails (#357). Final reviews use baseline diff paths when available, else the File Scope — code and final reviews never run with an empty scope when the packet has a File Scope. Worker-only packs (`taskplane-worker-cursor.mdc`) are excluded from reviewer context by default.
490
490
 
491
491
  **Documentation paths in File Scope ([#144](https://github.com/beettlle/pi-spine/issues/144)):** Every path under **Must Update** in `## Documentation Requirements` **must** also appear in `## File Scope`. If a doc is advisory only, move it to **Check If Affected** — do not require workers to edit paths outside File Scope. Mismatches (e.g. SP-435, SP-451) caused out-of-scope edits and merge dirty-file failures.
492
492
 
@@ -37,6 +37,7 @@ Avoid `` `bin/a.mjs,bin/b.mjs` `` — `tasks validate` warns (or errors in requi
37
37
  | Field | When to include | Value format |
38
38
  |-------|-----------------|--------------|
39
39
  | `testCommand` | **Required** for code tasks (Review Level ≥ 1, Size M/L, or implementation steps) | Shell command in backticks; max 500 chars; no newlines. **Code tasks:** prefix with project lint/analyze (`npm run lint &&` for pi-spine; `flutter analyze` scoped for Flutter). Contract verify executes this command at final review — lint runs in-lane when authored here. Post-integrate `release:check` remains the whole-repo backstop (full suite + coverage). Use `` `true` `` for docs-only S tasks with no code changes. When `` `true` ``, **always** pair with `fileScopeMustChange` (see below). |
40
+ | `reviewCommand` | Code tasks adding a stet review gate (SP-845); **omit** for docs-only and `Type: execute` packets | `` `bash scripts/spine-stet-contract-run.sh <lenient\|default\|strict> SP-###` ``. Runs **once** after `testCommand` passes (skipped when the test step fails), never retries, and is bounded by `contract.reviewTimeoutMs` (default 20 min) with policy `contract.reviewPolicy` (`blocking` default; `advisory` journals `contract.review_advisory` and records a STATUS Discoveries row instead of failing). **Never chain stet onto `testCommand`** — the review then runs under the 10-minute test timeout instead of its own. Strictness by size: S → `lenient` or `default`; M → `default`; security-sensitive → `strict`. The gate blocks only findings at severity `warning` or above with confidence ≥ 0.8 (override with `SPINE_STET_MIN_SEVERITY` / `SPINE_STET_MIN_CONFIDENCE`). |
40
41
  | `fileScopeMustChange` | When you need proof specific paths were touched; **required** when `testCommand` is `` `true` `` | Comma-separated paths/globs relative to repo root; **one backtick per path** (not `` `a.mjs,b.mjs` ``). Trailing `/` means directory prefix match (e.g. `src/domain/types/` matches any file under that directory). For docs-only tasks, list at least one documentation deliverable path — without it, workers can pass contract by creating only `.DONE` (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`). |
41
42
  | `fileScopeMustNotChange` | When **parallel lanes** must not collide on product paths (see semantics below) | Comma-separated paths/globs relative to repo root; **one backtick per path** |
42
43
  | `minLineCoverage` | Size L tasks that change application code (S/M rely on post-integrate `release:check` coverage) | Integer 0–100 (pi-spine policy: **77**) |
@@ -114,6 +115,7 @@ Symptom in journal: `testCommand` passes but `fileScopeMustNotChange` fails with
114
115
  | Field | Value |
115
116
  |-------|-------|
116
117
  | testCommand | `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 node --experimental-strip-types --test --test-reporter=dot tests/tasks/validate-prompt.test.mjs` |
118
+ | reviewCommand | `bash scripts/spine-stet-contract-run.sh <lenient\|default\|strict> SP-###` |
117
119
  | fileScopeMustChange | `src/tasks/packet/validate-prompt.mjs` |
118
120
  | minLineCoverage | 77 |
119
121
  ```
@@ -306,17 +306,24 @@ export async function waitForDetachedBatchResume({
306
306
  continue;
307
307
  }
308
308
 
309
+ const updatedAt = Number(raw.updatedAt ?? 0);
310
+
309
311
  if (raw.phase === "failed" || raw.phase === "aborted") {
310
- return {
311
- ok: false,
312
- error: "batch_engine_failed",
313
- batchId,
314
- phase: raw.phase,
315
- lastError: raw.lastError ?? null,
316
- };
312
+ // SP-851: only a failure written after the resume started
313
+ // (updatedAt > updatedAtBefore) is an engine failure. A pre-resume
314
+ // terminal state (e.g. resuming an already-failed batch) keeps polling
315
+ // until the new engine writes `running` or the wait times out.
316
+ if (updatedAt > updatedAtBefore) {
317
+ return {
318
+ ok: false,
319
+ error: "batch_engine_failed",
320
+ batchId,
321
+ phase: raw.phase,
322
+ lastError: raw.lastError ?? null,
323
+ };
324
+ }
317
325
  }
318
326
 
319
- const updatedAt = Number(raw.updatedAt ?? 0);
320
327
  if (raw.phase === "running" && updatedAt > updatedAtBefore) {
321
328
  engineStarted = true;
322
329
  if (!waitTerminal) {
@@ -61,6 +61,13 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
61
61
  case "completed_manual":
62
62
  return "spine batch dismiss";
63
63
  case "state_drift":
64
+ // SP-850 / #356, #371: the engine is verifiably alive and the phase is
65
+ // running — the drift window is the in-flight post-`.DONE`
66
+ // review/contract pipeline. Wait for it instead of force-resuming over
67
+ // live work.
68
+ if (ctx.phase === "running" && ctx.engineStillRunning === true) {
69
+ return "spine wait --until completed,failed,needs_integrate --timeout 2h";
70
+ }
64
71
  // Agent-safe detached recovery (#196 / SP-613) — never suggest --attached.
65
72
  if (
66
73
  ctx.phase === "running" ||
@@ -23,6 +23,7 @@ export { assertOrchIntegratable } from "./integrate-assert.mjs";
23
23
  import { tryRestoreBranch } from "./integrate-git.mjs";
24
24
  export { tryRestoreBranch } from "./integrate-git.mjs";
25
25
  import { checkIntegrateGate } from "./gate.mjs";
26
+ import { isLiveEngineInActivePhase } from "./lifecycle-archive.mjs";
26
27
  import { appendJournalEvent } from "./journal.mjs";
27
28
  import { countCommitsAhead } from "./lane-commit.mjs";
28
29
  import { inspectGitState, loadBatchStateFile, parseBatchState } from "./reconcile.mjs";
@@ -78,6 +79,20 @@ function runIntegrateMerge({ projectRoot, baseBranch, orchBranch, batchId }) {
78
79
  return plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeMessage });
79
80
  }
80
81
 
82
+ /**
83
+ * Post-merge suggestion (#371): a live engine in an active phase is still
84
+ * finishing its land loop — wait instead of pointing at a refusing complete.
85
+ * @param {unknown} raw raw batch state read at entry
86
+ * @returns {{ suggestedCommand: string, alternatives: string[] }|null}
87
+ */
88
+ function postMergeCompletionSuggestion(raw) {
89
+ if (!isLiveEngineInActivePhase(raw)) return null;
90
+ return {
91
+ suggestedCommand: "spine wait --until completed --timeout 10m",
92
+ alternatives: ["spine batch complete"],
93
+ };
94
+ }
95
+
81
96
  /**
82
97
  * @param {object} ctx
83
98
  * @param {string} ctx.projectRoot
@@ -156,6 +171,7 @@ export function integrateOrchToBase(ctx) {
156
171
  });
157
172
 
158
173
  if (gitState.orchMergedToBase) {
174
+ const waiting = postMergeCompletionSuggestion(loaded.raw);
159
175
  return {
160
176
  ok: true,
161
177
  exitCode: 0,
@@ -163,7 +179,8 @@ export function integrateOrchToBase(ctx) {
163
179
  baseBranch,
164
180
  orchBranch,
165
181
  headline: `Orch branch already merged into ${baseBranch}`,
166
- suggestedCommand: "spine batch complete",
182
+ suggestedCommand: waiting?.suggestedCommand ?? "spine batch complete",
183
+ ...(waiting ? { alternatives: waiting.alternatives } : {}),
167
184
  alreadyMerged: true,
168
185
  };
169
186
  }
@@ -395,6 +412,7 @@ export function integrateOrchToBase(ctx) {
395
412
  baseCheckedOutAtStart,
396
413
  });
397
414
 
415
+ const waiting = postMergeCompletionSuggestion(loaded.raw);
398
416
  return {
399
417
  ok: true,
400
418
  exitCode: 0,
@@ -405,8 +423,10 @@ export function integrateOrchToBase(ctx) {
405
423
  commitsAhead,
406
424
  gateRequired: gateCheck.required ?? false,
407
425
  headline: `Integrated ${orchBranch} into ${baseBranch}`,
408
- suggestedCommand: "spine batch complete",
409
- alternatives: ["spine status --diagnose"],
426
+ suggestedCommand: waiting?.suggestedCommand ?? "spine batch complete",
427
+ alternatives: waiting
428
+ ? ["spine batch complete", "spine status --diagnose"]
429
+ : ["spine status --diagnose"],
410
430
  ...(dirtyOverlapWarning ? { warnings: [dirtyOverlapWarning] } : {}),
411
431
  };
412
432
  } catch (err) {
@@ -38,6 +38,44 @@ function hasJournalTerminalLifecycle(lastEvent) {
38
38
  return JOURNAL_TERMINAL_LIFECYCLE.has(String(lastEvent.type ?? ""));
39
39
  }
40
40
 
41
+ /** @type {ReadonlySet<string>} Review/contract pipeline events that show the engine is mid-flight on post-`.DONE` work (SP-850 / #356, #371). */
42
+ const POST_DONE_PIPELINE_EVENT_TYPES = new Set([
43
+ "review.started",
44
+ "review.completed",
45
+ "review.failed",
46
+ "contract.verified",
47
+ "contract.failed",
48
+ "task.verdict_recorded",
49
+ ]);
50
+
51
+ /**
52
+ * True when the journal shows post-`.DONE` engine work still open for a task
53
+ * (SP-850 / #356, #371): an unresolved `review.started` (code/plan/final), or a
54
+ * resolved review with no terminal lifecycle yet — the engine is between
55
+ * reviews or running contract verification (which has no "started" marker; it
56
+ * only journals `contract.verified`/`contract.failed` when it finishes). A
57
+ * worker legitimately writes `.DONE` before the engine reviews it, so this
58
+ * window is not state drift. Terminal lifecycle resolution is checked by the
59
+ * caller (`hasJournalTerminalLifecycle`); terminal-artifact completeness is
60
+ * checked separately via `journalShowsDoneInLaneTerminalArtifacts` so the
61
+ * #170 heal keeps its drift trigger.
62
+ *
63
+ * @param {object[]} events
64
+ * @param {string} taskId
65
+ */
66
+ export function journalHasOpenPostDonePipeline(events, taskId) {
67
+ if (!Array.isArray(events)) return false;
68
+ for (const event of events) {
69
+ const type = String(event?.type ?? "");
70
+ if (!POST_DONE_PIPELINE_EVENT_TYPES.has(type)) continue;
71
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
72
+ const eventTaskId = event.taskId ?? payload.taskId;
73
+ if (eventTaskId !== taskId) continue;
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+
41
79
  /**
42
80
  * @param {object|null|undefined} classified
43
81
  */
@@ -244,7 +282,14 @@ export function detectBatchStateDrift(cachedState, rebuiltState, events = [], cl
244
282
  if (
245
283
  NON_TERMINAL_CACHE_STATUSES.has(cachedStatus) &&
246
284
  classifiedShowsDoneInLaneDrift(classified) &&
247
- !hasJournalTerminalLifecycle(lastEvent)
285
+ !hasJournalTerminalLifecycle(lastEvent) &&
286
+ // SP-850 / #356, #371: suppress the doneInLane drift entry while the
287
+ // post-`.DONE` review/contract pipeline is open (engine reviewing or
288
+ // verifying) and the terminal-artifact signature is not yet complete.
289
+ // When the signature IS complete (#170), keep the entry so
290
+ // reconcileBatchStateDrift can heal the stale cache to succeeded.
291
+ (!journalHasOpenPostDonePipeline(events, taskId) ||
292
+ journalShowsDoneInLaneTerminalArtifacts(events, taskId))
248
293
  ) {
249
294
  entries.push({
250
295
  taskId,
@@ -12,6 +12,8 @@ import {
12
12
  readBatchStateId,
13
13
  } from "./batch-state-io.mjs";
14
14
  import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs";
15
+ import { isEngineProcessAlive } from "../process/liveness.mjs";
16
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
15
17
 
16
18
  /**
17
19
  * Phases a resume/pause/engine writer can leave behind between a terminal
@@ -23,6 +25,27 @@ import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs
23
25
  */
24
26
  const ACTIVE_RESUME_PHASES = new Set(["planning", "running", "paused", "merging"]);
25
27
 
28
+ /**
29
+ * True when the batch is in an active resume phase and the recorded engine
30
+ * PID is alive — i.e. a detached engine is still finalizing its land loop
31
+ * (#371). Liveness is injectable so callers and tests can stub the probe
32
+ * (same shape as `isLiveEngineMidTask`).
33
+ *
34
+ * @param {unknown} raw raw batch state (e.g. the in-lock re-read)
35
+ * @param {object} [deps]
36
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
37
+ * @returns {boolean}
38
+ */
39
+ export function isLiveEngineInActivePhase(raw, deps = {}) {
40
+ if (!raw || typeof raw !== "object") return false;
41
+ const phase = String(/** @type {{ phase?: string }} */ (raw).phase ?? "");
42
+ if (!ACTIVE_RESUME_PHASES.has(phase)) return false;
43
+ const isEngineAlive =
44
+ deps.isEngineAlive ??
45
+ ((state) => isEngineProcessAlive(readBatchEnginePid(state), readBatchEngineStartedAt(state)));
46
+ return Boolean(isEngineAlive(raw));
47
+ }
48
+
26
49
  /**
27
50
  * Re-read the active batch state inside the terminal lock section
28
51
  * (SP-792 / #301) so archive, history, and clear act on the freshest on-disk
@@ -43,6 +66,8 @@ const ACTIVE_RESUME_PHASES = new Set(["planning", "running", "paused", "merging"
43
66
  * @param {boolean} [params.requireTerminalPhase] re-validate the terminal-phase precondition on the in-lock state
44
67
  * @param {boolean} [params.force] `dismiss --force` skips the phase re-validation
45
68
  * @param {string|null} [params.diagnosis] pre-lock diagnosis echoed on refusal
69
+ * @param {object} [params.deps]
70
+ * @param {(raw: object) => boolean} [params.deps.isEngineAlive] injectable engine liveness probe (#371)
46
71
  * @returns {{ state: { path: string, raw: object }|null, refusal: object|null }}
47
72
  */
48
73
  export function reloadStateForTerminalWrite({
@@ -53,6 +78,7 @@ export function reloadStateForTerminalWrite({
53
78
  requireTerminalPhase = false,
54
79
  force = false,
55
80
  diagnosis = null,
81
+ deps = {},
56
82
  }) {
57
83
  const refuse = () => ({
58
84
  ok: false,
@@ -77,6 +103,24 @@ export function reloadStateForTerminalWrite({
77
103
  if (requireTerminalPhase && !force) {
78
104
  const phase = String(/** @type {{ phase?: string }} */ (reloaded.raw).phase ?? "");
79
105
  if (ACTIVE_RESUME_PHASES.has(phase)) {
106
+ // #371: a live engine turned the batch active again between the pre-lock
107
+ // read and this reload — it is finishing its land loop, not crashing.
108
+ // Report a pending wait instead of the generic mid-write failure.
109
+ if (isLiveEngineInActivePhase(reloaded.raw, deps)) {
110
+ return {
111
+ state: null,
112
+ refusal: {
113
+ ok: false,
114
+ exitCode: 1,
115
+ pending: true,
116
+ error: "engine_finishing_land_loop",
117
+ headline: "Engine is finishing the land loop — wait for it to complete",
118
+ suggestedCommand: "spine wait --until completed --timeout 10m",
119
+ diagnosis: diagnosis ?? null,
120
+ batchId,
121
+ },
122
+ };
123
+ }
80
124
  return { state: null, refusal: refuse() };
81
125
  }
82
126
  }
@@ -102,6 +102,11 @@ function defaultRunGit(command, args, cwd) {
102
102
  /**
103
103
  * Resolve scope paths for reviewer rule glob matching by review phase.
104
104
  *
105
+ * `code` uses `git diff` paths, falling back to the PROMPT File Scope when the
106
+ * diff resolves to no paths (no baseline, git error, or empty diff) (#357).
107
+ * `final` uses baseline diff paths when a baseline is given and non-empty,
108
+ * else the PROMPT File Scope.
109
+ *
105
110
  * @param {object} params
106
111
  * @param {string} params.worktreePath Git worktree root for code reviews
107
112
  * @param {string} [params.baseline] Baseline commit for code review diff (optional)
@@ -123,12 +128,20 @@ export function resolveReviewScopePaths({
123
128
  case "plan":
124
129
  scopePaths = resolvePlanReviewScopePaths(taskFolder);
125
130
  break;
126
- case "code":
127
- scopePaths = resolveCodeReviewScopePaths(worktreePath, baseline, runGit);
131
+ case "code": {
132
+ const diffPaths = resolveCodeReviewScopePaths(worktreePath, baseline, runGit);
133
+ scopePaths =
134
+ diffPaths.length > 0 ? diffPaths : resolvePlanReviewScopePaths(taskFolder);
128
135
  break;
129
- case "final":
130
- scopePaths = [];
136
+ }
137
+ case "final": {
138
+ const diffPaths = baseline
139
+ ? resolveCodeReviewScopePaths(worktreePath, baseline, runGit)
140
+ : [];
141
+ scopePaths =
142
+ diffPaths.length > 0 ? diffPaths : resolvePlanReviewScopePaths(taskFolder);
131
143
  break;
144
+ }
132
145
  default:
133
146
  scopePaths = [];
134
147
  }
@@ -66,22 +66,37 @@ export function resolveContextDocPath(projectRoot, relPath) {
66
66
  }
67
67
 
68
68
  /**
69
+ * A path that was not loaded, with the reason it was skipped.
70
+ *
71
+ * @typedef {object} ContextDocSkip
72
+ * @property {string} path
73
+ * @property {"never_load"|"missing"|"byte_cap"} reason
74
+ * @property {number} [sizeBytes] UTF-8 size of the file, set for `byte_cap` skips.
75
+ */
76
+
77
+ /**
78
+ * SP-852: a path whose content would exceed the remaining byte budget is
79
+ * recorded in `skipped` and loading continues, so one oversize rule no longer
80
+ * drops later rules that fit.
81
+ *
69
82
  * @param {object} params
70
83
  * @param {string} params.projectRoot
71
84
  * @param {string[]} params.paths
72
85
  * @param {Set<string>} [params.neverLoad]
73
86
  * @param {number} [params.byteCap]
87
+ * @returns {{ ok: boolean, entries?: { relPath: string, content: string }[], truncated?: boolean, skipped?: ContextDocSkip[], bytesUsed?: number, byteCap?: number, error?: string, relPath?: string }}
74
88
  */
75
89
  export function loadContextDocEntries({ projectRoot, paths, neverLoad = new Set(), byteCap = DEFAULT_WORKER_CONTEXT_BYTE_CAP }) {
76
90
  /** @type {{ relPath: string, content: string }[]} */
77
91
  const loaded = [];
78
92
  let totalBytes = 0;
79
- /** @type {string[]} */
93
+ /** @type {ContextDocSkip[]} */
80
94
  const skipped = [];
95
+ let capSkipped = false;
81
96
 
82
97
  for (const relPath of paths) {
83
98
  if (neverLoad.has(relPath)) {
84
- skipped.push(relPath);
99
+ skipped.push({ path: relPath, reason: "never_load" });
85
100
  continue;
86
101
  }
87
102
 
@@ -91,21 +106,16 @@ export function loadContextDocEntries({ projectRoot, paths, neverLoad = new Set(
91
106
  }
92
107
 
93
108
  if (!fs.existsSync(resolved.absPath) || !fs.statSync(resolved.absPath).isFile()) {
94
- skipped.push(relPath);
109
+ skipped.push({ path: relPath, reason: "missing" });
95
110
  continue;
96
111
  }
97
112
 
98
113
  const content = fs.readFileSync(resolved.absPath, "utf-8");
99
114
  const size = Buffer.byteLength(content, "utf-8");
100
115
  if (totalBytes + size > byteCap) {
101
- return {
102
- ok: true,
103
- entries: loaded,
104
- truncated: true,
105
- skipped: [...skipped, relPath, "...remaining paths omitted (byte cap)"],
106
- bytesUsed: totalBytes,
107
- byteCap,
108
- };
116
+ skipped.push({ path: relPath, reason: "byte_cap", sizeBytes: size });
117
+ capSkipped = true;
118
+ continue;
109
119
  }
110
120
 
111
121
  loaded.push({ relPath: resolved.relPath, content });
@@ -115,7 +125,7 @@ export function loadContextDocEntries({ projectRoot, paths, neverLoad = new Set(
115
125
  return {
116
126
  ok: true,
117
127
  entries: loaded,
118
- truncated: false,
128
+ truncated: capSkipped,
119
129
  skipped,
120
130
  bytesUsed: totalBytes,
121
131
  byteCap,
@@ -223,7 +233,7 @@ export function emitWorkerRulesSelected(journal, payload) {
223
233
  * @param {string[]} [params.taskFileScope]
224
234
  * @param {number} [params.byteCap]
225
235
  * @param {WorkerRulesJournalContext} [params.journal]
226
- * @returns {{ text: string, entries: object[], truncated: boolean, skipped: string[], bytesUsed: number, byteCap: number, selection: object, error?: string, blockedPath?: string }}
236
+ * @returns {{ text: string, entries: object[], truncated: boolean, skipped: ContextDocSkip[], bytesUsed: number, byteCap: number, selection: object, error?: string, blockedPath?: string }}
227
237
  */
228
238
  export function buildWorkerContextAsync({
229
239
  config = {},
@@ -303,7 +313,7 @@ export function buildWorkerContextAsync({
303
313
  ...referenceDocs.filter((entry) => !neverLoad.has(entry) && !selectedSet.has(entry)),
304
314
  ];
305
315
 
306
- emitWorkerRulesSelected(journal, {
316
+ const journalPayload = {
307
317
  mode: "auto",
308
318
  manifestSource,
309
319
  profileSource: profileResult.source,
@@ -318,9 +328,12 @@ export function buildWorkerContextAsync({
318
328
  referenceDocCount: referenceDocs.filter(
319
329
  (entry) => !neverLoad.has(entry) && !selectedSet.has(entry),
320
330
  ).length,
321
- });
331
+ };
332
+ const emitPostLoad = (loadStats) =>
333
+ emitWorkerRulesSelected(journal, { ...journalPayload, ...loadStats });
322
334
 
323
335
  if (orderedPaths.length === 0) {
336
+ emitPostLoad({ bytesUsed: 0, byteCap, truncated: false, skipped: [] });
324
337
  return {
325
338
  text: "",
326
339
  entries: [],
@@ -344,6 +357,7 @@ export function buildWorkerContextAsync({
344
357
  byteCap,
345
358
  });
346
359
  if (!loaded.ok) {
360
+ emitPostLoad({ bytesUsed: 0, byteCap, truncated: false, skipped: [] });
347
361
  return {
348
362
  text: "",
349
363
  entries: [],
@@ -362,6 +376,13 @@ export function buildWorkerContextAsync({
362
376
  };
363
377
  }
364
378
 
379
+ emitPostLoad({
380
+ bytesUsed: loaded.bytesUsed,
381
+ byteCap: loaded.byteCap,
382
+ truncated: loaded.truncated,
383
+ skipped: loaded.skipped,
384
+ });
385
+
365
386
  const parts = loaded.entries.map(
366
387
  (entry) => `--- ${entry.relPath} ---\n${entry.content.trim()}\n`,
367
388
  );
@@ -24,7 +24,7 @@ import {
24
24
  } from "./stall-config.mjs";
25
25
  import { buildRulesManifestDoctorCheck } from "./rules-manifest.mjs";
26
26
  import { buildAgentTemplateDriftDoctorCheck } from "./agent-template-drift.mjs";
27
- import { buildStetCapacityDoctorCheck } from "./stet-capacity.mjs";
27
+ import { buildStetCapacityDoctorCheck, buildStetVersionDoctorCheck } from "./stet-capacity.mjs";
28
28
  import { buildWorktreeHealthDoctorCheck } from "./worktree-health.mjs";
29
29
  import { buildGitignoredPubspecAssetsDoctorCheck } from "../config/worktree-setup-hook.mjs";
30
30
  import { buildStaleWorktreesDoctorCheck } from "./stale-worktrees.mjs";
@@ -539,6 +539,7 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
539
539
  });
540
540
  }
541
541
  checks.push(buildAgentTemplateDriftDoctorCheck({ projectRoot }));
542
+ checks.push(buildStetVersionDoctorCheck());
542
543
  checks.push(buildStetCapacityDoctorCheck());
543
544
 
544
545
  const tasksRootPath = resolveTasksRoot(projectRoot, configResult);
@@ -114,6 +114,52 @@ export const DEFAULT_STET_CAPACITY_PROBES = {
114
114
  totalMemBytes: () => os.totalmem(),
115
115
  };
116
116
 
117
+ /** Contract gating needs `stet list --min-severity/--min-confidence`, added in stet v1.4.0. */
118
+ export const STET_MIN_VERSION = { major: 1, minor: 4, patch: 0 };
119
+ const STET_INSTALL_COMMAND = "curl -fsSL https://raw.githubusercontent.com/beettlle/stet/main/install.sh | bash";
120
+
121
+ /**
122
+ * @param {string} text raw `stet --version` stdout, e.g. "stet version v1.4.0"
123
+ * @returns {StetSemVer|null}
124
+ */
125
+ export function parseStetVersion(text) {
126
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(text);
127
+ return match ? { major: +match[1], minor: +match[2], patch: +match[3] } : null;
128
+ }
129
+
130
+ /** @typedef {{ major: number, minor: number, patch: number }} StetSemVer */
131
+
132
+ /** Numeric per-component compare (1.10.0 ≥ 1.4.0; string compare would not). @param {StetSemVer} v @param {StetSemVer} min */
133
+ function atLeast(v, min) {
134
+ return v.major !== min.major ? v.major > min.major
135
+ : v.minor !== min.minor ? v.minor > min.minor
136
+ : v.patch >= min.patch;
137
+ }
138
+
139
+ /**
140
+ * Advisory doctor check: warns (never fails) when stet predates the version that
141
+ * contract gating needs (`stet list --min-severity/--min-confidence`, stet v1.4.0+).
142
+ * @param {{ stetVersion?: () => string|null }} [opts]
143
+ */
144
+ export function buildStetVersionDoctorCheck(opts = {}) {
145
+ const probes = { stetVersion: () => tryExec("stet", ["--version"])?.trim() ?? null, ...opts };
146
+ const label = "stet version";
147
+ const raw = probes.stetVersion();
148
+ if (raw === null) return { label, ok: true, detail: "stet not on PATH (skipped)" };
149
+ const version = parseStetVersion(raw);
150
+ if (version !== null && atLeast(version, STET_MIN_VERSION)) {
151
+ return { label, ok: true, detail: `stet v${version.major}.${version.minor}.${version.patch}` };
152
+ }
153
+ const shown = raw.split("\n")[0].slice(0, 60) || "(no output)";
154
+ return {
155
+ label,
156
+ ok: true,
157
+ warning: true,
158
+ detail: `${shown}: older than or incompatible with stet v${STET_MIN_VERSION.major}.${STET_MIN_VERSION.minor}.${STET_MIN_VERSION.patch} — the contract gate falls back to gating on every active finding`,
159
+ suggestedCommand: STET_INSTALL_COMMAND,
160
+ };
161
+ }
162
+
117
163
  /** @param {number} bytes */
118
164
  const gib = (bytes) => `${(bytes / (1024 * BYTES_PER_MIB)).toFixed(1)} GiB`;
119
165