pi-spine 2.29.0 → 2.31.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.31.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.5.2",
76
76
  "@types/node": "^22.20.4",
77
- "eslint": "^10.11.0",
78
- "globals": "^17.12.0",
77
+ "eslint": "^10.15.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
  ```
@@ -143,10 +143,37 @@ export function releaseResumeHandoffLock(projectRoot, batchId) {
143
143
  */
144
144
  const LIVE_RESUME_OWNER_PHASES = new Set(["running", "gating"]);
145
145
 
146
+ /**
147
+ * True when the engine acknowledged the current pause episode: an
148
+ * `engine.pause_observed` journal event exists after the latest `batch.resumed`
149
+ * (SP-861 / #376). `pauseBatch` journals `batch.paused` only after the engine
150
+ * persisted phase: paused, and that engine-side persist also journals
151
+ * `engine.pause_observed` right before the engine loop stops — so after a
152
+ * confirmed pause the recorded enginePid belongs to a winding-down process that
153
+ * no longer drives the batch, i.e. a stale attached-child bookkeeping bit, not
154
+ * a live owner.
155
+ *
156
+ * @param {string} projectRoot
157
+ * @param {string} batchId
158
+ */
159
+ function hasEngineAcknowledgedPause(projectRoot, batchId) {
160
+ const events = readJournalEvents(projectRoot, batchId);
161
+ let lastResumedIdx = -1;
162
+ let lastObservedIdx = -1;
163
+ for (let i = 0; i < events.length; i++) {
164
+ const type = String(events[i].type ?? "");
165
+ if (type === "batch.resumed") lastResumedIdx = i;
166
+ if (type === "engine.pause_observed") lastObservedIdx = i;
167
+ }
168
+ return lastObservedIdx >= 0 && lastObservedIdx > lastResumedIdx;
169
+ }
170
+
146
171
  /**
147
172
  * Reject a second attached engine when resilience.enginePid is alive (SP-434, GitHub #89).
148
173
  * Serialized forced resume handoff when another resume --force is in flight (SP-533, #167).
149
174
  * Fail-fast while a live engine already owns a running batch (SP-660, #207).
175
+ * A paused batch whose engine acknowledged the pause hands recovery to the
176
+ * operator instead of refusing (SP-861, #376).
150
177
  *
151
178
  * @param {object} params
152
179
  * @param {string} params.projectRoot
@@ -239,6 +266,22 @@ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, o
239
266
  };
240
267
  }
241
268
 
269
+ // A paused batch whose engine acknowledged the pause has no live owner
270
+ // (SP-861 / #376): the recorded pid is a stale attached-child bookkeeping bit
271
+ // left behind by the pause handoff. Detached recovery must not be refused
272
+ // with a false "Attached batch engine already running" — clear the stale
273
+ // ownership instead so the resuming engine takes over cleanly. A live pid on
274
+ // a non-paused batch (engine still driving) keeps the refuse below.
275
+ if (fromPhase === "paused" && hasEngineAcknowledgedPause(projectRoot, batchId)) {
276
+ clearBatchEnginePid(state);
277
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
278
+ appendJournalEvent(projectRoot, batchId, "engine.stale_ownership_cleared", {
279
+ stalePid: enginePid,
280
+ fromPhase,
281
+ });
282
+ return releaseResumeLock ? { ok: true, releaseResumeLock } : { ok: true };
283
+ }
284
+
242
285
  const operationLabel = operation === "start" ? "start" : "resume";
243
286
  const output =
244
287
  `Attached batch engine already running (PID ${enginePid}, batch ${batchId}).\n` +
@@ -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" ||
@@ -13,14 +13,24 @@ import { countCommitsAhead } from "./lane-commit.mjs";
13
13
  * @param {string|null} ctx.orchBranch
14
14
  * @param {boolean} ctx.mergeResultsEmpty
15
15
  * @param {boolean} ctx.orchMergedToBase
16
+ * @param {boolean} [ctx.salvageLanded] salvage integrate landed every task's work on base (SP-862 / #374)
16
17
  */
17
18
  export function assertOrchIntegratable(projectRoot, ctx) {
18
- const { baseBranch, orchBranch, mergeResultsEmpty, orchMergedToBase } = ctx;
19
+ const { baseBranch, orchBranch, mergeResultsEmpty, orchMergedToBase, salvageLanded } = ctx;
19
20
 
20
21
  if (orchMergedToBase) {
21
22
  return { ok: true, reason: "orch_merged_to_base" };
22
23
  }
23
24
 
25
+ // SP-862 / #374: salvage integrate merged the lane task branches onto base —
26
+ // the work complete's merge gate cares about is on base even though the
27
+ // batch orch branch never merged. Only set when the salvage heal left zero
28
+ // unresolved tasks (fail-closed). Lifecycle complete is the only caller that
29
+ // passes this.
30
+ if (salvageLanded) {
31
+ return { ok: true, reason: "salvage_landed_to_base" };
32
+ }
33
+
24
34
  if (mergeResultsEmpty) {
25
35
  return { ok: true, reason: "no_merge_claimed" };
26
36
  }
@@ -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
  }
@@ -126,6 +170,27 @@ export function clearCompletedBatchState(projectRoot, batchStatePath, batchId) {
126
170
  clearActiveBatchStateIfMatches(batchStatePath, batchId, projectRoot);
127
171
  }
128
172
 
173
+ /**
174
+ * True when reconcile signals show live lane activity (running/pending tasks,
175
+ * or a lane whose status is running/active) — dismiss treats this as a live
176
+ * batch and requires --force.
177
+ *
178
+ * @param {object} signals
179
+ * @returns {boolean}
180
+ */
181
+ export function hasLiveLanes(signals) {
182
+ if (!signals) return false;
183
+ if (signals.hasRunningTasks || signals.hasPendingTasks) return true;
184
+ const lanes = signals.lanes;
185
+ return (
186
+ Array.isArray(lanes) &&
187
+ lanes.some((lane) => {
188
+ const status = String(lane?.status ?? "").toLowerCase();
189
+ return status === "running" || status === "active";
190
+ })
191
+ );
192
+ }
193
+
129
194
  /**
130
195
  * @param {object|null|undefined} config
131
196
  */
@@ -12,6 +12,7 @@ import {
12
12
  import {
13
13
  archiveBatchState,
14
14
  clearCompletedBatchState,
15
+ hasLiveLanes,
15
16
  reloadStateForTerminalWrite,
16
17
  } from "./lifecycle-archive.mjs";
17
18
  export { archiveBatchStatePath } from "./lifecycle-archive.mjs";
@@ -86,22 +87,6 @@ export function recordMergeBlocked({
86
87
  };
87
88
  }
88
89
 
89
- /**
90
- * @param {object} signals
91
- */
92
- function hasLiveLanes(signals) {
93
- if (!signals) return false;
94
- if (signals.hasRunningTasks || signals.hasPendingTasks) return true;
95
- const lanes = signals.lanes;
96
- return (
97
- Array.isArray(lanes) &&
98
- lanes.some((lane) => {
99
- const status = String(lane?.status ?? "").toLowerCase();
100
- return status === "running" || status === "active";
101
- })
102
- );
103
- }
104
-
105
90
  /**
106
91
  * @param {object} ctx
107
92
  * @param {string} ctx.projectRoot
@@ -177,7 +162,13 @@ export function dismissBatch(ctx) {
177
162
  };
178
163
  }
179
164
 
180
- if (diagnosis && !DISMISS_ALLOWED.has(diagnosis) && !force) {
165
+ // SP-862 / #374: needs_merge/needs_integrate after a full salvage heal is the
166
+ // empty batch shell (orch land loop never ran) — dismiss without --force.
167
+ const salvageCompleted =
168
+ Boolean(reconciliation.signals?.raw?.salvageLandedAllTasks) &&
169
+ Boolean(reconciliation.signals?.allTasksTerminalSuccess);
170
+
171
+ if (diagnosis && !DISMISS_ALLOWED.has(diagnosis) && !force && !salvageCompleted) {
181
172
  const output = buildDiagnosisOutput(diagnosis, {
182
173
  batchId,
183
174
  phase: reconciliation.phase,
@@ -323,7 +314,13 @@ export function completeBatch(ctx) {
323
314
  const diagnosis = reconciliation.diagnosis;
324
315
  const batchId = reconciliation.batchId ?? String(loaded.raw.batchId ?? loaded.raw.id ?? "");
325
316
  const signals = reconciliation.signals ?? {};
326
- const mergeSatisfied = !signals.mergeResultsEmpty || Boolean(signals.git?.orchMergedToBase);
317
+ // SP-862 / #374: salvage merges lane branches onto base (not orch) — after a
318
+ // full heal the salvage land is the merge evidence (fail-closed: evidence is
319
+ // only written when the heal left zero unresolved tasks, and allSuccess below
320
+ // still applies).
321
+ const salvageSatisfied = Boolean(signals.raw?.salvageLandedAllTasks);
322
+ const mergeSatisfied =
323
+ !signals.mergeResultsEmpty || Boolean(signals.git?.orchMergedToBase) || salvageSatisfied;
327
324
  const manualMergeOk =
328
325
  detectManualMerge &&
329
326
  (diagnosis === "completed_manual" || Boolean(signals.git?.orchMergedToBase));
@@ -372,6 +369,7 @@ export function completeBatch(ctx) {
372
369
  orchBranch: batch?.orchBranch ?? loaded.raw.orchBranch ?? null,
373
370
  mergeResultsEmpty: signals.mergeResultsEmpty,
374
371
  orchMergedToBase: Boolean(signals.git?.orchMergedToBase),
372
+ salvageLanded: salvageSatisfied,
375
373
  });
376
374
 
377
375
  if (!integratable.ok && !manualMergeOk) {
@@ -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
  }
@@ -16,6 +16,17 @@
16
16
  * Tasks outside the salvage set are never touched: non-salvageable failures
17
17
  * (contract/review failures) and evidence-less worker deaths remain failed and
18
18
  * keep blocking complete (SP-763 completion criteria).
19
+ *
20
+ * SP-862 / #374: when the heal leaves zero non-terminal tasks, the batch has no
21
+ * unresolved failure left, so the state also records `salvageLandedAllTasks`
22
+ * evidence (+ a `batch.salvage_landed_all_tasks` journal event). `complete` and
23
+ * `dismiss` use it to accept the salvage land as the batch's merge evidence —
24
+ * salvage merges lane task branches onto base, not the batch orch branch, so
25
+ * the orch-based merge gates (`mergeSatisfied`, needs_merge dismiss gate) would
26
+ * otherwise keep refusing and force `dismiss --force`. Fail-closed: the
27
+ * evidence alone never opens a gate — complete/dismiss still require every
28
+ * task terminal-success at gate time, so a later retry that re-opens tasks
29
+ * re-arms the refusal.
19
30
  */
20
31
 
21
32
  import { loadBatchStateFile } from "./batch-state-io.mjs";
@@ -107,6 +118,21 @@ export function healSalvagedTasksAfterIntegrate(projectRoot, batchId, options =
107
118
  return { ok: true, healedTaskIds, reason: "nothing_to_heal", error: null };
108
119
  }
109
120
 
121
+ // SP-862 / #374: no unresolved task remains after this heal — record the
122
+ // salvage land as batch-level merge evidence so complete/dismiss can accept
123
+ // it without --force (see module docstring for the fail-closed contract).
124
+ if (allTasksTerminalSuccess(loaded.raw)) {
125
+ loaded.raw.salvageLandedAllTasks = {
126
+ at: Date.now(),
127
+ mergeCommit: mergeCommit ?? null,
128
+ tasks: [...healedTaskIds],
129
+ };
130
+ appendJournalEvent(projectRoot, batchId, "batch.salvage_landed_all_tasks", {
131
+ mergeCommit: mergeCommit ?? null,
132
+ healedTaskIds: [...healedTaskIds],
133
+ });
134
+ }
135
+
110
136
  saveSpineBatchState(projectRoot, loaded.raw);
111
137
  return { ok: true, healedTaskIds, reason: null, error: null };
112
138
  } catch (err) {
@@ -114,3 +140,21 @@ export function healSalvagedTasksAfterIntegrate(projectRoot, batchId, options =
114
140
  return { ok: false, healedTaskIds: [], reason: "heal_threw", error: message };
115
141
  }
116
142
  }
143
+
144
+ /**
145
+ * True when every task in the raw batch state is terminal-success
146
+ * (`succeeded` / `skipped`) — i.e. no unresolved failure is left after the
147
+ * salvage heal. Unknown/missing statuses fail closed.
148
+ *
149
+ * @param {object} raw
150
+ * @returns {boolean}
151
+ */
152
+ function allTasksTerminalSuccess(raw) {
153
+ const tasks = Array.isArray(raw?.tasks) ? raw.tasks : [];
154
+ if (tasks.length === 0) return false;
155
+ return tasks.every((task) => {
156
+ if (!task || typeof task !== "object") return false;
157
+ const status = String(task.status ?? "").toLowerCase();
158
+ return status === "succeeded" || status === "skipped";
159
+ });
160
+ }
@@ -62,6 +62,14 @@ export function isBatchArchived(projectRoot, batchId) {
62
62
  * engine writers cannot be blocked by their own recorded PID; resurrection
63
63
  * protection always runs.
64
64
  *
65
+ * A live recorded PID does not reject writes to a **paused** batch (SP-861 / #376):
66
+ * a confirmed operator pause is an ownership handoff — the engine acknowledged the
67
+ * pause (persisted phase: paused + journaled `engine.pause_observed`) and stopped
68
+ * driving the batch, so its lingering process is not a writer owner. Refusing
69
+ * operator retry/skip recovery writes there dead-ends pause → retry → resume
70
+ * recovery. Engine-driven phases (`running`/`planning`) still refuse for any
71
+ * live foreign PID.
72
+ *
65
73
  * @param {string} projectRoot
66
74
  * @param {Record<string, any>} state
67
75
  * @param {{ skipOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
@@ -92,7 +100,8 @@ export function evaluateBatchStateWriteGuard(projectRoot, state, options = {}) {
92
100
  !options.skipOwnerCheck &&
93
101
  ownerPid &&
94
102
  ownerPid !== process.pid &&
95
- isEngineProcessAlive(ownerPid, ownerStartedAt)
103
+ isEngineProcessAlive(ownerPid, ownerStartedAt) &&
104
+ onDiskPhase !== "paused"
96
105
  ) {
97
106
  return { allowed: false, reason: "stale_engine_pid" };
98
107
  }
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import { DIAGNOSIS_TAXONOMY } from "../batch/diagnosis.mjs";
6
+ import { RUNNING_PHASES } from "../batch/reconcile-light-cache.mjs";
6
7
 
7
8
  /** Operator-facing wait targets not in reconcile diagnosis taxonomy. */
8
9
  export const WAIT_UNTIL_PSEUDO_DIAGNOSES = [
@@ -96,12 +97,52 @@ export function diagnosisMatchesUntil(diagnosis, untilDiagnoses) {
96
97
  }
97
98
 
98
99
  /**
100
+ * Partial-failure diagnoses that reconcile can report while sibling lane
101
+ * workers are still running (#375). All three derive from reconcile's
102
+ * `hasFailedTasks` branch, which fires on the first terminal-failure task —
103
+ * even mid-batch — so waking a land loop on them while a sibling lane is
104
+ * still live would pause/salvage/kill healthy lanes.
105
+ *
106
+ * @type {ReadonlySet<string>}
107
+ */
108
+ export const WAIT_LIVE_SIBLING_GATED_DIAGNOSES = new Set([
109
+ "needs_retry",
110
+ "worker_done_missing",
111
+ "needs_replan",
112
+ ]);
113
+
114
+ /**
115
+ * Whether any in-scope lane task is still live (#375). Prefers
116
+ * `signals.hasRunningTasks` — the per-task running classification reconcile
117
+ * itself derives — and only falls back to the batch phase when the result
118
+ * carries no signals block (injected reconcile fns, non-verbose results):
119
+ * the engine holds the phase in a live run state while lane workers are
120
+ * active and transitions to failed/completed only after lanes settle.
121
+ *
122
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} result
123
+ * @returns {boolean}
124
+ */
125
+ export function hasLiveSiblingLaneWorker(result) {
126
+ const signals = /** @type {Record<string, unknown> | null | undefined} */ (result?.signals);
127
+ if (signals != null && typeof signals === "object") {
128
+ return signals.hasRunningTasks === true;
129
+ }
130
+ return RUNNING_PHASES.has(String(result?.phase ?? ""));
131
+ }
132
+
133
+ /**
134
+ * Resolve which `--until` entry (taxonomy diagnosis, `failed` phase alias, or
135
+ * land-loop pseudo) a reconcile result matches; null when nothing matches.
136
+ * Single source of truth for match order — `describeMatchedDiagnosis` in the
137
+ * wait poll names the matched token through this helper.
138
+ *
99
139
  * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} result
100
140
  * @param {Set<string>} untilDiagnoses
141
+ * @returns {string | null}
101
142
  */
102
- export function reconciliationMatchesUntil(result, untilDiagnoses) {
143
+ export function matchReconciliationUntil(result, untilDiagnoses) {
103
144
  if (diagnosisMatchesUntil(result.diagnosis ?? null, untilDiagnoses)) {
104
- return true;
145
+ return result.diagnosis;
105
146
  }
106
147
 
107
148
  // `--until failed` must wake on terminal batch failure even when reconcile
@@ -109,14 +150,35 @@ export function reconciliationMatchesUntil(result, untilDiagnoses) {
109
150
  // engine_orphaned) instead of the literal "failed" token (#252). Explicit
110
151
  // diagnosis tokens still match directly via the check above.
111
152
  if (untilDiagnoses.has("failed") && result.phase === "failed") {
112
- return true;
153
+ return "failed";
113
154
  }
114
155
 
115
156
  for (const pseudo of deriveWaitPseudoDiagnoses(result)) {
116
157
  if (untilDiagnoses.has(pseudo)) {
117
- return true;
158
+ return pseudo;
118
159
  }
119
160
  }
120
161
 
121
- return false;
162
+ return null;
163
+ }
164
+
165
+ /**
166
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} result
167
+ * @param {Set<string>} untilDiagnoses
168
+ */
169
+ export function reconciliationMatchesUntil(result, untilDiagnoses) {
170
+ const matched = matchReconciliationUntil(result, untilDiagnoses);
171
+ if (matched == null) {
172
+ return false;
173
+ }
174
+ // Partial-failure hold (#375): needs_retry / worker_done_missing /
175
+ // needs_replan fire on the first failed task even while sibling lane
176
+ // workers are still running. Hold the match until the live siblings
177
+ // settle; terminal aliases (`failed`), success/integrate diagnoses, and
178
+ // gate pseudos keep their current behavior so a fully terminal batch
179
+ // never waits on imaginary siblings.
180
+ if (WAIT_LIVE_SIBLING_GATED_DIAGNOSES.has(matched) && hasLiveSiblingLaneWorker(result)) {
181
+ return false;
182
+ }
183
+ return true;
122
184
  }
package/src/cli/wait.mjs CHANGED
@@ -12,9 +12,8 @@ import path from "node:path";
12
12
 
13
13
  import { reconcileBatch } from "../batch/reconcile.mjs";
14
14
  import {
15
- deriveWaitPseudoDiagnoses,
16
- diagnosisMatchesUntil,
17
15
  parseUntilDiagnoses,
16
+ matchReconciliationUntil,
18
17
  reconciliationMatchesUntil,
19
18
  } from "./spine-wait.mjs";
20
19
  import {
@@ -132,19 +131,7 @@ function formatWaitElapsed(ms) {
132
131
  * @returns {string}
133
132
  */
134
133
  function describeMatchedDiagnosis(result, untilDiagnoses) {
135
- const diagnosis = result.diagnosis ?? null;
136
- if (diagnosisMatchesUntil(diagnosis, untilDiagnoses)) {
137
- return diagnosis;
138
- }
139
- if (untilDiagnoses.has("failed") && result.phase === "failed") {
140
- return "failed";
141
- }
142
- for (const pseudo of deriveWaitPseudoDiagnoses(result)) {
143
- if (untilDiagnoses.has(pseudo)) {
144
- return pseudo;
145
- }
146
- }
147
- return diagnosis ?? "matched";
134
+ return matchReconciliationUntil(result, untilDiagnoses) ?? result.diagnosis ?? "matched";
148
135
  }
149
136
 
150
137
  /**
@@ -341,7 +328,11 @@ export async function runSpineWait(options) {
341
328
 
342
329
  try {
343
330
  while (running) {
344
- const result = reconcileFn({ projectRoot });
331
+ // verbose: true (#375) — exposes signals.hasRunningTasks so the
332
+ // partial-failure match gate uses reconcile's own live-task
333
+ // classification instead of the phase fallback. buildWatchSnapshot
334
+ // picks explicit fields, so signals never leak into --json output.
335
+ const result = reconcileFn({ projectRoot, verbose: true });
345
336
  if (!scopedBatchIdCaptured) {
346
337
  const candidate = result.batchId ?? null;
347
338
  if (candidate != null) {
@@ -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