pi-spine 2.20.0 → 2.22.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.
@@ -1,21 +1,26 @@
1
1
  // @ts-nocheck
2
2
  /** Diagnosis derivation (SP-596/SP-606 / #192). */
3
3
 
4
- import fs from "node:fs";
5
- import { inferLaunchFailureFromWorkerOutputTail, inferLaunchFailureKind } from "./diagnosis.mjs";
4
+ import { inferLaunchFailureKind } from "./diagnosis.mjs";
6
5
  import {
7
6
  findPendingLaneLandTasks,
8
7
  shouldDiagnosePendingLaneLand,
9
8
  } from "./diagnosis-pending-lane.mjs";
10
9
  import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.mjs";
11
10
  import { inferStubExitReasonForTask } from "./diagnosis-stub.mjs";
12
- import { workerOutputLogPath, workerOutputLogRef } from "./worker-output.mjs";
13
11
  import { isPostMergeLimbo } from "./limbo-detect.mjs";
14
12
  import {
15
13
  LIMBO_PHASES,
16
14
  RUNNING_PHASES,
17
15
  } from "./reconcile-light-cache.mjs";
18
16
  export { buildReconcileDiagnosisContext } from "./reconcile-diagnosis-context.mjs";
17
+ export {
18
+ enrichLaunchFailureFromWorkerOutput,
19
+ enrichWorkerDoneMissingContext,
20
+ extractGitignoredPathsFromJournal,
21
+ hasGhostRunningCluster,
22
+ laneTaskBranchForDiagnosis,
23
+ } from "./reconcile-diagnosis-enrich.mjs";
19
24
 
