pi-spine 2.31.0 → 2.33.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/bin/spine-batch.mjs +16 -2
- package/bin/spine-gate.mjs +24 -2
- package/bin/spine-integrate.mjs +23 -3
- package/bin/spine-journal.mjs +25 -2
- package/bin/spine-plan.mjs +15 -5
- package/bin/spine-state.mjs +22 -1
- package/bin/spine-worker-runner.mjs +182 -15
- package/package.json +1 -1
- package/src/batch/batch-id.mjs +55 -0
- package/src/batch/contract-exec.mjs +64 -56
- package/src/batch/engine-lanes/matrix-run.mjs +69 -9
- package/src/batch/engine-lanes/queue.mjs +54 -1
- package/src/batch/engine-lanes/review-plan.mjs +111 -48
- package/src/batch/engine-lanes/review-poll.mjs +6 -0
- package/src/batch/gate-posture-approve.mjs +47 -46
- package/src/batch/gate-posture-streak.mjs +69 -25
- package/src/batch/integrate.mjs +1 -0
- package/src/batch/metrics.mjs +15 -0
- package/src/batch/pi-json-usage.mjs +262 -0
- package/src/batch/reconcile-classify.mjs +146 -164
- package/src/batch/review-scope.mjs +3 -0
- package/src/batch/review-spawn.mjs +48 -2
- package/src/batch/review-step.mjs +8 -0
- package/src/batch/worker-host.mjs +18 -18
- package/src/cli/handoff.mjs +14 -1
- package/src/config/cursor-rules/profile.mjs +7 -2
- package/src/config/worker-context.mjs +6 -3
- package/src/dashboard/server.mjs +101 -9
- package/src/tasks/validate-contract-warn.mjs +121 -0
- package/templates/rules-profile.json +1 -27
package/bin/spine-batch.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
startBatchDetached,
|
|
9
9
|
} from "../src/batch/detached-start.mjs";
|
|
10
10
|
import { dismissBatch } from "../src/batch/lifecycle.mjs";
|
|
11
|
+
import { batchIdRejectionReason } from "../src/batch/batch-id.mjs";
|
|
11
12
|
import { runBatchComplete } from "../src/cli/batch-complete.mjs";
|
|
12
13
|
import { forceMergeWave, startBatch } from "../src/batch/engine.mjs";
|
|
13
14
|
import { parseBatchStartWaveFilter } from "../src/planner/wave-scope.mjs";
|
|
@@ -158,8 +159,10 @@ export function parseBatchArgs(args) {
|
|
|
158
159
|
|
|
159
160
|
let batchId = null;
|
|
160
161
|
const batchIdx = args.indexOf("--batch");
|
|
161
|
-
if (batchIdx >= 0
|
|
162
|
-
|
|
162
|
+
if (batchIdx >= 0) {
|
|
163
|
+
// SP-869 (#313): a bare `--batch` (flag without a value) must not fall
|
|
164
|
+
// through to active-batch fallbacks; capture "" so the validator rejects.
|
|
165
|
+
batchId = args[batchIdx + 1] ?? "";
|
|
163
166
|
}
|
|
164
167
|
|
|
165
168
|
let reason = null;
|
|
@@ -264,6 +267,17 @@ export async function runSpineBatch(options) {
|
|
|
264
267
|
}
|
|
265
268
|
const parsed = parseBatchArgs(args);
|
|
266
269
|
|
|
270
|
+
// SP-869 (#313): reject unsafe --batch IDs before any runtime path join.
|
|
271
|
+
if (parsed.batchId != null) {
|
|
272
|
+
const reason = batchIdRejectionReason(parsed.batchId);
|
|
273
|
+
if (reason) {
|
|
274
|
+
return {
|
|
275
|
+
exitCode: 1,
|
|
276
|
+
output: `Invalid batch ID ${JSON.stringify(String(parsed.batchId))}: ${reason}\n`,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
267
281
|
if (parsed.subcommand === "dismiss") {
|
|
268
282
|
const result = dismissBatch({
|
|
269
283
|
projectRoot,
|
package/bin/spine-gate.mjs
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
import { isCliEntrypoint } from "./spine-cli/shared.mjs";
|
|
8
8
|
import { parseStrictArgs, strictArgsError } from "./spine-cli/cli-args.mjs";
|
|
9
|
+
import { validateBatchId } from "../src/batch/batch-id.mjs";
|
|
9
10
|
import { loadBatchStateFile } from "../src/batch/reconcile.mjs";
|
|
10
11
|
import {
|
|
11
12
|
approveIntegrateGate,
|
|
@@ -79,7 +80,8 @@ export function formatGateHuman(result, json = false) {
|
|
|
79
80
|
* @param {string|null} batchId
|
|
80
81
|
*/
|
|
81
82
|
function resolveActiveBatchId(projectRoot, batchId) {
|
|
82
|
-
|
|
83
|
+
// SP-869 (#313): reject unsafe --batch IDs before any .spine/runtime path join.
|
|
84
|
+
if (batchId) return validateBatchId(batchId);
|
|
83
85
|
const loaded = loadBatchStateFile(projectRoot, null);
|
|
84
86
|
if (!loaded.raw) return null;
|
|
85
87
|
return String(loaded.raw.batchId ?? loaded.raw.id ?? "");
|
|
@@ -104,7 +106,27 @@ export function runSpineGate(options) {
|
|
|
104
106
|
const action = parsed.positional[0] ?? "status";
|
|
105
107
|
const reason = parsed.values.get("--reason") ?? null;
|
|
106
108
|
const synthesis = parsed.values.get("--synthesis") ?? null;
|
|
107
|
-
|
|
109
|
+
|
|
110
|
+
let batchId;
|
|
111
|
+
try {
|
|
112
|
+
batchId = resolveActiveBatchId(projectRoot, parsed.values.get("--batch") ?? null);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
// SP-869 (#313): invalid --batch exits non-zero with a clear error instead
|
|
115
|
+
// of interpolating raw input into runtime paths.
|
|
116
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
117
|
+
const result = {
|
|
118
|
+
ok: false,
|
|
119
|
+
exitCode: 2,
|
|
120
|
+
headline: "Invalid --batch ID",
|
|
121
|
+
suggestedCommand: "spine gate status --batch <ID>",
|
|
122
|
+
error,
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
exitCode: result.exitCode,
|
|
126
|
+
output: formatGateHuman(result, flags.has("--json")),
|
|
127
|
+
result,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
108
130
|
if (!batchId) {
|
|
109
131
|
const result = {
|
|
110
132
|
ok: false,
|
package/bin/spine-integrate.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { integrateOrchToBase } from "../src/batch/integrate.mjs";
|
|
2
|
+
import { validateBatchId } from "../src/batch/batch-id.mjs";
|
|
2
3
|
import { parseStrictArgs, strictArgsError } from "./spine-cli/cli-args.mjs";
|
|
3
4
|
|
|
4
5
|
const INTEGRATE_USAGE = `
|
|
@@ -41,11 +42,15 @@ export function formatIntegrateHuman(result, json = false) {
|
|
|
41
42
|
if (result.mergePlan) {
|
|
42
43
|
lines.push(` Plan: ${result.mergePlan}`);
|
|
43
44
|
}
|
|
44
|
-
if (result.gateRequired) {
|
|
45
|
-
lines.push("", " Gate: approval required before integrate");
|
|
46
|
-
}
|
|
47
45
|
if (result.failureClass === "GateBlocked") {
|
|
46
|
+
// Integrate actually stopped for a pending/missing/rejected gate (#359).
|
|
48
47
|
lines.push("", " Gate: integrate blocked until approved");
|
|
48
|
+
} else if (result.dryRun && result.gatePending) {
|
|
49
|
+
// Dry-run plan: approval will be required before the real merge.
|
|
50
|
+
lines.push("", " Gate: approval required before integrate");
|
|
51
|
+
} else if (result.ok && result.gateRequired && !result.gateForced) {
|
|
52
|
+
// Successful merge with a configured gate — it was satisfied, not pending (#359).
|
|
53
|
+
lines.push("", " Gate: approved");
|
|
49
54
|
}
|
|
50
55
|
|
|
51
56
|
lines.push("", ` → ${result.suggestedCommand}`);
|
|
@@ -83,6 +88,21 @@ export function runSpineIntegrate(options) {
|
|
|
83
88
|
return { exitCode: 2, output: `${usageError}\n${INTEGRATE_USAGE}`, result: { ok: false, error: usageError } };
|
|
84
89
|
}
|
|
85
90
|
|
|
91
|
+
// SP-869 (#313): reject unsafe --batch IDs before runtime path joins.
|
|
92
|
+
const batchArg = parsed.values.get("--batch") ?? null;
|
|
93
|
+
if (batchArg) {
|
|
94
|
+
try {
|
|
95
|
+
validateBatchId(batchArg);
|
|
96
|
+
} catch (err) {
|
|
97
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
98
|
+
return {
|
|
99
|
+
exitCode: 2,
|
|
100
|
+
output: `${error}\n${INTEGRATE_USAGE}`,
|
|
101
|
+
result: { ok: false, error },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
86
106
|
const result = integrateOrchToBase({
|
|
87
107
|
projectRoot,
|
|
88
108
|
dryRun: flags.has("--dry-run"),
|
package/bin/spine-journal.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
readJournalEvents,
|
|
7
7
|
summarizeJournalEvent,
|
|
8
8
|
} from "../src/batch/journal.mjs";
|
|
9
|
+
import { batchIdRejectionReason } from "../src/batch/batch-id.mjs";
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* @param {string} timestamp
|
|
@@ -90,7 +91,18 @@ const JOURNAL_USAGE =
|
|
|
90
91
|
*/
|
|
91
92
|
function runJournalReplay(projectRoot, args) {
|
|
92
93
|
const batchIdx = args.indexOf("--batch");
|
|
93
|
-
const batchId = batchIdx >= 0 ? args[batchIdx + 1] : null;
|
|
94
|
+
const batchId = batchIdx >= 0 ? (args[batchIdx + 1] ?? "") : null;
|
|
95
|
+
// SP-869 (#313): reject unsafe --batch IDs (including a bare flag with no
|
|
96
|
+
// value, captured as "") before journal path joins.
|
|
97
|
+
if (batchId != null) {
|
|
98
|
+
const reason = batchIdRejectionReason(batchId);
|
|
99
|
+
if (reason) {
|
|
100
|
+
return {
|
|
101
|
+
exitCode: 1,
|
|
102
|
+
output: `Invalid batch ID ${JSON.stringify(String(batchId))}: ${reason}\n${JOURNAL_USAGE}`,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
94
106
|
const json = args.includes("--json");
|
|
95
107
|
|
|
96
108
|
if (!batchId) {
|
|
@@ -130,7 +142,18 @@ function runJournalExport(projectRoot, args) {
|
|
|
130
142
|
const exportUsage =
|
|
131
143
|
"Usage: spine journal export --batch {id} --format markdown|jsonl [--output path]\n";
|
|
132
144
|
const batchIdx = args.indexOf("--batch");
|
|
133
|
-
const batchId = batchIdx >= 0 ? args[batchIdx + 1] : null;
|
|
145
|
+
const batchId = batchIdx >= 0 ? (args[batchIdx + 1] ?? "") : null;
|
|
146
|
+
// SP-869 (#313): reject unsafe --batch IDs (including a bare flag with no
|
|
147
|
+
// value, captured as "") before journal path joins.
|
|
148
|
+
if (batchId != null) {
|
|
149
|
+
const reason = batchIdRejectionReason(batchId);
|
|
150
|
+
if (reason) {
|
|
151
|
+
return {
|
|
152
|
+
exitCode: 1,
|
|
153
|
+
output: `Invalid batch ID ${JSON.stringify(String(batchId))}: ${reason}\n${exportUsage}`,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
134
157
|
const formatIdx = args.indexOf("--format");
|
|
135
158
|
const format = formatIdx >= 0 ? args[formatIdx + 1] : null;
|
|
136
159
|
const outputIdx = args.indexOf("--output");
|
package/bin/spine-plan.mjs
CHANGED
|
@@ -22,15 +22,14 @@ function getTimestampForFilename(d = new Date()) {
|
|
|
22
22
|
return d.toISOString().replace(/[:.]/g, '-');
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
function writePlanArtifact({ projectRoot, plan }) {
|
|
25
|
+
async function writePlanArtifact({ projectRoot, plan }) {
|
|
26
26
|
const runtimeDir = path.join(projectRoot, '.spine', 'runtime');
|
|
27
|
-
fs.
|
|
27
|
+
await fs.promises.mkdir(runtimeDir, { recursive: true });
|
|
28
28
|
const timestamp = getTimestampForFilename();
|
|
29
29
|
const artifactPath = path.join(runtimeDir, `plan-${timestamp}.json`);
|
|
30
|
-
fs.
|
|
30
|
+
await fs.promises.writeFile(artifactPath, JSON.stringify(plan, null, 2), 'utf-8');
|
|
31
31
|
return artifactPath;
|
|
32
32
|
}
|
|
33
|
-
|
|
34
33
|
/**
|
|
35
34
|
* Format a friendly informational message when pending scope has zero tasks.
|
|
36
35
|
*
|
|
@@ -64,6 +63,17 @@ function formatEmptyPendingResult({ excludedCount = 0, discoveredCount = 0 }, la
|
|
|
64
63
|
return { plan: null, artifactPath: null, output: lines.join('\n') };
|
|
65
64
|
}
|
|
66
65
|
|
|
66
|
+
/**
|
|
67
|
+
* Build the plan, write the artifact, and return formatted output.
|
|
68
|
+
* SP-877 (#319): the artifact write is a real `await` — the signature is
|
|
69
|
+
* no longer fake-async (async with zero awaits).
|
|
70
|
+
*
|
|
71
|
+
* @param {object} [options]
|
|
72
|
+
* @param {string} [options.projectRoot]
|
|
73
|
+
* @param {string} [options.scope]
|
|
74
|
+
* @param {boolean} [options.json]
|
|
75
|
+
* @returns {Promise<{ plan: object|null, artifactPath: string|null, output: string }>}
|
|
76
|
+
*/
|
|
67
77
|
export async function runSpinePlan({
|
|
68
78
|
projectRoot = process.cwd(),
|
|
69
79
|
scope = 'all',
|
|
@@ -99,7 +109,7 @@ export async function runSpinePlan({
|
|
|
99
109
|
throw err;
|
|
100
110
|
}
|
|
101
111
|
|
|
102
|
-
const artifactPath = writePlanArtifact({ projectRoot, plan });
|
|
112
|
+
const artifactPath = await writePlanArtifact({ projectRoot, plan });
|
|
103
113
|
|
|
104
114
|
if (json) {
|
|
105
115
|
return { plan, artifactPath, output: JSON.stringify(plan, null, 2) };
|
package/bin/spine-state.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
resolveBatchStateFileForValidation,
|
|
5
5
|
validateBatchState,
|
|
6
6
|
} from "../src/batch/state.mjs";
|
|
7
|
+
import { batchIdRejectionReason } from "../src/batch/batch-id.mjs";
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* @param {object} options
|
|
@@ -22,10 +23,30 @@ export function runSpineState(options) {
|
|
|
22
23
|
}
|
|
23
24
|
|
|
24
25
|
const batchIdx = args.indexOf("--batch");
|
|
25
|
-
|
|
26
|
+
// SP-869 (#313): a bare `--batch` (flag without a value) is captured as ""
|
|
27
|
+
// so the validator below rejects it instead of falling back silently.
|
|
28
|
+
const batchId = batchIdx >= 0 ? (args[batchIdx + 1] ?? "") : null;
|
|
26
29
|
const json = args.includes("--json");
|
|
27
30
|
const diagnose = args.includes("--diagnose");
|
|
28
31
|
|
|
32
|
+
// SP-869 (#313): reject unsafe --batch IDs before state file path joins.
|
|
33
|
+
if (batchId != null) {
|
|
34
|
+
const reason = batchIdRejectionReason(batchId);
|
|
35
|
+
if (reason) {
|
|
36
|
+
const message = `Invalid batch ID ${JSON.stringify(String(batchId))}: ${reason}`;
|
|
37
|
+
if (json) {
|
|
38
|
+
return {
|
|
39
|
+
exitCode: 1,
|
|
40
|
+
output: `${JSON.stringify({ ok: false, error: message }, null, 2)}\n`,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
exitCode: 1,
|
|
45
|
+
output: `❌ ${message}\n → spine state validate --batch <ID>\n`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
29
50
|
const resolved = resolveBatchStateFileForValidation(projectRoot, batchId);
|
|
30
51
|
if (!resolved.path) {
|
|
31
52
|
const message = resolved.error ?? "No batch-state file found";
|
|
@@ -35,6 +35,10 @@ import {
|
|
|
35
35
|
truncateLiveLogBytes,
|
|
36
36
|
writeWorkerDoneMarker,
|
|
37
37
|
} from "../src/batch/worker-output.mjs";
|
|
38
|
+
import {
|
|
39
|
+
extractTextFromPiJsonStream,
|
|
40
|
+
sumUsageFromPiJsonStream,
|
|
41
|
+
} from "../src/batch/pi-json-usage.mjs";
|
|
38
42
|
import { buildWorkerTailPrompt, taskIdFromFolder } from "../src/batch/worker-prompt.mjs";
|
|
39
43
|
import { taskIdFromFolderName } from "../src/tasks/packet/discover.mjs";
|
|
40
44
|
import { DEFAULT_TASKS_ROOT } from "../src/config/spine-init-constants.mjs";
|
|
@@ -123,7 +127,11 @@ export async function buildWorkerPiArgs({
|
|
|
123
127
|
if (shouldWorkerUsePiNoExtensions({ projectRoot })) {
|
|
124
128
|
piArgs.push("-ne");
|
|
125
129
|
}
|
|
126
|
-
|
|
130
|
+
// SP-879 (#338): JSON mode turns stdout into a structured NDJSON event
|
|
131
|
+
// stream so provider-reported usage can be persisted into run-metrics.
|
|
132
|
+
// Positional contract: `-ne? -p --no-session --mode json …` — existing
|
|
133
|
+
// argv tests assert indexes before this point and the tail prompt last.
|
|
134
|
+
piArgs.push("-p", "--no-session", "--mode", "json");
|
|
127
135
|
if (workerAgentPath && fs.existsSync(workerAgentPath)) {
|
|
128
136
|
piArgs.push("--append-system-prompt", workerAgentPath);
|
|
129
137
|
}
|
|
@@ -168,6 +176,107 @@ export function buildDoneMissingPiOutputFlush(result, config = {}) {
|
|
|
168
176
|
};
|
|
169
177
|
}
|
|
170
178
|
|
|
179
|
+
/** Sidecar filename the engine reads in recordLaneTaskMetric (engine-lanes/queue.mjs). Keep both definitions in sync. */
|
|
180
|
+
const WORKER_USAGE_SIDECAR_FILENAME = "worker-usage.json";
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* True when the parsed pi JSON stream reported at least one usage counter.
|
|
184
|
+
*
|
|
185
|
+
* @param {{tokensIn?: number, tokensOut?: number, estimatedUsd?: number}} usage
|
|
186
|
+
* @returns {boolean}
|
|
187
|
+
*/
|
|
188
|
+
export function hasWorkerUsage(usage) {
|
|
189
|
+
return usage.tokensIn !== undefined || usage.tokensOut !== undefined || usage.estimatedUsd !== undefined;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Sum provider-reported usage from a pi spawn result's JSON-mode stdout.
|
|
194
|
+
* Delegates to the SP-878 parser: only events pi actually reported are
|
|
195
|
+
* counted; non-JSON output yields `{}` so no usage is ever invented.
|
|
196
|
+
*
|
|
197
|
+
* @param {{stdout?: string|null}} result
|
|
198
|
+
* @returns {{tokensIn?: number, tokensOut?: number, estimatedUsd?: number}}
|
|
199
|
+
*/
|
|
200
|
+
export function workerUsageFromResult(result) {
|
|
201
|
+
const stdout = typeof result?.stdout === "string" ? result.stdout : "";
|
|
202
|
+
if (stdout.length === 0) return {};
|
|
203
|
+
return sumUsageFromPiJsonStream(stdout);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Remove a stale usage sidecar left by a previous attempt. Must run before
|
|
208
|
+
* every pi spawn so an attempt that produces no usage cannot inherit the
|
|
209
|
+
* previous attempt's totals.
|
|
210
|
+
*
|
|
211
|
+
* @param {string} taskFolder
|
|
212
|
+
* @returns {void}
|
|
213
|
+
*/
|
|
214
|
+
export function clearWorkerUsageSidecar(taskFolder) {
|
|
215
|
+
try {
|
|
216
|
+
fs.rmSync(path.join(taskFolder, WORKER_USAGE_SIDECAR_FILENAME), { force: true });
|
|
217
|
+
} catch {
|
|
218
|
+
// Sidecar hygiene is best-effort; a leftover file at worst carries a
|
|
219
|
+
// previous attempt's real usage, never an invented one.
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Persist provider-reported usage next to the task packet. The engine reads
|
|
225
|
+
* this sidecar in recordLaneTaskMetric (engine-lanes/queue.mjs) and copies
|
|
226
|
+
* the finite counters onto the task metric record. Called only with totals
|
|
227
|
+
* the parser actually reported — never with defaults or guesses.
|
|
228
|
+
*
|
|
229
|
+
* @param {object} params
|
|
230
|
+
* @param {string} params.taskFolder
|
|
231
|
+
* @param {{tokensIn?: number, tokensOut?: number, estimatedUsd?: number}} params.usage
|
|
232
|
+
* @returns {string | null} sidecar path, or null when there is nothing to persist.
|
|
233
|
+
*/
|
|
234
|
+
export function persistWorkerUsageSidecar({ taskFolder, usage }) {
|
|
235
|
+
if (!taskFolder || !hasWorkerUsage(usage)) return null;
|
|
236
|
+
const sidecarPath = path.join(taskFolder, WORKER_USAGE_SIDECAR_FILENAME);
|
|
237
|
+
try {
|
|
238
|
+
fs.writeFileSync(
|
|
239
|
+
sidecarPath,
|
|
240
|
+
`${JSON.stringify(
|
|
241
|
+
{
|
|
242
|
+
schemaVersion: 1,
|
|
243
|
+
recordType: "worker-usage",
|
|
244
|
+
source: "pi-json-stdout",
|
|
245
|
+
endedAt: new Date().toISOString(),
|
|
246
|
+
...usage,
|
|
247
|
+
},
|
|
248
|
+
null,
|
|
249
|
+
"\t",
|
|
250
|
+
)}\n`,
|
|
251
|
+
"utf-8",
|
|
252
|
+
);
|
|
253
|
+
return sidecarPath;
|
|
254
|
+
} catch {
|
|
255
|
+
// Metrics are advisory: a read-only task folder must not fail the run.
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Human-readable assistant text from a pi JSON-mode stream, for tee-ing into
|
|
262
|
+
* run logs now that stdout carries NDJSON instead of prose. Empty when the
|
|
263
|
+
* stream holds no assistant text segments. Capped by the caller.
|
|
264
|
+
*
|
|
265
|
+
* @param {{stdout?: string|null}} result
|
|
266
|
+
* @returns {string}
|
|
267
|
+
*/
|
|
268
|
+
export function workerPiLogTextFromResult(result) {
|
|
269
|
+
const stdout = typeof result?.stdout === "string" ? result.stdout : "";
|
|
270
|
+
if (stdout.length === 0) return "";
|
|
271
|
+
try {
|
|
272
|
+
return extractTextFromPiJsonStream(stdout).join("\n\n");
|
|
273
|
+
} catch {
|
|
274
|
+
// extractText only throws on non-string/non-iterable input, which the
|
|
275
|
+
// guard above rules out; kept defensive so log tee-ing never kills a run.
|
|
276
|
+
return "";
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
171
280
|
/**
|
|
172
281
|
* @param {string} taskFolder
|
|
173
282
|
* @returns {string[]}
|
|
@@ -271,17 +380,42 @@ export function writeStubDeliveryStatusIfNeeded({ taskFolder, tasksRoot = DEFAUL
|
|
|
271
380
|
return true;
|
|
272
381
|
}
|
|
273
382
|
|
|
274
|
-
|
|
383
|
+
/**
|
|
384
|
+
* Resolve the task File Scope. `SPINE_TASK_FILE_SCOPE` (written by worker-spawn
|
|
385
|
+
* from the parsed Contract) wins when set. SP-877 (#319): a set-but-malformed
|
|
386
|
+
* value fails loudly instead of silently falling back to a PROMPT.md re-parse,
|
|
387
|
+
* which could hand the worker a stale or empty file scope.
|
|
388
|
+
*
|
|
389
|
+
* @param {string} taskFolder
|
|
390
|
+
* @returns {string[]}
|
|
391
|
+
* @throws {Error} when SPINE_TASK_FILE_SCOPE is set but is not valid JSON, not
|
|
392
|
+
* an array, or contains non-string entries.
|
|
393
|
+
*/
|
|
394
|
+
export function resolveTaskFileScope(taskFolder) {
|
|
275
395
|
const envScope = process.env.SPINE_TASK_FILE_SCOPE;
|
|
276
396
|
if (envScope) {
|
|
397
|
+
let parsed;
|
|
277
398
|
try {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
399
|
+
parsed = JSON.parse(envScope);
|
|
400
|
+
} catch (err) {
|
|
401
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
402
|
+
throw new Error(
|
|
403
|
+
`SPINE_TASK_FILE_SCOPE is not valid JSON (${reason}); fix the value or unset it to re-parse PROMPT.md`,
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
if (!Array.isArray(parsed)) {
|
|
407
|
+
throw new Error(
|
|
408
|
+
`SPINE_TASK_FILE_SCOPE must be a JSON array of file paths, got ${typeof parsed}`,
|
|
409
|
+
);
|
|
284
410
|
}
|
|
411
|
+
return parsed.map((entry, index) => {
|
|
412
|
+
if (typeof entry !== "string") {
|
|
413
|
+
throw new Error(
|
|
414
|
+
`SPINE_TASK_FILE_SCOPE[${index}] must be a string, got ${typeof entry}`,
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
return entry;
|
|
418
|
+
});
|
|
285
419
|
}
|
|
286
420
|
|
|
287
421
|
const promptPath = path.join(taskFolder, "PROMPT.md");
|
|
@@ -327,6 +461,9 @@ async function runWorkerRunner() {
|
|
|
327
461
|
const mode = process.argv.includes("--stub") ? "stub" : "pi";
|
|
328
462
|
|
|
329
463
|
if (mode === "stub") {
|
|
464
|
+
// SP-879 (#338): a stub attempt never produces usage; drop any sidecar a
|
|
465
|
+
// previous real-pi attempt left so stub metrics carry no inherited costs.
|
|
466
|
+
clearWorkerUsageSidecar(taskFolder);
|
|
330
467
|
const parsedTaskId = taskIdFromFolderName(path.basename(taskFolder)) ?? "";
|
|
331
468
|
const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
|
|
332
469
|
.split(/[,\s]+/)
|
|
@@ -463,23 +600,43 @@ async function runWorkerRunner() {
|
|
|
463
600
|
|
|
464
601
|
const projectRoot = process.env.SPINE_PROJECT_ROOT || worktreePath || process.cwd();
|
|
465
602
|
const spineConfig = loadSpineConfig(projectRoot).config ?? {};
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
603
|
+
// SP-877 (#319): malformed SPINE_TASK_FILE_SCOPE surfaces as a clear worker
|
|
604
|
+
// failure instead of an unhandled-rejection stack trace.
|
|
605
|
+
let piArgs;
|
|
606
|
+
try {
|
|
607
|
+
piArgs = await buildWorkerPiArgs({
|
|
608
|
+
worktreePath,
|
|
609
|
+
taskFolder,
|
|
610
|
+
donePath,
|
|
611
|
+
spineConfig,
|
|
612
|
+
journal: buildReviewJournal(),
|
|
613
|
+
});
|
|
614
|
+
} catch (err) {
|
|
615
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
616
|
+
process.exit(1);
|
|
617
|
+
}
|
|
473
618
|
|
|
474
619
|
const timeoutMs = Number(process.env.SPINE_WORKER_PI_TIMEOUT_MS || 60 * 60 * 1000);
|
|
620
|
+
// SP-879 (#338): a sidecar from a previous attempt must never survive into
|
|
621
|
+
// this attempt's metrics — clear it before pi runs.
|
|
622
|
+
clearWorkerUsageSidecar(taskFolder);
|
|
475
623
|
const result = spawnSync("pi", piArgs, {
|
|
476
624
|
cwd: worktreePath || process.cwd(),
|
|
477
625
|
encoding: "utf-8",
|
|
478
626
|
timeout: timeoutMs,
|
|
479
627
|
});
|
|
480
628
|
|
|
629
|
+
// SP-879 (#338): persist provider-reported usage before any terminal exit so
|
|
630
|
+
// success, done-missing, and non-zero paths all carry real spend. The parser
|
|
631
|
+
// only counts events pi reported; when stdout holds nothing parseable no
|
|
632
|
+
// sidecar is written and no usage is invented (stub/execute never reach here).
|
|
633
|
+
const usage = workerUsageFromResult(result);
|
|
634
|
+
persistWorkerUsageSidecar({ taskFolder, usage });
|
|
635
|
+
const piLogText = workerPiLogTextFromResult(result);
|
|
636
|
+
|
|
481
637
|
if (result.error?.code === "ETIMEDOUT") {
|
|
482
638
|
console.error("pi worker timed out");
|
|
639
|
+
if (piLogText) process.stdout.write(`\n[pi assistant output]\n${truncateLiveLogBytes(piLogText, resolveWorkerOutputConfig(spineConfig).maxBytes)}\n`);
|
|
483
640
|
process.exit(124);
|
|
484
641
|
}
|
|
485
642
|
|
|
@@ -491,6 +648,11 @@ async function runWorkerRunner() {
|
|
|
491
648
|
}
|
|
492
649
|
process.stderr.write(result.stderr ?? "");
|
|
493
650
|
process.stdout.write(result.stdout ?? "");
|
|
651
|
+
if (piLogText) {
|
|
652
|
+
process.stdout.write(
|
|
653
|
+
`\n[pi assistant output]\n${truncateLiveLogBytes(piLogText, resolveWorkerOutputConfig(spineConfig).maxBytes)}\n`,
|
|
654
|
+
);
|
|
655
|
+
}
|
|
494
656
|
process.exit(result.status ?? 1);
|
|
495
657
|
}
|
|
496
658
|
|
|
@@ -500,6 +662,11 @@ async function runWorkerRunner() {
|
|
|
500
662
|
const flush = buildDoneMissingPiOutputFlush(result, spineConfig);
|
|
501
663
|
if (flush.stderr) process.stderr.write(flush.stderr);
|
|
502
664
|
if (flush.stdout) process.stdout.write(flush.stdout);
|
|
665
|
+
if (piLogText) {
|
|
666
|
+
process.stdout.write(
|
|
667
|
+
`\n[pi assistant output]\n${truncateLiveLogBytes(piLogText, resolveWorkerOutputConfig(spineConfig).maxBytes)}\n`,
|
|
668
|
+
);
|
|
669
|
+
}
|
|
503
670
|
process.exit(1);
|
|
504
671
|
}
|
|
505
672
|
|
package/package.json
CHANGED
package/src/batch/batch-id.mjs
CHANGED
|
@@ -68,6 +68,61 @@ export function validateBatchId(batchId) {
|
|
|
68
68
|
return /** @type {string} */ (batchId);
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Allowlist pattern for review baselines (SP-869, issue #313).
|
|
73
|
+
*
|
|
74
|
+
* A baseline is interpolated into `git diff <baseline>..HEAD` argv
|
|
75
|
+
* (review-scope) and reviewer prompt text (review-step), so it must be a safe
|
|
76
|
+
* git object name: a full/short commit SHA or a plain ref (`main`,
|
|
77
|
+
* `origin/main`, `v1.2.3`). The first character must be alphanumeric so
|
|
78
|
+
* option-like values (`-`, `--output=…`) and absolute/traversal paths can
|
|
79
|
+
* never pass; the remainder allows only letters, digits, dot, dash, and
|
|
80
|
+
* slash. Whitespace, newlines, backslashes, and revision metacharacters
|
|
81
|
+
* (`~`, `^`, `:`, `@{`) are excluded.
|
|
82
|
+
*/
|
|
83
|
+
export const REVIEW_BASELINE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {unknown} baseline
|
|
87
|
+
* @returns {string|null} rejection reason, or null when the baseline is valid
|
|
88
|
+
*/
|
|
89
|
+
export function reviewBaselineRejectionReason(baseline) {
|
|
90
|
+
if (typeof baseline !== "string" || baseline.trim().length === 0) {
|
|
91
|
+
return "must be a non-empty string";
|
|
92
|
+
}
|
|
93
|
+
if (/^-/.test(baseline)) {
|
|
94
|
+
return "must not look like a command-line option";
|
|
95
|
+
}
|
|
96
|
+
if (/\s/.test(baseline)) {
|
|
97
|
+
return "must not contain whitespace or newlines";
|
|
98
|
+
}
|
|
99
|
+
if (baseline.includes("..")) {
|
|
100
|
+
return 'must not contain ".." path traversal sequences';
|
|
101
|
+
}
|
|
102
|
+
if (!REVIEW_BASELINE_PATTERN.test(baseline)) {
|
|
103
|
+
return (
|
|
104
|
+
`must match ${REVIEW_BASELINE_PATTERN} ` +
|
|
105
|
+
"(full/short commit SHA or plain git ref: letters, digits, dot, dash, slash)"
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Assert a review baseline is safe for `git diff <baseline>..HEAD` argv and
|
|
113
|
+
* reviewer prompt text; throw otherwise (SP-869, issue #313).
|
|
114
|
+
*
|
|
115
|
+
* @param {unknown} baseline
|
|
116
|
+
* @returns {string} the validated baseline
|
|
117
|
+
*/
|
|
118
|
+
export function validateReviewBaseline(baseline) {
|
|
119
|
+
const reason = reviewBaselineRejectionReason(baseline);
|
|
120
|
+
if (reason) {
|
|
121
|
+
throw new Error(`Invalid review baseline ${JSON.stringify(String(baseline))}: ${reason}`);
|
|
122
|
+
}
|
|
123
|
+
return /** @type {string} */ (baseline);
|
|
124
|
+
}
|
|
125
|
+
|
|
71
126
|
const MAX_UNIQUIFY_ATTEMPTS = 64;
|
|
72
127
|
|
|
73
128
|
/**
|