pi-spine 2.6.0 → 2.8.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.
@@ -11,6 +11,7 @@ import path from 'node:path';
11
11
  import { isCliEntrypoint } from './spine-cli/shared.mjs';
12
12
  import { loadSpineConfig } from './spine-config.mjs';
13
13
  import { resolveTasksRootPath } from '../src/config/env-overrides.mjs';
14
+ import { missingConfigHint } from '../src/config/missing-config-hint.mjs';
14
15
  import { buildPlan } from '../src/planner/index.mjs';
15
16
  import { formatPlanHuman } from '../src/planner/format-plan.mjs';
16
17
 
@@ -79,7 +80,7 @@ export async function runSpinePlan({
79
80
  const tasksRoot = resolveTasksRootPath(projectRoot, config);
80
81
  if (!tasksRoot) {
81
82
  const err = new Error('Cannot build plan: tasksRoot not configured');
82
- err.suggestedCommand = 'spine init';
83
+ err.suggestedCommand = missingConfigHint(projectRoot).suggestedCommand;
83
84
  throw err;
84
85
  }
85
86
 
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import { c, isCliEntrypoint, writeCommandResult } from './spine-cli/shared.mjs';
10
10
  import { loadSpineConfig } from './spine-config.mjs';
11
11
  import { resolveTasksRootPath } from '../src/config/env-overrides.mjs';
12
+ import { missingConfigHint } from '../src/config/missing-config-hint.mjs';
12
13
  import { analyzeTasksScope } from '../src/tasks/analyze/index.mjs';
13
14
  import {
14
15
  collectPromptValidationFailure,
@@ -188,7 +189,7 @@ export async function runSpineTasksValidate({
188
189
  const tasksRoot = resolveTasksRootPath(projectRoot, config);
189
190
  if (!tasksRoot) {
190
191
  throwTasksValidateError('Cannot validate tasks: tasksRoot not configured', {
191
- suggestedCommand: 'spine init',
192
+ suggestedCommand: missingConfigHint(projectRoot).suggestedCommand,
192
193
  });
193
194
  }
194
195
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.6.0",
3
+ "version": "2.8.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -27,6 +27,20 @@ import { laneDoneMarkerReadyForPromote } from "./journal-rebuild.mjs";
27
27
  import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
28
28
  import { journalHasTaskCompleted } from "./resume-common.mjs";
29
29
 
30
+ /**
31
+ * True when the batch still has in-flight work owned by a live engine.
32
+ * Terminal-success / post-merge limbo batches must remain --force recoverable.
33
+ *
34
+ * @param {object|null|undefined} state
35
+ */
36
+ function batchHasActiveTaskWork(state) {
37
+ const tasks = state?.tasks ?? [];
38
+ return tasks.some((task) => {
39
+ const status = String(task?.status ?? "");
40
+ return status === "running" || status === "pending";
41
+ });
42
+ }
43
+
30
44
  /**
31
45
  * @param {string} projectRoot
32
46
  * @param {string} batchId
@@ -122,9 +136,17 @@ export function releaseResumeHandoffLock(projectRoot, batchId) {
122
136
  }
123
137
  }
124
138
 
139
+ /**
140
+ * Phases where a live recorded enginePid is the single resume/batch owner.
141
+ * Force orphan handoff remains allowed from paused/failed recoveries (SP-434).
142
+ * @type {ReadonlySet<string>}
143
+ */
144
+ const LIVE_RESUME_OWNER_PHASES = new Set(["running", "gating"]);
145
+
125
146
  /**
126
147
  * Reject a second attached engine when resilience.enginePid is alive (SP-434, GitHub #89).
127
148
  * Serialized forced resume handoff when another resume --force is in flight (SP-533, #167).
149
+ * Fail-fast while a live engine already owns a running batch (SP-660, #207).
128
150
  *
129
151
  * @param {object} params
130
152
  * @param {string} params.projectRoot
@@ -139,13 +161,41 @@ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, o
139
161
  }
140
162
 
141
163
  const batchId = String(state.batchId ?? "");
164
+ const fromPhase = String(state.phase ?? "");
165
+ const enginePid = readBatchEnginePid(state);
142
166
  /** @type {(() => void) | undefined} */
143
167
  let releaseResumeLock;
144
168
 
169
+ // Detached resume child already recorded as engine owner — do not re-journal handoff (SP-660).
170
+ if (force && operation === "resume" && enginePid != null && enginePid === process.pid) {
171
+ return { ok: true };
172
+ }
173
+
145
174
  if (force && operation === "resume") {
175
+ // Live owner still driving active task work: refuse a second --force (dual engines).
176
+ // Terminal-success / post-merge limbo (no active task work) stays --force recoverable.
177
+ if (
178
+ enginePid != null &&
179
+ enginePid !== process.pid &&
180
+ isProcessAlive(enginePid) &&
181
+ LIVE_RESUME_OWNER_PHASES.has(fromPhase) &&
182
+ batchHasActiveTaskWork(state)
183
+ ) {
184
+ const output =
185
+ `Batch resume engine already owns this batch (PID ${enginePid}, batch ${batchId}, phase ${fromPhase}).\n` +
186
+ `Wait for that engine to finish, or stop it before starting another resume --force.\n`;
187
+ return {
188
+ ok: false,
189
+ exitCode: 1,
190
+ error: "concurrent_resume_blocked",
191
+ output,
192
+ batchId,
193
+ enginePid,
194
+ };
195
+ }
196
+
146
197
  const lock = tryAcquireResumeHandoffLock(projectRoot, batchId);
147
198
  if (!lock.ok) {
148
- const enginePid = readBatchEnginePid(state);
149
199
  const holderPid = lock.holderPid ?? null;
150
200
  const output =
151
201
  `Another batch resume --force is already in progress (batch ${batchId}` +
@@ -167,12 +217,10 @@ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, o
167
217
  });
168
218
  }
169
219
 
170
- const enginePid = readBatchEnginePid(state);
171
220
  if (enginePid == null || enginePid === process.pid || !isProcessAlive(enginePid)) {
172
221
  return releaseResumeLock ? { ok: true, releaseResumeLock } : { ok: true };
173
222
  }
174
223
 
175
- const fromPhase = String(state.phase ?? "");
176
224
  if (force) {
177
225
  const terminateResult = terminateStaleDetachedEngine({
178
226
  projectRoot,
@@ -3,6 +3,7 @@
3
3
  * Attached batch foreground runner — public facade (SP-343 / #34, SP-348 / #39).
4
4
  * Promote/exit: attached-runner-promote.mjs (SP-586).
5
5
  * Pause/resume reconcile: attached-runner-reconcile.mjs (SP-604).
6
+ * Single resume owner / concurrent force fail-fast: enforceAttachedEngineSingleOwner (SP-660 / #207).
6
7
  */
7
8
 
8
9
  export {
@@ -269,60 +269,67 @@ export async function resumeBatchDetached({
269
269
  // wave merge (#196); spawn the attached engine argv in detached mode (no --attached).
270
270
  const argv = buildAttachedBatchResumeArgv({ force });
271
271
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
272
- releaseResumeLock?.();
272
+ // Record the child owner before unlocking so a second resume --force cannot race in (SP-660 / #207).
273
+ persistDetachedEnginePid(projectRoot, enginePid);
273
274
  const waitTimeoutMs = resolveDetachedWaitTimeoutMs(waitTerminal);
274
- const wait = await waitForDetachedBatchResume({
275
- projectRoot,
276
- batchId,
277
- updatedAtBefore: updatedAt,
278
- taskId,
279
- waitTerminal,
280
- timeoutMs: waitTimeoutMs,
281
- });
275
+ try {
276
+ const wait = await waitForDetachedBatchResume({
277
+ projectRoot,
278
+ batchId,
279
+ updatedAtBefore: updatedAt,
280
+ taskId,
281
+ waitTerminal,
282
+ timeoutMs: waitTimeoutMs,
283
+ });
284
+
285
+ if (!wait.ok) {
286
+ /** @type {Record<string, unknown>} */
287
+ const payload = {
288
+ ok: false,
289
+ detached: true,
290
+ operation: "resume",
291
+ batchId,
292
+ taskId,
293
+ enginePid,
294
+ logPath,
295
+ error: wait.error,
296
+ lastError: wait.lastError ?? null,
297
+ output:
298
+ wait.error === "timeout_waiting_for_resume"
299
+ ? "Engine may still be running or orphaned — run `spine status --diagnose`."
300
+ : `Batch resume failed (phase=${wait.phase ?? "unknown"}).`,
301
+ suggestedCommand: "spine status --diagnose",
302
+ };
303
+ attachDetachedFailureDiagnostics(payload, { projectRoot, batchId, taskId, logPath });
304
+ return {
305
+ ok: false,
306
+ exitCode: 1,
307
+ output: formatDetachedEngineOutput(payload, json),
308
+ result: payload,
309
+ };
310
+ }
282
311
 
283
- if (!wait.ok) {
284
- /** @type {Record<string, unknown>} */
285
312
  const payload = {
286
- ok: false,
313
+ ok: true,
287
314
  detached: true,
288
315
  operation: "resume",
289
- batchId,
316
+ status: wait.status ?? "engine_started",
317
+ batchId: wait.batchId,
290
318
  taskId,
319
+ phase: wait.phase,
291
320
  enginePid,
292
321
  logPath,
293
- error: wait.error,
294
- lastError: wait.lastError ?? null,
295
- output:
296
- wait.error === "timeout_waiting_for_resume"
297
- ? "Engine may still be running or orphaned — run `spine status --diagnose`."
298
- : `Batch resume failed (phase=${wait.phase ?? "unknown"}).`,
299
322
  suggestedCommand: "spine status --diagnose",
300
323
  };
301
- attachDetachedFailureDiagnostics(payload, { projectRoot, batchId, taskId, logPath });
302
324
  return {
303
- ok: false,
304
- exitCode: 1,
325
+ ok: true,
326
+ exitCode: 0,
305
327
  output: formatDetachedEngineOutput(payload, json),
306
328
  result: payload,
307
329
  };
330
+ } finally {
331
+ // Hold the handoff lock across spawn+wait so paired attached/detached shells cannot
332
+ // start a second --force while this owner is taking ownership (SP-660 / #207).
333
+ releaseResumeLock?.();
308
334
  }
309
-
310
- const payload = {
311
- ok: true,
312
- detached: true,
313
- operation: "resume",
314
- status: wait.status ?? "engine_started",
315
- batchId: wait.batchId,
316
- taskId,
317
- phase: wait.phase,
318
- enginePid,
319
- logPath,
320
- suggestedCommand: "spine status --diagnose",
321
- };
322
- return {
323
- ok: true,
324
- exitCode: 0,
325
- output: formatDetachedEngineOutput(payload, json),
326
- result: payload,
327
- };
328
335
  }
@@ -3,6 +3,7 @@
3
3
  * Detached batch engine spawn — default for `spine batch start` and `spine batch resume`.
4
4
  * Thin re-export shim (SP-598): spawn → detached-spawn, diagnostics → detached-diagnostics,
5
5
  * wait/run → detached-wait + detached-run.
6
+ * Resume path holds handoff lock across spawn+wait and persists child enginePid (SP-660 / #207).
6
7
  */
7
8
 
8
9
  export {
@@ -7,9 +7,31 @@ import {
7
7
  isGitignoredArtifactPath,
8
8
  listGitignoredArtifactRoots,
9
9
  } from "./lane-dirty-check.mjs";
10
+ import { isGateReadyHeadlineContext } from "./diagnosis-gate-ready.mjs";
10
11
 
11
12
  const GITIGNORED_MERGE_FAILURE_CLASSES = new Set(["merge_failed_gitignored", "GitignoredDirtyWorktree"]);
12
13
 
14
+ /** Diagnoses that outrank historical GitignoredDirtyWorktree / merge-gitignored remediation (#205). */
15
+ const PRIMARY_OVER_GITIGNORED_DIAGNOSES = new Set(["worker_orphaned", "engine_orphaned"]);
16
+
17
+ /**
18
+ * Prefer gate-ready / orphan (latest primary failure) over stale gitignored merge headlines (#195 / #205).
19
+ * Keep mergeGitignoredFailure in diagnose signals; only demote the headline/command preference.
20
+ *
21
+ * @param {string} diagnosis
22
+ * @param {object} [ctx]
23
+ * @returns {boolean}
24
+ */
25
+ export function shouldPreferPrimaryOverGitignoredHeadline(diagnosis, ctx = {}) {
26
+ if (isGateReadyHeadlineContext(diagnosis, ctx)) {
27
+ return true;
28
+ }
29
+ if (PRIMARY_OVER_GITIGNORED_DIAGNOSES.has(diagnosis)) {
30
+ return true;
31
+ }
32
+ return false;
33
+ }
34
+
13
35
  /**
14
36
  * @param {object} [ctx]
15
37
  * @param {string|null} [ctx.exitReason]
@@ -16,11 +16,13 @@ export { buildAlternatives } from "./diagnosis-alternatives.mjs";
16
16
  import {
17
17
  buildMergeFailureHeadline,
18
18
  buildGitignoredMergeRepairCommand,
19
+ shouldPreferPrimaryOverGitignoredHeadline,
19
20
  } from "./diagnosis-merge-failure.mjs";
20
21
  export {
21
22
  buildMergeFailureHeadline,
22
23
  buildGitignoredMergeRepairCommand,
23
24
  inferMergeGitignoredFailure,
25
+ shouldPreferPrimaryOverGitignoredHeadline,
24
26
  summarizeMergeFailures,
25
27
  } from "./diagnosis-merge-failure.mjs";
26
28
  import { buildRunningTailHeadline, isPostIntegrateEngineLimbo, buildPostIntegrateEngineLimboHeadline } from "./diagnosis-tail-state.mjs";
@@ -126,14 +128,14 @@ const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
126
128
  * @param {object[]} [ctx.pendingLaneLandTasks]
127
129
  */
128
130
  export function buildSuggestedCommand(diagnosis, ctx = {}) {
129
- const preferGateReady = isGateReadyHeadlineContext(diagnosis, ctx);
130
- // Prefer gate-approve / land-loop next step over recovered merge/gitignored repair (#195).
131
- if (ctx.mergeGitignoredFailure && !preferGateReady) {
131
+ const preferPrimaryOverGitignored = shouldPreferPrimaryOverGitignoredHeadline(diagnosis, ctx);
132
+ // Prefer gate-approve / orphan primary over recovered merge/gitignored repair (#195 / #205).
133
+ if (ctx.mergeGitignoredFailure && !preferPrimaryOverGitignored) {
132
134
  return buildGitignoredMergeRepairCommand(ctx.taskBranch, ctx.gitignoredPaths);
133
135
  }
134
136
  if (
135
137
  ctx.mergeFailed &&
136
- !preferGateReady &&
138
+ !preferPrimaryOverGitignored &&
137
139
  (diagnosis === "failed" || diagnosis === "needs_retry")
138
140
  ) {
139
141
  return "spine batch resume --force";
@@ -291,16 +293,16 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
291
293
  */
292
294
  export function buildHeadline(diagnosis, ctx = {}) {
293
295
  const batchLabel = ctx.batchId ? `Batch ${ctx.batchId}` : "Batch";
294
- const preferGateReady = isGateReadyHeadlineContext(diagnosis, ctx);
296
+ const preferPrimaryOverGitignored = shouldPreferPrimaryOverGitignoredHeadline(diagnosis, ctx);
295
297
 
296
- // Historical merge/gitignored signals stay in diagnose signals — not the primary headline (#195).
297
- if (ctx.mergeGitignoredFailure && !preferGateReady) {
298
+ // Historical merge/gitignored signals stay in diagnose signals — not the primary headline (#195 / #205).
299
+ if (ctx.mergeGitignoredFailure && !preferPrimaryOverGitignored) {
298
300
  return `${batchLabel} merge blocked by gitignored paths on a lane branch — drop cached ignored files, then resume`;
299
301
  }
300
302
 
301
303
  if (
302
304
  ctx.mergeFailed &&
303
- !preferGateReady &&
305
+ !preferPrimaryOverGitignored &&
304
306
  (diagnosis === "failed" || diagnosis === "needs_retry")
305
307
  ) {
306
308
  return buildMergeFailureHeadline(batchLabel, ctx);
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Safe argv execution for config-derived integrate-gate evidence commands.
3
3
  * Allowlisted executables only; rejects shell metacharacters (no shell: true).
4
+ * Phase B: allowlisted package-manager segments may be joined with `&&` only.
4
5
  */
5
6
 
6
7
  import path from "node:path";
@@ -28,6 +29,10 @@ const PROJECT_LOCAL_VENV_PREFIXES = [".venv/", "venv/"];
28
29
  /** Relative prefix for validated gate-evidence scripts (posix-normalized). */
29
30
  const EVIDENCE_SCRIPTS_PREFIX = "scripts/";
30
31
 
32
+ /**
33
+ * Forbidden shell metacharacters. Checked after stripping allowlisted `&&`
34
+ * chain separators so a lone `&` still fails closed.
35
+ */
31
36
  const SHELL_METACHAR_PATTERN = /[;|&`<>]|>>|\$\(|\$\{/;
32
37
 
33
38
  export class EvidenceCommandError extends Error {
@@ -52,22 +57,113 @@ export function assertSafeEvidenceCommand(command) {
52
57
  if (/[\r\n]/.test(trimmed)) {
53
58
  throw new EvidenceCommandError("evidence command contains newlines");
54
59
  }
55
- if (SHELL_METACHAR_PATTERN.test(trimmed)) {
60
+
61
+ // Allow `&&` as the only chain operator; strip it before metachar / `$` scans.
62
+ const withoutChains = trimmed.replaceAll("&&", " ");
63
+ if (SHELL_METACHAR_PATTERN.test(withoutChains)) {
56
64
  throw new EvidenceCommandError("evidence command contains shell metacharacters");
57
65
  }
58
- if (/\$/.test(trimmed)) {
66
+ if (/\$/.test(withoutChains)) {
59
67
  throw new EvidenceCommandError("evidence command contains shell variable expansion");
60
68
  }
61
69
  }
62
70
 
71
+ /**
72
+ * Split an evidence command on `&&` outside quotes (Phase B chain grammar).
73
+ * @param {string} line
74
+ * @returns {string[]}
75
+ */
76
+ function splitEvidenceChainSegments(line) {
77
+ /** @type {string[]} */
78
+ const segments = [];
79
+ let current = "";
80
+ /** @type {"'" | '"' | null} */
81
+ let quote = null;
82
+
83
+ for (let i = 0; i < line.length; i++) {
84
+ const ch = line[i];
85
+ if (quote) {
86
+ // Preserve escapes so tokenizeCommandLine can re-parse the segment.
87
+ if (ch === "\\" && quote === '"' && i + 1 < line.length) {
88
+ current += ch;
89
+ i += 1;
90
+ current += line[i];
91
+ continue;
92
+ }
93
+ current += ch;
94
+ if (ch === quote) {
95
+ quote = null;
96
+ }
97
+ continue;
98
+ }
99
+
100
+ if (ch === "'" || ch === '"') {
101
+ quote = ch;
102
+ current += ch;
103
+ continue;
104
+ }
105
+
106
+ if (ch === "&" && line[i + 1] === "&") {
107
+ segments.push(current.trim());
108
+ current = "";
109
+ i += 1;
110
+ continue;
111
+ }
112
+
113
+ current += ch;
114
+ }
115
+
116
+ if (quote) {
117
+ throw new EvidenceCommandError("unclosed quote in evidence command");
118
+ }
119
+
120
+ segments.push(current.trim());
121
+ return segments;
122
+ }
123
+
124
+ /**
125
+ * Parse a config testing command into one or more argv arrays without a shell.
126
+ * Multi-segment results are allowlisted `&&` chains (Phase B).
127
+ * @param {string} command
128
+ * @returns {string[][]}
129
+ */
130
+ export function parseEvidenceCommandChain(command) {
131
+ assertSafeEvidenceCommand(command);
132
+ const segments = splitEvidenceChainSegments(command.trim());
133
+ if (segments.length === 0) {
134
+ throw new EvidenceCommandError("empty evidence command");
135
+ }
136
+ if (segments.some((segment) => !segment)) {
137
+ throw new EvidenceCommandError("empty evidence command chain segment");
138
+ }
139
+
140
+ const chainMode = segments.length > 1;
141
+ return segments.map((segment) => parseEvidenceSegmentArgv(segment, chainMode));
142
+ }
143
+
63
144
  /**
64
145
  * Parse a config testing command into argv without invoking a shell.
146
+ * Single-segment only; use {@link parseEvidenceCommandChain} for `&&` chains.
65
147
  * @param {string} command
66
148
  * @returns {string[]}
67
149
  */
68
150
  export function parseEvidenceCommandArgv(command) {
69
- assertSafeEvidenceCommand(command);
70
- const argv = tokenizeCommandLine(command.trim());
151
+ const chain = parseEvidenceCommandChain(command);
152
+ if (chain.length !== 1) {
153
+ throw new EvidenceCommandError(
154
+ "evidence command && chains must use parseEvidenceCommandChain or runEvidenceCommand",
155
+ );
156
+ }
157
+ return chain[0];
158
+ }
159
+
160
+ /**
161
+ * @param {string} segment
162
+ * @param {boolean} chainMode
163
+ * @returns {string[]}
164
+ */
165
+ function parseEvidenceSegmentArgv(segment, chainMode) {
166
+ const argv = tokenizeCommandLine(segment);
71
167
  if (argv.length === 0) {
72
168
  throw new EvidenceCommandError("empty evidence command");
73
169
  }
@@ -76,10 +172,13 @@ export function parseEvidenceCommandArgv(command) {
76
172
  if (ALLOWED_EVIDENCE_EXECUTABLES.has(executable)) {
77
173
  return argv;
78
174
  }
79
- if (isAllowedProjectLocalInterpreter(argv[0])) {
175
+
176
+ // Phase A single-segment paths stay available; multi-segment chains are
177
+ // package-manager / node allowlist only (FR-REL270-05).
178
+ if (!chainMode && isAllowedProjectLocalInterpreter(argv[0])) {
80
179
  return argv;
81
180
  }
82
- if (isAllowedEvidenceScriptsPath(argv[0])) {
181
+ if (!chainMode && isAllowedEvidenceScriptsPath(argv[0])) {
83
182
  return argv;
84
183
  }
85
184
 
@@ -247,16 +346,21 @@ export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024)
247
346
  if (!command) return { ok: false, skipped: true, output: "" };
248
347
 
249
348
  try {
250
- const argv = parseEvidenceCommandArgv(command);
251
- const execArgv = resolveEvidenceScriptsArgv(projectRoot, argv);
252
- const output = execFileSync(execArgv[0], execArgv.slice(1), {
253
- cwd: projectRoot,
254
- encoding: "utf-8",
255
- stdio: ["ignore", "pipe", "pipe"],
256
- timeout: 10 * 60 * 1000,
257
- maxBuffer: maxBytes,
258
- });
259
- return { ok: true, skipped: false, output: String(output ?? "") };
349
+ const chain = parseEvidenceCommandChain(command);
350
+ /** @type {string[]} */
351
+ const outputs = [];
352
+ for (const argv of chain) {
353
+ const execArgv = resolveEvidenceScriptsArgv(projectRoot, argv);
354
+ const output = execFileSync(execArgv[0], execArgv.slice(1), {
355
+ cwd: projectRoot,
356
+ encoding: "utf-8",
357
+ stdio: ["ignore", "pipe", "pipe"],
358
+ timeout: 10 * 60 * 1000,
359
+ maxBuffer: maxBytes,
360
+ });
361
+ outputs.push(String(output ?? ""));
362
+ }
363
+ return { ok: true, skipped: false, output: outputs.join("") };
260
364
  } catch (err) {
261
365
  if (err instanceof EvidenceCommandError) {
262
366
  return {
@@ -7,7 +7,12 @@ import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
9
  import { filterGitignoredPaths, gitAddFilteredPaths } from "./git-helpers.mjs";
10
- import { classifyGitignoredPaths, formatGitignoredRemediationMessage } from "./lane-dirty-check.mjs";
10
+ import {
11
+ classifyGitignoredPaths,
12
+ formatGitignoredRemediationMessage,
13
+ isGitignoredArtifactPath,
14
+ sanitizeGitignoredArtifactsBeforeLaneCommit,
15
+ } from "./lane-dirty-check.mjs";
11
16
  import { gitExec } from "./git-exec.mjs";
12
17
  import { parseContract } from "../tasks/packet/parse-prompt.mjs";
13
18
  import {
@@ -263,14 +268,43 @@ export function commitLaneWorktree({
263
268
  worktreePath,
264
269
  stageCandidatePaths,
265
270
  );
266
- const gitignoredPaths = [...new Set([...gitignoredDirtyPaths, ...ignoredUntrackedPaths])];
271
+ let gitignoredPaths = [...new Set([...gitignoredDirtyPaths, ...ignoredUntrackedPaths])];
267
272
  if (stageable.length === 0 && gitignoredPaths.length > 0) {
268
- const { indexTracked, worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredPaths);
273
+ let { indexTracked, worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredPaths);
274
+ // SP-659 / #206: marked artifacts may regenerate after the pre-commit sanitize.
275
+ // Re-clean once before fail-closed GitignoredDirtyWorktree.
276
+ const worktreeOnlyMarkedArtifacts =
277
+ indexTracked.length === 0 &&
278
+ worktreeOnly.length > 0 &&
279
+ worktreeOnly.every((filePath) => isGitignoredArtifactPath(filePath));
280
+ if (worktreeOnlyMarkedArtifacts) {
281
+ sanitizeGitignoredArtifactsBeforeLaneCommit(worktreePath, {
282
+ projectRoot: identityRoot,
283
+ });
284
+ gitignoredPaths = listIgnoredUntrackedPaths(worktreePath);
285
+ if (gitignoredPaths.length === 0) {
286
+ return {
287
+ ok: true,
288
+ committed: false,
289
+ skippedIgnorePaths,
290
+ skippedGitignoredPaths: [...gitignoredDirtyPaths, ...ignoredUntrackedPaths],
291
+ };
292
+ }
293
+ ({ indexTracked, worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredPaths));
294
+ }
295
+ if (indexTracked.length === 0 && worktreeOnly.length === 0) {
296
+ return {
297
+ ok: true,
298
+ committed: false,
299
+ skippedIgnorePaths,
300
+ skippedGitignoredPaths: gitignoredPaths,
301
+ };
302
+ }
269
303
  return {
270
304
  ok: false,
271
305
  error: formatGitignoredRemediationMessage(indexTracked, worktreeOnly),
272
306
  failureClass: "GitignoredDirtyWorktree",
273
- gitignoredPaths,
307
+ gitignoredPaths: [...indexTracked, ...worktreeOnly],
274
308
  };
275
309
  }
276
310
 
@@ -291,6 +325,10 @@ export function commitLaneWorktree({
291
325
  const message = `feat(${taskId}): batch ${batchId} worker completion`;
292
326
  git(worktreePath, ["commit", "-m", message], identityRoot);
293
327
  const commitSha = git(worktreePath, ["rev-parse", "HEAD"], identityRoot);
328
+ // SP-659 / #206: post-commit hooks may regenerate marked gitignored artifacts.
329
+ sanitizeGitignoredArtifactsBeforeLaneCommit(worktreePath, {
330
+ projectRoot: identityRoot,
331
+ });
294
332
  return {
295
333
  ok: true,
296
334
  committed: true,
@@ -35,6 +35,8 @@ export const GITIGNORED_ARTIFACT_MARKERS = [
35
35
  "graphify-out/",
36
36
  "/.review/",
37
37
  ".review/",
38
+ "/.pi-smart-router/",
39
+ ".pi-smart-router/",
38
40
  "/.spine/runtime/",
39
41
  ".spine/runtime/",
40
42
  ];
@@ -150,6 +152,9 @@ function gitignoredArtifactRootForPath(filePath) {
150
152
  if (normalized === ".review" || normalized.startsWith(".review/")) {
151
153
  return ".review";
152
154
  }
155
+ if (normalized === ".pi-smart-router" || normalized.startsWith(".pi-smart-router/")) {
156
+ return ".pi-smart-router";
157
+ }
153
158
  if (normalized === ".spine/runtime" || normalized.startsWith(".spine/runtime/")) {
154
159
  return ".spine/runtime";
155
160
  }
@@ -58,6 +58,8 @@ export const GITIGNORED_ARTIFACT_MARKERS = [
58
58
  "graphify-out/",
59
59
  "/.review/",
60
60
  ".review/",
61
+ "/.pi-smart-router/",
62
+ ".pi-smart-router/",
61
63
  "/.spine/runtime/",
62
64
  ".spine/runtime/",
63
65
  ];
@@ -273,6 +275,9 @@ function gitignoredArtifactRootForPath(filePath) {
273
275
  if (normalized === ".review" || normalized.startsWith(".review/")) {
274
276
  return ".review";
275
277
  }
278
+ if (normalized === ".pi-smart-router" || normalized.startsWith(".pi-smart-router/")) {
279
+ return ".pi-smart-router";
280
+ }
276
281
  if (normalized === ".spine/runtime" || normalized.startsWith(".spine/runtime/")) {
277
282
  return ".spine/runtime";
278
283
  }
@@ -1,23 +1,29 @@
1
1
  // @ts-nocheck
2
- /** Orphan reconcile helpers (SP-606 / #192). */
2
+ /** Orphan reconcile helpers (SP-606 / #192). Post-DONE heal: SP-657 / #205. */
3
3
 
4
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
5
+ import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
6
+ import { isProcessAlive } from "../process/liveness.mjs";
7
+ import { classifyTaskDoneSemantics } from "./diagnosis-task-done.mjs";
4
8
  import {
5
9
  appendJournalEvent,
6
10
  readJournalEvents,
7
11
  } from "./journal.mjs";
12
+ import { laneDoneMarkerReadyForPromote } from "./journal-rebuild.mjs";
8
13
  import {
9
14
  detectOrphanRunning,
10
15
  journalEventsSinceResume,
11
16
  } from "./orphan-detect.mjs";
12
- import { isProcessAlive } from "../process/liveness.mjs";
17
+ import { reconcileBatch } from "./reconcile-batch.mjs";
18
+ import { journalHasTaskCompleted } from "./resume-common.mjs";
13
19
  import {
14
20
  clearBatchEnginePid,
15
21
  readBatchEnginePid,
22
+ recordTaskSucceeded,
16
23
  recomputeTaskCounters,
17
24
  saveSpineBatchState,
18
25
  updateSegmentForTask,
19
26
  } from "./state.mjs";
20
- import { reconcileBatch } from "./reconcile-batch.mjs";
21
27
 
22
28
  /**
23
29
  * @param {object} ctx
@@ -71,13 +77,76 @@ function journalHasTaskEvent(journalEvents, taskId, eventType) {
71
77
  });
72
78
  }
73
79
 
80
+ /**
81
+ * True when lane has committed `.DONE` ready for skip-done / skippedDoneOnDisk promote.
82
+ *
83
+ * @param {object} params
84
+ * @param {string} params.projectRoot
85
+ * @param {string} params.batchId
86
+ * @param {object} params.task
87
+ * @param {unknown[]} params.lanes
88
+ * @param {string|null} params.tasksRoot
89
+ */
90
+ function orphanTaskReadyForSkipDoneHeal({ projectRoot, batchId, task, lanes, tasksRoot }) {
91
+ const classified = classifyTaskDoneSemantics(task, {
92
+ tasksRoot,
93
+ projectRoot,
94
+ batchId,
95
+ lanes,
96
+ });
97
+ return laneDoneMarkerReadyForPromote({
98
+ projectRoot,
99
+ batchId,
100
+ task,
101
+ lanes,
102
+ classified,
103
+ });
104
+ }
105
+
106
+ /**
107
+ * Promote a post-DONE orphaned running task via skippedDoneOnDisk semantics
108
+ * (mirrors attached-runner / resume-multi skip-done journal shape).
109
+ *
110
+ * @param {object} params
111
+ * @param {string} params.projectRoot
112
+ * @param {string} params.batchId
113
+ * @param {object} params.state
114
+ * @param {object} params.task
115
+ * @param {object[]} params.journalEvents
116
+ * @returns {boolean}
117
+ */
118
+ function healPostDoneOrphanTask({ projectRoot, batchId, state, task, journalEvents }) {
119
+ const taskId = String(task?.taskId ?? "");
120
+ if (!taskId) return false;
121
+ if (String(task.status ?? "") !== "running") return false;
122
+
123
+ if (!recordTaskSucceeded(state, taskId, { doneFileFound: true, exitReason: "done" })) {
124
+ return false;
125
+ }
126
+
127
+ if (!journalHasTaskCompleted(journalEvents, taskId)) {
128
+ const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
129
+ appendJournalEvent(projectRoot, batchId, "task.completed", {
130
+ taskId,
131
+ laneNumber: task.laneNumber ?? null,
132
+ laneId: lane?.laneId ?? null,
133
+ reconciled: true,
134
+ skippedDoneOnDisk: true,
135
+ });
136
+ }
137
+
138
+ return true;
139
+ }
140
+
74
141
  /**
75
142
  * Transition orphan running tasks to failed so retry/resume paths succeed (SP-315 / #20).
143
+ * When lane `.DONE` is committed (fail-closed promote gate), heal to succeeded with
144
+ * `skippedDoneOnDisk` instead of failing into merge_blocked (SP-657 / #205).
76
145
  *
77
146
  * @param {object} params
78
147
  * @param {string} params.projectRoot
79
148
  * @param {object} params.state
80
- * @returns {{ reconciled: boolean, taskId?: string|null, kind?: string, exitReason?: string }}
149
+ * @returns {{ reconciled: boolean, taskId?: string|null, kind?: string, exitReason?: string, healedTaskIds?: string[] }}
81
150
  */
82
151
  export function reconcileOrphanRunningState({ projectRoot, state }) {
83
152
  if (!state || typeof state !== "object") {
@@ -108,7 +177,7 @@ export function reconcileOrphanRunningState({ projectRoot, state }) {
108
177
 
109
178
  const exitReason = orphanRunning.kind === "engine" ? "engine_orphaned" : "worker_orphaned";
110
179
  /** @type {string[]} */
111
- const taskIdsToFail =
180
+ const taskIdsToConsider =
112
181
  orphanRunning.kind === "lane" && orphanRunning.taskId
113
182
  ? [orphanRunning.taskId]
114
183
  : classifiedTasks
@@ -116,22 +185,55 @@ export function reconcileOrphanRunningState({ projectRoot, state }) {
116
185
  .map((task) => task.taskId)
117
186
  .filter(Boolean);
118
187
 
119
- if (taskIdsToFail.length === 0) {
188
+ if (taskIdsToConsider.length === 0) {
120
189
  return { reconciled: false };
121
190
  }
122
191
 
192
+ const configResult = loadSpineConfig(projectRoot);
193
+ const tasksRoot = resolveTasksRoot(projectRoot, configResult);
194
+ const lanes = state.lanes ?? [];
195
+
123
196
  const now = Date.now();
124
197
  let changed = false;
198
+ /** @type {string[]} */
199
+ const healedTaskIds = [];
200
+ /** @type {string[]} */
201
+ const taskIdsFailed = [];
125
202
 
126
- for (const taskId of taskIdsToFail) {
203
+ for (const taskId of taskIdsToConsider) {
127
204
  const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
128
205
  if (!task || task.status !== "running") continue;
129
206
 
207
+ if (
208
+ orphanTaskReadyForSkipDoneHeal({
209
+ projectRoot,
210
+ batchId,
211
+ task,
212
+ lanes,
213
+ tasksRoot,
214
+ })
215
+ ) {
216
+ if (
217
+ healPostDoneOrphanTask({
218
+ projectRoot,
219
+ batchId,
220
+ state,
221
+ task,
222
+ journalEvents,
223
+ })
224
+ ) {
225
+ healedTaskIds.push(taskId);
226
+ changed = true;
227
+ }
228
+ continue;
229
+ }
230
+
130
231
  task.status = "failed";
131
232
  task.endedAt = now;
132
233
  task.exitReason = exitReason;
133
234
  updateSegmentForTask(state, taskId, "failed");
134
235
  changed = true;
236
+ taskIdsFailed.push(taskId);
135
237
 
136
238
  if (!journalHasTaskEvent(scopedJournalEvents, taskId, "task.failed")) {
137
239
  const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
@@ -179,20 +281,21 @@ export function reconcileOrphanRunningState({ projectRoot, state }) {
179
281
  }
180
282
 
181
283
  recomputeTaskCounters(state);
182
- if (String(state.phase ?? "") === "running") {
284
+ if (taskIdsFailed.length > 0 && String(state.phase ?? "") === "running") {
183
285
  state.phase = "failed";
184
286
  state.endedAt = state.endedAt ?? now;
185
287
  state.lastError =
186
- state.lastError ?? `Orphan reconcile: ${exitReason} (task ${taskIdsToFail.join(", ")})`;
288
+ state.lastError ??
289
+ `Orphan reconcile: ${exitReason} (task ${taskIdsFailed.join(", ")})`;
187
290
  }
188
291
 
189
292
  saveSpineBatchState(projectRoot, state);
190
293
 
191
294
  return {
192
295
  reconciled: true,
193
- taskId: orphanRunning.taskId ?? taskIdsToFail[0] ?? null,
296
+ taskId: orphanRunning.taskId ?? healedTaskIds[0] ?? taskIdsFailed[0] ?? null,
194
297
  kind: orphanRunning.kind,
195
298
  exitReason,
299
+ healedTaskIds,
196
300
  };
197
301
  }
198
-
@@ -1,6 +1,7 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Batch pause and resume for single-lane batches (TP-015, PRD §18.2).
4
+ * Single-owner gate is enforceAttachedEngineSingleOwner (SP-660 / #207).
4
5
  */
5
6
 
6
7
  import path from "node:path";
@@ -0,0 +1,19 @@
1
+ // @ts-check
2
+ import path from "node:path";
3
+
4
+ /**
5
+ * Honest missing-config / wrong-cwd hint (FR-REL270-01 / FR-REL270-02 / #202).
6
+ * Single source of truth for message + suggestedCommand when `.spine/spine-config.json`
7
+ * is absent under the resolved project root.
8
+ *
9
+ * @param {string} projectRoot
10
+ * @returns {{ resolvedRoot: string, message: string, suggestedCommand: string }}
11
+ */
12
+ export function missingConfigHint(projectRoot) {
13
+ const resolvedRoot = path.resolve(projectRoot);
14
+ return {
15
+ resolvedRoot,
16
+ message: `.spine/spine-config.json not found under ${resolvedRoot} (cwd/$PWD). Change to your project root, or run spine init here if this directory should be initialized.`,
17
+ suggestedCommand: `cd ${resolvedRoot} # if wrong directory — or run: spine init`,
18
+ };
19
+ }
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { loadSpineConfig } from "../spine-config-load.mjs";
6
+ import { missingConfigHint } from "../missing-config-hint.mjs";
6
7
  import { resolveTasksRootPath } from "../env-overrides.mjs";
7
8
  import { validateWorktreeSetupHookConfig } from "../worktree-setup-hook.mjs";
8
9
  import { discoverTasks } from "../../tasks/packet/discover.mjs";
@@ -61,7 +62,7 @@ export function checkTasksRoot(ctx) {
61
62
 
62
63
  if (!tasksRootPath) {
63
64
  return makeCheck("tasks-root", false, "tasks root not configured", {
64
- suggestedCommand: "spine init",
65
+ suggestedCommand: missingConfigHint(ctx.projectRoot).suggestedCommand,
65
66
  });
66
67
  }
67
68
 
@@ -108,7 +109,7 @@ export function checkDependenciesJson(ctx) {
108
109
 
109
110
  if (!tasksRootPath) {
110
111
  return makeCheck("dependencies-json", false, "tasks root not configured", {
111
- suggestedCommand: "spine init",
112
+ suggestedCommand: missingConfigHint(ctx.projectRoot).suggestedCommand,
112
113
  });
113
114
  }
114
115
 
@@ -255,15 +256,16 @@ export function checkTasksValidate(ctx) {
255
256
  const config = configResult?.config;
256
257
 
257
258
  if (!config || configResult?.error) {
259
+ const hint = missingConfigHint(projectRoot);
258
260
  return makeCheck("tasks-validate", false, "cannot validate tasks without spine config", {
259
- suggestedCommand: "spine init",
261
+ suggestedCommand: hint.suggestedCommand,
260
262
  });
261
263
  }
262
264
 
263
265
  const tasksRootPath = resolveTasksRoot(projectRoot, configResult);
264
266
  if (!tasksRootPath) {
265
267
  return makeCheck("tasks-validate", false, "tasks root not configured", {
266
- suggestedCommand: "spine init",
268
+ suggestedCommand: missingConfigHint(projectRoot).suggestedCommand,
267
269
  });
268
270
  }
269
271
 
@@ -11,6 +11,7 @@ import { validateWorkerContextConfig } from "./worker-context.mjs";
11
11
  import { validateWorkerLaunchScriptConfig } from "./worker-launch-script.mjs";
12
12
  import { validateWorktreeSetupHookConfig } from "./worktree-setup-hook.mjs";
13
13
  import { validateOrchestratorConfig } from "./spine-config-schema.mjs";
14
+ import { missingConfigHint } from "./missing-config-hint.mjs";
14
15
 
15
16
  export { resolveGatePostureConfig } from "./gate-posture-config.mjs";
16
17
 
@@ -58,13 +59,14 @@ export function loadSpineConfigFile(projectRoot) {
58
59
  const configPath = path.join(projectRoot, ".spine", "spine-config.json");
59
60
 
60
61
  if (!fs.existsSync(configPath)) {
62
+ const hint = missingConfigHint(projectRoot);
61
63
  return {
62
64
  configPath,
63
65
  config: null,
64
66
  error: {
65
67
  code: "CONFIG_MISSING",
66
- message: ".spine/spine-config.json not found",
67
- suggestedCommand: "spine init",
68
+ message: hint.message,
69
+ suggestedCommand: hint.suggestedCommand,
68
70
  },
69
71
  };
70
72
  }
@@ -43,8 +43,12 @@ export const TASKPLANE_COMPAT_TASKS_ROOT = "taskplane-tasks";
43
43
  export const TASKPLANE_COMPAT_PRESET = "taskplane-compat";
44
44
  export const LEGACY_TASKPLANE_PRESET_ALIASES = [TASKPLANE_COMPAT_PRESET];
45
45
 
46
- export const SPINE_INIT_TESTING_COMMAND = "npm run typecheck && npm test";
46
+ /** Phase-A-safe evidence argv (no shell metacharacters); matches templates/spine-config.json. */
47
+ export const SPINE_INIT_BUILD_COMMAND = "npm run typecheck";
48
+ export const SPINE_INIT_TEST_COMMAND = "npm test";
47
49
  export const SPINE_INIT_COVERAGE_COMMAND = "npm run coverage:check";
50
+ /** @deprecated Prefer SPINE_INIT_BUILD_COMMAND / SPINE_INIT_TEST_COMMAND. */
51
+ export const SPINE_INIT_TESTING_COMMAND = SPINE_INIT_TEST_COMMAND;
48
52
 
49
53
  export const SPINE_GITIGNORE_ENTRIES = [
50
54
  ".pi/",
@@ -166,8 +170,8 @@ export function parseInitArgs(args) {
166
170
 
167
171
  /** Apply production-ready defaults for every greenfield init. */
168
172
  export function applySpineInitDefaults(config) {
169
- config.testing.build = SPINE_INIT_TESTING_COMMAND;
170
- config.testing.test = SPINE_INIT_TESTING_COMMAND;
173
+ config.testing.build = SPINE_INIT_BUILD_COMMAND;
174
+ config.testing.test = SPINE_INIT_TEST_COMMAND;
171
175
  config.testing.testWithCoverage = SPINE_INIT_COVERAGE_COMMAND;
172
176
  config.dashboard = { ...(config.dashboard ?? {}), port: 8109 };
173
177
  config.gates = {
@@ -9,8 +9,8 @@
9
9
  },
10
10
  "baseBranch": "main",
11
11
  "testing": {
12
- "build": "npm run typecheck && npm test",
13
- "test": "npm run typecheck && npm test",
12
+ "build": "npm run typecheck",
13
+ "test": "npm test",
14
14
  "testWithCoverage": "npm run coverage:check"
15
15
  },
16
16
  "agents": {