pi-spine 2.32.0 → 2.33.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/spine-plan.mjs +15 -5
- package/bin/spine-worker-runner.mjs +182 -15
- package/package.json +1 -1
- 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/flutter-analyzer-hygiene.mjs +107 -0
- package/src/batch/heartbeat.mjs +3 -0
- package/src/batch/lane-dirty-check.mjs +18 -102
- 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-spawn.mjs +48 -2
- package/src/batch/review-step.mjs +5 -0
- package/src/batch/worker-done-marker.mjs +131 -0
- package/src/batch/worker-host.mjs +18 -18
- package/src/batch/worker-output-json-summary.mjs +95 -0
- package/src/batch/worker-output.mjs +38 -128
- package/src/batch/worker-usage-sidecar.mjs +23 -0
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) };
|
|
@@ -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
|
@@ -38,7 +38,9 @@ import {
|
|
|
38
38
|
findContractCommandMetacharIssue,
|
|
39
39
|
isRefusedContractMetacharCommand,
|
|
40
40
|
parseContract,
|
|
41
|
+
parsePrompt,
|
|
41
42
|
} from "../../tasks/packet/parse-prompt.mjs";
|
|
43
|
+
import { loadTaskPacket } from "../../tasks/packet/index.mjs";
|
|
42
44
|
import { verifyContract } from "../contract-verify.mjs";
|
|
43
45
|
import { gitExec } from "../git-exec.mjs";
|
|
44
46
|
|
|
@@ -54,6 +56,55 @@ export function readParentContract(parentTaskFolderAbs) {
|
|
|
54
56
|
return parseContract(fs.readFileSync(promptPath, "utf-8"));
|
|
55
57
|
}
|
|
56
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Fail closed when a declared matrix packet fails to load (#311).
|
|
61
|
+
*
|
|
62
|
+
* `loadMatrixTaskRows` collapses every packet load error into `null`, which
|
|
63
|
+
* callers read as "not a matrix task" — silently demoting a matrix parent to
|
|
64
|
+
* plain worker mode, where its row fan-out never happens and raw `{matrix.*}`
|
|
65
|
+
* placeholders leak into the served prompt. When `loadMatrixTaskRows` returned
|
|
66
|
+
* null, re-load the packet here: if it throws and the raw PROMPT.md declares
|
|
67
|
+
* a `## Matrix` section, propagate a clear error instead of the silent
|
|
68
|
+
* demotion. Plain (non-matrix) packets keep the null → plain-worker behavior
|
|
69
|
+
* unchanged, and a missing PROMPT.md stays "not a task packet".
|
|
70
|
+
*
|
|
71
|
+
* @param {string} parentTaskFolderAbs Absolute parent task folder.
|
|
72
|
+
* @returns {void}
|
|
73
|
+
* @throws When the packet fails to load and the task declares `## Matrix`.
|
|
74
|
+
*/
|
|
75
|
+
function assertMatrixPacketLoaded(parentTaskFolderAbs) {
|
|
76
|
+
const promptPath = path.join(parentTaskFolderAbs, "PROMPT.md");
|
|
77
|
+
if (!fs.existsSync(promptPath)) return;
|
|
78
|
+
let packetError = null;
|
|
79
|
+
try {
|
|
80
|
+
loadTaskPacket(parentTaskFolderAbs);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
packetError = err;
|
|
83
|
+
}
|
|
84
|
+
if (!packetError) return;
|
|
85
|
+
const message = packetError instanceof Error ? packetError.message : String(packetError);
|
|
86
|
+
let rawPrompt = null;
|
|
87
|
+
try {
|
|
88
|
+
rawPrompt = fs.readFileSync(promptPath, "utf-8");
|
|
89
|
+
} catch {
|
|
90
|
+
rawPrompt = null;
|
|
91
|
+
}
|
|
92
|
+
if (rawPrompt === null) {
|
|
93
|
+
// PROMPT.md exists but is unreadable (e.g. a directory): the packet is
|
|
94
|
+
// broken and whether it declared matrix is unknowable — fail closed.
|
|
95
|
+
throw new Error(
|
|
96
|
+
`task packet failed to load: ${parentTaskFolderAbs} — ${message}. Refusing to proceed on an unreadable packet (#311).`,
|
|
97
|
+
{ cause: packetError },
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
const declaresMatrix = Boolean(parsePrompt(rawPrompt).sections?.Matrix);
|
|
101
|
+
if (!declaresMatrix) return;
|
|
102
|
+
throw new Error(
|
|
103
|
+
`matrix packet failed to load: ${parentTaskFolderAbs} — ${message}. Refusing to demote a declared matrix task to plain worker mode (#311).`,
|
|
104
|
+
{ cause: packetError },
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
57
108
|
/**
|
|
58
109
|
* Matrix-specific refusal copy for an execute row whose substituted command
|
|
59
110
|
* contains shell metacharacters (#297). Deliberately distinct from the
|
|
@@ -513,8 +564,14 @@ export async function runMatrixTaskForResume({
|
|
|
513
564
|
laneCorrelationId,
|
|
514
565
|
fileScopePaths,
|
|
515
566
|
}) {
|
|
516
|
-
const
|
|
517
|
-
|
|
567
|
+
const parentTaskFolderAbs = path.join(projectRoot, taskFolderRel);
|
|
568
|
+
const matrix = loadMatrixTaskRows(parentTaskFolderAbs);
|
|
569
|
+
if (!matrix) {
|
|
570
|
+
// Fail closed on a declared matrix packet that fails to load (#311);
|
|
571
|
+
// genuinely non-matrix packets still fall through to the plain path.
|
|
572
|
+
assertMatrixPacketLoaded(parentTaskFolderAbs);
|
|
573
|
+
return { isMatrix: false };
|
|
574
|
+
}
|
|
518
575
|
const result = await runMatrixTaskOnLane({
|
|
519
576
|
projectRoot,
|
|
520
577
|
state,
|
|
@@ -705,14 +762,17 @@ export async function runMatrixTaskOnLane({
|
|
|
705
762
|
// row's distinct lane identity. Always release so a crashed row cannot
|
|
706
763
|
// leak a slot and stall the batch.
|
|
707
764
|
const rowLaneNumber = await acquireLaneSlot(state, maxParallel);
|
|
708
|
-
// Per-row live status (#230): flip to `running` only once the row actually
|
|
709
|
-
// holds a slot, and persist so `spine status` sees it from another process.
|
|
710
|
-
const runningEntry = task.matrixRows.find((/** @type {any} */ m) => m.rowId === row.rowId);
|
|
711
|
-
if (runningEntry) {
|
|
712
|
-
runningEntry.status = "running";
|
|
713
|
-
await saveEngineBatchState(projectRoot, state);
|
|
714
|
-
}
|
|
715
765
|
try {
|
|
766
|
+
// Per-row live status (#230): flip to `running` only once the row actually
|
|
767
|
+
// holds a slot, and persist so `spine status` sees it from another process.
|
|
768
|
+
// Inside the try (#311): this save is the first operation that can throw
|
|
769
|
+
// while the slot is held — before SP-876 it ran outside the try, so a
|
|
770
|
+
// save failure leaked the slot and stalled the global pool.
|
|
771
|
+
const runningEntry = task.matrixRows.find((/** @type {any} */ m) => m.rowId === row.rowId);
|
|
772
|
+
if (runningEntry) {
|
|
773
|
+
runningEntry.status = "running";
|
|
774
|
+
await saveEngineBatchState(projectRoot, state);
|
|
775
|
+
}
|
|
716
776
|
return await runMatrixSubLane({
|
|
717
777
|
projectRoot,
|
|
718
778
|
batchId,
|
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import path from "node:path";
|
|
7
|
+
import fs from "node:fs";
|
|
7
8
|
import { loadTaskPacket } from "../../tasks/packet/index.mjs";
|
|
8
9
|
import { appendJournalEvent } from "../journal.mjs";
|
|
9
|
-
import { recordTaskTerminalMetric } from "../metrics.mjs";
|
|
10
|
+
import { recordTaskTerminalMetric, resolveTaskMetricOutcome } from "../metrics.mjs";
|
|
10
11
|
import { buildTaskLaneAssignments, countPlanTasks } from "../engine-scope.mjs";
|
|
11
12
|
import {
|
|
12
13
|
recordTaskSucceeded,
|
|
@@ -27,6 +28,12 @@ import { laneTaskBranch, laneWorktreePath } from "../worktree.mjs";
|
|
|
27
28
|
* @param {{ laneNumber?: number }} [params.lane]
|
|
28
29
|
*/
|
|
29
30
|
export function recordLaneTaskMetric({ projectRoot, batchId, task, config, taskFolder, lane }) {
|
|
31
|
+
// SP-879 (#338): attach provider-reported worker usage from the sidecar the
|
|
32
|
+
// runner wrote after the pi JSON run. Skipped tasks never ran a worker, so
|
|
33
|
+
// they must not inherit a stale committed sidecar from an earlier batch.
|
|
34
|
+
if (resolveTaskMetricOutcome(task) !== "skipped") {
|
|
35
|
+
attachTaskUsageFromSidecar({ taskFolder, task });
|
|
36
|
+
}
|
|
30
37
|
const metricParams = {
|
|
31
38
|
projectRoot,
|
|
32
39
|
batchId,
|
|
@@ -38,6 +45,52 @@ export function recordLaneTaskMetric({ projectRoot, batchId, task, config, taskF
|
|
|
38
45
|
recordTaskTerminalMetric(metricParams);
|
|
39
46
|
}
|
|
40
47
|
|
|
48
|
+
/** Sidecar filename the worker runner writes after a pi JSON run (bin/spine-worker-runner.mjs). Keep both definitions in sync. */
|
|
49
|
+
const WORKER_USAGE_SIDECAR_FILENAME = "worker-usage.json";
|
|
50
|
+
const WORKER_USAGE_KEYS = ["tokensIn", "tokensOut", "estimatedUsd"];
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Copy finite worker usage counters from the runner's `worker-usage.json`
|
|
54
|
+
* sidecar onto the task object before the metric record is built
|
|
55
|
+
* (`buildTaskMetricRecord` copies finite `task.tokens*` / `task.estimatedUsd`).
|
|
56
|
+
*
|
|
57
|
+
* Lenient by design: a missing, malformed, or partially valid sidecar never
|
|
58
|
+
* throws and never invents values — only present, finite, non-negative
|
|
59
|
+
* numbers are copied, and existing finite task fields win.
|
|
60
|
+
*
|
|
61
|
+
* @param {object} params
|
|
62
|
+
* @param {string} [params.taskFolder]
|
|
63
|
+
* @param {Record<string, any>} params.task
|
|
64
|
+
* @returns {boolean} true when at least one usage field was attached.
|
|
65
|
+
*/
|
|
66
|
+
export function attachTaskUsageFromSidecar({ taskFolder, task }) {
|
|
67
|
+
if (!taskFolder || !task) return false;
|
|
68
|
+
const sidecarPath = path.join(taskFolder, WORKER_USAGE_SIDECAR_FILENAME);
|
|
69
|
+
let raw;
|
|
70
|
+
try {
|
|
71
|
+
if (!fs.existsSync(sidecarPath)) return false;
|
|
72
|
+
raw = fs.readFileSync(sidecarPath, "utf-8");
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
let parsed;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
83
|
+
let attached = false;
|
|
84
|
+
for (const key of WORKER_USAGE_KEYS) {
|
|
85
|
+
const value = parsed[key];
|
|
86
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0 && !Number.isFinite(task[key])) {
|
|
87
|
+
task[key] = value;
|
|
88
|
+
attached = true;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return attached;
|
|
92
|
+
}
|
|
93
|
+
|
|
41
94
|
/**
|
|
42
95
|
* @param {string} taskFolderPath
|
|
43
96
|
* @returns {{ ok: true, fileScopePaths: string[] } | { ok: false, error: string, errors?: string[], promptPath: string }}
|