pi-spine 2.13.0 → 2.14.1

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.
@@ -30,7 +30,11 @@ import { reportTaskProgress } from "../src/worker-tools/report-progress.mjs";
30
30
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
31
31
  import { loadSpineConfig } from "./spine-config.mjs";
32
32
  import { isStubDeliveryOnlyScope } from "../src/batch/contract-stub-delivery.mjs";
33
- import { writeWorkerDoneMarker } from "../src/batch/worker-output.mjs";
33
+ import {
34
+ resolveWorkerOutputConfig,
35
+ truncateLiveLogBytes,
36
+ writeWorkerDoneMarker,
37
+ } from "../src/batch/worker-output.mjs";
34
38
  import { buildWorkerTailPrompt, taskIdFromFolder } from "../src/batch/worker-prompt.mjs";
35
39
  import { DEFAULT_TASKS_ROOT } from "../src/config/spine-init-constants.mjs";
36
40
  import {
@@ -130,6 +134,25 @@ export async function buildWorkerPiArgs({
130
134
  return piArgs;
131
135
  }
132
136
 
137
+ /**
138
+ * SP-708 (#253): build the pi stdout/stderr flush payload for the DONE-missing path.
139
+ * Mirrors the non-zero exit path so operators keep salvage context when pi exits 0
140
+ * without writing .DONE. Each stream is byte-capped with the same truncation helper
141
+ * as terminal worker-output capture; the cap comes from lanes.workerOutputMaxBytes
142
+ * (default 262144 bytes, see resolveWorkerOutputConfig).
143
+ *
144
+ * @param {{stdout?: string|null, stderr?: string|null}} result
145
+ * @param {object} [config] spine-config object (lanes.workerOutputMaxBytes override)
146
+ * @returns {{stdout: string, stderr: string}}
147
+ */
148
+ export function buildDoneMissingPiOutputFlush(result, config = {}) {
149
+ const maxBytes = resolveWorkerOutputConfig(config).maxBytes;
150
+ return {
151
+ stderr: truncateLiveLogBytes(result?.stderr ?? "", maxBytes),
152
+ stdout: truncateLiveLogBytes(result?.stdout ?? "", maxBytes),
153
+ };
154
+ }
155
+
133
156
  /**
134
157
  * @param {string} taskFolder
135
158
  * @returns {string[]}
@@ -445,6 +468,10 @@ async function runWorkerRunner() {
445
468
 
446
469
  if (!fs.existsSync(donePath)) {
447
470
  console.error("pi exited but .DONE was not created");
471
+ // SP-708 (#253): flush capped pi output for salvage context, same as non-zero path.
472
+ const flush = buildDoneMissingPiOutputFlush(result, spineConfig);
473
+ if (flush.stderr) process.stderr.write(flush.stderr);
474
+ if (flush.stdout) process.stdout.write(flush.stdout);
448
475
  process.exit(1);
449
476
  }
450
477
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.13.0",
3
+ "version": "2.14.1",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -436,13 +436,25 @@ COMMIT=$(git rev-parse HEAD)
436
436
  gh run list --workflow ci.yml --commit "$COMMIT" --json databaseId,conclusion,status --limit 5
437
437
  ```
438
438
 
439
- **Fail closed** when no run has `conclusion: success`. If the latest run is `in_progress` or `queued`, wait:
439
+ **Fail closed** when no run has `conclusion: success`. **Cancelled or absent CI is no signal** — neither green nor red (post-mortem v2.12.3 F-C). Branch by run state:
440
+
441
+ - **`in_progress` / `queued`:** wait:
442
+
443
+ ```bash
444
+ gh run watch --exit-status <run-id>
445
+ ```
446
+
447
+ - **`cancelled` or no run exists for `HEAD`:** re-run **CI** via `workflow_dispatch` (trigger added in `edb7919d`), then wait for `conclusion: success` on current `HEAD`:
440
448
 
441
449
  ```bash
450
+ gh workflow run ci.yml
451
+ gh run list --workflow ci.yml --commit "$COMMIT" --json databaseId,conclusion,status --limit 5
442
452
  gh run watch --exit-status <run-id>
443
453
  ```
444
454
 
445
- If CI **failed** or **no CI run** exists for `HEAD`, **STOP** — fix CI on `main`, re-run Phase 5, then re-attempt this gate. Do not `npm version` or `git push --tags`.
455
+ Never treat a cancelled run as green or as a reason to skip this gate.
456
+
457
+ If CI **failed**, **STOP** — fix CI on `main`, re-run Phase 5, then re-attempt this gate. Do not `npm version` or `git push --tags` until a green CI run exists on `HEAD`.
446
458
 
447
459
  Only after Phase 5 **and** pre-tag CI gate pass:
448
460
 
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Shared error type for evidence command parse/exec failures.
3
+ * Kept separate so path-prefix helpers can throw without a cycle on evidence-command.mjs.
4
+ */
5
+
6
+ export class EvidenceCommandError extends Error {
7
+ /**
8
+ * @param {string} message
9
+ */
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "EvidenceCommandError";
13
+ }
14
+ }
@@ -7,13 +7,30 @@
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
9
  import { validateWorkerLaunchScriptPath } from "../config/worker-launch-script.mjs";
10
+ import { EvidenceCommandError } from "./evidence-command-error.mjs";
11
+ import {
12
+ expandEvidencePathEntries,
13
+ isAllowedEvidencePathEntry,
14
+ splitEvidencePathPrefix,
15
+ } from "./evidence-path-prefix.mjs";
16
+
17
+ export { EvidenceCommandError };
18
+ export { isAllowedEvidencePathEntry };
10
19
 
11
20
  /**
12
21
  * Allowed first-token executables for evidence commands.
13
22
  * Extend this set deliberately when adding new package-manager or runtime support.
14
23
  * @type {Set<string>}
15
24
  */
16
- export const ALLOWED_EVIDENCE_EXECUTABLES = new Set(["npm", "node", "pnpm", "yarn", "npx"]);
25
+ export const ALLOWED_EVIDENCE_EXECUTABLES = new Set([
26
+ "npm",
27
+ "node",
28
+ "pnpm",
29
+ "yarn",
30
+ "npx",
31
+ "cargo",
32
+ "task",
33
+ ]);
17
34
 
18
35
  /**
19
36
  * Interpreter basenames allowed only as project-local relative paths under
@@ -35,16 +52,6 @@ const EVIDENCE_SCRIPTS_PREFIX = "scripts/";
35
52
  */
36
53
  const SHELL_METACHAR_PATTERN = /[;|&`<>]|>>|\$\(|\$\{/;
37
54
 
38
- export class EvidenceCommandError extends Error {
39
- /**
40
- * @param {string} message
41
- */
42
- constructor(message) {
43
- super(message);
44
- this.name = "EvidenceCommandError";
45
- }
46
- }
47
-
48
55
  /**
49
56
  * @param {string} command
50
57
  */
@@ -58,8 +65,14 @@ export function assertSafeEvidenceCommand(command) {
58
65
  throw new EvidenceCommandError("evidence command contains newlines");
59
66
  }
60
67
 
68
+ // Strip documented `PATH="…"` prefixes per `&&` segment first; the bounded
69
+ // entry allowlist above keeps `$HOME` / `$PATH` / project-relative dirs only.
70
+ // Any `$` surviving the strip is still rejected below (fail-closed).
71
+ const segments = splitEvidenceChainSegments(trimmed);
72
+ const stripped = segments.map((segment) => splitEvidencePathPrefix(segment).rest);
73
+
61
74
  // Allow `&&` as the only chain operator; strip it before metachar / `$` scans.
62
- const withoutChains = trimmed.replaceAll("&&", " ");
75
+ const withoutChains = stripped.join(" ").replaceAll("&&", " ");
63
76
  if (SHELL_METACHAR_PATTERN.test(withoutChains)) {
64
77
  throw new EvidenceCommandError("evidence command contains shell metacharacters");
65
78
  }
@@ -163,7 +176,8 @@ export function parseEvidenceCommandArgv(command) {
163
176
  * @returns {string[]}
164
177
  */
165
178
  function parseEvidenceSegmentArgv(segment, chainMode) {
166
- const argv = tokenizeCommandLine(segment);
179
+ const { rest } = splitEvidencePathPrefix(segment);
180
+ const argv = tokenizeCommandLine(rest);
167
181
  if (argv.length === 0) {
168
182
  throw new EvidenceCommandError("empty evidence command");
169
183
  }
@@ -337,6 +351,23 @@ function tokenizeCommandLine(line) {
337
351
  return tokens;
338
352
  }
339
353
 
354
+ /**
355
+ * Collect validated `PATH="…"` prefix entries across all `&&` segments.
356
+ * Assumes {@link assertSafeEvidenceCommand} already ran for the command.
357
+ *
358
+ * @param {string} command
359
+ * @returns {string[]}
360
+ */
361
+ function collectEvidencePathPrefixEntries(command) {
362
+ const segments = splitEvidenceChainSegments(command.trim());
363
+ /** @type {string[]} */
364
+ const entries = [];
365
+ for (const segment of segments) {
366
+ entries.push(...splitEvidencePathPrefix(segment).pathEntries);
367
+ }
368
+ return entries;
369
+ }
370
+
340
371
  /**
341
372
  * @param {string} projectRoot
342
373
  * @param {string} command
@@ -347,6 +378,16 @@ export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024)
347
378
 
348
379
  try {
349
380
  const chain = parseEvidenceCommandChain(command);
381
+ const pathEntries = collectEvidencePathPrefixEntries(command);
382
+ /** @type {NodeJS.ProcessEnv | undefined} */
383
+ let env;
384
+ if (pathEntries.length > 0) {
385
+ const expanded = expandEvidencePathEntries(pathEntries);
386
+ if (process.env.PATH) {
387
+ expanded.push(process.env.PATH);
388
+ }
389
+ env = { ...process.env, PATH: expanded.join(path.delimiter) };
390
+ }
350
391
  /** @type {string[]} */
351
392
  const outputs = [];
352
393
  for (const argv of chain) {
@@ -357,6 +398,7 @@ export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024)
357
398
  stdio: ["ignore", "pipe", "pipe"],
358
399
  timeout: 10 * 60 * 1000,
359
400
  maxBuffer: maxBytes,
401
+ ...(env ? { env } : {}),
360
402
  });
361
403
  outputs.push(String(output ?? ""));
362
404
  }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Documented `PATH="…"` prefix for gate evidence commands (SP-710 / #254).
3
+ * Bounded allowlist only — no general shell variable expansion.
4
+ */
5
+
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { EvidenceCommandError } from "./evidence-command-error.mjs";
9
+
10
+ /**
11
+ * Documented `PATH="…"` segment prefix. Only the double-quoted assignment form
12
+ * at the start of a segment is recognized; every colon-separated entry must
13
+ * pass {@link isAllowedEvidencePathEntry}.
14
+ */
15
+ const PATH_PREFIX_PATTERN = /^PATH="([^"]*)"(\s+|$)/;
16
+
17
+ /** Charset for a safe PATH entry (no whitespace, shell metacharacters, or `~`). */
18
+ const SAFE_PATH_ENTRY_PATTERN = /^[A-Za-z0-9._/-]+$/;
19
+
20
+ /**
21
+ * Bounded allowlist for `PATH="…"` prefix entries:
22
+ * - literal `$PATH` (preserve the inherited lookup path),
23
+ * - `$HOME/<relative>` toolchain dirs such as `$HOME/.cargo/bin`,
24
+ * - project-relative paths such as `node_modules/.bin` (resolved against the
25
+ * evidence cwd, never absolute and never traversing `..`).
26
+ * Any other `$` expansion, absolute path, or parent traversal is rejected so the
27
+ * prefix cannot widen into general shell variable expansion.
28
+ *
29
+ * @param {string} entry
30
+ * @returns {boolean}
31
+ */
32
+ export function isAllowedEvidencePathEntry(entry) {
33
+ if (entry === "$PATH") {
34
+ return true;
35
+ }
36
+ if (entry.startsWith("$HOME/")) {
37
+ return isSafeRelativePathEntry(entry.slice("$HOME/".length));
38
+ }
39
+ if (entry.includes("$")) {
40
+ return false;
41
+ }
42
+ return isSafeRelativePathEntry(entry);
43
+ }
44
+
45
+ /**
46
+ * @param {string} relativePath
47
+ * @returns {boolean}
48
+ */
49
+ function isSafeRelativePathEntry(relativePath) {
50
+ if (!relativePath || !SAFE_PATH_ENTRY_PATTERN.test(relativePath)) {
51
+ return false;
52
+ }
53
+ if (path.posix.isAbsolute(relativePath) || /^[A-Za-z]:/.test(relativePath)) {
54
+ return false;
55
+ }
56
+ return !relativePath.split("/").some((segment) => segment === "..");
57
+ }
58
+
59
+ /**
60
+ * Split a validated `PATH="…"` prefix off the start of a chain segment.
61
+ * Returns the raw colon-separated entries plus the remaining command text.
62
+ *
63
+ * @param {string} segment
64
+ * @returns {{ pathEntries: string[], rest: string }}
65
+ */
66
+ export function splitEvidencePathPrefix(segment) {
67
+ const match = segment.match(PATH_PREFIX_PATTERN);
68
+ if (!match) {
69
+ return { pathEntries: [], rest: segment };
70
+ }
71
+ const pathEntries = match[1].split(":");
72
+ for (const entry of pathEntries) {
73
+ if (!isAllowedEvidencePathEntry(entry)) {
74
+ throw new EvidenceCommandError(
75
+ `evidence PATH prefix entry not allowed: ${entry}`,
76
+ );
77
+ }
78
+ }
79
+ const rest = segment.slice(match[0].length).trim();
80
+ if (!rest) {
81
+ throw new EvidenceCommandError("evidence PATH prefix without a command");
82
+ }
83
+ return { pathEntries, rest };
84
+ }
85
+
86
+ /**
87
+ * Expand validated PATH prefix entries into concrete directories (no shell).
88
+ * `$HOME` maps to `os.homedir()`, `$PATH` splices the inherited lookup path,
89
+ * and project-relative entries stay relative to the evidence cwd.
90
+ *
91
+ * @param {string[]} entries
92
+ * @returns {string[]}
93
+ */
94
+ export function expandEvidencePathEntries(entries) {
95
+ /** @type {string[]} */
96
+ const expanded = [];
97
+ for (const entry of entries) {
98
+ if (entry === "$PATH") {
99
+ if (process.env.PATH) {
100
+ expanded.push(...process.env.PATH.split(path.delimiter).filter(Boolean));
101
+ }
102
+ continue;
103
+ }
104
+ if (entry.startsWith("$HOME/")) {
105
+ expanded.push(path.join(os.homedir(), entry.slice("$HOME/".length)));
106
+ continue;
107
+ }
108
+ expanded.push(entry);
109
+ }
110
+ return expanded;
111
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Journal event checksums and bounded jsonl append (extracted from journal.mjs
3
+ * so the facade stays under the Phase 23 500 LOC cap).
4
+ */
5
+
6
+ import crypto from "node:crypto";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+
10
+ /** Bounded retry policy for transient append failures (EBUSY/ENOENT). */
11
+ const APPEND_RETRY_ATTEMPTS = 3;
12
+ const APPEND_RETRY_DELAY_MS = 25;
13
+ const RETRYABLE_APPEND_CODES = new Set(["EBUSY", "ENOENT"]);
14
+
15
+ /**
16
+ * Synchronous sleep for retry backoff. Atomics.wait is permitted on the Node
17
+ * main thread (unlike browsers), so this works in the sync append path.
18
+ * @param {number} ms
19
+ */
20
+ function sleepSync(ms) {
21
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
22
+ }
23
+
24
+ /**
25
+ * SHA-256 integrity checksum for new journal events. Computed over the
26
+ * canonical JSON of the entry without the checksum field; the field is
27
+ * appended last so JSON.parse preserves key order and readers can recompute
28
+ * by stripping `checksum` and re-stringifying. Legacy lines without the
29
+ * field remain valid.
30
+ * @param {Record<string, unknown>} entry Entry without a checksum field.
31
+ * @returns {string} Hex digest.
32
+ */
33
+ export function computeJournalChecksum(entry) {
34
+ return crypto.createHash("sha256").update(JSON.stringify(entry), "utf-8").digest("hex");
35
+ }
36
+
37
+ /**
38
+ * Verify a parsed journal line's checksum when present.
39
+ * @param {Record<string, unknown>} event
40
+ * @returns {boolean} True when checksum is absent (legacy) or matches.
41
+ */
42
+ export function verifyJournalChecksum(event) {
43
+ if (!event || typeof event !== "object") return false;
44
+ const { checksum, ...rest } = event;
45
+ if (typeof checksum !== "string" || !checksum) return true;
46
+ return computeJournalChecksum(rest) === checksum;
47
+ }
48
+
49
+ /**
50
+ * Append one jsonl line with fsync and bounded EBUSY/ENOENT retry.
51
+ * Does not rewrite the journal file. In-process callers remain serialized
52
+ * because this function is fully synchronous.
53
+ * @param {string} filePath
54
+ * @param {string} line
55
+ */
56
+ export function appendJsonlLineSync(filePath, line) {
57
+ let lastError;
58
+ let appended = false;
59
+ for (let attempt = 1; attempt <= APPEND_RETRY_ATTEMPTS; attempt += 1) {
60
+ try {
61
+ if (!appended) {
62
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
63
+ fs.appendFileSync(filePath, line, "utf-8");
64
+ appended = true;
65
+ }
66
+
67
+ const fd = fs.openSync(filePath, "r+");
68
+ try {
69
+ fs.fsyncSync(fd);
70
+ } finally {
71
+ fs.closeSync(fd);
72
+ }
73
+ return;
74
+ } catch (error) {
75
+ lastError = error;
76
+ const code = error && /** @type {NodeJS.ErrnoException} */ (error).code;
77
+ if (typeof code !== "string" || !RETRYABLE_APPEND_CODES.has(code) || attempt === APPEND_RETRY_ATTEMPTS) {
78
+ throw error;
79
+ }
80
+ sleepSync(APPEND_RETRY_DELAY_MS);
81
+ }
82
+ }
83
+ throw lastError;
84
+ }
@@ -6,6 +6,13 @@
6
6
  import crypto from "node:crypto";
7
7
  import fs from "node:fs";
8
8
  import path from "node:path";
9
+ import {
10
+ appendJsonlLineSync,
11
+ computeJournalChecksum,
12
+ verifyJournalChecksum,
13
+ } from "./journal-checksum.mjs";
14
+
15
+ export { verifyJournalChecksum };
9
16
 
10
17
  export const JOURNAL_SCHEMA_VERSION = 1;
11
18
  export const MAX_PAYLOAD_BYTES = 32 * 1024;
@@ -169,7 +176,6 @@ export function normalizeJournalEvent(line) {
169
176
  */
170
177
  export function appendJournalEvent(projectRoot, batchId, type, options = {}) {
171
178
  const filePath = journalPath(projectRoot, batchId);
172
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
173
179
 
174
180
  const rawPayload = extractPayload(options);
175
181
  const payload = capPayloadSize(redactSecrets(rawPayload));
@@ -194,16 +200,16 @@ export function appendJournalEvent(projectRoot, batchId, type, options = {}) {
194
200
  const taskId = options.taskId;
195
201
  if (typeof taskId === "string" && taskId) entry.taskId = taskId;
196
202
 
197
- const line = `${JSON.stringify(entry)}\n`;
198
- fs.appendFileSync(filePath, line, "utf-8");
203
+ // checksum: SHA-256 hex of the canonical JSON of the entry without this
204
+ // field. Added last so readers recompute by stripping `checksum` and
205
+ // re-stringifying; absent on legacy lines.
206
+ entry.checksum = computeJournalChecksum(entry);
199
207
 
200
- const fd = fs.openSync(filePath, "r+");
201
- try {
202
- fs.fsyncSync(fd);
203
- } finally {
204
- fs.closeSync(fd);
205
- }
208
+ const line = `${JSON.stringify(entry)}\n`;
206
209
 
210
+ // In-process serialization: appendJsonlLineSync is fully synchronous, so
211
+ // concurrent event-loop callers cannot interleave partial jsonl lines.
212
+ appendJsonlLineSync(filePath, line);
207
213
  return entry;
208
214
  }
209
215
 
@@ -227,6 +233,22 @@ export function exportJournalJsonl(projectRoot, batchId) {
227
233
  return fs.readFileSync(filePath, "utf-8");
228
234
  }
229
235
 
236
+ /**
237
+ * Parse jsonl journal content into normalized events. Lines whose checksum is
238
+ * present but mismatches are skipped (fail-closed per-line) without
239
+ * discarding the rest of the file; legacy lines without checksum load as-is.
240
+ * @param {string} content Raw jsonl content.
241
+ * @returns {object[]}
242
+ */
243
+ function parseJournalLines(content) {
244
+ return content
245
+ .split("\n")
246
+ .filter(Boolean)
247
+ .map((line) => JSON.parse(line))
248
+ .filter((parsed) => verifyJournalChecksum(parsed))
249
+ .map((parsed) => normalizeJournalEvent(parsed));
250
+ }
251
+
230
252
  /**
231
253
  * @param {string} projectRoot
232
254
  * @param {string} batchId
@@ -236,11 +258,7 @@ export function readJournalEvents(projectRoot, batchId) {
236
258
  const filePath = journalPath(projectRoot, batchId);
237
259
  if (!fs.existsSync(filePath)) return [];
238
260
 
239
- return fs
240
- .readFileSync(filePath, "utf-8")
241
- .split("\n")
242
- .filter(Boolean)
243
- .map((line) => normalizeJournalEvent(JSON.parse(line)));
261
+ return parseJournalLines(fs.readFileSync(filePath, "utf-8"));
244
262
  }
245
263
 
246
264
  /**
@@ -273,11 +291,7 @@ export function readJournalEventsCached(projectRoot, batchId) {
273
291
  return _journalCache.events;
274
292
  }
275
293
 
276
- const events = fs
277
- .readFileSync(filePath, "utf-8")
278
- .split("\n")
279
- .filter(Boolean)
280
- .map((line) => normalizeJournalEvent(JSON.parse(line)));
294
+ const events = parseJournalLines(fs.readFileSync(filePath, "utf-8"));
281
295
 
282
296
  _journalCache.filePath = filePath;
283
297
  _journalCache.mtimeMs = stat.mtimeMs;
@@ -98,6 +98,9 @@ function extractSummary(reviewContent) {
98
98
  export function parseReviewVerdict(reviewContent, options = {}) {
99
99
  const reviewType = options.reviewType ?? "code";
100
100
  const isFinal = reviewType === "final";
101
+ // A json fence signals structured-output intent; if it cannot yield a valid
102
+ // verdict, fail closed instead of salvaging a verdict from prose heuristics.
103
+ const hasJsonFence = /```json/i.test(reviewContent);
101
104
 
102
105
  const jsonMatch = reviewContent.match(/```json\s*\n([\s\S]*?)\n```/i);
103
106
  if (jsonMatch) {
@@ -126,6 +129,10 @@ export function parseReviewVerdict(reviewContent, options = {}) {
126
129
  };
127
130
  }
128
131
 
132
+ if (hasJsonFence) {
133
+ return { verdict: null, feedback: extractSummary(reviewContent) };
134
+ }
135
+
129
136
  const lower = reviewContent.toLowerCase();
130
137
  if (
131
138
  lower.includes("changes requested") ||
@@ -104,6 +104,14 @@ export function reconciliationMatchesUntil(result, untilDiagnoses) {
104
104
  return true;
105
105
  }
106
106
 
107
+ // `--until failed` must wake on terminal batch failure even when reconcile
108
+ // reports a failure-class diagnosis (worker_done_missing, worker_orphaned,
109
+ // engine_orphaned) instead of the literal "failed" token (#252). Explicit
110
+ // diagnosis tokens still match directly via the check above.
111
+ if (untilDiagnoses.has("failed") && result.phase === "failed") {
112
+ return true;
113
+ }
114
+
107
115
  for (const pseudo of deriveWaitPseudoDiagnoses(result)) {
108
116
  if (untilDiagnoses.has(pseudo)) {
109
117
  return true;
@@ -16,14 +16,21 @@ import { missingConfigHint } from "./missing-config-hint.mjs";
16
16
  export { resolveGatePostureConfig } from "./gate-posture-config.mjs";
17
17
 
18
18
  /**
19
- * Default hook paths skipped at lane commit when config omits ignore paths (SP-640 / #200).
20
- * Worktree setup hooks commonly `ln -s` `.venv` into lane worktrees; do not stage that symlink.
19
+ * Default hook paths skipped at lane commit when config omits ignore paths (SP-640 / #200,
20
+ * SP-711 / #255). Worktree setup hooks commonly `ln -s` `.venv` into lane worktrees, and pi
21
+ * worker sessions write runtime trees under `.pi/` / `.pi-smart-router/`; do not stage any of
22
+ * those into orch merges.
21
23
  */
22
- export const DEFAULT_WORKTREE_SETUP_IGNORE_PATHS = Object.freeze([".venv"]);
24
+ export const DEFAULT_WORKTREE_SETUP_IGNORE_PATHS = Object.freeze([
25
+ ".venv",
26
+ ".pi",
27
+ ".pi-smart-router",
28
+ ]);
23
29
 
24
30
  /**
25
31
  * Resolve effective `worktreeSetupIgnorePaths`, always unioning defaults so hook `.venv`
26
- * stays ignored. Opt in to committing an ignore path via task `fileScope`, not by clearing config.
32
+ * and pi session trees stay ignored. Opt in to committing an ignore path via task
33
+ * `fileScope`, not by clearing config.
27
34
  *
28
35
  * @param {Record<string, unknown> | null | undefined} config
29
36
  * @returns {string[]}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Advisory doctor checks for gate-evidence command safety (SP-710, #254).
3
+ *
4
+ * Every `testing.*` evidence slot runs through the no-shell argv executor in
5
+ * `src/batch/evidence-command.mjs` at integrate-gate time. When a configured
6
+ * command would be rejected there (unallowed executable, shell metacharacters,
7
+ * arbitrary `$` expansion), evidence output degrades to a `[rejected]` line and
8
+ * operators lose test/build proof. These checks surface that misconfiguration
9
+ * early as non-blocking warnings (`ok: true, warning: true`) — doctor and
10
+ * preflight must stay green.
11
+ */
12
+
13
+ import { parseEvidenceCommandChain } from "../batch/evidence-command.mjs";
14
+
15
+ /** Evidence slots executed through the no-shell evidence executor. */
16
+ const EVIDENCE_TESTING_KEYS = ["build", "test", "testWithCoverage", "review"];
17
+
18
+ /**
19
+ * Warn (non-blocking) when a configured `testing.*` evidence command would be
20
+ * rejected by the gate evidence validator.
21
+ *
22
+ * @param {{ testing?: Record<string, string> }} [config] spine-config object
23
+ * @returns {Array<{ label: string, ok: boolean, warning?: boolean, detail: string, suggestedCommand?: string }>}
24
+ */
25
+ export function buildEvidenceConfigWarnDoctorChecks(config = {}) {
26
+ const testing = config.testing ?? {};
27
+ /** @type {Array<{ label: string, ok: boolean, warning?: boolean, detail: string, suggestedCommand?: string }>} */
28
+ const checks = [];
29
+
30
+ for (const key of EVIDENCE_TESTING_KEYS) {
31
+ const command = testing[key];
32
+ if (typeof command !== "string" || !command.trim()) {
33
+ continue;
34
+ }
35
+ try {
36
+ parseEvidenceCommandChain(command);
37
+ } catch (err) {
38
+ const message = err instanceof Error ? err.message : String(err);
39
+ checks.push({
40
+ label: `testing.${key} evidence-safe`,
41
+ ok: true,
42
+ warning: true,
43
+ detail: `testing.${key} would be rejected at gate evidence time: ${message}`,
44
+ suggestedCommand: `spine settings set testing.${key} "<allowlisted evidence command>"`,
45
+ });
46
+ }
47
+ }
48
+
49
+ return checks;
50
+ }
@@ -34,6 +34,7 @@ import { buildPiExtensionConflictDoctorCheck } from "./pi-extension-conflict.mjs
34
34
  import { buildSupervisorConfigDoctorCheck } from "./supervisor.mjs";
35
35
  import { buildAttachedOrphanRiskDoctorCheck } from "./attached-orphan-risk.mjs";
36
36
  import { buildQuotaRiskDoctorCheck } from "./quota-risk.mjs";
37
+ import { buildEvidenceConfigWarnDoctorChecks } from "./evidence-config-warn.mjs";
37
38
  import { metricsFilePath, readMetricsLines } from "../batch/metrics.mjs";
38
39
  import {
39
40
  buildCheckoutVersionSkewDoctorCheck,
@@ -166,39 +167,73 @@ function parsePiListModelsOutput(output) {
166
167
  return null;
167
168
  }
168
169
 
169
- function checkModelProvider() {
170
- if (!commandExists("pi")) {
170
+ const LIST_MODELS_TIMEOUT_MS = 30_000;
171
+
172
+ function isListModelsTimeout(err) {
173
+ return err?.code === "ETIMEDOUT";
174
+ }
175
+
176
+ function listModelsTimeoutCheck() {
177
+ // Advisory (#256): a slow model catalog fetch is not an auth failure, so
178
+ // preflight must not hard-fail or suggest `pi login` on timeout alone.
179
+ return {
180
+ ok: true,
181
+ warning: true,
182
+ detail: `pi --list-models timed out after ${LIST_MODELS_TIMEOUT_MS / 1000}s (slow model catalog fetch) — not an auth failure`,
183
+ suggestedCommand: "retry spine doctor",
184
+ };
185
+ }
186
+
187
+ /**
188
+ * @param {object} [options]
189
+ * @param {(cmd: string, args: string[], opts: object) => any} [options.spawn]
190
+ * @param {(cmd: string) => boolean} [options.commandExistsFn]
191
+ */
192
+ export function checkModelProvider({ spawn = spawnSync, commandExistsFn = commandExists } = {}) {
193
+ if (!commandExistsFn("pi")) {
171
194
  return { ok: false, detail: "pi not installed", suggestedCommand: "https://pi.dev" };
172
195
  }
173
196
 
197
+ let result;
174
198
  try {
175
- const result = spawnSync("pi", ["--list-models"], {
199
+ result = spawn("pi", ["--list-models"], {
176
200
  encoding: "utf-8",
177
201
  stdio: ["ignore", "pipe", "pipe"],
178
- timeout: 30_000,
202
+ timeout: LIST_MODELS_TIMEOUT_MS,
179
203
  });
180
- if (result.error) throw result.error;
181
- const output = `${result.stdout ?? ""}
182
- ${result.stderr ?? ""}`.trim();
183
- const model = parsePiListModelsOutput(output);
184
- if (!model) {
185
- return {
186
- ok: false,
187
- detail: "no models available",
188
- suggestedCommand: "pi login",
189
- };
190
- }
191
- return {
192
- ok: true,
193
- detail: `${model.provider}/${model.id}`,
194
- };
195
204
  } catch (err) {
205
+ if (isListModelsTimeout(err)) return listModelsTimeoutCheck();
196
206
  return {
197
207
  ok: false,
198
208
  detail: err.message,
199
209
  suggestedCommand: "pi login",
200
210
  };
201
211
  }
212
+
213
+ const spawnError = result?.error;
214
+ if (isListModelsTimeout(spawnError)) return listModelsTimeoutCheck();
215
+ if (spawnError) {
216
+ return {
217
+ ok: false,
218
+ detail: spawnError.message,
219
+ suggestedCommand: "pi login",
220
+ };
221
+ }
222
+
223
+ const output = `${result?.stdout ?? ""}
224
+ ${result?.stderr ?? ""}`.trim();
225
+ const model = parsePiListModelsOutput(output);
226
+ if (!model) {
227
+ return {
228
+ ok: false,
229
+ detail: "no models available",
230
+ suggestedCommand: "pi login",
231
+ };
232
+ }
233
+ return {
234
+ ok: true,
235
+ detail: `${model.provider}/${model.id}`,
236
+ };
202
237
  }
203
238
 
204
239
  function resolveTasksRoot(projectRoot, configResult) {
@@ -327,6 +362,7 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
327
362
  record("model provider configured", modelCheck.ok, {
328
363
  detail: modelCheck.detail,
329
364
  suggestedCommand: modelCheck.suggestedCommand,
365
+ warning: modelCheck.warning,
330
366
  });
331
367
 
332
368
  const configResult = loadSpineConfig(projectRoot);
@@ -410,6 +446,11 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
410
446
  for (const testingCheck of buildTestingEvidenceDoctorChecks(configResult.config)) {
411
447
  checks.push(testingCheck);
412
448
  }
449
+ // Advisory only (SP-710): warn when configured testing.* commands would be
450
+ // rejected by the no-shell evidence executor at gate time; never hard-fail.
451
+ for (const evidenceWarnCheck of buildEvidenceConfigWarnDoctorChecks(configResult.config)) {
452
+ checks.push(evidenceWarnCheck);
453
+ }
413
454
  let quotaMetricsLines;
414
455
  try {
415
456
  quotaMetricsLines = readMetricsLines(