20
25
  /**
21
26
  * @param {unknown} rawTasks
@@ -92,138 +97,6 @@ function deriveFailureContext(failedTaskId, exitReason, signals) {
92
97
  return { exitReason: resolvedExitReason, launchFailureKind };
93
98
  }
94
99
 
95
- const WORKER_OUTPUT_TAIL_LINES = 20;
96
-
97
- /**
98
- * @param {string} filePath
99
- * @param {number} [lineCount]
100
- * @returns {string|null}
101
- */
102
- function readWorkerOutputLogTail(filePath, lineCount = WORKER_OUTPUT_TAIL_LINES) {
103
- if (!fs.existsSync(filePath)) return null;
104
- const content = fs.readFileSync(filePath, "utf-8");
105
- const lines = content.split("\n");
106
- if (lines.at(-1) === "") lines.pop();
107
- if (lines.length === 0) return null;
108
- return lines.slice(-lineCount).join("\n");
109
- }
110
-
111
- /**
112
- * @param {string} projectRoot
113
- * @param {string} batchId
114
- * @param {string|null} failedTaskId
115
- * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
116
- * @param {string|null} launchFailureKind
117
- * @returns {string|null}
118
- */
119
- export function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId, tasks, launchFailureKind) {
120
- if (launchFailureKind || !failedTaskId || !batchId) return launchFailureKind;
121
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
122
- if (!task || task.laneNumber == null) return launchFailureKind;
123
- const logPath = workerOutputLogPath(projectRoot, batchId, task.laneNumber, failedTaskId);
124
- const tail = readWorkerOutputLogTail(logPath);
125
- return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
126
- }
127
-
128
- /**
129
- * @param {string} projectRoot
130
- * @param {string} batchId
131
- * @param {string|null} failedTaskId
132
- * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
133
- * @param {object|null} doneMissingHint
134
- * @returns {{ workerOutputLogRef: string|null, workerOutputLogPath: string|null, workerOutputTail: string|null, workerOutputSnippet: string|null, changedFileCount: number|null }}
135
- */
136
- export function enrichWorkerDoneMissingContext(
137
- projectRoot,
138
- batchId,
139
- failedTaskId,
140
- tasks,
141
- doneMissingHint,
142
- ) {
143
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
144
- const laneNumber = task?.laneNumber;
145
- const logRef =
146
- doneMissingHint?.workerOutputLogRef ??
147
- (failedTaskId && laneNumber != null
148
- ? workerOutputLogRef(batchId, laneNumber, failedTaskId)
149
- : null);
150
- const logPath =
151
- doneMissingHint?.workerOutputLogPath ??
152
- (failedTaskId && laneNumber != null
153
- ? workerOutputLogPath(projectRoot, batchId, laneNumber, failedTaskId)
154
- : null);
155
- const tailFromDisk = logPath ? readWorkerOutputLogTail(logPath) : null;
156
- const outputText = [doneMissingHint?.output, tailFromDisk].filter(Boolean).join("\n");
157
- const snippet = outputText
158
- ? outputText
159
- .split("\n")
160
- .filter(Boolean)
161
- .slice(-3)
162
- .join(" | ")
163
- : null;
164
-
165
- return {
166
- workerOutputLogRef: logRef,
167
- workerOutputLogPath: logPath,
168
- workerOutputTail: tailFromDisk,
169
- workerOutputSnippet: snippet,
170
- changedFileCount:
171
- doneMissingHint?.changedFileCount != null ? doneMissingHint.changedFileCount : null,
172
- };
173
- }
174
-
175
- /**
176
- * @param {Array<{ taskId: string, classification: string, laneNumber?: number|null }>} tasks
177
- * @param {string|null} failedTaskId
178
- * @returns {boolean}
179
- */
180
- export function hasGhostRunningCluster(tasks, failedTaskId) {
181
- if (!failedTaskId) return false;
182
- const task = tasks.find((entry) => entry.taskId === failedTaskId);
183
- if (!task || task.laneNumber == null) return false;
184
- const laneNumber = Number(task.laneNumber);
185
- return (
186
- tasks.filter(
187
- (entry) =>
188
- entry.classification === "running" && Number(entry.laneNumber) === laneNumber,
189
- ).length > 1
190
- );
191
- }
192
-
193
- /**
194
- * @param {object[]} journalEvents
195
- * @param {string|null} failedTaskId
196
- * @returns {string[]}
197
- */
198
- export function extractGitignoredPathsFromJournal(journalEvents, failedTaskId) {
199
- if (!Array.isArray(journalEvents)) return [];
200
- for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
201
- const event = journalEvents[index];
202
- if (event.type !== "task.failed") continue;
203
- const eventTaskId = event.taskId ?? event.payload?.taskId;
204
- if (failedTaskId && eventTaskId && eventTaskId !== failedTaskId) continue;
205
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
206
- if (Array.isArray(payload.gitignoredPaths)) {
207
- return payload.gitignoredPaths.filter((entry) => typeof entry === "string");
208
- }
209
- }
210
- return [];
211
- }
212
-
213
- /**
214
- * @param {Record<string, unknown>|null|undefined} raw
215
- * @param {string} batchId
216
- * @param {string} taskId
217
- * @returns {string|null}
218
- */
219
- export function laneTaskBranchForDiagnosis(raw, batchId, taskId) {
220
- const tasks = raw?.tasks;
221
- if (!Array.isArray(tasks)) return null;
222
- const task = tasks.find((entry) => entry?.taskId === taskId);
223
- if (!task || task.laneNumber == null) return null;
224
- return `task/spine-lane-${task.laneNumber}-${batchId}`;
225
- }
226
-
227
100
  /**
228
101
  * @param {string} diagnosis
229
102
  * @param {string|null} failedTaskId
@@ -262,6 +135,50 @@ function hasNeedsReplanBlocker(signals) {
262
135
  return tasks.some((task) => task?.exitReason === "needs_replan");
263
136
  }
264
137
 
138
+ /**
139
+ * Plan-review exit reasons where reviewer infrastructure failed after the
140
+ * worker had already completed its lane work (#291 / SP-762). Mirrors the
141
+ * SP-718 final-review distinction: spawn failure / timeout mean no verdict
142
+ * was produced — the implementation itself is not the failure.
143
+ */
144
+ const POST_DONE_PLAN_REVIEW_EXIT_REASONS = new Set([
145
+ "plan_review_spawn_failed",
146
+ "plan_review_timeout",
147
+ ]);
148
+
149
+ /**
150
+ * Failed task whose lane work already completed (done evidence / `.DONE` in
151
+ * the lane worktree) but whose engine plan review failed to spawn or timed
152
+ * out. Such tasks are salvageable land-loop candidates — a full worker retry
153
+ * would re-run expensive work that is already on disk (#291 / SP-762).
154
+ *
155
+ * Parsed batch-state tasks drop `exitReason` (normalizeTasks), so the exit
156
+ * reason is resolved the same way deriveFailureContext resolves it: from the
157
+ * task entry when present, else raw state / journal `task.failed` events.
158
+ * The salvage command itself hard-gates on commits-ahead, so pointing at it
159
+ * without lane commits is safe (dry-run reports none salvageable).
160
+ *
161
+ * @param {object} signals
162
+ * @returns {object|null}
163
+ */
164
+ function findPostDonePlanReviewSpawnFailedTask(signals) {
165
+ const tasks = Array.isArray(signals.tasks) ? signals.tasks : [];
166
+ for (const task of tasks) {
167
+ if (String(task?.status ?? "").toLowerCase() !== "failed") continue;
168
+ const hasDoneEvidence =
169
+ task?.doneInLane === true ||
170
+ task?.doneOnMain === true ||
171
+ task?.doneFileFound === true ||
172
+ String(task?.classification ?? "").toLowerCase() === "terminal-success";
173
+ if (!hasDoneEvidence) continue;
174
+ const taskId = String(task?.taskId ?? "");
175
+ const exitReason = task?.exitReason ?? resolvePrimaryFailureExitReason(taskId, signals);
176
+ if (!POST_DONE_PLAN_REVIEW_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
177
+ return task;
178
+ }
179
+ return null;
180
+ }
181
+
265
182
  /**
266
183
  * @param {object} signals
267
184
  */
@@ -362,6 +279,17 @@ export function deriveDiagnosis(signals) {
362
279
  if (doneMissing) {
363
280
  return withFailureContext("worker_done_missing", failedTaskId, signals);
364
281
  }
282
+ // Post-DONE plan-review spawn failure: lane work is complete, so map to
283
+ // pending_lane_land (salvage / land-loop guidance) instead of needs_retry,
284
+ // whose retry language would force an expensive worker re-run (#291 / SP-762).
285
+ const postDonePlanReviewTask = findPostDonePlanReviewSpawnFailedTask(signals);
286
+ if (postDonePlanReviewTask) {
287
+ return withFailureContext(
288
+ "pending_lane_land",
289
+ postDonePlanReviewTask.taskId ?? failedTaskId,
290
+ signals,
291
+ );
292
+ }
365
293
  return withFailureContext("needs_retry", failedTaskId, signals);
366
294
  }
367
295
 
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Heal failed-task gates after a successful salvage integrate (#292 / SP-763).
3
+ *
4
+ * When `spine batch salvage --lane N --integrate` lands lane work on the base
5
+ * branch, the active batch state still records the salvaged tasks as failed
6
+ * (status "failed", failed segment, failedTasks counter), so
7
+ * `spine batch complete` keeps refusing (`needs_retry` / `pending_lane_land`)
8
+ * and operators are forced to `dismiss --force`. Once the land succeeded there
9
+ * is no unresolved failure left for those tasks, so the failed-task gate is
10
+ * healed here: each salvageable task is promoted with `recordTaskSucceeded`
11
+ * (task status, segments, and succeeded/failed counters in one step) and a
12
+ * reconciled `task.completed` journal event keeps journal-derived rebuilds in
13
+ * agreement — the same promotion `reconcileBatchStateDrift` applies on
14
+ * done-in-lane terminal evidence.
15
+ *
16
+ * Tasks outside the salvage set are never touched: non-salvageable failures
17
+ * (contract/review failures) and evidence-less worker deaths remain failed and
18
+ * keep blocking complete (SP-763 completion criteria).
19
+ */
20
+
21
+ import { loadBatchStateFile } from "./batch-state-io.mjs";
22
+ import { appendJournalEvent } from "./journal.mjs";
23
+ import { recordTaskSucceeded, saveSpineBatchState } from "./state.mjs";
24
+
25
+ /**
26
+ * Heal the failed-task gate for a lane a salvage integrate just landed, and
27
+ * journal `batch.salvage_heal_failed` when the heal itself fails without
28
+ * failing the integrate — the merge has already landed (#292 / SP-763).
29
+ *
30
+ * @param {string} projectRoot
31
+ * @param {string} batchId
32
+ * @param {object} lane
33
+ * @param {string|null} mergeCommit
34
+ * @returns {{ ok: boolean, healedTaskIds: string[], healError: string|null }}
35
+ */
36
+ export function healAfterSalvageLand(projectRoot, batchId, lane, mergeCommit) {
37
+ const heal = healSalvagedTasksAfterIntegrate(projectRoot, batchId, {
38
+ salvageableTasks: lane.salvageableTasks ?? [],
39
+ mergeCommit,
40
+ });
41
+ if (!heal.ok) {
42
+ appendJournalEvent(projectRoot, batchId, "batch.salvage_heal_failed", {
43
+ laneNumber: lane.laneNumber ?? null,
44
+ salvageableTasks: lane.salvageableTasks ?? [],
45
+ reason: heal.reason,
46
+ error: heal.error,
47
+ });
48
+ }
49
+ return { ok: heal.ok, healedTaskIds: heal.healedTaskIds, healError: heal.ok ? null : heal.error };
50
+ }
51
+
52
+ /**
53
+ * Heal the failed-task gate for tasks whose lane work a salvage integrate just
54
+ * landed on the base branch. Never throws into the salvage path: the merge has
55
+ * already landed, so a heal problem is reported as a result, not a command
56
+ * failure.
57
+ *
58
+ * @param {string} projectRoot
59
+ * @param {string} batchId
60
+ * @param {object} [options]
61
+ * @param {string[]} [options.salvageableTasks] Task ids the salvage landed.
62
+ * @param {string|null} [options.mergeCommit] Salvage merge commit, when known.
63
+ * @returns {{ ok: boolean, healedTaskIds: string[], reason: string|null, error: string|null }}
64
+ */
65
+ export function healSalvagedTasksAfterIntegrate(projectRoot, batchId, options = {}) {
66
+ const salvageableTasks = (options.salvageableTasks ?? []).map((taskId) => String(taskId ?? "")).filter(Boolean);
67
+ const mergeCommit = options.mergeCommit ?? null;
68
+ if (salvageableTasks.length === 0) {
69
+ return { ok: true, healedTaskIds: [], reason: "no_salvageable_tasks", error: null };
70
+ }
71
+
72
+ try {
73
+ const loaded = loadBatchStateFile(projectRoot);
74
+ // Salvage also runs against archived batches; without an active state
75
+ // there is no gate to heal and `complete` is not applicable anyway.
76
+ if (!loaded.path || !loaded.raw) {
77
+ return { ok: true, healedTaskIds: [], reason: "no_active_batch_state", error: null };
78
+ }
79
+ if (loaded.parseError) {
80
+ return { ok: false, healedTaskIds: [], reason: "batch_state_unreadable", error: loaded.parseError };
81
+ }
82
+ const stateBatchId = String(loaded.raw.batchId ?? loaded.raw.id ?? "");
83
+ if (stateBatchId !== batchId) {
84
+ return { ok: true, healedTaskIds: [], reason: "batch_id_mismatch", error: null };
85
+ }
86
+
87
+ const healedTaskIds = [];
88
+ for (const taskId of salvageableTasks) {
89
+ const task = (loaded.raw.tasks ?? []).find(
90
+ (entry) => entry && typeof entry === "object" && entry.taskId === taskId,
91
+ );
92
+ if (!task) continue;
93
+ const status = String(task.status ?? "").toLowerCase();
94
+ if (status === "succeeded" || status === "skipped") continue;
95
+ if (!recordTaskSucceeded(loaded.raw, taskId, { exitReason: "done", doneFileFound: true })) continue;
96
+ healedTaskIds.push(taskId);
97
+ appendJournalEvent(projectRoot, batchId, "task.completed", {
98
+ taskId,
99
+ laneNumber: task.laneNumber ?? null,
100
+ reconciled: true,
101
+ reconcileReason: "salvage_integrated",
102
+ mergeCommit,
103
+ });
104
+ }
105
+
106
+ if (healedTaskIds.length === 0) {
107
+ return { ok: true, healedTaskIds, reason: "nothing_to_heal", error: null };
108
+ }
109
+
110
+ saveSpineBatchState(projectRoot, loaded.raw);
111
+ return { ok: true, healedTaskIds, reason: null, error: null };
112
+ } catch (err) {
113
+ const message = err instanceof Error ? err.message : String(err);
114
+ return { ok: false, healedTaskIds: [], reason: "heal_threw", error: message };
115
+ }
116
+ }
@@ -16,6 +16,7 @@ import {
16
16
  gateBlockedOnMissingGate,
17
17
  openGateFromSalvageEvidence,
18
18
  } from "./salvage-batch-integrate-gate.mjs";
19
+ import { healAfterSalvageLand } from "./salvage-batch-integrate-heal.mjs";
19
20
  import { laneTaskBranch } from "./worktree.mjs";
20
21
  import { listSalvageableLanes } from "./salvage-batch-list.mjs";
21
22
 
@@ -141,10 +142,15 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
141
142
  }
142
143
 
143
144
  if (commitsAhead <= 0) {
145
+ // Lane work is already fully merged (manual land or re-run) — heal the
146
+ // failed-task gate on the same landed-work evidence (#292 / SP-763).
147
+ const heal = healAfterSalvageLand(projectRoot, resolvedBatchId, lane, null);
144
148
  return {
145
149
  ok: true,
146
150
  exitCode: 0,
147
151
  alreadyMerged: true,
152
+ healedTaskIds: heal.healedTaskIds,
153
+ healError: heal.healError,
148
154
  batchId: resolvedBatchId,
149
155
  laneNumber: laneNum,
150
156
  baseBranch,
@@ -385,6 +391,9 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
385
391
  };
386
392
  }
387
393
 
394
+ // Landed lane work clears the salvaged tasks' failure gate (#292 / SP-763).
395
+ const heal = healAfterSalvageLand(projectRoot, resolvedBatchId, lane, mergeCommit);
396
+
388
397
  appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrated", {
389
398
  laneNumber: laneNum,
390
399
  taskBranch,
@@ -393,6 +402,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
393
402
  commitsAhead,
394
403
  salvageableTasks: lane.salvageableTasks,
395
404
  excludedTasks: lane.excludedTasks,
405
+ healedTaskIds: heal.healedTaskIds,
396
406
  });
