pi-spine 2.14.0 → 2.15.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.
@@ -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.14.0",
3
+ "version": "2.15.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -34,7 +34,7 @@
34
34
  "typecheck": "tsc --project tsconfig.json --noEmit && tsc --project tsconfig.batch.json --noEmit",
35
35
  "verify:reconcile-fixtures": "node scripts/verify-reconcile-test-fixtures.mjs",
36
36
  "pretest": "npm run verify:reconcile-fixtures",
37
- "test": "SPINE_SUPPRESS_JOURNAL_ATTACH=1 node --experimental-strip-types --test tests/*.test.mjs tests/cli/*.test.mjs tests/compat/*.test.mjs tests/tasks/*.test.mjs tests/config/*.test.mjs tests/config/cursor-rules/*.test.mjs tests/planner/*.test.mjs tests/batch/*.test.mjs tests/metrics/*.test.mjs tests/agents/*.test.mjs tests/adoption/*.test.mjs tests/dashboard/*.test.mjs tests/doctor/*.test.mjs tests/init/*.test.mjs tests/migrate/*.test.mjs tests/worker-tools/*.test.mjs tests/coverage/*.test.mjs tests/extensions/*.test.mjs",
37
+ "test": "SPINE_SUPPRESS_JOURNAL_ATTACH=1 node --experimental-strip-types --test tests/*.test.mjs tests/cli/*.test.mjs tests/compat/*.test.mjs tests/tasks/*.test.mjs tests/config/*.test.mjs tests/config/cursor-rules/*.test.mjs tests/planner/*.test.mjs tests/batch/*.test.mjs tests/metrics/*.test.mjs tests/agents/*.test.mjs tests/adoption/*.test.mjs tests/dashboard/*.test.mjs tests/doctor/*.test.mjs tests/init/*.test.mjs tests/migrate/*.test.mjs tests/worker-tools/*.test.mjs tests/coverage/*.test.mjs tests/extensions/*.test.mjs tests/arch/*.test.mjs tests/fs/*.test.mjs",
38
38
  "test:batch": "SPINE_SUPPRESS_JOURNAL_ATTACH=1 node --experimental-strip-types --test tests/batch/*.test.mjs",
39
39
  "test:core": "SPINE_SUPPRESS_JOURNAL_ATTACH=1 node --experimental-strip-types --test tests/*.test.mjs tests/cli/*.test.mjs tests/compat/*.test.mjs tests/tasks/*.test.mjs tests/config/*.test.mjs tests/config/cursor-rules/*.test.mjs tests/planner/*.test.mjs tests/agents/*.test.mjs tests/adoption/*.test.mjs tests/dashboard/*.test.mjs tests/doctor/*.test.mjs tests/migrate/*.test.mjs tests/worker-tools/*.test.mjs tests/coverage/*.test.mjs",
40
40
  "test:coverage": "node scripts/run-coverage.mjs --report-only",
