pi-spine 2.18.0 → 2.20.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.
@@ -14,6 +14,7 @@ import { parseBatchStartWaveFilter } from "../src/planner/wave-scope.mjs";
14
14
  import { pauseBatch } from "../src/batch/pause.mjs";
15
15
  import { resumeBatch } from "../src/batch/resume.mjs";
16
16
  import { retryTask, skipTask } from "../src/batch/retry.mjs";
17
+ import { retryTaskRow, skipTaskRow, parseMatrixRowRef } from "../src/batch/retry-row.mjs";
17
18
  import { reconcileBatch } from "../src/batch/reconcile.mjs";
18
19
  import {
19
20
  finishAttachedBatchCli,
@@ -38,7 +39,8 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
38
39
  */
39
40
  export function printBatchHelp() {
40
41
  return (
41
- "Usage: spine batch start <scope>|pause|resume|retry <taskId>|skip <taskId>|force-merge [--wave N]|salvage|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n" +
42
+ "Usage: spine batch start <scope>|pause|resume|retry <taskId|[rowId]>|skip <taskId|[rowId]>|force-merge [--wave N]|salvage|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n" +
43
+ " Row identity: retry/skip 'SP-X[rowId]' targets one matrix row; plain SP-X targets the whole task.\n" +
42
44
  " abort --dry-run Preview abort (reason/archive target); does not archive, journal, or clear live batch\n"
43
45
  );
44
46
  }
@@ -349,10 +351,13 @@ export async function runSpineBatch(options) {
349
351
  if (!parsed.taskId) {
350
352
  return {
351
353
  exitCode: 1,
352
- output: "Usage: spine batch retry <taskId> [--json]\n",
354
+ output: "Usage: spine batch retry <taskId> | <taskId>[rowId] [--json]\n",
353
355
  };
354
356
  }
355
- const result = retryTask({ projectRoot, taskId: parsed.taskId });
357
+ const rowRef = parseMatrixRowRef(parsed.taskId);
358
+ const result = rowRef
359
+ ? retryTaskRow({ projectRoot, taskId: rowRef.taskId, rowId: rowRef.rowId })
360
+ : retryTask({ projectRoot, taskId: parsed.taskId });
356
361
  if (parsed.json) {
357
362
  return {
358
363
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
@@ -368,6 +373,7 @@ export async function runSpineBatch(options) {
368
373
  ];
369
374
  if (result.batchId) lines.push("", ` Batch: ${result.batchId}`);
370
375
  if (result.taskId) lines.push(` Task: ${result.taskId}`);
376
+ if (result.rowId) lines.push(` Row: ${result.rowId}`);
371
377
  if (result.pendingSegments != null) lines.push(` Pending segments: ${result.pendingSegments}`);
372
378
  lines.push("");
373
379
  return {
@@ -381,10 +387,13 @@ export async function runSpineBatch(options) {
381
387
  if (!parsed.taskId) {
382
388
  return {
383
389
  exitCode: 1,
384
- output: "Usage: spine batch skip <taskId> [--json]\n",
390
+ output: "Usage: spine batch skip <taskId> | <taskId>[rowId] [--json]\n",
385
391
  };
386
392
  }
387
- const result = skipTask({ projectRoot, taskId: parsed.taskId });
393
+ const rowRef = parseMatrixRowRef(parsed.taskId);
394
+ const result = rowRef
395
+ ? skipTaskRow({ projectRoot, taskId: rowRef.taskId, rowId: rowRef.rowId })
396
+ : skipTask({ projectRoot, taskId: parsed.taskId });
388
397
  if (parsed.json) {
389
398
  return {
390
399
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
@@ -400,6 +409,7 @@ export async function runSpineBatch(options) {
400
409
  ];
401
410
  if (result.batchId) lines.push("", ` Batch: ${result.batchId}`);
402
411
  if (result.taskId) lines.push(` Task: ${result.taskId}`);
412
+ if (result.rowId) lines.push(` Row: ${result.rowId}`);
403
413
  lines.push("");
404
414
  return {
405
415
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * Integrate gate inspection and resolution (PRD §12, FR-GATE).
4
- * Usage: spine gate [approve|reject|status|reopen] [--batch ID] [--reason text] [--json]
4
+ * Usage: spine gate [approve|reject|status|reopen] [--batch ID] [--reason text] [--synthesis text] [--json]
5
5
  */
6
6
 
7
7
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
@@ -32,6 +32,10 @@ export function formatGateHuman(result, json = false) {
32
32
  ` Status: ${result.gate.status}`,
33
33
  ` Kind: ${result.gate.kind}`,
34
34
  );
35
+ // SP-747 / #280: show the operator's synthesis readback when one was recorded.
36
+ if (typeof result.gate.synthesis === "string" && result.gate.synthesis.trim() !== "") {
37
+ lines.push(` Synthesis: ${result.gate.synthesis}`);
38
+ }
35
39
  if (Array.isArray(result.gate.evidenceRefs) && result.gate.evidenceRefs.length > 0) {
36
40
  lines.push("", " Evidence:");
37
41
  for (const ref of result.gate.evidenceRefs) {
@@ -87,6 +91,12 @@ export function runSpineGate(options) {
87
91
  reason = args[reasonIdx + 1];
88
92
  }
89
93
 
94
+ let synthesis = null;
95
+ const synthesisIdx = args.indexOf("--synthesis");
96
+ if (synthesisIdx >= 0 && args[synthesisIdx + 1]) {
97
+ synthesis = args[synthesisIdx + 1];
98
+ }
99
+
90
100
  batchId = resolveActiveBatchId(projectRoot, batchId);
91
101
  if (!batchId) {
92
102
  const result = {
@@ -106,10 +116,15 @@ export function runSpineGate(options) {
106
116
  let result;
107
117
  switch (action) {
108
118
  case "approve":
109
- result = approveIntegrateGate({ projectRoot, batchId });
119
+ result = approveIntegrateGate({ projectRoot, batchId, synthesis: synthesis ?? undefined });
110
120
  break;
111
121
  case "reject":
112
- result = rejectIntegrateGate({ projectRoot, batchId, reason: reason ?? undefined });
122
+ result = rejectIntegrateGate({
123
+ projectRoot,
124
+ batchId,
125
+ reason: reason ?? undefined,
126
+ synthesis: synthesis ?? undefined,
127
+ });
113
128
  break;
114
129
  case "status":
115
130
  result = getIntegrateGateStatus({ projectRoot, batchId });
@@ -4,6 +4,49 @@ import { readJournalEvents, readJournalTail } from "../src/batch/journal.mjs";
4
4
  import { reconcileBatch } from "../src/batch/reconcile.mjs";
5
5
  import { formatStatusJson } from "../src/batch/status-json.mjs";
6
6
 
7
+ /**
8
+ * Per-row matrix state lines (#230): one block per matrix task listing each
9
+ * row's running/succeeded/failed state, plus concrete retry/cancel commands
10
+ * for the failing rows. Rendered for both plain and --diagnose human output.
11
+ *
12
+ * @param {string[]} lines Output lines (mutated).
13
+ * @param {object} result Reconciliation result from reconcileBatch.
14
+ */
15
+ function appendMatrixRowSections(lines, result) {
16
+ const matrixTasks = (result.signals?.tasks ?? []).filter(
17
+ (task) => Array.isArray(task?.matrixRows) && task.matrixRows.length > 0,
18
+ );
19
+ if (matrixTasks.length === 0) return;
20
+
21
+ for (const task of matrixTasks) {
22
+ const failedRowIds = task.matrixRows
23
+ .filter((row) => row && row.status === "failed")
24
+ .map((row) => row.rowId)
25
+ .filter(Boolean);
26
+ lines.push("", ` Matrix rows (${task.taskId}):`);
27
+ for (const row of task.matrixRows) {
28
+ if (!row || typeof row !== "object") continue;
29
+ const status = String(row.status ?? "pending");
30
+ const exit = row.exitCode != null ? ` exit=${row.exitCode}` : "";
31
+ const commit = typeof row.commitSha === "string" && row.commitSha ? ` @ ${row.commitSha.slice(0, 8)}` : "";
32
+ lines.push(` ${row.rowId}: ${status}${exit}${commit}`);
33
+ }
34
+ if (failedRowIds.length > 0) {
35
+ lines.push(
36
+ ` → Retry one failed row: spine batch retry '${task.taskId}[${failedRowIds[0]}]'`,
37
+ );
38
+ }
39
+ const cancellable = task.matrixRows.some(
40
+ (row) => row && row.status !== "succeeded" && row.status !== "canceled",
41
+ );
42
+ if (cancellable) {
43
+ lines.push(
44
+ ` → Cancel one row: spine batch skip '${task.taskId}[<rowId>]' (whole matrix: spine batch skip ${task.taskId})`,
45
+ );
46
+ }
47
+ }
48
+ }
49
+
7
50
  /**
8
51
  * @param {object} options
9
52
  * @param {string} options.projectRoot
@@ -37,8 +80,26 @@ export function runSpineStatus(options) {
37
80
  lines.push(` Macro phase: ${result.macroPhaseLabel ?? result.macroPhase}`);
38
81
  }
39
82
 
40
- lines.push("", ` ${result.headline}`, "");
41
- lines.push(` → ${result.suggestedCommand}`);
83
+ if (diagnose && result.headline != null) {
84
+ // SBAR handoff layout (#278 / SP-745): Situation → Background → Assessment → Recommendation.
85
+ lines.push("", ` Situation: ${result.headline}`);
86
+ if (result.background?.length) {
87
+ lines.push("", " Background:");
88
+ for (const fact of result.background) {
89
+ lines.push(` • ${fact}`);
90
+ }
91
+ }
92
+ if (result.assessmentReason) {
93
+ lines.push("", ` Assessment: ${result.diagnosis} — ${result.assessmentReason}`);
94
+ }
95
+ lines.push("");
96
+ lines.push(` Recommendation: ${result.suggestedCommand}`);
97
+ } else {
98
+ lines.push("", ` ${result.headline}`, "");
99
+ lines.push(` → ${result.suggestedCommand}`);
100
+ }
101
+
102
+ appendMatrixRowSections(lines, result);
42
103
 
43
104
  if (diagnose && result.mergeFailed) {
44
105
  lines.push("");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.18.0",
3
+ "version": "2.20.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -15,8 +15,11 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
15
15
 
16
16
  ## Review Level: [0-3] ([None | Plan Only | Plan and Code | Full])
17
17
 
18
- **Assessment:** [1-2 sentences explaining the score]
18
+ **Risk:** [1-2 sentences: severity/blast radius — what breaks and how far the change reaches]
19
19
  **Score:** [N]/8 — Blast radius: [N], Pattern novelty: [N], Security: [N], Reversibility: [N]
20
+ **Problem theory:** [Optional, bug-fix tasks — working diagnosis: why the fault occurs and why this change resolves it]
21
+
22
+ > **Assessment disambiguation ([#281](https://github.com/beettlle/pi-spine/issues/281)):** Use `**Risk:**` for severity/blast (pairs with **Score**) and `**Problem theory:**` for the working diagnosis. Legacy `**Assessment:**` alone remains accepted by tooling and validators — do not mass-rewrite historical packets.
20
23
 
21
24
  > **Real-pi batches (SP-195/SP-278):** Do **not** add per-step "Call `spine_review_step`" checkboxes for Review Level ≥ 1. The batch engine runs plan, code, and final reviews after worker `.DONE`. Stub batches (`SPINE_WORKER_STUB=1`) may still use in-worker stub plan review via the tool when a checkpoint marker requires it.
22
25
 
@@ -180,6 +183,18 @@ for this task MUST include the task ID for traceability:
180
183
 
181
184
  ---
182
185
 
186
+ ## Example — Review Level block fields ([#281](https://github.com/beettlle/pi-spine/issues/281))
187
+
188
+ Use unambiguous field names: `**Risk:**` for severity/blast (pairs with **Score**), `**Problem theory:**` for the working diagnosis. Legacy `**Assessment:**` alone remains valid — do not mass-rewrite historical packets.
189
+
190
+ ```markdown
191
+ **Risk:** Docs and templates only; no runtime code paths touched.
192
+ **Score:** 1/8 — Blast radius: 1, Pattern novelty: 0, Security: 0, Reversibility: 0
193
+ **Problem theory:** The `Assessment` field was overloaded — packets used it for score blurbs and fault theories interchangeably, so workers could not tell severity from diagnosis.
194
+ ```
195
+
196
+ ---
197
+
183
198
  # STATUS.md Template
184
199
 
185
200
  Create alongside PROMPT.md. If omitted, the execution engine may auto-generate
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Contract testCommand execution, npm guard, and verifyContract (SP-603 / SP-541).
4
3
  */
@@ -29,7 +28,7 @@ import {
29
28
  import { formatRefusedContractMetacharMessage, isRefusedContractMetacharCommand } from "../tasks/packet/parse-prompt.mjs";
30
29
 
31
30
  // Shared pre-spawn refusal envelope for the npm-scope (#187) and metachar (#268) guards.
32
- function refusedBeforeSpawnResult(summary) {
31
+ function refusedBeforeSpawnResult(/** @type {string} */ summary) {
33
32
  return { ok: false, exitCode: 1, output: summary, summary, refusedBeforeSpawn: true };
34
33
  }
35
34
 
@@ -147,12 +146,11 @@ function formatRefusedNpmTestDashDashMessage(command) {
147
146
  return `Contract testCommand refused before spawn: npm test -- <path> is blocked at runtime (command: ${command}). ${TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT}`;
148
147
  }
149
148
 
150
- /**
151
-
152
149
  /**
153
150
  * @param {string} worktreePath
154
151
  * @param {string} command
155
152
  * @param {{ maxBuffer?: number }} [options]
153
+ * @returns {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean }}
156
154
  */
157
155
  export function runContractTestCommand(worktreePath, command, options = {}) {
158
156
  const trimmed = String(command ?? "").trim();
@@ -183,7 +181,7 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
183
181
  const stderr = String(result.stderr ?? "");
184
182
  const output = `${stdout}\n${stderr}`;
185
183
 
186
- if (result.error?.code === "ENOBUFS") {
184
+ if (/** @type {NodeJS.ErrnoException | undefined} */ (result.error)?.code === "ENOBUFS") {
187
185
  const limitLabel = formatMaxBufferLabel(maxBuffer);
188
186
  return {
189
187
  ok: false,
@@ -204,8 +202,7 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
204
202
  }
205
203
 
206
204
  /**
207
- * @param {string} worktreePath
208
- * @param {object} config
205
+ * @param {{ testing?: { test?: string, testWithCoverage?: string } }} [config]
209
206
  */
210
207
  function resolveCoverageCommand(config) {
211
208
  return (
@@ -260,7 +257,7 @@ function findArtifactMatch(worktreePath, artifactPattern) {
260
257
  /** @type {Array<{ abs: string, rel: string }>} */
261
258
  const stack = [{ abs: searchRoot, rel: baseDir === "." ? "" : baseDir }];
262
259
  while (stack.length > 0) {
263
- const { abs, rel } = stack.pop();
260
+ const { abs, rel } = /** @type {{ abs: string, rel: string }} */ (stack.pop());
264
261
  for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
265
262
  const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
266
263
  const entryAbs = path.join(abs, entry.name);
@@ -306,6 +303,9 @@ export function prepareContractVerifyEnvironment(worktreePath, parsedContract, c
306
303
  * @param {string} [config.batchId] Batch ID for journal events (optional).
307
304
  * @param {string} [config.taskId] Task ID for journal events (optional).
308
305
  * @param {string} [config.taskFolder] Task folder path for writing failure logs to .reviews/ (optional).
306
+ * @param {{ testRetries?: number, testRetryDelayMs?: number }} [config.contract] Retry tuning for testCommand attempts.
307
+ * @param {number} [config.contractTestMaxBuffer] stdout/stderr capture limit override.
308
+ * @param {{ test?: string, testWithCoverage?: string }} [config.testing] Coverage command selection.
309
309
  * @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }}
310
310
  */
311
311
  export function verifyContract(worktreePath, parsedContract, config = {}) {
@@ -315,7 +315,8 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
315
315
  const sinceCommit = config?.sinceCommit ?? config?.taskStartCommit ?? undefined;
316
316
  const committedFiles = listChangedFiles(worktreePath, baseBranch, sinceCommit);
317
317
 
318
- let indexAndWorktreeFiles = [];
318
+ /** @type {string[]} */
319
+ let indexAndWorktreeFiles = /** @type {string[]} */ ([]);
319
320
  try {
320
321
  const stdout = execFileSync("git", ["diff", "--name-only", "HEAD"], { cwd: worktreePath, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
321
322
  indexAndWorktreeFiles = stdout.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
@@ -334,8 +335,7 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
334
335
  const maxRetries = config?.contract?.testRetries ?? CONTRACT_TEST_DEFAULT_RETRIES;
335
336
  const retryDelayMs = config?.contract?.testRetryDelayMs ?? CONTRACT_TEST_RETRY_DELAY_MS;
336
337
  const totalAttempts = maxRetries + 1;
337
- let lastResult = null;
338
- let successAttempt = 0;
338
+ let lastResult = /** @type {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean } | null} */ (null), successAttempt = 0;
339
339
 
340
340
  for (let attempt = 1; attempt <= totalAttempts; attempt++) {
341
341
  lastResult = runContractTestCommand(worktreePath, parsedContract.testCommand, {
@@ -369,19 +369,20 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
369
369
  }
370
370
  }
371
371
 
372
- testCommandOutput = lastResult.output;
373
- testCommandOk = lastResult.ok;
372
+ const finalResult = /** @type {{ ok: boolean, exitCode: number, output: string, bufferOverflow?: boolean, summary?: string, refusedBeforeSpawn?: boolean }} */ (lastResult);
373
+ testCommandOutput = finalResult.output;
374
+ testCommandOk = finalResult.ok;
374
375
  const attemptLabel = successAttempt > 1
375
376
  ? ` (passed on attempt ${successAttempt} of ${totalAttempts})`
376
377
  : "";
377
378
  checks.push({
378
379
  field: "testCommand",
379
- ok: lastResult.ok,
380
- message: lastResult.ok
380
+ ok: finalResult.ok,
381
+ message: finalResult.ok
381
382
  ? `testCommand passed${attemptLabel}`
382
- : lastResult.bufferOverflow
383
- ? `Contract ${lastResult.summary}`
384
- : `Contract testCommand failed after ${totalAttempts} attempt(s) (exit ${lastResult.exitCode}): ${lastResult.summary || "(no output)"}`,
383
+ : finalResult.bufferOverflow
384
+ ? `Contract ${finalResult.summary}`
385
+ : `Contract testCommand failed after ${totalAttempts} attempt(s) (exit ${finalResult.exitCode}): ${finalResult.summary || "(no output)"}`,
385
386
  });
386
387
  }
387
388
 
@@ -0,0 +1,148 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Diagnose handoff packet fields (#278 / SP-745) — SBAR Background + Assessment rationale.
4
+ * Kept out of diagnosis.mjs so the parent stays under the phase23 LOC cap.
5
+ */
6
+
7
+ /**
8
+ * SBAR Background — short decision-relevant facts that explain the state the
9
+ * assessment was derived from. Facts are additive; consumers that ignore
10
+ * unknown fields keep working.
11
+ *
12
+ * @param {string} diagnosis
13
+ * @param {object} ctx
14
+ * @returns {string[]}
15
+ */
16
+ export function buildBackground(diagnosis, ctx = {}) {
17
+ const facts = [];
18
+ if (ctx.batchId) {
19
+ facts.push(`Batch: ${ctx.batchId}`);
20
+ }
21
+ if (ctx.phase || ctx.macroPhase) {
22
+ facts.push(`Phase: ${ctx.phase ?? "unknown"}${ctx.macroPhase ? ` (macro: ${ctx.macroPhase})` : ""}`);
23
+ }
24
+ if (ctx.totalTasks != null) {
25
+ const progressBits = [`${ctx.succeededTasks ?? 0}/${ctx.totalTasks} tasks succeeded`];
26
+ if (ctx.failedTasks) progressBits.push(`${ctx.failedTasks} failed`);
27
+ if (ctx.pendingTaskCount) progressBits.push(`${ctx.pendingTaskCount} pending`);
28
+ facts.push(`Progress: ${progressBits.join(", ")}`);
29
+ }
30
+ if (ctx.failedTaskId) {
31
+ facts.push(
32
+ `Failed task: ${ctx.failedTaskId}${ctx.exitReason ? ` (exit: ${ctx.exitReason})` : ""}`,
33
+ );
34
+ }
35
+ if (ctx.launchFailureKind) {
36
+ facts.push(`Launch failure kind: ${ctx.launchFailureKind}`);
37
+ }
38
+ if (ctx.engineStillRunning === true && ctx.enginePid != null) {
39
+ facts.push(`Engine PID ${ctx.enginePid} is still running`);
40
+ }
41
+ if (ctx.staleEnginePid === true && ctx.enginePid != null) {
42
+ facts.push(`Engine PID ${ctx.enginePid} is stale (process not alive)`);
43
+ }
44
+ if (ctx.engineOrphanCause) {
45
+ facts.push(`Engine orphan cause: ${ctx.engineOrphanCause}`);
46
+ }
47
+ if (ctx.mergeFailed) {
48
+ facts.push(
49
+ `Lane merge failed${ctx.failedWaveIndex != null ? ` (wave index ${ctx.failedWaveIndex})` : ""}`,
50
+ );
51
+ }
52
+ if (ctx.gitMerged === true) {
53
+ facts.push(`Orch branch already merged to ${ctx.baseBranch ?? "base"}`);
54
+ }
55
+ if (ctx.integrateGateOpen === true) {
56
+ facts.push("Integrate gate is open");
57
+ }
58
+ if (ctx.salvageRetryCommand) {
59
+ facts.push(`Tried: ${ctx.salvageRetryCommand}`);
60
+ }
61
+ if (Array.isArray(ctx.journalHints)) {
62
+ for (const hint of ctx.journalHints) {
63
+ if (typeof hint === "string") {
64
+ facts.push(`Journal: ${hint}`);
65
+ } else if (hint && typeof hint === "object" && (hint.summary || hint.type)) {
66
+ facts.push(`Journal: ${hint.type ?? "event"}${hint.summary ? ` — ${hint.summary}` : ""}`);
67
+ }
68
+ }
69
+ }
70
+ return facts;
71
+ }
72
+
73
+ /**
74
+ * SBAR Assessment rationale — why this diagnosis enum was selected from
75
+ * reconcile signals, not just its label.
76
+ *
77
+ * @param {string} diagnosis
78
+ * @param {object} ctx
79
+ * @returns {string}
80
+ */
81
+ export function buildAssessmentReason(diagnosis, ctx = {}) {
82
+ switch (diagnosis) {
83
+ case "engine_still_running":
84
+ return `Engine PID ${ctx.enginePid ?? "?"} is alive, so completion was refused to avoid clobbering an active run`;
85
+ case "limbo_stale":
86
+ return "Batch ended but state is stale and no engine or worker is active — only a dismiss can clear it";
87
+ case "completed_manual":
88
+ return "Work is already on the base branch while the batch record is still active — operator completed it manually";
89
+ case "needs_retry":
90
+ if (ctx.failedTaskId && ctx.exitReason) {
91
+ return `Task ${ctx.failedTaskId} exited "${ctx.exitReason}" without completing its contract, so the batch cannot proceed until it is retried`;
92
+ }
93
+ if (ctx.failedTaskId) {
94
+ return `Worker for task ${ctx.failedTaskId} died before writing .DONE, so the batch cannot proceed until it is retried`;
95
+ }
96
+ return "Failed phase left only pending tasks with no live workers — retry limbo resolves as a retry";
97
+ case "state_drift":
98
+ return ctx.failedTaskId
99
+ ? `Journal history for task ${ctx.failedTaskId} disagrees with the batch-state cache — no single source of truth`
100
+ : "Journal history disagrees with the batch-state cache — no single source of truth";
101
+ case "worker_orphaned":
102
+ if (ctx.engineDead) {
103
+ return `Engine and lane worker both died while task ${ctx.failedTaskId ?? "?"} was still running`;
104
+ }
105
+ if (ctx.ghostRunningCluster) {
106
+ return `Lane worker died but multiple tasks are still marked running (ghost running cluster)${ctx.failedTaskId ? `, e.g. ${ctx.failedTaskId}` : ""}`;
107
+ }
108
+ return `Lane worker stopped while task ${ctx.failedTaskId ?? "?"} was still marked running — heartbeats ended without a terminal journal event`;
109
+ case "worker_done_missing":
110
+ return `Task ${ctx.failedTaskId ?? "?"} reported progress in the journal but no .DONE file was found in the lane or batch tasks root`;
111
+ case "engine_orphaned":
112
+ if (ctx.engineOrphanCause) {
113
+ return `Engine process is gone (${ctx.engineOrphanCause}) while tasks were still running`;
114
+ }
115
+ return `Engine process died mid-run${ctx.failedTaskId ? ` with task ${ctx.failedTaskId} still running` : ""} — journal has no engine shutdown event`;
116
+ case "needs_merge":
117
+ return "All assigned tasks finished in their lanes, but lane merges into the orch branch are still pending";
118
+ case "needs_integrate":
119
+ if (ctx.integrateGateOpen) {
120
+ return "Land loop is paused at the integrate gate with the gate open — approval continues the land";
121
+ }
122
+ return `Tasks are terminal-success and merged to the orch branch, which is not yet integrated into ${ctx.baseBranch ?? "base"}`;
123
+ case "needs_replan":
124
+ return ctx.failedTaskId
125
+ ? `Task ${ctx.failedTaskId} failed in a way that requires a contract (PROMPT.md) change, not just a retry`
126
+ : "Failed tasks require a contract (PROMPT.md) change, not just a retry";
127
+ case "running":
128
+ return "Engine and workers are alive with no failure, drift, or orphan signals observed";
129
+ case "paused":
130
+ return `Batch was paused by an operator or gate with ${ctx.pendingTaskCount ?? 0} task(s) pending — resume continues from journal state`;
131
+ case "failed":
132
+ return `Batch recorded failure in phase ${ctx.phase ?? "unknown"} (${ctx.failedTasks ?? 0} failed task(s)) with no recoverable retry path`;
133
+ case "aborted":
134
+ return "Batch was aborted by an operator; state remains for audit";
135
+ case "completed":
136
+ return `All tasks succeeded and the orch branch landed on ${ctx.baseBranch ?? "base"}`;
137
+ case "human_base_diverged": {
138
+ const overlapCount = Array.isArray(ctx.overlapPaths) ? ctx.overlapPaths.length : 0;
139
+ return `Human commits on ${ctx.baseBranch ?? "base"} overlap orch land${overlapCount > 0 ? ` (${overlapCount} path(s))` : ""} — reconciliation needs a human sync decision`;
140
+ }
141
+ case "integrate_isolated_ok":
142
+ return "Isolated integrate landed cleanly; the human checkout only needs a sync with base";
143
+ case "pending_lane_land":
144
+ return "Done-in-lane work is sitting in lane worktrees waiting to be landed";
145
+ default:
146
+ return `Reconcile signals selected "${diagnosis}" for phase ${ctx.phase ?? "unknown"}`;
147
+ }
148
+ }
@@ -0,0 +1,177 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Operator suggestedCommand builders — extracted from diagnosis.mjs for phase23 LOC.
4
+ */
5
+ import { buildWorkerDoneMissingSuggestedCommand } from "./diagnosis-worker-done-missing.mjs";
6
+ import {
7
+ buildFailedPhasePendingOnlySuggestedCommand,
8
+ isFailedPhasePendingOnlyLimbo,
9
+ } from "./diagnosis-retry-limbo.mjs";
10
+ import {
11
+ buildGitignoredMergeRepairCommand,
12
+ shouldPreferPrimaryOverGitignoredHeadline,
13
+ } from "./diagnosis-merge-failure.mjs";
14
+ import {
15
+ buildStubFailureSuggestedCommand,
16
+ STUB_EXIT_REASONS,
17
+ } from "./diagnosis-stub.mjs";
18
+ import { buildPrimaryFailureSuggestedCommand } from "./diagnosis-primary-failure.mjs";
19
+ import { buildEngineOrphanParentExitSuggestedCommand } from "./diagnosis-parent-exit.mjs";
20
+ import { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
21
+ import { buildPendingLaneLandSuggestedCommand } from "./diagnosis-pending-lane.mjs";
22
+
23
+ /**
24
+ * @param {string} diagnosis
25
+ * @param {object} [ctx]
26
+ * @param {string|null} [ctx.failedTaskId]
27
+ * @param {string|null} [ctx.batchId]
28
+ * @param {string|null} [ctx.salvageRetryCommand]
29
+ * @param {string|null} [ctx.exitReason]
30
+ * @param {string|null} [ctx.launchFailureKind]
31
+ * @param {boolean} [ctx.mergeGitignoredFailure]
32
+ * @param {boolean} [ctx.mergeFailed]
33
+ * @param {string|null} [ctx.taskBranch]
34
+ * @param {string[]|null} [ctx.gitignoredPaths]
35
+ * @param {object[]} [ctx.pendingLaneLandTasks]
36
+ */
37
+ export function buildSuggestedCommand(diagnosis, ctx = {}) {
38
+ const preferPrimaryOverGitignored = shouldPreferPrimaryOverGitignoredHeadline(diagnosis, ctx);
39
+ // Prefer gate-approve / orphan primary over recovered merge/gitignored repair (#195 / #205).
40
+ if (ctx.mergeGitignoredFailure && !preferPrimaryOverGitignored) {
41
+ return buildGitignoredMergeRepairCommand(ctx.taskBranch, ctx.gitignoredPaths);
42
+ }
43
+ if (
44
+ ctx.mergeFailed &&
45
+ !preferPrimaryOverGitignored &&
46
+ (diagnosis === "failed" || diagnosis === "needs_retry")
47
+ ) {
48
+ return "spine batch resume --force";
49
+ }
50
+ if (ctx.phase === "merge_blocked") {
51
+ return "spine batch resume --force";
52
+ }
53
+
54
+ switch (diagnosis) {
55
+ case "engine_still_running":
56
+ return "spine wait --until completed,failed,needs_integrate --timeout 2h";
57
+ case "limbo_stale":
58
+ case "completed_manual":
59
+ return "spine batch dismiss";
60
+ case "state_drift":
61
+ // Agent-safe detached recovery (#196 / SP-613) — never suggest --attached.
62
+ if (
63
+ ctx.phase === "running" ||
64
+ ctx.staleEnginePid === true ||
65
+ ctx.engineDead === true ||
66
+ ctx.allTasksTerminalSuccess === true
67
+ ) {
68
+ return "spine batch resume --force";
69
+ }
70
+ if (ctx.failedTaskId) {
71
+ const driftStatus = String(ctx.driftTaskStatus ?? "").toLowerCase();
72
+ if (driftStatus === "running") {
73
+ return "spine batch resume --force";
74
+ }
75
+ return `spine batch retry ${ctx.failedTaskId}`;
76
+ }
77
+ return "spine status --diagnose";
78
+ case "needs_retry":
79
+ if (STUB_EXIT_REASONS.has(ctx.exitReason ?? "")) {
80
+ return buildStubFailureSuggestedCommand(ctx);
81
+ }
82
+ const primaryCommand = buildPrimaryFailureSuggestedCommand(ctx);
83
+ if (primaryCommand) return primaryCommand;
84
+ if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
85
+ return "spine doctor";
86
+ }
87
+ if (ctx.launchFailureKind === "worktree_unhealthy") {
88
+ return "spine doctor";
89
+ }
90
+ if (ctx.salvageRetryCommand) {
91
+ return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
92
+ }
93
+ if (isFailedPhasePendingOnlyLimbo(ctx)) {
94
+ return buildFailedPhasePendingOnlySuggestedCommand(ctx);
95
+ }
96
+ return ctx.failedTaskId
97
+ ? `spine batch retry ${ctx.failedTaskId}`
98
+ : "spine status --diagnose";
99
+ case "worker_orphaned":
100
+ if (ctx.planReviewNestedSpawnBlocked) {
101
+ if (ctx.stalePathSpine) {
102
+ return ctx.failedTaskId
103
+ ? `node bin/spine.mjs batch retry ${ctx.failedTaskId}`
104
+ : "npm link && spine batch resume --attached";
105
+ }
106
+ if (ctx.failedTaskId) {
107
+ return `spine batch retry ${ctx.failedTaskId}`;
108
+ }
109
+ }
110
+ if (ctx.engineDead) {
111
+ return "spine batch resume --attached --force";
112
+ }
113
+ if (ctx.ghostRunningCluster) return "spine batch abort";
114
+ if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
115
+ return "spine doctor";
116
+ }
117
+ if (ctx.launchFailureKind === "worktree_unhealthy") {
118
+ return "spine doctor";
119
+ }
120
+ if (ctx.salvageRetryCommand) {
121
+ return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
122
+ }
123
+ return ctx.failedTaskId
124
+ ? `spine batch retry ${ctx.failedTaskId}`
125
+ : "spine batch abort";
126
+ case "worker_done_missing":
127
+ return buildWorkerDoneMissingSuggestedCommand(ctx);
128
+ case "engine_orphaned": {
129
+ const parentExitCommand = buildEngineOrphanParentExitSuggestedCommand(ctx);
130
+ if (parentExitCommand) return parentExitCommand;
131
+ // Terminal-success / doneInLane heal with dead engine — detached resume (#196 / #163).
132
+ if (ctx.allTasksTerminalSuccess === true) {
133
+ return "spine batch resume --force";
134
+ }
135
+ return ctx.failedTaskId
136
+ ? `spine batch retry ${ctx.failedTaskId}`
137
+ : "spine batch resume --attached";
138
+ }
139
+ case "needs_merge":
140
+ return "spine batch resume --force";
141
+ case "needs_integrate":
142
+ if (ctx.integrateGateOpen) {
143
+ return "spine gate approve";
144
+ }
145
+ if (ctx.postMergeLimbo && ctx.phase === "running") {
146
+ if (ctx.stalePathSpine) {
147
+ return "node bin/spine.mjs batch resume --attached";
148
+ }
149
+ return "spine batch resume --force";
150
+ }
151
+ return "spine integrate";
152
+ case "needs_replan": {
153
+ const tasksRoot = ctx.tasksRoot ?? "spine-tasks";
154
+ return ctx.failedTaskId
155
+ ? `edit ${tasksRoot}/${ctx.failedTaskId}/PROMPT.md then spine batch retry ${ctx.failedTaskId}`
156
+ : "spine status --diagnose";
157
+ }
158
+ case "running":
159
+ return "/spine-status --diagnose";
160
+ case "paused":
161
+ return "spine batch resume";
162
+ case "failed":
163
+ return "spine status --diagnose";
164
+ case "aborted":
165
+ return "spine batch dismiss";
166
+ case "completed":
167
+ return "spine preflight";
168
+ case "human_base_diverged":
169
+ return "spine sync-base";
170
+ case "integrate_isolated_ok":
171
+ return "spine sync-base";
172
+ case "pending_lane_land":
173
+ return buildPendingLaneLandSuggestedCommand(ctx.batchId, ctx.pendingLaneLandTasks ?? []);
174
+ default:
175
+ return "spine status --diagnose";
176
+ }
177
+ }