397
407
 
398
408
  return {
@@ -406,6 +416,8 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
406
416
  commitsAhead,
407
417
  salvageableTasks: lane.salvageableTasks,
408
418
  excludedTasks: lane.excludedTasks,
419
+ healedTaskIds: heal.healedTaskIds,
420
+ healError: heal.healError,
409
421
  gateOpenedBySalvage,
410
422
  headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
411
423
  suggestedCommand: "spine status --diagnose",
@@ -455,6 +467,12 @@ export function formatSalvageIntegrateOutput(result, options = {}) {
455
467
  if (result.mergeCommit) {
456
468
  lines.push(` Merge commit: ${result.mergeCommit}`);
457
469
  }
470
+ if (result.healedTaskIds?.length) {
471
+ lines.push(` Healed tasks: ${result.healedTaskIds.join(", ")}`);
472
+ }
473
+ if (result.healError) {
474
+ lines.push(` Heal failed: ${result.healError} — failed-task gate not cleared (see journal)`);
475
+ }
458
476
 
459
477
  if (result.suggestedCommand) {
460
478
  lines.push("", ` → ${result.suggestedCommand}`);
package/src/cli/wait.mjs CHANGED
@@ -11,7 +11,12 @@ import fs from "node:fs";
11
11
  import path from "node:path";
12
12
 
13
13
  import { reconcileBatch } from "../batch/reconcile.mjs";
14
- import { parseUntilDiagnoses, reconciliationMatchesUntil } from "./spine-wait.mjs";
14
+ import {
15
+ deriveWaitPseudoDiagnoses,
16
+ diagnosisMatchesUntil,
17
+ parseUntilDiagnoses,
18
+ reconciliationMatchesUntil,
19
+ } from "./spine-wait.mjs";
15
20
  import {
16
21
  buildWatchSnapshot,
17
22
  DEFAULT_WATCH_INTERVAL_SEC,
@@ -95,6 +100,120 @@ export function parseWaitArgs(argv) {
95
100
  return args;
96
101
  }
97
102
 
103
+ /**
104
+ * Human duration for wait headlines (e.g. `12.0s`, `1m5s`). Returns null when the
105
+ * elapsed value is not representable so callers can omit the suffix instead of
106
+ * printing a garbage number (nowFn pairs are expected sane, this is defensive).
107
+ *
108
+ * @param {number} ms
109
+ * @returns {string | null}
110
+ */
111
+ function formatWaitElapsed(ms) {
112
+ if (!Number.isFinite(ms) || ms < 0) {
113
+ return null;
114
+ }
115
+ const seconds = ms / 1000;
116
+ if (seconds < 60) {
117
+ return `${seconds.toFixed(1)}s`;
118
+ }
119
+ const minutes = Math.floor(seconds / 60);
120
+ const remainder = Math.round(seconds % 60);
121
+ return `${minutes}m${remainder}s`;
122
+ }
123
+
124
+ /**
125
+ * Label for what actually matched the `--until` set: the literal taxonomy diagnosis
126
+ * when it matched, the `failed` token when the phase-based alias fired (#252), or the
127
+ * pseudo diagnosis (e.g. gate_open) that fired. Keeps headlines honest for pseudo
128
+ * matches where the raw diagnosis (e.g. "running") is not what woke the wait.
129
+ *
130
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult} result
131
+ * @param {Set<string>} untilDiagnoses
132
+ * @returns {string}
133
+ */
134
+ 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";
148
+ }
149
+
150
+ /**
151
+ * @param {Set<string>} untilDiagnoses
152
+ * @returns {string}
153
+ */
154
+ function formatUntilList(untilDiagnoses) {
155
+ return [...untilDiagnoses].sort().join(",");
156
+ }
157
+
158
+ /**
159
+ * @param {string | null} scopedBatchId
160
+ * @returns {string}
161
+ */
162
+ function formatBatchSuffix(scopedBatchId) {
163
+ return scopedBatchId != null ? ` (batch ${scopedBatchId})` : "";
164
+ }
165
+
166
+ /**
167
+ * Start banner for human waits (#286, SP-754). Printed once, right before the first poll
168
+ * sleep, so the batch id captured on that poll is included when known. Instant matches
169
+ * never see a banner — their single-line output stays exactly one line.
170
+ *
171
+ * @param {object} options
172
+ * @param {Set<string>} options.untilDiagnoses
173
+ * @param {string | null} options.batchId
174
+ * @param {number} options.intervalSec
175
+ * @param {number | null} options.timeoutMs
176
+ * @returns {string}
177
+ */
178
+ function formatWaitBanner({ untilDiagnoses, batchId, intervalSec, timeoutMs }) {
179
+ const timeoutPart =
180
+ timeoutMs != null
181
+ ? `timeout ${formatWaitElapsed(timeoutMs) ?? `${timeoutMs}ms`}`
182
+ : "no timeout";
183
+ return `Waiting for ${formatUntilList(untilDiagnoses)}${formatBatchSuffix(batchId)} — polling every ${intervalSec}s, ${timeoutPart}`;
184
+ }
185
+
186
+ /**
187
+ * Interval-aligned liveness line (#286, SP-754). The poll loop sleeps exactly one
188
+ * `--interval` per iteration, so one progress line per non-matching poll is aligned by
189
+ * construction and can never spam micro-sleeps. Carries diagnosis/phase (plus wave and
190
+ * pending-task counts when reconcile surfaces them) and elapsed so agent hosts can prove
191
+ * the wait is alive between the start banner and the terminal headline.
192
+ *
193
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult} result
194
+ * @param {string | null} scopedBatchId
195
+ * @param {number} elapsedMs
196
+ * @returns {string}
197
+ */
198
+ function formatWaitProgress(result, scopedBatchId, elapsedMs) {
199
+ /** @type {string[]} */
200
+ const parts = [result.diagnosis ?? "no diagnosis"];
201
+ if (result.phase != null) {
202
+ parts.push(`phase=${result.phase}`);
203
+ }
204
+ if (result.currentWaveIndex != null && result.waveCount != null) {
205
+ parts.push(`wave ${result.currentWaveIndex + 1}/${result.waveCount}`);
206
+ }
207
+ if (result.pendingTasks != null) {
208
+ parts.push(`pending tasks ${result.pendingTasks}`);
209
+ }
210
+ const elapsed = formatWaitElapsed(elapsedMs);
211
+ if (elapsed != null) {
212
+ parts.push(`elapsed ${elapsed}`);
213
+ }
214
+ return `Wait progress: ${parts.join(", ")}${formatBatchSuffix(scopedBatchId)}`;
215
+ }
216
+
98
217
  /** Exit code when the waited-on batch was archived or superseded by another session (#215). */
99
218
  export const WAIT_SUPERSEDED_EXIT_CODE = 2;
100
219
 
@@ -211,6 +330,15 @@ export async function runSpineWait(options) {
211
330
  let scopedBatchId = null;
212
331
  let scopedBatchIdCaptured = false;
213
332
 
333
+ /**
334
+ * Human start banner (#286, SP-754): flipped after the first poll that continues past
335
+ * the match/supersede/timeout checks, so the banner is printed exactly once and only
336
+ * when the wait actually waits. `--json` never prints it.
337
+ *
338
+ * @type {boolean}
339
+ */
340
+ let bannerPrinted = false;
341
+
214
342
  try {
215
343
  while (running) {
216
344
  const result = reconcileFn({ projectRoot });
@@ -266,6 +394,13 @@ export async function runSpineWait(options) {
266
394
  if (reconciliationMatchesUntil(result, untilDiagnoses)) {
267
395
  if (json) {
268
396
  writeStdout(`${JSON.stringify(buildWatchSnapshot(result, nowFn()))}\n`);
397
+ } else {
398
+ // Terminal headline (#286): long waits must not look hung on success. One
399
+ // stdout line naming what matched, the scoped batch, and elapsed time.
400
+ const elapsed = formatWaitElapsed(nowFn() - startedAt);
401
+ writeStdout(
402
+ `Wait matched: ${describeMatchedDiagnosis(result, untilDiagnoses)}${formatBatchSuffix(scopedBatchId)}${elapsed != null ? ` after ${elapsed}` : ""}\n`,
403
+ );
269
404
  }
270
405
  return {
271
406
  exitCode: 0,
@@ -279,6 +414,13 @@ export async function runSpineWait(options) {
279
414
  if (deadline != null && nowFn() >= deadline) {
280
415
  if (json) {
281
416
  writeStdout(`${JSON.stringify(buildWatchSnapshot(result, nowFn()))}\n`);
417
+ } else {
418
+ // Terminal headline (#286): stderr keeps the non-success terminal state off
419
+ // stdout and is clearly distinct from the match line.
420
+ const elapsed = formatWaitElapsed(nowFn() - startedAt);
421
+ writeStderr(
422
+ `Wait timed out${elapsed != null ? ` after ${elapsed}` : ""} waiting for ${formatUntilList(untilDiagnoses)}${formatBatchSuffix(scopedBatchId)} — last diagnosis: ${diagnosis ?? "none"}\n`,
423
+ );
282
424
  }
283
425
  return {
284
426
  exitCode: 1,
@@ -289,9 +431,29 @@ export async function runSpineWait(options) {
289
431
  };
290
432
  }
291
433
 
434
+ if (!json) {
435
+ if (!bannerPrinted) {
436
+ // Start banner (#286, SP-754): once, only when the wait actually continues —
437
+ // instant matches keep their single-line output. batchId was captured above.
438
+ bannerPrinted = true;
439
+ writeStdout(
440
+ `${formatWaitBanner({ untilDiagnoses, batchId: scopedBatchId, intervalSec, timeoutMs })}\n`,
441
+ );
442
+ } else {
443
+ // Interval-aligned progress (#286, SP-754): one line per non-matching poll.
444
+ writeStdout(`${formatWaitProgress(result, scopedBatchId, nowFn() - startedAt)}\n`);
445
+ }
446
+ }
447
+
292
448
  await sleepFn(intervalSec * 1000);
293
449
  }
294
450
 
451
+ if (!json) {
452
+ // Terminal headline (#286): SIGINT must not exit silently either.
453
+ writeStderr(
454
+ `Wait interrupted — exited without matching ${formatUntilList(untilDiagnoses)}${formatBatchSuffix(scopedBatchId)}\n`,
455
+ );
456
+ }
295
457
  return { exitCode: 130, matched: false, diagnosis: null, timedOut: false, interrupted: true };
296
458
  } finally {
297
459
  process.off("SIGINT", onSigInt);