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.
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Worker `.DONE` marker parse/write and backgrounded-verification detection (#276).
3
+ * Extracted from worker-output.mjs so that module stays under the LOC cap.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
8
+
9
+ /**
10
+ * Targeted `worker_done_missing` hint for backgrounded verifications (SP-741, #276).
11
+ * A worker that exits while a long verification is still running (waiting on a
12
+ * completion wake) cannot be resumed — the session dies with the turn.
13
+ */
14
+ export const BACKGROUND_VERIFICATION_HINT =
15
+ "backgrounded verification detected — long verifications must run in the foreground and finish in-session before .DONE";
16
+
17
+ /** Output phrases that on their own indicate background-and-exit behavior. */
18
+ const BACKGROUND_VERIFICATION_STRONG_MARKERS = [
19
+ "completion wake",
20
+ "running in the background",
21
+ "background monitor",
22
+ "backgrounded",
23
+ "monitorcreate",
24
+ ];
25
+
26
+ /** Output phrases indicating a verification has not finished yet. */
27
+ const BACKGROUND_VERIFICATION_PENDING_MARKERS = [
28
+ "still running",
29
+ "still in progress",
30
+ "not finished",
31
+ "hasn't finished",
32
+ "has not finished",
33
+ ];
34
+
35
+ /** Phrases that pair with pending work to indicate it was detached/backgrounded. */
36
+ const BACKGROUND_VERIFICATION_CONTEXT_MARKERS = [
37
+ "background",
38
+ "wake",
39
+ "monitor",
40
+ "redirected",
41
+ "detached",
42
+ ];
43
+
44
+ /**
45
+ * Detect worker output suggesting a long verification was backgrounded instead
46
+ * of run in the foreground (#276). Matched against the captured output tail
47
+ * at `worker_done_missing` diagnosis time; advisory only.
48
+ *
49
+ * @param {string|null|undefined} outputText
50
+ * @returns {boolean}
51
+ */
52
+ export function detectBackgroundedVerification(outputText) {
53
+ if (!outputText || !String(outputText).trim()) return false;
54
+ const normalized = String(outputText).toLowerCase();
55
+ if (BACKGROUND_VERIFICATION_STRONG_MARKERS.some((marker) => normalized.includes(marker))) {
56
+ return true;
57
+ }
58
+ const hasPending = BACKGROUND_VERIFICATION_PENDING_MARKERS.some((marker) =>
59
+ normalized.includes(marker),
60
+ );
61
+ if (!hasPending) return false;
62
+ return BACKGROUND_VERIFICATION_CONTEXT_MARKERS.some((marker) => normalized.includes(marker));
63
+ }
64
+
65
+ /**
66
+ * Parse a `.DONE` marker body. Legacy empty/text markers remain valid (SP-321).
67
+ *
68
+ * @param {string} content
69
+ */
70
+ export function parseWorkerDoneMarker(content) {
71
+ const trimmed = String(content ?? "").trim();
72
+ if (!trimmed) {
73
+ return { valid: true, legacy: true, kind: "empty" };
74
+ }
75
+
76
+ if (trimmed.startsWith("{")) {
77
+ try {
78
+ const data = JSON.parse(trimmed);
79
+ if (
80
+ typeof data?.taskId === "string" &&
81
+ data.taskId.length > 0 &&
82
+ typeof data?.completedAt === "string" &&
83
+ data.completedAt.length > 0
84
+ ) {
85
+ return {
86
+ valid: true,
87
+ legacy: false,
88
+ kind: "json",
89
+ taskId: data.taskId,
90
+ completedAt: data.completedAt,
91
+ };
92
+ }
93
+ return { valid: false, legacy: false, kind: "json_partial", reason: "missing_fields" };
94
+ } catch {
95
+ return { valid: false, legacy: false, kind: "json_partial", reason: "parse_error" };
96
+ }
97
+ }
98
+
99
+ return { valid: true, legacy: true, kind: "text" };
100
+ }
101
+
102
+ /**
103
+ * @param {string} content
104
+ */
105
+ export function isWorkerDoneMarkerValid(content) {
106
+ return parseWorkerDoneMarker(content).valid;
107
+ }
108
+
109
+ /**
110
+ * @param {string} donePath
111
+ */
112
+ export function readWorkerDoneMarker(donePath) {
113
+ if (!fs.existsSync(donePath)) {
114
+ return { present: false, valid: false };
115
+ }
116
+ const parsed = parseWorkerDoneMarker(fs.readFileSync(donePath, "utf-8"));
117
+ return { present: true, ...parsed };
118
+ }
119
+
120
+ /**
121
+ * Atomically write a structured `.DONE` marker for engine validation.
122
+ *
123
+ * @param {string} donePath
124
+ * @param {{ taskId: string }} params
125
+ */
126
+ export function writeWorkerDoneMarker(donePath, { taskId }) {
127
+ writeJsonAtomic(donePath, {
128
+ taskId,
129
+ completedAt: new Date().toISOString(),
130
+ });
131
+ }
@@ -232,6 +232,9 @@ export async function runWorker({
232
232
 
233
233
  const workerBackend = useStub ? "subprocess" : resolveWorkerBackend(config);
234
234
  const workerMode = useStub ? "stub" : workerBackend === "agentSession" ? "agentSession" : "pi";
235
+ // Preflight failure shape shared by the guards below (keeps worker-host under the 500-LOC policy).
236
+ /** @param {string} classification @param {string} output */
237
+ const failPreflight = (classification, output) => ({ ok: false, exitCode: 1, mode: workerMode, output, classification, doneFound: false });
235
238
  const useLaunchScript = Boolean(
236
239
  projectRoot ? resolveWorkerLaunchScript(projectRoot, config) : null,
237
240
  );
@@ -249,21 +252,14 @@ export async function runWorker({
249
252
  phase: "preflight",
250
253
  });
251
254
  }
252
- return {
253
- ok: false,
254
- exitCode: 1,
255
- mode: workerMode,
256
- output: reviewCheck.error ?? "review tool unavailable",
257
- classification: "review_failed",
258
- doneFound: false,
259
- };
255
+ return failPreflight("review_failed", reviewCheck.error ?? "review tool unavailable");
260
256
  }
261
257
 
262
258
  const taskSize = parseTaskSizeFromFolder(taskFolder);
263
259
  const promptPath = path.join(taskFolder, "PROMPT.md");
264
260
  const promptText = fs.existsSync(promptPath) ? fs.readFileSync(promptPath, "utf-8") : "";
265
261
  const parsedPrompt = promptText ? parsePrompt(promptText) : null;
266
- const contract = promptText ? parseContract(promptText) : { stallTimeoutMinutes: null, extendGraceOnFileScope: null, runCommand: null, testCommand: null };
262
+ const contract = promptText ? parseContract(promptText) : { stallTimeoutMinutes: null, extendGraceOnFileScope: null, runCommand: null, testCommand: null, errors: [] };
267
263
  const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
268
264
  const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
269
265
  const startedAt = Date.now();
@@ -271,6 +267,18 @@ export async function runWorker({
271
267
  const isExecute = parsedPrompt?.type === "execute";
272
268
  const runCommand = contract.runCommand || contract.testCommand;
273
269
 
270
+ // SP-877 (#319): surface parseContract() errors — execute tasks fail closed at
271
+ // preflight instead of the guaranteed-failing `echo … && exit 1` fallback; pi
272
+ // workers proceed (the contract only feeds stall budgets, which tolerate nulls).
273
+ if (contract.errors.length > 0) {
274
+ const detail = contract.errors.join("; ");
275
+ if (projectRoot && batchId) {
276
+ appendJournalEvent(projectRoot, batchId, "worker.contract_parse_failed", { taskId, laneNumber, correlationId: laneCorrelationId, errors: contract.errors, phase: "preflight" });
277
+ }
278
+ if (isExecute) return failPreflight("contract_parse_failed", `Contract parse failed: ${detail}`);
279
+ console.error(`worker-host: contract parse issues for ${taskId ?? taskFolder}: ${detail}`);
280
+ }
281
+
274
282
  // #299 (SP-801): fail closed when the pi CLI is missing rather than silently
275
283
  // falling back to the stub. Placed after the review gate so review-tool
276
284
  // unavailability keeps its `review_failed` precedence, and scoped to
@@ -286,15 +294,7 @@ export async function runWorker({
286
294
  phase: "preflight",
287
295
  });
288
296
  }
289
- return {
290
- ok: false,
291
- exitCode: 1,
292
- mode: workerMode,
293
- output:
294
- "worker requires pi on PATH (fail closed); set SPINE_WORKER_STUB=1 only for stub runs",
295
- classification: "launch_failed",
296
- doneFound: false,
297
- };
297
+ return failPreflight("launch_failed", "worker requires pi on PATH (fail closed); set SPINE_WORKER_STUB=1 only for stub runs");
298
298
  }
299
299
 
300
300
  const child = isExecute
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Compact `--mode json` failure summaries for `task.failed` journals (SP-882 / #381).
3
+ *
4
+ * Extracted from worker-output.mjs so that module stays under the LOC cap.
5
+ */
6
+
7
+ import { extractTextFromPiJsonStream } from "./pi-json-usage.mjs";
8
+
9
+ /** Soft cap for journaled failure summaries (well under MAX_PAYLOAD_BYTES). */
10
+ const JSON_FAILURE_SUMMARY_MAX_CHARS = 6_000;
11
+
12
+ /**
13
+ * True when stdout looks like a `pi --mode json` NDJSON event stream.
14
+ * Used so failure journals can summarize instead of dumping the system prompt.
15
+ *
16
+ * @param {string} text
17
+ * @returns {boolean}
18
+ */
19
+ export function looksLikePiJsonNdjson(text) {
20
+ if (!text || typeof text !== "string") return false;
21
+ const head = text.slice(0, 4096);
22
+ return (
23
+ head.includes('"type":"session"') ||
24
+ head.includes('"type": "session"') ||
25
+ head.includes('"type":"message_start"') ||
26
+ head.includes('"type": "message_start"') ||
27
+ head.includes('"type":"agent_start"') ||
28
+ head.includes('"type": "agent_start"')
29
+ );
30
+ }
31
+
32
+ /**
33
+ * Compact failure summary for `task.failed` when workers use `--mode json`.
34
+ * Full NDJSON remains on disk via worker-output logs; journals get exit signal
35
+ * + assistant/error text only (SP-882 / #381).
36
+ *
37
+ * @param {string} rawOutput
38
+ * @param {{ exitCode?: number | null, classification?: string, logRef?: string | null }} [meta]
39
+ * @returns {string}
40
+ */
41
+ export function summarizePiJsonFailureOutput(rawOutput, meta = {}) {
42
+ const exitCode = meta.exitCode;
43
+ const classification = meta.classification ?? "failed";
44
+ const logRef = meta.logRef ?? null;
45
+
46
+ /** @type {string[]} */
47
+ const errorBits = [];
48
+ for (const line of String(rawOutput).split(/\r?\n/)) {
49
+ if (!line.trim()) continue;
50
+ try {
51
+ const event = JSON.parse(line);
52
+ if (event?.type === "error") {
53
+ const msg =
54
+ typeof event.error === "string"
55
+ ? event.error
56
+ : typeof event.message === "string"
57
+ ? event.message
58
+ : JSON.stringify(event.error ?? event).slice(0, 400);
59
+ if (msg) errorBits.push(msg);
60
+ }
61
+ } catch {
62
+ // non-JSON line — ignore for summary
63
+ }
64
+ }
65
+
66
+ let assistantText = "";
67
+ try {
68
+ assistantText = extractTextFromPiJsonStream(rawOutput).join("\n").trim();
69
+ } catch {
70
+ assistantText = "";
71
+ }
72
+
73
+ const parts = [
74
+ `pi --mode json failure: classification=${classification}` +
75
+ (exitCode != null ? ` exitCode=${exitCode}` : ""),
76
+ ];
77
+ if (errorBits.length > 0) {
78
+ parts.push(`errors: ${errorBits.slice(0, 5).join(" | ")}`);
79
+ }
80
+ if (assistantText) {
81
+ const clipped =
82
+ assistantText.length > JSON_FAILURE_SUMMARY_MAX_CHARS
83
+ ? `${assistantText.slice(0, JSON_FAILURE_SUMMARY_MAX_CHARS)}\n…[assistant text truncated]`
84
+ : assistantText;
85
+ parts.push(`assistant:\n${clipped}`);
86
+ } else if (errorBits.length === 0) {
87
+ parts.push(
88
+ "no assistant text or error events in stream (often SIGTERM/early exit after system prompt)",
89
+ );
90
+ }
91
+ if (logRef) {
92
+ parts.push(`fullLog: ${logRef}`);
93
+ }
94
+ return parts.join("\n");
95
+ }
@@ -5,9 +5,27 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
- import { writeJsonAtomic, writeTextAtomic } from "../fs/atomic-write.mjs";
8
+ import { writeTextAtomic } from "../fs/atomic-write.mjs";
9
9
  import { redactTextSecrets } from "../util/secret-redact.mjs";
10
10
  import { appendJournalEvent } from "./journal.mjs";
11
+ import {
12
+ looksLikePiJsonNdjson,
13
+ summarizePiJsonFailureOutput,
14
+ } from "./worker-output-json-summary.mjs";
15
+
16
+ export {
17
+ looksLikePiJsonNdjson,
18
+ summarizePiJsonFailureOutput,
19
+ } from "./worker-output-json-summary.mjs";
20
+
21
+ export {
22
+ BACKGROUND_VERIFICATION_HINT,
23
+ detectBackgroundedVerification,
24
+ isWorkerDoneMarkerValid,
25
+ parseWorkerDoneMarker,
26
+ readWorkerDoneMarker,
27
+ writeWorkerDoneMarker,
28
+ } from "./worker-done-marker.mjs";
11
29
 
12
30
  const DEFAULT_MAX_BYTES = 262_144;
13
31
  const DEFAULT_LIVE_LOG_MAX_BYTES = 262_144;
@@ -326,12 +344,17 @@ export function finalizeWorkerOutput({
326
344
  }
327
345
 
328
346
  const redacted = redactWorkerOutput(rawOutput, outputConfig);
329
- const output = captureWorkerOutputTail(redacted, outputConfig) || redacted;
347
+ const tailed = captureWorkerOutputTail(redacted, outputConfig) || redacted;
330
348
 
331
349
  if (!projectRoot || !batchId || laneNumber == null || !taskId) {
350
+ const output =
351
+ !ok && looksLikePiJsonNdjson(redacted)
352
+ ? summarizePiJsonFailureOutput(redacted, { exitCode, classification })
353
+ : tailed;
332
354
  return { output, logPath: null, logRef: null };
333
355
  }
334
356
 
357
+ // Persist the full (redacted) stream to the lane log for operator digs.
335
358
  const persisted = persistWorkerOutputLog({
336
359
  projectRoot,
337
360
  batchId,
@@ -356,137 +379,24 @@ export function finalizeWorkerOutput({
356
379
  });
357
380
  }
358
381
 
382
+ const logRef = persisted?.logRef ?? null;
383
+ // Journal path: never dump --mode json system-prompt NDJSON into task.failed.
384
+ const output =
385
+ !ok && looksLikePiJsonNdjson(redacted)
386
+ ? summarizePiJsonFailureOutput(redacted, {
387
+ exitCode,
388
+ classification,
389
+ logRef,
390
+ })
391
+ : (persisted?.output ?? tailed);
392
+
359
393
  return {
360
- output: persisted?.output ?? output,
394
+ output,
361
395
  logPath: persisted?.logPath ?? null,
362
- logRef: persisted?.logRef ?? null,
396
+ logRef,
363
397
  };
364
398
  }
365
399
 
366
- /**
367
- * Targeted `worker_done_missing` hint for backgrounded verifications (SP-741, #276).
368
- * A worker that exits while a long verification is still running (waiting on a
369
- * completion wake) cannot be resumed — the session dies with the turn.
370
- */
371
- export const BACKGROUND_VERIFICATION_HINT =
372
- "backgrounded verification detected — long verifications must run in the foreground and finish in-session before .DONE";
373
-
374
- /** Output phrases that on their own indicate background-and-exit behavior. */
375
- const BACKGROUND_VERIFICATION_STRONG_MARKERS = [
376
- "completion wake",
377
- "running in the background",
378
- "background monitor",
379
- "backgrounded",
380
- "monitorcreate",
381
- ];
382
-
383
- /** Output phrases indicating a verification has not finished yet. */
384
- const BACKGROUND_VERIFICATION_PENDING_MARKERS = [
385
- "still running",
386
- "still in progress",
387
- "not finished",
388
- "hasn't finished",
389
- "has not finished",
390
- ];
391
-
392
- /** Phrases that pair with pending work to indicate it was detached/backgrounded. */
393
- const BACKGROUND_VERIFICATION_CONTEXT_MARKERS = [
394
- "background",
395
- "wake",
396
- "monitor",
397
- "redirected",
398
- "detached",
399
- ];
400
-
401
- /**
402
- * Detect worker output suggesting a long verification was backgrounded instead
403
- * of run in the foreground (#276). Matched against the captured output tail
404
- * at `worker_done_missing` diagnosis time; advisory only.
405
- *
406
- * @param {string|null|undefined} outputText
407
- * @returns {boolean}
408
- */
409
- export function detectBackgroundedVerification(outputText) {
410
- if (!outputText || !String(outputText).trim()) return false;
411
- const normalized = String(outputText).toLowerCase();
412
- if (BACKGROUND_VERIFICATION_STRONG_MARKERS.some((marker) => normalized.includes(marker))) {
413
- return true;
414
- }
415
- const hasPending = BACKGROUND_VERIFICATION_PENDING_MARKERS.some((marker) =>
416
- normalized.includes(marker),
417
- );
418
- if (!hasPending) return false;
419
- return BACKGROUND_VERIFICATION_CONTEXT_MARKERS.some((marker) => normalized.includes(marker));
420
- }
421
-
422
- /**
423
- * Parse a `.DONE` marker body. Legacy empty/text markers remain valid (SP-321).
424
- *
425
- * @param {string} content
426
- */
427
- export function parseWorkerDoneMarker(content) {
428
- const trimmed = String(content ?? "").trim();
429
- if (!trimmed) {
430
- return { valid: true, legacy: true, kind: "empty" };
431
- }
432
-
433
- if (trimmed.startsWith("{")) {
434
- try {
435
- const data = JSON.parse(trimmed);
436
- if (
437
- typeof data?.taskId === "string" &&
438
- data.taskId.length > 0 &&
439
- typeof data?.completedAt === "string" &&
440
- data.completedAt.length > 0
441
- ) {
442
- return {
443
- valid: true,
444
- legacy: false,
445
- kind: "json",
446
- taskId: data.taskId,
447
- completedAt: data.completedAt,
448
- };
449
- }
450
- return { valid: false, legacy: false, kind: "json_partial", reason: "missing_fields" };
451
- } catch {
452
- return { valid: false, legacy: false, kind: "json_partial", reason: "parse_error" };
453
- }
454
- }
455
-
456
- return { valid: true, legacy: true, kind: "text" };
457
- }
458
-
459
- /**
460
- * @param {string} content
461
- */
462
- export function isWorkerDoneMarkerValid(content) {
463
- return parseWorkerDoneMarker(content).valid;
464
- }
465
-
466
- /**
467
- * @param {string} donePath
468
- */
469
- export function readWorkerDoneMarker(donePath) {
470
- if (!fs.existsSync(donePath)) {
471
- return { present: false, valid: false };
472
- }
473
- const parsed = parseWorkerDoneMarker(fs.readFileSync(donePath, "utf-8"));
474
- return { present: true, ...parsed };
475
- }
476
-
477
- /**
478
- * Atomically write a structured `.DONE` marker for engine validation.
479
- *
480
- * @param {string} donePath
481
- * @param {{ taskId: string }} params
482
- */
483
- export function writeWorkerDoneMarker(donePath, { taskId }) {
484
- writeJsonAtomic(donePath, {
485
- taskId,
486
- completedAt: new Date().toISOString(),
487
- });
488
- }
489
-
490
400
  export {
491
401
  TRUNCATION_MARKER,
492
402
  DEFAULT_MAX_BYTES,
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Engine-owned worker usage sidecar helpers (SP-879 / SP-881 / #380).
3
+ *
4
+ * Kept as a tiny leaf so heartbeat / lane-dirty-check stay under the LOC cap.
5
+ */
6
+
7
+ /** Basename of the SP-879 worker usage sidecar (keep in sync with runner/queue). */
8
+ export const WORKER_USAGE_SIDECAR_FILENAME = "worker-usage.json";
9
+
10
+ /**
11
+ * True when the porcelain path is the engine-owned worker usage sidecar.
12
+ *
13
+ * @param {string} filePath
14
+ * @returns {boolean}
15
+ */
16
+ export function isWorkerUsageSidecarPath(filePath) {
17
+ if (!filePath || typeof filePath !== "string") return false;
18
+ const normalized = filePath.replace(/\\/g, "/");
19
+ const base = normalized.includes("/")
20
+ ? normalized.slice(normalized.lastIndexOf("/") + 1)
21
+ : normalized;
22
+ return base === WORKER_USAGE_SIDECAR_FILENAME;
23
+ }