pi-spine 2.14.1 → 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.
- package/package.json +2 -2
- package/src/batch/batch-id.mjs +103 -0
- package/src/batch/diagnosis.mjs +12 -7
- package/src/batch/engine.mjs +1 -1
- package/src/batch/journal.mjs +9 -32
- package/src/batch/metrics.mjs +13 -26
- package/src/batch/reconcile-orphan.mjs +3 -2
- package/src/batch/salvage-batch-list.mjs +12 -1
- package/src/batch/state-guards.mjs +26 -3
- package/src/batch/state-io.mjs +62 -4
- package/src/batch/state.mjs +7 -13
- package/src/batch/worker-output.mjs +5 -16
- package/src/cli/handoff.mjs +10 -27
- package/src/cli/journal-follow.mjs +11 -2
- package/src/cli/lane-logs.mjs +9 -1
- package/src/process/liveness.mjs +188 -1
- package/src/util/secret-redact.mjs +140 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-spine",
|
|
3
|
-
"version": "2.
|
|
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
|
+
}
|
package/src/batch/diagnosis.mjs
CHANGED
|
@@ -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
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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}
|
|
347
|
-
: `${batchLabel} reviewer spawn
|
|
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`;
|
package/src/batch/engine.mjs
CHANGED
|
@@ -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
|
|
package/src/batch/journal.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
/**
|
package/src/batch/metrics.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
*
|
|
84
|
-
*
|
|
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} */ (
|
|
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 && !
|
|
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
|
-
|
|
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
|
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
8
|
-
import {
|
|
8
|
+
import { isEngineProcessAlive } from "../process/liveness.mjs";
|
|
9
9
|
|
|
10
10
|
/** @type {ReadonlySet<string>} */
|
|
11
11
|
export const ACTIVE_PHASES = new Set(["planning", "running", "paused"]);
|
|
@@ -54,16 +54,17 @@ export function evaluateBatchStateWriteGuard(projectRoot, state) {
|
|
|
54
54
|
const incomingBatchId = String(state.batchId ?? "");
|
|
55
55
|
const onDiskPhase = String(onDisk.phase ?? "");
|
|
56
56
|
const ownerPid = readBatchEnginePid(onDisk);
|
|
57
|
+
const ownerStartedAt = readBatchEngineStartedAt(onDisk);
|
|
57
58
|
if (
|
|
58
59
|
incomingBatchId &&
|
|
59
60
|
onDiskBatchId &&
|
|
60
61
|
incomingBatchId !== onDiskBatchId &&
|
|
61
62
|
TERMINAL_BATCH_PHASES.has(onDiskPhase) &&
|
|
62
|
-
(!ownerPid || !
|
|
63
|
+
(!ownerPid || !isEngineProcessAlive(ownerPid, ownerStartedAt))
|
|
63
64
|
) {
|
|
64
65
|
return { allowed: true };
|
|
65
66
|
}
|
|
66
|
-
if (ownerPid && ownerPid !== process.pid &&
|
|
67
|
+
if (ownerPid && ownerPid !== process.pid && isEngineProcessAlive(ownerPid, ownerStartedAt)) {
|
|
67
68
|
return { allowed: false, reason: "stale_engine_pid" };
|
|
68
69
|
}
|
|
69
70
|
} catch {
|
|
@@ -97,6 +98,28 @@ export function readBatchEnginePid(raw) {
|
|
|
97
98
|
return null;
|
|
98
99
|
}
|
|
99
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Stored engine start time (epoch ms) paired with `enginePid` for PID-reuse-safe
|
|
103
|
+
* liveness checks (SP-715 / #259).
|
|
104
|
+
*
|
|
105
|
+
* @param {unknown} raw
|
|
106
|
+
* @returns {number|null}
|
|
107
|
+
*/
|
|
108
|
+
export function readBatchEngineStartedAt(raw) {
|
|
109
|
+
if (!raw || typeof raw !== "object") return null;
|
|
110
|
+
/** @type {Record<string, unknown>} */
|
|
111
|
+
const state = /** @type {Record<string, unknown>} */ (raw);
|
|
112
|
+
const resilience =
|
|
113
|
+
state.resilience && typeof state.resilience === "object"
|
|
114
|
+
? /** @type {Record<string, unknown>} */ (state.resilience)
|
|
115
|
+
: null;
|
|
116
|
+
const fromResilience = Number(resilience?.engineStartedAt);
|
|
117
|
+
if (Number.isFinite(fromResilience) && fromResilience > 0) return fromResilience;
|
|
118
|
+
const topLevel = Number(state.engineStartedAt);
|
|
119
|
+
if (Number.isFinite(topLevel) && topLevel > 0) return topLevel;
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
100
123
|
/**
|
|
101
124
|
* @param {object} state
|
|
102
125
|
* @param {number} enginePid
|
package/src/batch/state-io.mjs
CHANGED
|
@@ -111,6 +111,52 @@ export function resolveBatchStateFileForValidation(projectRoot, batchId = null)
|
|
|
111
111
|
}
|
|
112
112
|
|
|
113
113
|
/**
|
|
114
|
+
* Quarantine a corrupt batch-history file instead of silently resetting it to
|
|
115
|
+
* `[]`. The audit trail is operator-facing state: losing it silently hides
|
|
116
|
+
* evidence of what batches ran, so the original bytes are preserved under
|
|
117
|
+
* `.spine/runtime/` and a loud error is emitted (#261).
|
|
118
|
+
*
|
|
119
|
+
* @param {string} projectRoot
|
|
120
|
+
* @param {string} filePath
|
|
121
|
+
* @param {string} reason
|
|
122
|
+
* @returns {string|null} quarantine path, or null if quarantine failed
|
|
123
|
+
*/
|
|
124
|
+
function quarantineCorruptBatchHistory(projectRoot, filePath, reason) {
|
|
125
|
+
const quarantineDir = path.join(projectRoot, ".spine", "runtime");
|
|
126
|
+
const quarantinePath = path.join(quarantineDir, `batch-history.json.corrupt.${Date.now()}`);
|
|
127
|
+
try {
|
|
128
|
+
fs.mkdirSync(quarantineDir, { recursive: true });
|
|
129
|
+
try {
|
|
130
|
+
fs.renameSync(filePath, quarantinePath);
|
|
131
|
+
} catch {
|
|
132
|
+
// Fall back to copy+unlink when rename is unsupported (e.g. cross-device).
|
|
133
|
+
fs.copyFileSync(filePath, quarantinePath);
|
|
134
|
+
fs.unlinkSync(filePath);
|
|
135
|
+
}
|
|
136
|
+
} catch (err) {
|
|
137
|
+
console.error(
|
|
138
|
+
`[spine] batch-history.json is corrupt (${reason}) and quarantine failed: ${
|
|
139
|
+
err instanceof Error ? err.message : String(err)
|
|
140
|
+
}. Refusing to overwrite the corrupt file.`,
|
|
141
|
+
);
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
console.error(
|
|
145
|
+
`[spine] batch-history.json is corrupt (${reason}); quarantined to ${path.relative(
|
|
146
|
+
projectRoot,
|
|
147
|
+
quarantinePath,
|
|
148
|
+
)}. Starting a fresh history — inspect the quarantined file to recover prior entries.`,
|
|
149
|
+
);
|
|
150
|
+
return quarantinePath;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Append an entry to `.spine/batch-history.json` atomically.
|
|
155
|
+
*
|
|
156
|
+
* The write goes through `writeJsonAtomic` (temp file + rename) so a crash or
|
|
157
|
+
* concurrent reader never observes a truncated history (#261). A corrupt
|
|
158
|
+
* existing file is quarantined, never silently reset to `[]`.
|
|
159
|
+
*
|
|
114
160
|
* @param {string} projectRoot
|
|
115
161
|
* @param {object} entry
|
|
116
162
|
*/
|
|
@@ -123,13 +169,25 @@ export function appendBatchHistoryEntry(projectRoot, entry) {
|
|
|
123
169
|
if (fs.existsSync(filePath)) {
|
|
124
170
|
try {
|
|
125
171
|
const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
126
|
-
if (Array.isArray(parsed))
|
|
127
|
-
|
|
128
|
-
|
|
172
|
+
if (Array.isArray(parsed)) {
|
|
173
|
+
history = parsed;
|
|
174
|
+
} else {
|
|
175
|
+
if (quarantineCorruptBatchHistory(projectRoot, filePath, "root value is not an array") === null) {
|
|
176
|
+
throw new Error(`Refusing to append batch history: ${filePath} is corrupt and could not be quarantined`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
} catch (err) {
|
|
180
|
+
if (err instanceof SyntaxError) {
|
|
181
|
+
if (quarantineCorruptBatchHistory(projectRoot, filePath, err.message) === null) {
|
|
182
|
+
throw new Error(`Refusing to append batch history: ${filePath} is corrupt and could not be quarantined`);
|
|
183
|
+
}
|
|
184
|
+
} else {
|
|
185
|
+
throw err;
|
|
186
|
+
}
|
|
129
187
|
}
|
|
130
188
|
}
|
|
131
189
|
|
|
132
190
|
history.push(entry);
|
|
133
|
-
|
|
191
|
+
writeJsonAtomic(filePath, history);
|
|
134
192
|
return filePath;
|
|
135
193
|
}
|
package/src/batch/state.mjs
CHANGED
|
@@ -34,19 +34,13 @@ export {
|
|
|
34
34
|
clearBatchEnginePid,
|
|
35
35
|
validateBatchState,
|
|
36
36
|
} from "./state-guards.mjs";
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const d = String(now.getUTCDate()).padStart(2, "0");
|
|
45
|
-
const h = String(now.getUTCHours()).padStart(2, "0");
|
|
46
|
-
const min = String(now.getUTCMinutes()).padStart(2, "0");
|
|
47
|
-
const s = String(now.getUTCSeconds()).padStart(2, "0");
|
|
48
|
-
return `${y}${m}${d}T${h}${min}${s}`;
|
|
49
|
-
}
|
|
37
|
+
export {
|
|
38
|
+
BATCH_ID_PATTERN,
|
|
39
|
+
batchIdRejectionReason,
|
|
40
|
+
generateBatchId,
|
|
41
|
+
isValidBatchId,
|
|
42
|
+
validateBatchId,
|
|
43
|
+
} from "./batch-id.mjs";
|
|
50
44
|
|
|
51
45
|
/**
|
|
52
46
|
* Reset lane stall clocks at resume handoff so dashboard does not show pre-resume heartbeats as stale.
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { writeJsonAtomic, writeTextAtomic } from "../fs/atomic-write.mjs";
|
|
9
|
+
import { redactTextSecrets } from "../util/secret-redact.mjs";
|
|
9
10
|
import { appendJournalEvent } from "./journal.mjs";
|
|
10
11
|
|
|
11
12
|
const DEFAULT_MAX_BYTES = 262_144;
|
|
@@ -13,14 +14,6 @@ const DEFAULT_LIVE_LOG_MAX_BYTES = 262_144;
|
|
|
13
14
|
const DEFAULT_TAIL_LINES = 200;
|
|
14
15
|
const TRUNCATION_MARKER = "\n...[worker output truncated]...\n";
|
|
15
16
|
|
|
16
|
-
const BUILTIN_REDACT_PATTERNS = [
|
|
17
|
-
/DATABASE_URL=\S+/gi,
|
|
18
|
-
/(?:postgres|mysql|mongodb)(?:\+srv)?:\/\/[^\s]+/gi,
|
|
19
|
-
/(?:bearer|token|secret|password|api[_-]?key)\s*[:=]\s*\S+/gi,
|
|
20
|
-
/sk-[a-zA-Z0-9]{20,}/g,
|
|
21
|
-
/ghp_[a-zA-Z0-9]{20,}/g,
|
|
22
|
-
];
|
|
23
|
-
|
|
24
17
|
/**
|
|
25
18
|
* @param {object} [config]
|
|
26
19
|
*/
|
|
@@ -57,19 +50,15 @@ export function resolveWorkerOutputConfig(config = {}) {
|
|
|
57
50
|
}
|
|
58
51
|
|
|
59
52
|
/**
|
|
53
|
+
* Redact value-shaped secrets in worker output via the shared policy
|
|
54
|
+
* (SP-716); caller-configured deny patterns run after the builtin set.
|
|
55
|
+
*
|
|
60
56
|
* @param {string} text
|
|
61
57
|
* @param {ReturnType<typeof resolveWorkerOutputConfig>} outputConfig
|
|
62
58
|
*/
|
|
63
59
|
export function redactWorkerOutput(text, outputConfig) {
|
|
64
60
|
if (!text) return "";
|
|
65
|
-
|
|
66
|
-
for (const pattern of BUILTIN_REDACT_PATTERNS) {
|
|
67
|
-
out = out.replace(pattern, "[REDACTED]");
|
|
68
|
-
}
|
|
69
|
-
for (const pattern of outputConfig.denyPatterns) {
|
|
70
|
-
out = out.replace(pattern, "[REDACTED]");
|
|
71
|
-
}
|
|
72
|
-
return out;
|
|
61
|
+
return /** @type {string} */ (redactTextSecrets(String(text), outputConfig.denyPatterns));
|
|
73
62
|
}
|
|
74
63
|
|
|
75
64
|
/**
|
package/src/cli/handoff.mjs
CHANGED
|
@@ -16,47 +16,30 @@ import {
|
|
|
16
16
|
import {
|
|
17
17
|
readJournalEvents,
|
|
18
18
|
readJournalTail,
|
|
19
|
-
redactSecrets,
|
|
20
19
|
} from "../batch/journal.mjs";
|
|
20
|
+
import { redactSecretsDeep, redactTextSecrets } from "../util/secret-redact.mjs";
|
|
21
21
|
import { computePendingTasks } from "../batch/resume-multi-validate.mjs";
|
|
22
22
|
import { formatJournalTailEntry } from "../dashboard/snapshot.mjs";
|
|
23
23
|
|
|
24
|
-
const SECRET_VALUE_PATTERN =
|
|
25
|
-
/\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET)[A-Z0-9_]*\s*=\s*\S+|\b(sk-[A-Za-z0-9_-]{8,})\b/gi;
|
|
26
|
-
|
|
27
24
|
const JOURNAL_TAIL_LIMIT = 10;
|
|
28
25
|
|
|
29
26
|
/**
|
|
27
|
+
* Redact value-shaped secrets in free text via the shared policy (SP-716).
|
|
28
|
+
*
|
|
30
29
|
* @param {string} text
|
|
31
30
|
*/
|
|
32
31
|
export function redactHandoffText(text) {
|
|
33
|
-
|
|
34
|
-
return text.replace(SECRET_VALUE_PATTERN, "[REDACTED]");
|
|
32
|
+
return redactTextSecrets(text);
|
|
35
33
|
}
|
|
36
34
|
|
|
37
35
|
/**
|
|
36
|
+
* Recursively redact denylisted keys and value-shaped secrets via the
|
|
37
|
+
* shared policy (SP-716).
|
|
38
|
+
*
|
|
38
39
|
* @param {unknown} value
|
|
39
40
|
*/
|
|
40
41
|
export function redactHandoffSecrets(value) {
|
|
41
|
-
|
|
42
|
-
return typeof value === "string" ? redactHandoffText(value) : value;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
if (Array.isArray(value)) {
|
|
46
|
-
return value.map((entry) => redactHandoffSecrets(entry));
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const redacted = redactSecrets(value);
|
|
50
|
-
if (!redacted || typeof redacted !== "object") {
|
|
51
|
-
return typeof redacted === "string" ? redactHandoffText(redacted) : redacted;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** @type {Record<string, unknown>} */
|
|
55
|
-
const out = {};
|
|
56
|
-
for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (redacted))) {
|
|
57
|
-
out[key] = redactHandoffSecrets(entry);
|
|
58
|
-
}
|
|
59
|
-
return out;
|
|
42
|
+
return redactSecretsDeep(value);
|
|
60
43
|
}
|
|
61
44
|
|
|
62
45
|
/**
|
|
@@ -97,7 +80,7 @@ function loadArchivedBatchState(projectRoot, batchId) {
|
|
|
97
80
|
function buildLaneSummary(lanes, classifiedTasks) {
|
|
98
81
|
return (lanes ?? []).map((lane) => {
|
|
99
82
|
const taskIds = lane.taskIds ?? [];
|
|
100
|
-
return
|
|
83
|
+
return redactHandoffSecrets({
|
|
101
84
|
laneNumber: lane.laneNumber,
|
|
102
85
|
laneId: lane.laneId ?? `lane-${lane.laneNumber}`,
|
|
103
86
|
taskIds,
|
|
@@ -132,7 +115,7 @@ function buildRestoreCommands(reconciliation) {
|
|
|
132
115
|
*/
|
|
133
116
|
function formatPendingTasks(pendingTasks) {
|
|
134
117
|
return pendingTasks.map((task) =>
|
|
135
|
-
|
|
118
|
+
redactHandoffSecrets({
|
|
136
119
|
taskId: task.taskId,
|
|
137
120
|
status: task.status ?? "pending",
|
|
138
121
|
taskFolder: task.taskFolder ?? null,
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import fs from "node:fs";
|
|
6
|
+
import { validateBatchId } from "../batch/batch-id.mjs";
|
|
6
7
|
import {
|
|
7
8
|
journalPath,
|
|
8
9
|
normalizeJournalEvent,
|
|
@@ -40,7 +41,7 @@ export function formatJournalFollowLine(event) {
|
|
|
40
41
|
* @param {string|null|undefined} batchId
|
|
41
42
|
*/
|
|
42
43
|
export function resolveFollowBatchId(projectRoot, batchId) {
|
|
43
|
-
if (batchId) return batchId;
|
|
44
|
+
if (batchId) return validateBatchId(batchId);
|
|
44
45
|
|
|
45
46
|
const reconciliation = reconcileBatch({ projectRoot });
|
|
46
47
|
if (reconciliation.batchId) return reconciliation.batchId;
|
|
@@ -160,7 +161,15 @@ const defaultDeps = {
|
|
|
160
161
|
export async function runJournalFollow(options) {
|
|
161
162
|
const { projectRoot, args = [], follow = true, deps = defaultDeps } = options;
|
|
162
163
|
const { batchId: argBatchId, laneId, json } = parseJournalFollowArgs(args);
|
|
163
|
-
|
|
164
|
+
let batchId = null;
|
|
165
|
+
try {
|
|
166
|
+
batchId = resolveFollowBatchId(projectRoot, argBatchId);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return {
|
|
169
|
+
exitCode: 1,
|
|
170
|
+
output: `${error instanceof Error ? error.message : String(error)}\n`,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
164
173
|
|
|
165
174
|
if (!batchId) {
|
|
166
175
|
return {
|
package/src/cli/lane-logs.mjs
CHANGED
|
@@ -204,7 +204,15 @@ export async function runLaneLogs(options) {
|
|
|
204
204
|
};
|
|
205
205
|
}
|
|
206
206
|
|
|
207
|
-
|
|
207
|
+
let batchId = null;
|
|
208
|
+
try {
|
|
209
|
+
batchId = resolveFollowBatchId(projectRoot, argBatchId);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
return {
|
|
212
|
+
exitCode: 1,
|
|
213
|
+
output: `${error instanceof Error ? error.message : String(error)}\n`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
208
216
|
if (!batchId) {
|
|
209
217
|
return {
|
|
210
218
|
exitCode: 1,
|
package/src/process/liveness.mjs
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Cross-platform process liveness
|
|
2
|
+
* Cross-platform process liveness checks (signal 0 / kill -0 equivalent),
|
|
3
|
+
* plus engine liveness paired with process start time (SP-715 / #259).
|
|
3
4
|
*/
|
|
4
5
|
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Default tolerance (ms) when comparing a probed process start time with the
|
|
11
|
+
* stored `engineStartedAt`. Absorbs `ps lstart` second-level granularity and
|
|
12
|
+
* the delay between engine process spawn and `recordBatchEnginePid`.
|
|
13
|
+
*/
|
|
14
|
+
export const ENGINE_STARTTIME_TOLERANCE_MS = 60_000;
|
|
15
|
+
|
|
5
16
|
/**
|
|
6
17
|
* @param {unknown} pid
|
|
7
18
|
* @returns {boolean}
|
|
@@ -19,3 +30,179 @@ export function isProcessAlive(pid) {
|
|
|
19
30
|
return false;
|
|
20
31
|
}
|
|
21
32
|
}
|
|
33
|
+
|
|
34
|
+
/** @type {number|null} */
|
|
35
|
+
let cachedClockTicksPerSecond = null;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Clock ticks per second (sysconf _SC_CLK_TCK) for /proc starttime conversion.
|
|
39
|
+
*
|
|
40
|
+
* @returns {number}
|
|
41
|
+
*/
|
|
42
|
+
function clockTicksPerSecond() {
|
|
43
|
+
if (cachedClockTicksPerSecond != null) return cachedClockTicksPerSecond;
|
|
44
|
+
let hz = 100;
|
|
45
|
+
try {
|
|
46
|
+
const out = execFileSync("getconf", ["CLK_TCK"], {
|
|
47
|
+
encoding: "utf-8",
|
|
48
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
49
|
+
}).trim();
|
|
50
|
+
const parsed = Number(out);
|
|
51
|
+
if (Number.isFinite(parsed) && parsed > 0) hz = parsed;
|
|
52
|
+
} catch {
|
|
53
|
+
/* getconf unavailable — Linux default USER_HZ is 100 */
|
|
54
|
+
}
|
|
55
|
+
cachedClockTicksPerSecond = hz;
|
|
56
|
+
return hz;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Linux: absolute process start time from `/proc/<pid>/starttime` (field 22 of
|
|
61
|
+
* stat, clock ticks since boot) combined with `btime` from /proc/stat.
|
|
62
|
+
* The comm field (2) may contain spaces/parens, so fields are parsed after the
|
|
63
|
+
* last ")".
|
|
64
|
+
*
|
|
65
|
+
* @param {number} pid
|
|
66
|
+
* @returns {number|null} epoch ms
|
|
67
|
+
*/
|
|
68
|
+
function readLinuxProcessStartMs(pid) {
|
|
69
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
70
|
+
const closeParen = stat.lastIndexOf(")");
|
|
71
|
+
if (closeParen < 0) return null;
|
|
72
|
+
const rest = stat.slice(closeParen + 1).trim().split(/\s+/);
|
|
73
|
+
// rest[0] is field 3 (state); starttime is field 22 → index 19.
|
|
74
|
+
const startTicks = Number(rest[19]);
|
|
75
|
+
if (!Number.isFinite(startTicks) || startTicks < 0) return null;
|
|
76
|
+
const procStat = fs.readFileSync("/proc/stat", "utf-8");
|
|
77
|
+
const btimeLine = procStat.split("\n").find((line) => line.startsWith("btime "));
|
|
78
|
+
if (!btimeLine) return null;
|
|
79
|
+
const bootSeconds = Number(btimeLine.slice("btime ".length).trim());
|
|
80
|
+
if (!Number.isFinite(bootSeconds) || bootSeconds <= 0) return null;
|
|
81
|
+
return (bootSeconds + startTicks / clockTicksPerSecond()) * 1000;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** @type {Record<string, number>} */
|
|
85
|
+
const PS_MONTH_INDEX = {
|
|
86
|
+
Jan: 0,
|
|
87
|
+
Feb: 1,
|
|
88
|
+
Mar: 2,
|
|
89
|
+
Apr: 3,
|
|
90
|
+
May: 4,
|
|
91
|
+
Jun: 5,
|
|
92
|
+
Jul: 6,
|
|
93
|
+
Aug: 7,
|
|
94
|
+
Sep: 8,
|
|
95
|
+
Oct: 9,
|
|
96
|
+
Nov: 10,
|
|
97
|
+
Dec: 11,
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Parse `ps -o lstart=` output ("Www Mmm dd hh:mm:ss yyyy") without relying on
|
|
102
|
+
* Date.parse, whose acceptance of this shape is implementation-defined.
|
|
103
|
+
*
|
|
104
|
+
* @param {string} text
|
|
105
|
+
* @returns {number|null} epoch ms (local time, matching ps output)
|
|
106
|
+
*/
|
|
107
|
+
function parsePsLstartMs(text) {
|
|
108
|
+
const match = /^\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/.exec(
|
|
109
|
+
text.trim(),
|
|
110
|
+
);
|
|
111
|
+
if (!match) return null;
|
|
112
|
+
const month = PS_MONTH_INDEX[match[1]];
|
|
113
|
+
if (month == null) return null;
|
|
114
|
+
const ms = new Date(
|
|
115
|
+
Number(match[6]),
|
|
116
|
+
month,
|
|
117
|
+
Number(match[2]),
|
|
118
|
+
Number(match[3]),
|
|
119
|
+
Number(match[4]),
|
|
120
|
+
Number(match[5]),
|
|
121
|
+
).getTime();
|
|
122
|
+
return Number.isFinite(ms) ? ms : null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* macOS / generic Unix fallback: process start time via `ps -p <pid> -o lstart=`.
|
|
127
|
+
*
|
|
128
|
+
* @param {number} pid
|
|
129
|
+
* @returns {number|null} epoch ms
|
|
130
|
+
*/
|
|
131
|
+
function readPsProcessStartMs(pid) {
|
|
132
|
+
const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
|
|
133
|
+
encoding: "utf-8",
|
|
134
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
135
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
136
|
+
}).trim();
|
|
137
|
+
if (!out) return null;
|
|
138
|
+
return parsePsLstartMs(out);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Best-effort absolute process start time (epoch ms) for a live pid.
|
|
143
|
+
* Returns null when the platform or probe cannot provide one.
|
|
144
|
+
*
|
|
145
|
+
* @param {unknown} pid
|
|
146
|
+
* @returns {number|null}
|
|
147
|
+
*/
|
|
148
|
+
export function probeProcessStartTimeMs(pid) {
|
|
149
|
+
const n = Number(pid);
|
|
150
|
+
if (!Number.isFinite(n) || n <= 0) return null;
|
|
151
|
+
// Windows limitation (SP-715 / #259): no start-time probe here; callers fall
|
|
152
|
+
// back to PID-only liveness, which can confuse a recycled PID for the engine.
|
|
153
|
+
if (process.platform === "win32") return null;
|
|
154
|
+
try {
|
|
155
|
+
if (process.platform === "linux") {
|
|
156
|
+
const fromProc = readLinuxProcessStartMs(n);
|
|
157
|
+
if (fromProc != null) return fromProc;
|
|
158
|
+
}
|
|
159
|
+
return readPsProcessStartMs(n);
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Engine liveness paired with the stored `engineStartedAt` so a recycled PID
|
|
167
|
+
* owned by an unrelated process is not mistaken for the batch engine
|
|
168
|
+
* (SP-715 / #259).
|
|
169
|
+
*
|
|
170
|
+
* Fallbacks (all preserve the previous PID-only behavior):
|
|
171
|
+
* - no `expectedStartedAt` recorded → PID-only
|
|
172
|
+
* - Windows → PID-only (documented limitation: PID reuse is not detected)
|
|
173
|
+
* - start-time probe unavailable → PID-only
|
|
174
|
+
*
|
|
175
|
+
* @param {unknown} pid
|
|
176
|
+
* @param {unknown} expectedStartedAt epoch ms recorded by recordBatchEnginePid
|
|
177
|
+
* @param {object} [options]
|
|
178
|
+
* @param {(pid: unknown) => boolean} [options.isAlive] injectable liveness probe
|
|
179
|
+
* @param {(pid: unknown) => number|null} [options.probeStartTimeMs] injectable start-time probe
|
|
180
|
+
* @param {string} [options.platform] injectable platform override
|
|
181
|
+
* @param {number} [options.toleranceMs] match tolerance (default ENGINE_STARTTIME_TOLERANCE_MS)
|
|
182
|
+
* @returns {boolean}
|
|
183
|
+
*/
|
|
184
|
+
export function isEngineProcessAlive(pid, expectedStartedAt, options = {}) {
|
|
185
|
+
const isAlive = options.isAlive ?? isProcessAlive;
|
|
186
|
+
if (!isAlive(pid)) return false;
|
|
187
|
+
|
|
188
|
+
const expected = Number(expectedStartedAt);
|
|
189
|
+
if (!Number.isFinite(expected) || expected <= 0) return true;
|
|
190
|
+
|
|
191
|
+
const platform = options.platform ?? process.platform;
|
|
192
|
+
if (platform === "win32") return true;
|
|
193
|
+
|
|
194
|
+
const probe = options.probeStartTimeMs ?? probeProcessStartTimeMs;
|
|
195
|
+
/** @type {number|null} */
|
|
196
|
+
let startedMs = null;
|
|
197
|
+
try {
|
|
198
|
+
startedMs = probe(pid);
|
|
199
|
+
} catch {
|
|
200
|
+
startedMs = null;
|
|
201
|
+
}
|
|
202
|
+
if (startedMs == null || !Number.isFinite(startedMs) || startedMs <= 0) return true;
|
|
203
|
+
|
|
204
|
+
const tolerance = Number.isFinite(Number(options.toleranceMs))
|
|
205
|
+
? Number(options.toleranceMs)
|
|
206
|
+
: ENGINE_STARTTIME_TOLERANCE_MS;
|
|
207
|
+
return Math.abs(startedMs - expected) <= tolerance;
|
|
208
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unified secret redaction policy shared across journal, worker-output,
|
|
3
|
+
* handoff, and metrics channels (SP-716, closes #260).
|
|
4
|
+
*
|
|
5
|
+
* Two complementary mechanisms:
|
|
6
|
+
* 1. Key denylist — object keys matching REDACT_KEY_PATTERN have their
|
|
7
|
+
* values replaced wholesale (see redactSecretsDeep).
|
|
8
|
+
* 2. Value patterns — well-known secret shapes (sk-, ghp_, bearer headers,
|
|
9
|
+
* connection strings, ENV-style assignments) are masked inside free
|
|
10
|
+
* text (see redactTextSecrets).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const REDACTED = "[REDACTED]";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Keys whose values are always redacted, matched case-insensitively.
|
|
17
|
+
* Must stay non-global: it is used with RegExp.prototype.test, which is
|
|
18
|
+
* stateful for global regexes.
|
|
19
|
+
*/
|
|
20
|
+
export const REDACT_KEY_PATTERN = /key|token|secret|password/i;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Value-shaped secret patterns, ordered most-specific first so that
|
|
24
|
+
* assignment-shaped matches (e.g. OPENAI_API_KEY=sk-...) are consumed whole
|
|
25
|
+
* before the generic key:value fallback can leave partial fragments behind.
|
|
26
|
+
*
|
|
27
|
+
* Safety: these regexes carry the global flag and are only safe to use with
|
|
28
|
+
* String.prototype.replace, which resets lastIndex before iterating. Do not
|
|
29
|
+
* use them with .test() or .exec().
|
|
30
|
+
*/
|
|
31
|
+
export const SECRET_VALUE_PATTERNS = Object.freeze([
|
|
32
|
+
// ENV-style assignments: OPENAI_API_KEY=..., GITHUB_TOKEN = ...
|
|
33
|
+
/\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*\s*=\s*\S+/g,
|
|
34
|
+
// Bearer authorization headers.
|
|
35
|
+
/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/g,
|
|
36
|
+
// Database connection strings embed credentials.
|
|
37
|
+
/(?:postgres|mysql|mongodb)(?:\+srv)?:\/\/[^\s]+/gi,
|
|
38
|
+
/\bDATABASE_URL=\S+/gi,
|
|
39
|
+
// Well-known token shapes.
|
|
40
|
+
/\bsk-[A-Za-z0-9_-]{8,}/g,
|
|
41
|
+
/\bghp_[A-Za-z0-9]{8,}/g,
|
|
42
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
43
|
+
/\bAKIA[0-9A-Z]{16}/g,
|
|
44
|
+
/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
|
|
45
|
+
// Generic key:value / key=value fallback.
|
|
46
|
+
/\b(?:bearer|token|secret|password|api[_-]?key)\s*[:=]\s*\S+/gi,
|
|
47
|
+
]);
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Mask value-shaped secrets in free text. Extra caller-supplied patterns
|
|
51
|
+
* (e.g. workerOutputDenyPatterns from config) run after the builtin set.
|
|
52
|
+
*
|
|
53
|
+
* @param {unknown} text
|
|
54
|
+
* @param {RegExp[]} [extraPatterns]
|
|
55
|
+
* @returns {unknown}
|
|
56
|
+
*/
|
|
57
|
+
export function redactTextSecrets(text, extraPatterns = []) {
|
|
58
|
+
if (typeof text !== "string" || !text) return text;
|
|
59
|
+
let out = text;
|
|
60
|
+
for (const pattern of SECRET_VALUE_PATTERNS) {
|
|
61
|
+
out = out.replace(pattern, REDACTED);
|
|
62
|
+
}
|
|
63
|
+
for (const pattern of extraPatterns) {
|
|
64
|
+
out = out.replace(pattern, REDACTED);
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Recursively redact secrets in a JSON-shaped value:
|
|
71
|
+
* - object keys matching the key denylist are replaced wholesale,
|
|
72
|
+
* - string values are scanned for value-shaped secrets,
|
|
73
|
+
* - arrays and nested objects are traversed.
|
|
74
|
+
*
|
|
75
|
+
* @param {unknown} value
|
|
76
|
+
* @param {object} [options]
|
|
77
|
+
* @param {RegExp} [options.keyPattern] Override key denylist (must be
|
|
78
|
+
* non-global; RegExp.prototype.test is stateful for global regexes).
|
|
79
|
+
* @param {Set<string>} [options.allowedKeys] Keys exempt from the denylist
|
|
80
|
+
* (e.g. usage counters like tokensIn).
|
|
81
|
+
* @param {RegExp[]} [options.extraPatterns] Additional value patterns.
|
|
82
|
+
* @returns {unknown}
|
|
83
|
+
*/
|
|
84
|
+
export function redactSecretsDeep(value, options = {}) {
|
|
85
|
+
const keyPattern = options.keyPattern ?? REDACT_KEY_PATTERN;
|
|
86
|
+
const allowedKeys = options.allowedKeys ?? null;
|
|
87
|
+
const extraPatterns = Array.isArray(options.extraPatterns) ? options.extraPatterns : [];
|
|
88
|
+
|
|
89
|
+
if (typeof value === "string") {
|
|
90
|
+
return redactTextSecrets(value, extraPatterns);
|
|
91
|
+
}
|
|
92
|
+
if (value == null || typeof value !== "object") {
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
if (Array.isArray(value)) {
|
|
96
|
+
return value.map((entry) => redactSecretsDeep(entry, options));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @type {Record<string, unknown>} */
|
|
100
|
+
const out = {};
|
|
101
|
+
for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
|
|
102
|
+
if (keyPattern.test(key) && !(allowedKeys && allowedKeys.has(key))) {
|
|
103
|
+
out[key] = REDACTED;
|
|
104
|
+
} else {
|
|
105
|
+
out[key] = redactSecretsDeep(entry, options);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Cap a JSON-serializable payload by UTF-8 bytes — not string length — so
|
|
113
|
+
* multi-byte characters cannot push the serialized record past the budget.
|
|
114
|
+
* Returns the payload unchanged when it already fits; otherwise returns a
|
|
115
|
+
* truncation marker record whose preview is sliced on byte boundaries.
|
|
116
|
+
*
|
|
117
|
+
* @param {Record<string, unknown>} payload
|
|
118
|
+
* @param {number} maxBytes
|
|
119
|
+
* @returns {Record<string, unknown>}
|
|
120
|
+
*/
|
|
121
|
+
export function capPayloadBytes(payload, maxBytes) {
|
|
122
|
+
const serialized = JSON.stringify(payload);
|
|
123
|
+
const originalBytes = Buffer.byteLength(serialized, "utf-8");
|
|
124
|
+
if (originalBytes <= maxBytes) {
|
|
125
|
+
return payload;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Reserve 256 bytes of headroom for the truncation wrapper so the
|
|
129
|
+
// re-serialized record stays near maxBytes. Buffer.subarray slices on byte
|
|
130
|
+
// boundaries; decoding never emits invalid UTF-8 (partial trailing
|
|
131
|
+
// sequences become U+FFFD).
|
|
132
|
+
const budget = Math.max(0, maxBytes - 256);
|
|
133
|
+
const preview = Buffer.from(serialized, "utf-8").subarray(0, budget).toString("utf-8");
|
|
134
|
+
return {
|
|
135
|
+
_truncated: true,
|
|
136
|
+
_originalBytes: originalBytes,
|
|
137
|
+
_maxBytes: maxBytes,
|
|
138
|
+
preview,
|
|
139
|
+
};
|
|
140
|
+
}
|