pi-spine 2.24.0 → 2.26.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-worker-runner.mjs +2 -1
- package/package.json +1 -1
- package/src/batch/abort.mjs +74 -38
- package/src/batch/attached-engine-handoff.mjs +2 -2
- package/src/batch/attached-runner-promote.mjs +15 -1
- package/src/batch/attached-runner-reconcile.mjs +1 -1
- package/src/batch/batch-meta-reconstruct.mjs +6 -1
- package/src/batch/batch-state-io.mjs +120 -45
- package/src/batch/batch-state-lock.mjs +173 -31
- package/src/batch/contract-exec.mjs +46 -45
- package/src/batch/contract-spawn.mjs +225 -0
- package/src/batch/contract-verify.mjs +2 -1
- package/src/batch/detached-wait.mjs +1 -1
- package/src/batch/engine-crash-guard.mjs +143 -0
- package/src/batch/engine-lanes/matrix-run.mjs +34 -8
- package/src/batch/engine-lanes/matrix.mjs +143 -8
- package/src/batch/engine-lanes/merge.mjs +135 -34
- package/src/batch/engine-lanes/review-final.mjs +1 -1
- package/src/batch/engine-lanes.mjs +11 -9
- package/src/batch/engine.mjs +10 -10
- package/src/batch/integrate-dirty-overlap.mjs +35 -0
- package/src/batch/integrate-worktree.mjs +106 -13
- package/src/batch/integrate.mjs +34 -93
- package/src/batch/journal-checksum.mjs +26 -0
- package/src/batch/journal.mjs +32 -13
- package/src/batch/lifecycle-archive.mjs +84 -3
- package/src/batch/lifecycle-cleanup.mjs +110 -0
- package/src/batch/lifecycle.mjs +100 -72
- package/src/batch/parent-session-monitor.mjs +77 -70
- package/src/batch/pause.mjs +92 -25
- package/src/batch/post-merge-limbo.mjs +35 -5
- package/src/batch/reconcile-batch.mjs +13 -1
- package/src/batch/resume-gate-reopen.mjs +24 -8
- package/src/batch/resume-multi.mjs +1 -1
- package/src/batch/resume.mjs +1 -1
- package/src/batch/salvage-batch-integrate.mjs +13 -17
- package/src/batch/sequence-run.mjs +26 -8
- package/src/batch/sequence-wait.mjs +87 -8
- package/src/batch/state-guards.mjs +39 -7
- package/src/batch/state-io.mjs +131 -17
- package/src/batch/state.mjs +23 -1
- package/src/batch/worker-heartbeat.mjs +29 -8
- package/src/batch/worker-host.mjs +61 -8
- package/src/batch/worker-output.mjs +9 -6
- package/src/batch/worker-prompt.mjs +4 -2
- package/src/batch/worker-spawn.mjs +99 -12
- package/src/config/defaults.mjs +15 -1
- package/src/config/preflight/discovery.mjs +20 -12
- package/src/config/preflight/git-batch.mjs +47 -0
- package/src/config/spine-config-schema.mjs +67 -1
- package/src/fs/atomic-write.mjs +37 -1
- package/src/planner/scope.mjs +3 -1
- package/src/tasks/packet/discover.mjs +59 -3
|
@@ -34,17 +34,42 @@ function archivedBatchStatePath(projectRoot, batchId) {
|
|
|
34
34
|
return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Whether `<root>/.spine/runtime/<batchId>/archive/batch-state.json` exists — i.e. the
|
|
39
|
+
* batch was archived by `spine batch complete` / `dismiss` / `abort` (SP-790 / #293).
|
|
40
|
+
* Callers use this to check archive status without duplicating the path.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} projectRoot
|
|
43
|
+
* @param {string} batchId
|
|
44
|
+
* @returns {boolean}
|
|
45
|
+
*/
|
|
46
|
+
export function isBatchArchived(projectRoot, batchId) {
|
|
47
|
+
const id = String(batchId ?? "");
|
|
48
|
+
if (!id) return false;
|
|
49
|
+
return fs.existsSync(archivedBatchStatePath(projectRoot, id));
|
|
50
|
+
}
|
|
51
|
+
|
|
37
52
|
/**
|
|
38
53
|
* Reject cache writes from non-owner engines or post-archive resurrection (SP-254).
|
|
39
54
|
*
|
|
55
|
+
* The resurrection check applies to **every** incoming phase, including terminal
|
|
56
|
+
* ones (`completed`/`failed`): a late land-loop finalize after `spine batch complete`
|
|
57
|
+
* archived the batch must not recreate `.spine/batch-state.json` (SP-790 / #293).
|
|
58
|
+
* Operator recovery that intentionally rebuilds an archived batch passes
|
|
59
|
+
* `allowArchivedResurrection: true` (force-resume from batch-meta, #126).
|
|
60
|
+
*
|
|
61
|
+
* `skipOwnerCheck` skips only the live-foreign-owner-PID rejection so trusted
|
|
62
|
+
* engine writers cannot be blocked by their own recorded PID; resurrection
|
|
63
|
+
* protection always runs.
|
|
64
|
+
*
|
|
40
65
|
* @param {string} projectRoot
|
|
41
66
|
* @param {Record<string, any>} state
|
|
67
|
+
* @param {{ skipOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
|
|
42
68
|
* @returns {{ allowed: boolean, reason?: string }}
|
|
43
69
|
*/
|
|
44
|
-
export function evaluateBatchStateWriteGuard(projectRoot, state) {
|
|
70
|
+
export function evaluateBatchStateWriteGuard(projectRoot, state, options = {}) {
|
|
45
71
|
const filePath = spineBatchStatePath(projectRoot);
|
|
46
72
|
const batchId = String(state.batchId ?? "");
|
|
47
|
-
const incomingPhase = String(state.phase ?? "");
|
|
48
73
|
|
|
49
74
|
if (fs.existsSync(filePath)) {
|
|
50
75
|
try {
|
|
@@ -63,16 +88,23 @@ export function evaluateBatchStateWriteGuard(projectRoot, state) {
|
|
|
63
88
|
) {
|
|
64
89
|
return { allowed: true };
|
|
65
90
|
}
|
|
66
|
-
if (
|
|
91
|
+
if (
|
|
92
|
+
!options.skipOwnerCheck &&
|
|
93
|
+
ownerPid &&
|
|
94
|
+
ownerPid !== process.pid &&
|
|
95
|
+
isEngineProcessAlive(ownerPid, ownerStartedAt)
|
|
96
|
+
) {
|
|
67
97
|
return { allowed: false, reason: "stale_engine_pid" };
|
|
68
98
|
}
|
|
69
99
|
} catch {
|
|
70
100
|
/* corrupt on-disk state — allow overwrite */
|
|
71
101
|
}
|
|
72
|
-
} else if (
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
102
|
+
} else if (
|
|
103
|
+
batchId &&
|
|
104
|
+
!options.allowArchivedResurrection &&
|
|
105
|
+
isBatchArchived(projectRoot, batchId)
|
|
106
|
+
) {
|
|
107
|
+
return { allowed: false, reason: "archived_batch_resurrection" };
|
|
76
108
|
}
|
|
77
109
|
|
|
78
110
|
return { allowed: true };
|
package/src/batch/state-io.mjs
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import fs from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { writeJsonAtomic } from "../fs/atomic-write.mjs";
|
|
8
|
+
import { appendJournalEvent } from "./journal.mjs";
|
|
8
9
|
import { withBatchStateLock } from "./batch-state-lock.mjs";
|
|
9
10
|
import {
|
|
10
11
|
clearBatchEnginePid,
|
|
@@ -52,6 +53,69 @@ function archivedBatchStatePath(projectRoot, batchId) {
|
|
|
52
53
|
return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
|
|
53
54
|
}
|
|
54
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Make a rejected batch-state write visible instead of silent (#293 / SP-790):
|
|
58
|
+
* journal `batch.state_write_rejected` (when the incoming state carries a batchId)
|
|
59
|
+
* and print one `[spine]` line to stderr so a swallowed late write is diagnosable.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} projectRoot
|
|
62
|
+
* @param {Record<string, any>} state
|
|
63
|
+
* @param {string} reason
|
|
64
|
+
*/
|
|
65
|
+
function reportRejectedBatchStateWrite(projectRoot, state, reason) {
|
|
66
|
+
const batchId = String(state?.batchId ?? "");
|
|
67
|
+
if (batchId) {
|
|
68
|
+
try {
|
|
69
|
+
appendJournalEvent(projectRoot, batchId, "batch.state_write_rejected", {
|
|
70
|
+
reason,
|
|
71
|
+
incomingPhase: String(state.phase ?? ""),
|
|
72
|
+
});
|
|
73
|
+
} catch {
|
|
74
|
+
/* journal failure must not turn a guarded no-op into a crash */
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
console.error(
|
|
78
|
+
`[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state`,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Guard + write path shared by `saveSpineBatchState` and `updateSpineBatchState`
|
|
84
|
+
* (SP-791 / #301). The caller must already hold the batch-state lock; the
|
|
85
|
+
* guard evaluation and the write run in one critical section so the
|
|
86
|
+
* check-then-act pair cannot race a concurrent writer from another process.
|
|
87
|
+
*
|
|
88
|
+
* Returns a structured result so callers can distinguish a rejected write
|
|
89
|
+
* (`{ ok: false, reason }`, disk state returned as `state`) from a persisted
|
|
90
|
+
* one (`{ ok: true, state: next }`).
|
|
91
|
+
*
|
|
92
|
+
* @param {string} projectRoot
|
|
93
|
+
* @param {Record<string, any>} state
|
|
94
|
+
* @param {{ bypassOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} options
|
|
95
|
+
* @returns {{ ok: true, state: Record<string, any> } | { ok: false, reason: string, state: Record<string, any> }}
|
|
96
|
+
*/
|
|
97
|
+
function persistSpineBatchStateGuarded(projectRoot, state, options) {
|
|
98
|
+
const guard = evaluateBatchStateWriteGuard(projectRoot, state, {
|
|
99
|
+
skipOwnerCheck: options.bypassOwnerCheck === true,
|
|
100
|
+
allowArchivedResurrection: options.allowArchivedResurrection === true,
|
|
101
|
+
});
|
|
102
|
+
if (!guard.allowed) {
|
|
103
|
+
const reason = String(guard.reason ?? "unknown");
|
|
104
|
+
reportRejectedBatchStateWrite(projectRoot, state, reason);
|
|
105
|
+
const loaded = loadSpineBatchState(projectRoot);
|
|
106
|
+
return { ok: false, reason, state: loaded.raw ?? state };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const filePath = spineBatchStatePath(projectRoot);
|
|
110
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
111
|
+
if (TERMINAL_BATCH_PHASES.has(String(state.phase ?? ""))) {
|
|
112
|
+
clearBatchEnginePid(state);
|
|
113
|
+
}
|
|
114
|
+
const next = { ...state, updatedAt: Date.now() };
|
|
115
|
+
writeJsonAtomic(filePath, next);
|
|
116
|
+
return { ok: true, state: next };
|
|
117
|
+
}
|
|
118
|
+
|
|
55
119
|
/**
|
|
56
120
|
* Persist batch state under the global batch-state lock (SP-722 / #264).
|
|
57
121
|
*
|
|
@@ -59,29 +123,79 @@ function archivedBatchStatePath(projectRoot, batchId) {
|
|
|
59
123
|
* check-then-act pair cannot race a concurrent writer from another process
|
|
60
124
|
* (engine vs. CLI complete/resume/abort).
|
|
61
125
|
*
|
|
126
|
+
* `bypassOwnerCheck: true` skips only the live-foreign-owner-PID check; the
|
|
127
|
+
* post-archive resurrection check always runs (SP-790 / #293).
|
|
128
|
+
* `allowArchivedResurrection: true` is reserved for operator recovery that
|
|
129
|
+
* intentionally rebuilds an archived batch (force-resume from batch-meta, #126).
|
|
130
|
+
*
|
|
131
|
+
* When the guard rejects, the on-disk state (or the incoming state when no
|
|
132
|
+
* disk state exists) is returned unchanged so existing callers keep their
|
|
133
|
+
* pre-SP-790 contract.
|
|
134
|
+
*
|
|
62
135
|
* @param {string} projectRoot
|
|
63
136
|
* @param {Record<string, any>} state
|
|
64
|
-
* @param {{
|
|
137
|
+
* @param {{ bypassOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
|
|
65
138
|
*/
|
|
66
139
|
export function saveSpineBatchState(projectRoot, state, options = {}) {
|
|
67
|
-
return withBatchStateLock(projectRoot, () =>
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (!guard.allowed) {
|
|
72
|
-
const loaded = loadSpineBatchState(projectRoot);
|
|
73
|
-
return loaded.raw ?? state;
|
|
74
|
-
}
|
|
140
|
+
return withBatchStateLock(projectRoot, () =>
|
|
141
|
+
persistSpineBatchStateGuarded(projectRoot, state, options).state,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
75
144
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
145
|
+
/**
|
|
146
|
+
* Atomic read-modify-write on `.spine/batch-state.json` (SP-791 / #301).
|
|
147
|
+
*
|
|
148
|
+
* Load, clone, mutate, and guarded save all run inside ONE `withBatchStateLock`
|
|
149
|
+
* hold, so racing processes (engine progress save vs. operator pause/resume)
|
|
150
|
+
* each mutate the latest committed state instead of clobbering each other with
|
|
151
|
+
* stale whole-file snapshots. The lock is re-entrant per process, so callers
|
|
152
|
+
* may already hold it (e.g. under `withBatchStateLock`) and the nested
|
|
153
|
+
* acquisition composes instead of self-deadlocking.
|
|
154
|
+
*
|
|
155
|
+
* `mutate(draft, { diskState })` receives a `structuredClone` of the raw disk
|
|
156
|
+
* state plus the disk state itself for read-only reference; mutating `draft`
|
|
157
|
+
* never affects the returned `diskState`. Returning exactly `false` from
|
|
158
|
+
* `mutate` is a no-op: nothing is written and `{ changed: false }` is returned.
|
|
159
|
+
*
|
|
160
|
+
* Results:
|
|
161
|
+
* - `{ ok: false, reason: "missing" }` — no batch-state.json on disk
|
|
162
|
+
* - `{ ok: false, reason: "corrupt" }` — batch-state.json is unparseable
|
|
163
|
+
* - `{ ok: false, reason, state }` — the write guard rejected (e.g.
|
|
164
|
+
* `stale_engine_pid`, `archived_batch_resurrection`); `state` is the on-disk
|
|
165
|
+
* state that was kept
|
|
166
|
+
* - `{ ok: true, changed: false, state }` — `mutate` returned `false`;
|
|
167
|
+
* `state` is the untouched disk state
|
|
168
|
+
* - `{ ok: true, changed: true, state }` — mutated state persisted
|
|
169
|
+
*
|
|
170
|
+
* `options` passes through to the same guard/write path as
|
|
171
|
+
* `saveSpineBatchState` (`bypassOwnerCheck` / `allowArchivedResurrection`).
|
|
172
|
+
*
|
|
173
|
+
* @param {string} projectRoot
|
|
174
|
+
* @param {(draft: Record<string, any>, ctx: { diskState: Record<string, any> }) => boolean | unknown} mutate
|
|
175
|
+
* @param {{ bypassOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
|
|
176
|
+
* @returns {{ ok: boolean, reason?: string, changed?: boolean, state?: Record<string, any> }}
|
|
177
|
+
*/
|
|
178
|
+
export function updateSpineBatchState(projectRoot, mutate, options = {}) {
|
|
179
|
+
const result = /** @type {{ ok: boolean, reason?: string, changed?: boolean, state?: Record<string, any> }} */ (
|
|
180
|
+
withBatchStateLock(projectRoot, () => {
|
|
181
|
+
const loaded = loadSpineBatchState(projectRoot);
|
|
182
|
+
if (!loaded.raw) {
|
|
183
|
+
return { ok: false, reason: loaded.parseError ? "corrupt" : "missing" };
|
|
80
184
|
}
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
185
|
+
const diskState = loaded.raw;
|
|
186
|
+
const draft = structuredClone(diskState);
|
|
187
|
+
const mutated = mutate(draft, { diskState });
|
|
188
|
+
if (mutated === false) {
|
|
189
|
+
return { ok: true, changed: false, state: diskState };
|
|
190
|
+
}
|
|
191
|
+
const persisted = persistSpineBatchStateGuarded(projectRoot, draft, options);
|
|
192
|
+
if (!persisted.ok) {
|
|
193
|
+
return { ok: false, reason: persisted.reason, state: persisted.state };
|
|
194
|
+
}
|
|
195
|
+
return { ok: true, changed: true, state: persisted.state };
|
|
196
|
+
})
|
|
197
|
+
);
|
|
198
|
+
return result;
|
|
85
199
|
}
|
|
86
200
|
|
|
87
201
|
/**
|
package/src/batch/state.mjs
CHANGED
|
@@ -21,6 +21,7 @@ export {
|
|
|
21
21
|
spineBatchStatePath,
|
|
22
22
|
loadSpineBatchState,
|
|
23
23
|
saveSpineBatchState,
|
|
24
|
+
updateSpineBatchState,
|
|
24
25
|
batchHistoryPath,
|
|
25
26
|
resolveBatchStateFileForValidation,
|
|
26
27
|
appendBatchHistoryEntry,
|
|
@@ -125,10 +126,24 @@ export function failBatchFromEngineError({
|
|
|
125
126
|
}
|
|
126
127
|
|
|
127
128
|
/**
|
|
129
|
+
* Fail closed when the on-disk batch state must not be silently replaced.
|
|
130
|
+
*
|
|
131
|
+
* Corrupt spine-owned state is quarantined (never deleted) and start refuses
|
|
132
|
+
* with an actionable recovery message (SP-786 / #303). This gate runs even
|
|
133
|
+
* when preflight is skipped: the engine calls `assertNoActiveBatch`
|
|
134
|
+
* unconditionally on every start path. A Taskplane-owned `.pi/batch-state.json`
|
|
135
|
+
* is never modified — a corrupt one is reported instead.
|
|
136
|
+
*
|
|
128
137
|
* @param {string} projectRoot
|
|
129
138
|
*/
|
|
130
139
|
export function assertNoActiveBatch(projectRoot) {
|
|
131
|
-
clearStaleTerminalBatchStateForStart(projectRoot);
|
|
140
|
+
const clearResult = clearStaleTerminalBatchStateForStart(projectRoot);
|
|
141
|
+
if (clearResult.reason === "corrupt") {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`Batch state was corrupt and has been quarantined to ${clearResult.quarantinedPath}. ` +
|
|
144
|
+
"Inspect it and the journal (spine status --diagnose), then run spine batch dismiss --force before starting a new batch.",
|
|
145
|
+
);
|
|
146
|
+
}
|
|
132
147
|
|
|
133
148
|
const spine = loadSpineBatchState(projectRoot);
|
|
134
149
|
if (spine.path && spine.raw) {
|
|
@@ -141,6 +156,13 @@ export function assertNoActiveBatch(projectRoot) {
|
|
|
141
156
|
}
|
|
142
157
|
|
|
143
158
|
const any = loadBatchStateFile(projectRoot);
|
|
159
|
+
if (any.path && any.parseError) {
|
|
160
|
+
// Corrupt Taskplane-owned state: reported, never modified by spine (SP-786 / #303).
|
|
161
|
+
throw new Error(
|
|
162
|
+
`Batch state at ${any.path} is corrupt and was left unmodified by spine (${any.parseError}). ` +
|
|
163
|
+
"Inspect it (spine status --diagnose), then repair or remove it with the owning tool before starting a new batch.",
|
|
164
|
+
);
|
|
165
|
+
}
|
|
144
166
|
if (any.path && any.raw) {
|
|
145
167
|
const phase = String(any.raw.phase ?? "");
|
|
146
168
|
const active =
|
|
@@ -37,10 +37,20 @@ import { terminateProcessTree } from "../process/terminate-tree.mjs";
|
|
|
37
37
|
/**
|
|
38
38
|
* @param {number} ms
|
|
39
39
|
*/
|
|
40
|
-
function
|
|
40
|
+
function defaultSleep(ms) {
|
|
41
41
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Injectable timing for `pollWorkerUntilSettled` (SP-779 / #308). Tests pass a
|
|
46
|
+
* virtual clock so stall classification is wall-clock independent; production
|
|
47
|
+
* callers omit `deps` and keep the Date.now/setTimeout defaults.
|
|
48
|
+
*
|
|
49
|
+
* @typedef {object} WorkerPollDeps
|
|
50
|
+
* @property {() => number} [now] Clock read at the top of every poll (default `Date.now`).
|
|
51
|
+
* @property {(ms: number) => Promise<void>} [sleep] Inter-poll wait (default `setTimeout`).
|
|
52
|
+
*/
|
|
53
|
+
|
|
44
54
|
/**
|
|
45
55
|
* @typedef {object} WorkerPollState
|
|
46
56
|
* @property {number} stallAnchorAt
|
|
@@ -112,6 +122,7 @@ export function createWorkerPollState(startedAt, workerPhase) {
|
|
|
112
122
|
* signals?: object;
|
|
113
123
|
* }) => object} params.buildFailureResult
|
|
114
124
|
* @param {string} params.workerMode
|
|
125
|
+
* @param {WorkerPollDeps} [params.deps] Injectable timing; defaults preserve production behavior.
|
|
115
126
|
* @returns {Promise<
|
|
116
127
|
* | { kind: "settled"; postDoneTerminated: boolean }
|
|
117
128
|
* | { kind: "failure"; result: object }
|
|
@@ -139,7 +150,9 @@ export async function pollWorkerUntilSettled({
|
|
|
139
150
|
onHeartbeat,
|
|
140
151
|
buildFailureResult,
|
|
141
152
|
workerMode,
|
|
153
|
+
deps = {},
|
|
142
154
|
}) {
|
|
155
|
+
const { now: nowFn = Date.now, sleep: sleepFn = defaultSleep } = deps;
|
|
143
156
|
let {
|
|
144
157
|
stallAnchorAt,
|
|
145
158
|
lastCheckpointAt,
|
|
@@ -157,7 +170,7 @@ export async function pollWorkerUntilSettled({
|
|
|
157
170
|
|
|
158
171
|
while (true) {
|
|
159
172
|
const doneOnDisk = fs.existsSync(donePath);
|
|
160
|
-
const now =
|
|
173
|
+
const now = nowFn();
|
|
161
174
|
|
|
162
175
|
if (doneOnDisk && postDoneStartedAt === null) {
|
|
163
176
|
postDoneStartedAt = now;
|
|
@@ -208,7 +221,10 @@ export async function pollWorkerUntilSettled({
|
|
|
208
221
|
await terminateHungWorkerChild(workerChild, childDone);
|
|
209
222
|
break;
|
|
210
223
|
}
|
|
211
|
-
|
|
224
|
+
// #308: race the inter-poll wait against child exit so a worker that
|
|
225
|
+
// finishes right after writing .DONE is observed on its next wake
|
|
226
|
+
// instead of a full interval later.
|
|
227
|
+
await Promise.race([sleepFn(Math.min(stallConfig.pollIntervalMs, 5_000)), childDone]);
|
|
212
228
|
continue;
|
|
213
229
|
}
|
|
214
230
|
|
|
@@ -346,6 +362,15 @@ export async function pollWorkerUntilSettled({
|
|
|
346
362
|
lastHeartbeatAt = now;
|
|
347
363
|
}
|
|
348
364
|
|
|
365
|
+
// #308: observe child exit before the stall deadline. A worker that exits
|
|
366
|
+
// on its own between polls is settled work, never a stall — even when the
|
|
367
|
+
// next poll lands past the budget (the old order classified such exits
|
|
368
|
+
// `stall_timeout`). The bottom sleep races `childDone`, so exits are seen
|
|
369
|
+
// promptly; handles resolve `childDone` only after `exitCode` is set.
|
|
370
|
+
if (workerChild.exitCode !== null) {
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
|
|
349
374
|
const stallDeadline = computeStallDeadline({
|
|
350
375
|
startedAt,
|
|
351
376
|
lastProgressAt: lastCheckpointAt,
|
|
@@ -396,11 +421,7 @@ export async function pollWorkerUntilSettled({
|
|
|
396
421
|
};
|
|
397
422
|
}
|
|
398
423
|
|
|
399
|
-
|
|
400
|
-
break;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
|
|
424
|
+
await Promise.race([sleepFn(Math.min(stallConfig.pollIntervalMs, 5_000)), childDone]);
|
|
404
425
|
}
|
|
405
426
|
|
|
406
427
|
return { kind: "settled", postDoneTerminated };
|
|
@@ -13,7 +13,11 @@ import {
|
|
|
13
13
|
import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
|
|
14
14
|
import { appendJournalEvent } from "./journal.mjs";
|
|
15
15
|
import { assertReviewToolAvailable } from "./review.mjs";
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
finalizeWorkerOutput,
|
|
18
|
+
createWorkerLiveLogWriter,
|
|
19
|
+
resolveWorkerOutputConfig,
|
|
20
|
+
} from "./worker-output.mjs";
|
|
17
21
|
import { resolveWorkerBackend } from "../config/worker-backend.mjs";
|
|
18
22
|
import { commandExists } from "../util/command-exists.mjs";
|
|
19
23
|
import {
|
|
@@ -179,10 +183,12 @@ export async function runWorker({
|
|
|
179
183
|
return { ok: true, exitCode: 0, mode: "already-done" };
|
|
180
184
|
}
|
|
181
185
|
|
|
182
|
-
const
|
|
183
|
-
process.env.SPINE_WORKER_STUB === "1" ||
|
|
184
|
-
|
|
185
|
-
|
|
186
|
+
const stubExplicit =
|
|
187
|
+
process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
|
|
188
|
+
// #299 (SP-801): the stub is opt-in only. The old implicit fallback
|
|
189
|
+
// (missing `pi` → stub) could mark review-level-0 tasks done with no work
|
|
190
|
+
// when PATH lacked `pi`; the fail-closed guard below replaces it.
|
|
191
|
+
const useStub = stubExplicit;
|
|
186
192
|
|
|
187
193
|
const workerBackend = useStub ? "subprocess" : resolveWorkerBackend(config);
|
|
188
194
|
const workerMode = useStub ? "stub" : workerBackend === "agentSession" ? "agentSession" : "pi";
|
|
@@ -225,6 +231,32 @@ export async function runWorker({
|
|
|
225
231
|
const isExecute = parsedPrompt?.type === "execute";
|
|
226
232
|
const runCommand = contract.runCommand || contract.testCommand;
|
|
227
233
|
|
|
234
|
+
// #299 (SP-801): fail closed when the pi CLI is missing rather than silently
|
|
235
|
+
// falling back to the stub. Placed after the review gate so review-tool
|
|
236
|
+
// unavailability keeps its `review_failed` precedence, and scoped to
|
|
237
|
+
// non-execute tasks (execute-only runs the contract command, never `pi`);
|
|
238
|
+
// agentSession workers spawn in-process and never consult PATH for `pi`.
|
|
239
|
+
if (!stubExplicit && !isExecute && workerBackend !== "agentSession" && !commandExists("pi")) {
|
|
240
|
+
if (projectRoot && batchId) {
|
|
241
|
+
appendJournalEvent(projectRoot, batchId, "worker.spawn_failed", {
|
|
242
|
+
taskId,
|
|
243
|
+
laneNumber,
|
|
244
|
+
correlationId: laneCorrelationId,
|
|
245
|
+
reason: "pi_missing",
|
|
246
|
+
phase: "preflight",
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
ok: false,
|
|
251
|
+
exitCode: 1,
|
|
252
|
+
mode: workerMode,
|
|
253
|
+
output:
|
|
254
|
+
"worker requires pi on PATH (fail closed); set SPINE_WORKER_STUB=1 only for stub runs",
|
|
255
|
+
classification: "launch_failed",
|
|
256
|
+
doneFound: false,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
228
260
|
const child = isExecute
|
|
229
261
|
? spawnExecutionOnlyHandle({
|
|
230
262
|
worktreePath,
|
|
@@ -262,6 +294,7 @@ export async function runWorker({
|
|
|
262
294
|
childPastPreflight = true;
|
|
263
295
|
});
|
|
264
296
|
onWorkerPid?.(workerChild.pid ?? 0);
|
|
297
|
+
const outputConfig = resolveWorkerOutputConfig(config);
|
|
265
298
|
const liveLogWriter = createWorkerLiveLogWriter({
|
|
266
299
|
projectRoot,
|
|
267
300
|
batchId,
|
|
@@ -269,7 +302,7 @@ export async function runWorker({
|
|
|
269
302
|
taskId,
|
|
270
303
|
config,
|
|
271
304
|
});
|
|
272
|
-
const childDone = collectChildOutput(workerChild, liveLogWriter);
|
|
305
|
+
const childDone = collectChildOutput(workerChild, liveLogWriter, outputConfig.maxBytes);
|
|
273
306
|
|
|
274
307
|
const pollState = createWorkerPollState(startedAt, initialWorkerPhase);
|
|
275
308
|
const pollOutcome = await pollWorkerUntilSettled({
|
|
@@ -315,12 +348,32 @@ export async function runWorker({
|
|
|
315
348
|
|
|
316
349
|
const childResult = await Promise.race([childDone, sleep(CHILD_DONE_TIMEOUT_MS).then(() => null)]);
|
|
317
350
|
let exitCode, output;
|
|
351
|
+
/** @type {boolean} */
|
|
352
|
+
let spawnFailed = false;
|
|
318
353
|
if (childResult) {
|
|
319
|
-
({ exitCode, output } = childResult);
|
|
354
|
+
({ exitCode, output, spawnError: spawnFailed = false } = childResult);
|
|
320
355
|
} else {
|
|
321
356
|
// close event didn't fire — sub-processes likely hold stdio pipes open.
|
|
322
357
|
const fallback = await terminateHungWorkerChild(workerChild, childDone);
|
|
323
|
-
({ exitCode, output } = fallback);
|
|
358
|
+
({ exitCode, output, spawnError: spawnFailed = false } = fallback);
|
|
359
|
+
}
|
|
360
|
+
// SP-787 (#306): the child never spawned (EACCES/ENOENT/missing execPath).
|
|
361
|
+
// Report `launch_failed` for this lane through the standard failure path so
|
|
362
|
+
// the engine keeps running; no worker code ran, so .DONE cannot be honored.
|
|
363
|
+
if (spawnFailed) {
|
|
364
|
+
return buildWorkerFailureResult({
|
|
365
|
+
rawOutput: output,
|
|
366
|
+
classification: "launch_failed",
|
|
367
|
+
exitCode,
|
|
368
|
+
mode: workerMode,
|
|
369
|
+
doneFound: fs.existsSync(donePath),
|
|
370
|
+
projectRoot,
|
|
371
|
+
batchId,
|
|
372
|
+
laneNumber,
|
|
373
|
+
taskId,
|
|
374
|
+
laneCorrelationId,
|
|
375
|
+
config,
|
|
376
|
+
});
|
|
324
377
|
}
|
|
325
378
|
const doneFound = fs.existsSync(donePath);
|
|
326
379
|
if (postDoneTerminated && !doneFound) {
|
|
@@ -192,7 +192,9 @@ export function truncateLiveLogBytes(text, maxBytes) {
|
|
|
192
192
|
}
|
|
193
193
|
|
|
194
194
|
/**
|
|
195
|
-
* Append redacted worker output to the live log
|
|
195
|
+
* Append redacted worker output to the live log (SP-787 / #306). The hot path
|
|
196
|
+
* is a pure append — the file is never re-read per chunk. Only when it has
|
|
197
|
+
* grown past twice `workerLiveLogMaxBytes` is it truncated back to the cap.
|
|
196
198
|
*
|
|
197
199
|
* @param {object} params
|
|
198
200
|
* @param {string} params.logPath
|
|
@@ -205,12 +207,13 @@ export function appendWorkerLiveLogChunk({ logPath, rawChunk, outputConfig }) {
|
|
|
205
207
|
const redacted = redactWorkerOutput(String(rawChunk), outputConfig);
|
|
206
208
|
if (!redacted) return;
|
|
207
209
|
|
|
208
|
-
const prior = fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf-8") : "";
|
|
209
|
-
const combined = `${prior}${redacted}`;
|
|
210
|
-
const capped = truncateLiveLogBytes(combined, outputConfig.workerLiveLogMaxBytes);
|
|
211
|
-
if (!capped) return;
|
|
212
|
-
|
|
213
210
|
fs.mkdirSync(path.dirname(logPath), { recursive: true });
|
|
211
|
+
fs.appendFileSync(logPath, redacted);
|
|
212
|
+
|
|
213
|
+
const size = fs.statSync(logPath, { throwIfNoEntry: false })?.size ?? 0;
|
|
214
|
+
if (size <= outputConfig.workerLiveLogMaxBytes * 2) return;
|
|
215
|
+
|
|
216
|
+
const capped = truncateLiveLogBytes(fs.readFileSync(logPath, "utf-8"), outputConfig.workerLiveLogMaxBytes);
|
|
214
217
|
writeTextAtomic(logPath, capped);
|
|
215
218
|
}
|
|
216
219
|
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { buildWorkerContextAsync } from "../config/worker-context.mjs";
|
|
9
|
+
import { taskIdFromFolderName } from "../tasks/packet/discover.mjs";
|
|
9
10
|
|
|
10
11
|
export function buildReviewLevelHint(reviewLevel) {
|
|
11
12
|
if (reviewLevel <= 0) {
|
|
@@ -44,7 +45,7 @@ export async function buildWorkerTailPrompt({
|
|
|
44
45
|
worktreePath,
|
|
45
46
|
taskFolder,
|
|
46
47
|
donePath,
|
|
47
|
-
taskIdHint =
|
|
48
|
+
taskIdHint = taskIdFromFolder(taskFolder),
|
|
48
49
|
reviewLevel = 0,
|
|
49
50
|
includePromptInclude = false,
|
|
50
51
|
config = {},
|
|
@@ -81,5 +82,6 @@ export async function buildWorkerTailPrompt({
|
|
|
81
82
|
}
|
|
82
83
|
|
|
83
84
|
export function taskIdFromFolder(taskFolder) {
|
|
84
|
-
|
|
85
|
+
// Shared pattern (SP-785, #300); keeps the TASK-ID fallback for unparseable names.
|
|
86
|
+
return taskIdFromFolderName(path.basename(taskFolder)) ?? "TASK-ID";
|
|
85
87
|
}
|