pi-spine 2.33.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.33.0",
3
+ "version": "2.33.1",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Flutter analyzer / build hygiene for lane worktrees (#78).
3
+ * Extracted from lane-dirty-check.mjs so that module stays under the LOC cap.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+
9
+ /** Flutter build output dir that can pollute unscoped `flutter analyze` (#78). */
10
+ export const FLUTTER_BUILD_DIR = "build";
11
+
12
+ /**
13
+ * @param {string} segment
14
+ * @returns {boolean}
15
+ */
16
+ export function isUnscopedFlutterAnalyzeSegment(segment) {
17
+ const trimmed = String(segment ?? "").trim().toLowerCase();
18
+ if (!/\bflutter\s+analyze\b/.test(trimmed)) {
19
+ return false;
20
+ }
21
+
22
+ const match = trimmed.match(/\bflutter\s+analyze\b(.*)$/);
23
+ if (!match) {
24
+ return false;
25
+ }
26
+
27
+ const remainder = (match[1] ?? "").trim();
28
+ if (!remainder) {
29
+ return true;
30
+ }
31
+
32
+ for (const token of remainder.split(/\s+/)) {
33
+ if (token.startsWith("-")) {
34
+ continue;
35
+ }
36
+ return false;
37
+ }
38
+
39
+ return true;
40
+ }
41
+
42
+ /**
43
+ * True when testCommand invokes unscoped `flutter analyze` (whole project tree).
44
+ * Scoped forms like `flutter analyze lib test` are excluded.
45
+ *
46
+ * @param {string} command
47
+ * @returns {boolean}
48
+ */
49
+ export function isUnscopedFlutterAnalyzeCommand(command) {
50
+ const trimmed = String(command ?? "").trim();
51
+ if (!trimmed) {
52
+ return false;
53
+ }
54
+
55
+ const segments = trimmed
56
+ .split(/&&|;/)
57
+ .map((segment) => segment.trim())
58
+ .filter(Boolean);
59
+ return segments.some((segment) => isUnscopedFlutterAnalyzeSegment(segment));
60
+ }
61
+
62
+ /**
63
+ * True when testCommand combines flutter analyze with flutter test.
64
+ *
65
+ * @param {string} command
66
+ * @returns {boolean}
67
+ */
68
+ export function isFlutterAnalyzeTestCompoundCommand(command) {
69
+ const trimmed = String(command ?? "").trim().toLowerCase();
70
+ return /\bflutter\s+analyze\b/.test(trimmed) && /\bflutter\s+test\b/.test(trimmed);
71
+ }
72
+
73
+ /**
74
+ * Whether contract verify should remove `build/` before running testCommand.
75
+ *
76
+ * @param {string} testCommand
77
+ * @param {{ contract?: { flutterAnalyzerHygiene?: boolean } }} [config]
78
+ * @returns {boolean}
79
+ */
80
+ export function shouldCleanFlutterBuildBeforeAnalyze(testCommand, config = {}) {
81
+ const enabled = config?.contract?.flutterAnalyzerHygiene ?? true;
82
+ if (!enabled) {
83
+ return false;
84
+ }
85
+ return isUnscopedFlutterAnalyzeCommand(testCommand);
86
+ }
87
+
88
+ /**
89
+ * Remove stale Flutter build artifacts so unscoped analyze does not scan SourcePackages (#78).
90
+ *
91
+ * @param {string} worktreePath
92
+ * @param {{ enabled?: boolean }} [options]
93
+ * @returns {{ cleaned: boolean, buildDir?: string, reason?: string }}
94
+ */
95
+ export function sanitizeFlutterBuildBeforeAnalyze(worktreePath, { enabled = true } = {}) {
96
+ if (!enabled) {
97
+ return { cleaned: false, reason: "disabled" };
98
+ }
99
+
100
+ const buildPath = path.join(worktreePath, FLUTTER_BUILD_DIR);
101
+ if (!fs.existsSync(buildPath)) {
102
+ return { cleaned: false, reason: "no_build_dir" };
103
+ }
104
+
105
+ fs.rmSync(buildPath, { recursive: true, force: true });
106
+ return { cleaned: true, buildDir: FLUTTER_BUILD_DIR };
107
+ }
@@ -17,6 +17,7 @@ import {
17
17
  buildHeartbeatPayloadFields,
18
18
  buildProgressSnapshotPayload,
19
19
  } from "./heartbeat-subprocess.mjs";
20
+ import { isWorkerUsageSidecarPath } from "./worker-usage-sidecar.mjs";
20
21
 
21
22
  export {
22
23
  clearGitPorcelainDebounceCache,
@@ -146,6 +147,8 @@ export function resolveScopedDirtyPaths(worktreePath, fileScopePaths, taskFolder
146
147
  let filePath = line.length > 2 && line[2] === " " ? line.slice(3) : line.slice(2);
147
148
  filePath = filePath.trim();
148
149
  const renamed = filePath.includes(" -> ") ? filePath.split(" -> ").pop()?.trim() : filePath;
150
+ // SP-881 / #380: engine-owned usage sidecar is never salvageable product dirt.
151
+ if (renamed && isWorkerUsageSidecarPath(renamed)) continue;
149
152
  if (renamed && inScope(renamed)) dirty.add(renamed);
150
153
  }
151
154
  return [...dirty].sort();
@@ -6,8 +6,6 @@
6
6
  */
7
7
 
8
8
  import { execFileSync } from "node:child_process";
9
- import fs from "node:fs";
10
- import path from "node:path";
11
9
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
12
10
  import { resolveLaneCommitKeepPaths } from "../config/spine-config-schema.mjs";
13
11
  import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
@@ -44,6 +42,21 @@ import {
44
42
  listTrackedPorcelainPaths,
45
43
  repairSetupHookSymlinkDrift,
46
44
  } from "./lane-dirty-check-git.mjs";
45
+ import { WORKER_USAGE_SIDECAR_FILENAME } from "./worker-usage-sidecar.mjs";
46
+
47
+ export {
48
+ WORKER_USAGE_SIDECAR_FILENAME,
49
+ isWorkerUsageSidecarPath,
50
+ } from "./worker-usage-sidecar.mjs";
51
+
52
+ export {
53
+ FLUTTER_BUILD_DIR,
54
+ isFlutterAnalyzeTestCompoundCommand,
55
+ isUnscopedFlutterAnalyzeCommand,
56
+ isUnscopedFlutterAnalyzeSegment,
57
+ sanitizeFlutterBuildBeforeAnalyze,
58
+ shouldCleanFlutterBuildBeforeAnalyze,
59
+ } from "./flutter-analyzer-hygiene.mjs";
47
60
 
48
61
  /**
49
62
  * Path segments for gitignored build artifacts that npm test and similar tools
@@ -64,108 +77,11 @@ export const GITIGNORED_ARTIFACT_MARKERS = [
64
77
  ".pi-smart-router/",
65
78
  "/.spine/runtime/",
66
79
  ".spine/runtime/",
80
+ // SP-881 / #380: engine-owned usage sidecar under task folders (must not salvage-thrash)
81
+ `/${WORKER_USAGE_SIDECAR_FILENAME}`,
82
+ WORKER_USAGE_SIDECAR_FILENAME,
67
83
  ];
68
84
 
69
- /** Flutter build output dir that can pollute unscoped `flutter analyze` (#78). */
70
- export const FLUTTER_BUILD_DIR = "build";
71
-
72
- /**
73
- * @param {string} segment
74
- * @returns {boolean}
75
- */
76
- export function isUnscopedFlutterAnalyzeSegment(segment) {
77
- const trimmed = String(segment ?? "").trim().toLowerCase();
78
- if (!/\bflutter\s+analyze\b/.test(trimmed)) {
79
- return false;
80
- }
81
-
82
- const match = trimmed.match(/\bflutter\s+analyze\b(.*)$/);
83
- if (!match) {
84
- return false;
85
- }
86
-
87
- const remainder = (match[1] ?? "").trim();
88
- if (!remainder) {
89
- return true;
90
- }
91
-
92
- for (const token of remainder.split(/\s+/)) {
93
- if (token.startsWith("-")) {
94
- continue;
95
- }
96
- return false;
97
- }
98
-
99
- return true;
100
- }
101
-
102
- /**
103
- * True when testCommand invokes unscoped `flutter analyze` (whole project tree).
104
- * Scoped forms like `flutter analyze lib test` are excluded.
105
- *
106
- * @param {string} command
107
- * @returns {boolean}
108
- */
109
- export function isUnscopedFlutterAnalyzeCommand(command) {
110
- const trimmed = String(command ?? "").trim();
111
- if (!trimmed) {
112
- return false;
113
- }
114
-
115
- const segments = trimmed
116
- .split(/&&|;/)
117
- .map((segment) => segment.trim())
118
- .filter(Boolean);
119
- return segments.some((segment) => isUnscopedFlutterAnalyzeSegment(segment));
120
- }
121
-
122
- /**
123
- * True when testCommand combines flutter analyze with flutter test.
124
- *
125
- * @param {string} command
126
- * @returns {boolean}
127
- */
128
- export function isFlutterAnalyzeTestCompoundCommand(command) {
129
- const trimmed = String(command ?? "").trim().toLowerCase();
130
- return /\bflutter\s+analyze\b/.test(trimmed) && /\bflutter\s+test\b/.test(trimmed);
131
- }
132
-
133
- /**
134
- * Whether contract verify should remove `build/` before running testCommand.
135
- *
136
- * @param {string} testCommand
137
- * @param {object} [config]
138
- * @returns {boolean}
139
- */
140
- export function shouldCleanFlutterBuildBeforeAnalyze(testCommand, config = {}) {
141
- const enabled = config?.contract?.flutterAnalyzerHygiene ?? true;
142
- if (!enabled) {
143
- return false;
144
- }
145
- return isUnscopedFlutterAnalyzeCommand(testCommand);
146
- }
147
-
148
- /**
149
- * Remove stale Flutter build artifacts so unscoped analyze does not scan SourcePackages (#78).
150
- *
151
- * @param {string} worktreePath
152
- * @param {{ enabled?: boolean }} [options]
153
- * @returns {{ cleaned: boolean, buildDir?: string, reason?: string }}
154
- */
155
- export function sanitizeFlutterBuildBeforeAnalyze(worktreePath, { enabled = true } = {}) {
156
- if (!enabled) {
157
- return { cleaned: false, reason: "disabled" };
158
- }
159
-
160
- const buildPath = path.join(worktreePath, FLUTTER_BUILD_DIR);
161
- if (!fs.existsSync(buildPath)) {
162
- return { cleaned: false, reason: "no_build_dir" };
163
- }
164
-
165
- fs.rmSync(buildPath, { recursive: true, force: true });
166
- return { cleaned: true, buildDir: FLUTTER_BUILD_DIR };
167
- }
168
-
169
85
  /**
170
86
  * Restore tracked and remove untracked out-of-scope coverage before lane commit.
171
87
  *
@@ -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
+ }
@@ -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
+ }