@@ -0,0 +1,103 @@
1
+ // @ts-check
2
+ /**
3
+ * Batch ID validation and uniquified generation (SP-714, issue #258).
4
+ *
5
+ * Batch IDs become directory names under `.spine/runtime/{batchId}` and are
6
+ * also accepted from operators via CLI `--batch`. Validation is allowlist-based
7
+ * so path traversal (`..`, `/`, `\`, NUL, empty, absolute paths) is rejected at
8
+ * the CLI boundary before any `path.join`.
9
+ */
10
+
11
+ import crypto from "node:crypto";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+
15
+ /**
16
+ * Allowlist pattern for batch IDs.
17
+ *
18
+ * The first character must be alphanumeric so `.`, `..`, and hidden relative
19
+ * segments can never pass; the remainder permits `.`, `_`, and `-` for
20
+ * backward compatibility with archived timestamp IDs (`YYYYMMDDTHHMMSS`) and
21
+ * the uniquified `YYYYMMDDTHHMMSS-xxxx` form. Slashes, backslashes, colons,
22
+ * and NUL are excluded, which also rejects absolute and UNC paths.
23
+ */
24
+ export const BATCH_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
25
+
26
+ /**
27
+ * @param {unknown} batchId
28
+ * @returns {string|null} rejection reason, or null when the ID is valid
29
+ */
30
+ export function batchIdRejectionReason(batchId) {
31
+ if (typeof batchId !== "string" || batchId.length === 0) {
32
+ return "must be a non-empty string";
33
+ }
34
+ if (batchId.includes("\0")) {
35
+ return "must not contain NUL bytes";
36
+ }
37
+ if (!BATCH_ID_PATTERN.test(batchId)) {
38
+ return (
39
+ `must match ${BATCH_ID_PATTERN} ` +
40
+ "(letters, digits, dot, underscore, dash; must start with a letter or digit; no path separators)"
41
+ );
42
+ }
43
+ if (batchId.includes("..")) {
44
+ return 'must not contain ".." path traversal sequences';
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * @param {unknown} batchId
51
+ * @returns {boolean}
52
+ */
53
+ export function isValidBatchId(batchId) {
54
+ return batchIdRejectionReason(batchId) === null;
55
+ }
56
+
57
+ /**
58
+ * Assert a batch ID is safe to join under `.spine/runtime/`; throw otherwise.
59
+ *
60
+ * @param {unknown} batchId
61
+ * @returns {string} the validated batch ID
62
+ */
63
+ export function validateBatchId(batchId) {
64
+ const reason = batchIdRejectionReason(batchId);
65
+ if (reason) {
66
+ throw new Error(`Invalid batch ID ${JSON.stringify(String(batchId))}: ${reason}`);
67
+ }
68
+ return /** @type {string} */ (batchId);
69
+ }
70
+
71
+ const MAX_UNIQUIFY_ATTEMPTS = 64;
72
+
73
+ /**
74
+ * Generate a collision-resistant batch ID `{YYYYMMDD}T{HHmmss}-{hex4}` (UTC).
75
+ *
76
+ * The random 4-hex suffix keeps concurrent calls distinct; when `projectRoot`
77
+ * is provided the loop also re-draws while `.spine/runtime/{id}` exists, so a
78
+ * stale runtime/archive directory can never be reused.
79
+ *
80
+ * @param {Date} [now]
81
+ * @param {string|null} [projectRoot] when set, loop until the runtime dir is absent
82
+ * @param {(() => string)|null} [randomSuffix] injectable suffix source for tests
83
+ * @returns {string}
84
+ */
85
+ export function generateBatchId(now = new Date(), projectRoot = null, randomSuffix = null) {
86
+ const y = now.getUTCFullYear();
87
+ const m = String(now.getUTCMonth() + 1).padStart(2, "0");
88
+ const d = String(now.getUTCDate()).padStart(2, "0");
89
+ const h = String(now.getUTCHours()).padStart(2, "0");
90
+ const min = String(now.getUTCMinutes()).padStart(2, "0");
91
+ const s = String(now.getUTCSeconds()).padStart(2, "0");
92
+ const base = `${y}${m}${d}T${h}${min}${s}`;
93
+ const draw = randomSuffix ?? (() => crypto.randomBytes(2).toString("hex"));
94
+
95
+ for (let attempt = 0; attempt < MAX_UNIQUIFY_ATTEMPTS; attempt += 1) {
96
+ const id = `${base}-${draw()}`;
97
+ if (!projectRoot) return id;
98
+ if (!fs.existsSync(path.join(projectRoot, ".spine", "runtime", id))) return id;
99
+ }
100
+ throw new Error(
101
+ `Unable to generate a unique batch ID after ${MAX_UNIQUIFY_ATTEMPTS} attempts`,
102
+ );
103
+ }
@@ -337,14 +337,19 @@ export function buildHeadline(diagnosis, ctx = {}) {
337
337
  return `${batchLabel} failed at worker launch — repair lane worktree git, then retry`;
338
338
  }
339
339
  if (REVIEW_SPAWN_FAILURE_EXIT_REASONS.has(ctx.exitReason ?? "")) {
340
- const reviewKind =
341
- ctx.exitReason === "final_review_spawn_failed" ||
342
- ctx.exitReason === "final_review_timeout"
343
- ? "final review"
344
- : "code review";
340
+ const isFinal = ctx.exitReason.startsWith("final_review");
341
+ const isTimeout = ctx.exitReason.endsWith("_timeout");
342
+ const reviewKind = isFinal ? "final review" : "code review";
343
+
344
+ if (isTimeout) {
345
+ return ctx.failedTaskId
346
+ ? `${batchLabel} ${reviewKind} timed out for task ${ctx.failedTaskId} — retry or increase SPINE_REVIEW_TIMEOUT_MS`
347
+ : `${batchLabel} reviewer spawn timed out — retry`;
348
+ }
349
+
345
350
  return ctx.failedTaskId
346
- ? `${batchLabel} ${reviewKind} timed out for task ${ctx.failedTaskId} — retry or increase SPINE_REVIEW_TIMEOUT_MS`
347
- : `${batchLabel} reviewer spawn timed out — retry`;
351
+ ? `${batchLabel} ${reviewKind} spawn failed for task ${ctx.failedTaskId} — retry`
352
+ : `${batchLabel} reviewer spawn failed — retry`;
348
353
  }
349
354
  if (ctx.salvageChangedFileCount > 0 && ctx.failedTaskId) {
350
355
  return `${batchLabel} failed (${ctx.failedTaskId}): ${ctx.salvageChangedFileCount} uncommitted file(s) in scope`;
@@ -172,7 +172,7 @@ export async function startBatch({
172
172
  };
173
173
  }
174
174
 
175
- const batchId = generateBatchId();
175
+ const batchId = generateBatchId(new Date(), projectRoot);
176
176
  const baseBranch = config.baseBranch ?? "main";
177
177
  const orchBranch = `orch/spine-${batchId}`;
178
178
 
@@ -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
+ }
@@ -11,6 +11,7 @@ import {
11
11
  computeJournalChecksum,
12
12
  verifyJournalChecksum,
13
13
  } from "./journal-checksum.mjs";
14
+ import { capPayloadBytes, redactSecretsDeep } from "../util/secret-redact.mjs";
14
15
 
15
16
  export { verifyJournalChecksum };
16
17
 
@@ -52,8 +53,6 @@ export const STRUCTURAL_JOURNAL_EVENT_TYPES = Object.freeze(
52
53
 
53
54
  const META_KEYS = new Set(["correlationId", "laneId", "laneNumber", "taskId", "payload"]);
54
55
 
55
- const REDACT_KEY_PATTERN = /key|token|secret|password/i;
56
-
57
56
  /**
58
57
  * @param {string} projectRoot
59
58
  * @param {string} batchId
@@ -63,46 +62,24 @@ export function journalPath(projectRoot, batchId) {
63
62
  }
64
63
 
65
64
  /**
65
+ * Redact secrets in a journal payload via the shared policy (SP-716):
66
+ * denylisted keys are masked and string values are scanned for
67
+ * value-shaped secrets (sk-, ghp_, bearer, connection strings, ...).
68
+ *
66
69
  * @param {unknown} value
67
70
  * @returns {unknown}
68
71
  */
69
72
  export function redactSecrets(value) {
70
- if (value == null || typeof value !== "object") return value;
71
-
72
- if (Array.isArray(value)) {
73
- return value.map((entry) => redactSecrets(entry));
74
- }
75
-
76
- /** @type {Record<string, unknown>} */
77
- const out = {};
78
- for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
79
- if (REDACT_KEY_PATTERN.test(key)) {
80
- out[key] = "[REDACTED]";
81
- } else if (entry && typeof entry === "object") {
82
- out[key] = redactSecrets(entry);
83
- } else {
84
- out[key] = entry;
85
- }
86
- }
87
- return out;
73
+ return redactSecretsDeep(value);
88
74
  }
89
75
 
90
76
  /**
77
+ * Cap payload size by UTF-8 bytes (SP-716).
78
+ *
91
79
  * @param {Record<string, unknown>} payload
92
80
  */
93
81
  export function capPayloadSize(payload) {
94
- const serialized = JSON.stringify(payload);
95
- if (Buffer.byteLength(serialized, "utf-8") <= MAX_PAYLOAD_BYTES) {
96
- return payload;
97
- }
98
-
99
- const truncated = {
100
- _truncated: true,
101
- _originalBytes: Buffer.byteLength(serialized, "utf-8"),
102
- _maxBytes: MAX_PAYLOAD_BYTES,
103
- preview: serialized.slice(0, MAX_PAYLOAD_BYTES - 256),
104
- };
105
- return truncated;
82
+ return capPayloadBytes(payload, MAX_PAYLOAD_BYTES);
106
83
  }
107
84
 
108
85
  /**
@@ -7,9 +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 { METRICS_DEFAULTS } from "../config/defaults.mjs";
10
+ import { redactSecretsDeep } from "../util/secret-redact.mjs";
10
11
  import { readReviewLevel } from "./review.mjs";
11
12
 
12
- const REDACT_KEY_PATTERN = /key|token|secret|password|prompt/i;
13
+ // Metrics additionally redacts prompt text (worker prompts may embed
14
+ // secrets) while preserving usage counters for cost rollup.
15
+ const METRICS_REDACT_KEY_PATTERN = /key|token|secret|password|prompt/i;
13
16
  const USAGE_KEYS = new Set(["tokensIn", "tokensOut", "estimatedUsd"]);
14
17
 
15
18
  /**
@@ -80,34 +83,18 @@ export function isRunMetricsAppendOnlyDrift(
80
83
  }
81
84
 
82
85
  /**
83
- * @param {unknown} value
84
- * @returns {unknown}
85
- */
86
- function redactMetricValue(value) {
87
- if (value == null || typeof value !== "object") return value;
88
- if (Array.isArray(value)) {
89
- return value.map((entry) => redactMetricValue(entry));
90
- }
91
-
92
- /** @type {Record<string, unknown>} */
93
- const out = {};
94
- for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
95
- if (REDACT_KEY_PATTERN.test(key) && !USAGE_KEYS.has(key)) {
96
- out[key] = "[REDACTED]";
97
- } else if (entry && typeof entry === "object") {
98
- out[key] = redactMetricValue(entry);
99
- } else {
100
- out[key] = entry;
101
- }
102
- }
103
- return out;
104
- }
105
-
106
- /**
86
+ * Redact secret-like fields via the shared policy (SP-716), keeping the
87
+ * metrics-specific prompt denylist and usage-counter exemptions.
88
+ *
107
89
  * @param {object} record
108
90
  */
109
91
  export function sanitizeMetricRecord(record) {
110
- return /** @type {typeof record} */ (redactMetricValue(record));
92
+ return /** @type {typeof record} */ (
93
+ redactSecretsDeep(record, {
94
+ keyPattern: METRICS_REDACT_KEY_PATTERN,
95
+ allowedKeys: USAGE_KEYS,
96
+ })
97
+ );
111
98
  }
112
99
 
113
100
  /**
@@ -3,7 +3,7 @@
3
3
 
4
4
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
5
5
  import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
6
- import { isProcessAlive } from "../process/liveness.mjs";
6
+ import { isEngineProcessAlive, isProcessAlive } from "../process/liveness.mjs";
7
7
  import { classifyTaskDoneSemantics } from "./diagnosis-task-done.mjs";
8
8
  import {
9
9
  appendJournalEvent,
@@ -24,6 +24,7 @@ import {
24
24
  saveSpineBatchState,
25
25
  updateSegmentForTask,
26
26
  } from "./state.mjs";
27
+ import { readBatchEngineStartedAt } from "./state-guards.mjs";
27
28
 
28
29
  /**
29
30
  * @param {object} ctx
@@ -271,7 +272,7 @@ export function reconcileOrphanRunningState({ projectRoot, state }) {
271
272
  }
272
273
 
273
274
  const enginePid = readBatchEnginePid(state);
274
- if (enginePid != null && !isProcessAlive(enginePid)) {
275
+ if (enginePid != null && !isEngineProcessAlive(enginePid, readBatchEngineStartedAt(state))) {
275
276
  clearBatchEnginePid(state);
276
277
  changed = true;
277
278
  }
@@ -12,6 +12,7 @@ import { journalPath, readJournalEvents } from "./journal.mjs";
12
12
  import { rebuildBatchStateFromJournal } from "./journal-rebuild.mjs";
13
13
  import { loadBatchStateFile } from "./reconcile.mjs";
14
14
  import { laneTaskBranch } from "./worktree.mjs";
15
+ import { classifyTaskDoneSemantics } from "./diagnosis-task-done.mjs";
15
16
 
16
17
  /** Exit reasons that block salvage even when a lane commit exists. */
17
18
  export const NON_SALVAGEABLE_EXIT_REASONS = new Set([
@@ -199,12 +200,22 @@ export function listSalvageableLanes(projectRoot, batchId) {
199
200
  const baseBranch = String(rebuilt.baseBranch ?? seedState?.baseBranch ?? "main");
200
201
  const committedTaskIds = laneCommittedTaskIds(journalEvents);
201
202
  const seedTasks = seedState?.tasks;
203
+ const tasksRoot = seedState?.tasksRoot ?? "spine-tasks";
202
204
 
203
205
  /** @type {Map<number, { laneNumber: number, salvageableTasks: string[], excludedTasks: string[] }>} */
204
206
  const laneMap = new Map();
205
207
 
206
208
  for (const rawTask of rebuilt.tasks ?? []) {
207
- const task = enrichTaskWithSeedEvidence(rawTask, seedTasks);
209
+ let task = enrichTaskWithSeedEvidence(rawTask, seedTasks);
210
+ if (task.doneInLane !== true && task.doneOnMain !== true) {
211
+ task = classifyTaskDoneSemantics(task, {
212
+ projectRoot,
213
+ batchId: resolvedBatchId,
214
+ tasksRoot,
215
+ lanes: seedState?.lanes ?? [],
216
+ });
217
+ }
218
+
208
219
  const laneNumber = Number(task?.laneNumber);
209
220
  if (!Number.isFinite(laneNumber) || laneNumber <= 0) continue;
210
221