pi-spine 2.25.0 → 2.27.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.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +14 -1
  4. package/package.json +3 -3
  5. package/skills/spine-release-operator/SKILL.md +3 -0
  6. package/src/batch/abort.mjs +74 -38
  7. package/src/batch/attached-engine-handoff.mjs +2 -2
  8. package/src/batch/attached-runner-promote.mjs +1 -1
  9. package/src/batch/attached-runner-reconcile.mjs +1 -1
  10. package/src/batch/batch-meta-reconstruct.mjs +9 -1
  11. package/src/batch/batch-state-lock.mjs +173 -31
  12. package/src/batch/contract-exec.mjs +48 -47
  13. package/src/batch/contract-parse.mjs +2 -2
  14. package/src/batch/contract-prelanded.mjs +2 -2
  15. package/src/batch/contract-spawn.mjs +225 -0
  16. package/src/batch/contract-verify.mjs +2 -1
  17. package/src/batch/detached-wait.mjs +1 -1
  18. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  19. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  20. package/src/batch/engine-lanes/matrix-run.mjs +6 -6
  21. package/src/batch/engine-lanes/merge.mjs +135 -34
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  24. package/src/batch/engine-lanes/review-code.mjs +1 -0
  25. package/src/batch/engine-lanes/review-final.mjs +83 -46
  26. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  27. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  28. package/src/batch/engine-lanes.mjs +17 -16
  29. package/src/batch/engine.mjs +10 -10
  30. package/src/batch/journal.mjs +15 -0
  31. package/src/batch/lifecycle-archive.mjs +76 -1
  32. package/src/batch/lifecycle-cleanup.mjs +110 -0
  33. package/src/batch/lifecycle.mjs +100 -72
  34. package/src/batch/metrics.mjs +13 -1
  35. package/src/batch/parent-session-monitor.mjs +77 -70
  36. package/src/batch/pause.mjs +92 -25
  37. package/src/batch/post-merge-limbo.mjs +35 -5
  38. package/src/batch/provider-quota.mjs +220 -0
  39. package/src/batch/quota-fallback.mjs +319 -0
  40. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  41. package/src/batch/resume-gate-reopen.mjs +24 -8
  42. package/src/batch/resume-multi-queue.mjs +25 -10
  43. package/src/batch/resume-multi.mjs +1 -1
  44. package/src/batch/resume.mjs +1 -1
  45. package/src/batch/review-artifacts.mjs +93 -15
  46. package/src/batch/review-spawn-retry.mjs +106 -0
  47. package/src/batch/review-spawn.mjs +48 -2
  48. package/src/batch/review-step-run.mjs +96 -6
  49. package/src/batch/reviewer-output.mjs +162 -0
  50. package/src/batch/sequence-run.mjs +26 -8
  51. package/src/batch/sequence-wait.mjs +87 -8
  52. package/src/batch/state-guards.mjs +39 -7
  53. package/src/batch/state-io.mjs +131 -17
  54. package/src/batch/state.mjs +1 -0
  55. package/src/batch/worker-host.mjs +81 -7
  56. package/src/config/cursor-rules/discover.mjs +2 -2
  57. package/src/config/cursor-rules/match-globs.mjs +6 -4
  58. package/src/config/defaults.mjs +15 -1
  59. package/src/config/env-overrides.mjs +41 -4
  60. package/src/config/preflight/git-batch.mjs +47 -0
  61. package/src/config/settings-fields.mjs +6 -0
  62. package/src/config/spine-config-schema.mjs +91 -1
  63. package/src/doctor/quota-risk.mjs +45 -0
  64. package/src/fs/atomic-write.mjs +37 -1
  65. package/src/planner/file-scope.mjs +6 -6
  66. package/src/tasks/packet/validate-contract.mjs +3 -3
@@ -3,12 +3,17 @@
3
3
  */
4
4
 
5
5
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
- import { DEFAULT_SEQUENCE_POLL_MS } from "../config/spine-config-schema.mjs";
7
- import { isProcessAlive } from "../process/liveness.mjs";
6
+ import {
7
+ DEFAULT_SEQUENCE_MAX_WAIT_MS,
8
+ DEFAULT_SEQUENCE_POLL_MS,
9
+ DEFAULT_SEQUENCE_STALL_MS,
10
+ } from "../config/spine-config-schema.mjs";
11
+ import { isEngineProcessAlive, isProcessAlive } from "../process/liveness.mjs";
8
12
  import { approveIntegrateGate, loadGateRecord, maybeAutoApproveIntegrateGate } from "./gate.mjs";
9
13
  import { integrateOrchToBase } from "./integrate.mjs";
10
14
  import { completeBatch } from "./lifecycle.mjs";
11
15
  import { reconcileBatch } from "./reconcile.mjs";
16
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
12
17
  import { loadSpineBatchState } from "./state.mjs";
13
18
 
14
19
  const WAVE_BATCH_SETTLED_DIAGNOSES = new Set([
@@ -49,12 +54,28 @@ export async function waitForSequenceBatchTerminal({
49
54
  projectRoot,
50
55
  pollIntervalMs = DEFAULT_SEQUENCE_POLL_MS,
51
56
  timeoutMs = 120_000,
57
+ maxWaitMs = DEFAULT_SEQUENCE_MAX_WAIT_MS,
58
+ stallMs = DEFAULT_SEQUENCE_STALL_MS,
52
59
  enginePid = null,
53
60
  reconcileFn = reconcileBatch,
54
61
  }) {
55
- const deadline = Date.now() + timeoutMs;
62
+ const startedAt = Date.now();
63
+ const deadline = startedAt + timeoutMs;
64
+ const hardCap = startedAt + maxWaitMs;
65
+ let lastProgressAt = startedAt;
56
66
  let useLightReconcile = false;
57
67
  while (Date.now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
68
+ if (Date.now() >= hardCap) {
69
+ const reconciliation = reconcileFn({ projectRoot });
70
+ return {
71
+ ok: false,
72
+ error: "sequence_wait_timeout",
73
+ diagnosis: reconciliation.diagnosis ?? null,
74
+ reconciliation,
75
+ batchId: reconciliation.batchId ?? null,
76
+ suggestedCommand: "spine status --diagnose",
77
+ };
78
+ }
58
79
  const reconciliation = reconcileFn({ projectRoot, light: useLightReconcile });
59
80
  useLightReconcile = true;
60
81
  const diagnosis = reconciliation.diagnosis;
@@ -75,6 +96,20 @@ export async function waitForSequenceBatchTerminal({
75
96
  batchId: reconciliation.batchId ?? null,
76
97
  };
77
98
  }
99
+ const progressAt = newestProgressSignalMs(reconciliation);
100
+ if (progressAt != null && progressAt > lastProgressAt) {
101
+ lastProgressAt = progressAt;
102
+ }
103
+ if (Date.now() - lastProgressAt >= stallMs) {
104
+ return {
105
+ ok: false,
106
+ error: "engine_stalled",
107
+ diagnosis,
108
+ reconciliation,
109
+ batchId: reconciliation.batchId ?? null,
110
+ suggestedCommand: "spine status --diagnose",
111
+ };
112
+ }
78
113
  await sleep(pollIntervalMs);
79
114
  }
80
115
  const reconciliation = reconcileFn({ projectRoot });
@@ -88,14 +123,58 @@ export async function waitForSequenceBatchTerminal({
88
123
  }
89
124
 
90
125
  /**
91
- * Returns true when a detached engine PID is alive or the batch phase is active,
92
- * preventing sequence timeout while work is still in progress.
126
+ * Newest progress signal exposed by a reconciliation, in epoch ms: batch-state
127
+ * `updatedAt` or the latest journal event timestamp (lane heartbeats are
128
+ * journal `lane.heartbeat` events, so they are covered by the journal tail).
129
+ * Returns null when no signal is available (SP-802 / #307).
130
+ *
131
+ * @param {object} reconciliation
132
+ * @returns {number|null}
133
+ */
134
+ function newestProgressSignalMs(reconciliation) {
135
+ const signals = reconciliation?.signals ?? {};
136
+ /** @type {number|null} */
137
+ let newest = null;
138
+ const updatedAt = Number(signals.raw?.updatedAt);
139
+ if (Number.isFinite(updatedAt) && updatedAt > 0) {
140
+ newest = updatedAt;
141
+ }
142
+ const events = Array.isArray(signals.journalEvents) ? signals.journalEvents : [];
143
+ for (let index = events.length - 1; index >= 0; index -= 1) {
144
+ const ts = Date.parse(String(events[index]?.timestamp ?? ""));
145
+ if (Number.isFinite(ts) && ts > 0) {
146
+ if (newest == null || ts > newest) newest = ts;
147
+ break;
148
+ }
149
+ }
150
+ return newest;
151
+ }
152
+
153
+ /**
154
+ * Returns true when the batch engine is verifiably still running, so the wait
155
+ * extends past `timeoutMs` while work is in progress. PID-reuse-safe (SP-802 /
156
+ * #307, #259): the explicit `enginePid` is paired with the state's recorded
157
+ * `engineStartedAt` when the PIDs match; the state fallback uses the recorded
158
+ * PID + start time from `resilience`; otherwise it degrades to PID-only
159
+ * liveness.
160
+ *
161
+ * @param {number|null} enginePid
162
+ * @param {string} projectRoot
93
163
  */
94
164
  function isEngineStillRunning(enginePid, projectRoot) {
95
- if (enginePid && isProcessAlive(enginePid)) return true;
96
165
  const { raw } = loadSpineBatchState(projectRoot);
97
- const pid = raw?.enginePid ?? null;
98
- if (pid && isProcessAlive(pid)) return true;
166
+ const statePid = readBatchEnginePid(raw);
167
+ const stateStartedAt = readBatchEngineStartedAt(raw);
168
+ const pid = Number(enginePid);
169
+ if (Number.isFinite(pid) && pid > 0) {
170
+ if (statePid != null && statePid === pid) {
171
+ return isEngineProcessAlive(pid, stateStartedAt);
172
+ }
173
+ if (isProcessAlive(pid)) return true;
174
+ }
175
+ if (statePid != null) {
176
+ return isEngineProcessAlive(statePid, stateStartedAt);
177
+ }
99
178
  return false;
100
179
  }
101
180
 
@@ -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 (ownerPid && ownerPid !== process.pid && isEngineProcessAlive(ownerPid, ownerStartedAt)) {
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 (batchId && ACTIVE_PHASES.has(incomingPhase)) {
73
- if (fs.existsSync(archivedBatchStatePath(projectRoot, batchId))) {
74
- return { allowed: false, reason: "archived_batch_resurrection" };
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 };
@@ -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 {{ bypassWriteGuard?: boolean }} [options]
137
+ * @param {{ bypassOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
65
138
  */
66
139
  export function saveSpineBatchState(projectRoot, state, options = {}) {
67
- return withBatchStateLock(projectRoot, () => {
68
- const guard = options.bypassWriteGuard
69
- ? { allowed: true }
70
- : evaluateBatchStateWriteGuard(projectRoot, state);
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
- const filePath = spineBatchStatePath(projectRoot);
77
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
78
- if (TERMINAL_BATCH_PHASES.has(String(state.phase ?? ""))) {
79
- clearBatchEnginePid(state);
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 next = { ...state, updatedAt: Date.now() };
82
- writeJsonAtomic(filePath, next);
83
- return next;
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
  /**
@@ -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,
@@ -12,6 +12,8 @@ import {
12
12
  } from "./task-stall-budget.mjs";
13
13
  import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
14
14
  import { appendJournalEvent } from "./journal.mjs";
15
+ import { classifyProviderQuotaError } from "./provider-quota.mjs";
16
+ import { resolveWorkerQuotaFallbackContext } from "./engine-lanes/quota-fallback-state.mjs";
15
17
  import { assertReviewToolAvailable } from "./review.mjs";
16
18
  import {
17
19
  finalizeWorkerOutput,
@@ -49,6 +51,36 @@ const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
49
51
  */
50
52
  const WORKER_TIMEOUT_EXIT_CODE = 124;
51
53
 
54
+ /**
55
+ * Reclassify a plain `failed` worker exit as a provider quota/overload exit
56
+ * when forwarded output matches a known provider payload, and journal
57
+ * `worker.quota_exhausted` for quota-exhausted exits (#329, SP-806). Aborted,
58
+ * stall, launch and review failures keep their meaning; overload is not
59
+ * journaled. Callers must run this after finalizeWorkerOutput so output
60
+ * capture still sees the original `failed` (shouldCaptureWorkerOutput matches
61
+ * the literal) while consumers receive the provider-quota exit reason.
62
+ *
63
+ * @param {{ classification: string, rawOutput: string, workerModel?: string, projectRoot?: string, batchId?: string, taskId?: string, laneNumber?: number, laneCorrelationId?: string }} params
64
+ * @returns {{ classification: string, providerQuota: import("./provider-quota.mjs").ProviderQuotaError | null }}
65
+ */
66
+ function applyProviderQuotaClassification({ classification, rawOutput, workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId }) {
67
+ if (classification !== "failed") return { classification, providerQuota: null };
68
+ // SP-808 (#329): the caller resolves the effective model (fallback profile
69
+ // when a hop is active) so classification and the journal tell the truth.
70
+ const model = typeof workerModel === "string" ? workerModel : undefined;
71
+ const providerQuota = classifyProviderQuotaError(rawOutput, model);
72
+ if (!providerQuota) return { classification, providerQuota: null };
73
+ if (providerQuota.kind === "quota_exhausted" && projectRoot && batchId) {
74
+ appendJournalEvent(projectRoot, batchId, "worker.quota_exhausted", {
75
+ taskId, laneNumber, correlationId: laneCorrelationId, poolId: providerQuota.poolId,
76
+ providerCode: providerQuota.providerCode, httpStatus: providerQuota.httpStatus,
77
+ resetAtRaw: providerQuota.resetAtRaw, ...(model ? { model } : {}),
78
+ });
79
+ }
80
+ const reclassified = providerQuota.kind === "quota_exhausted" ? "provider_quota_exhausted" : "provider_overloaded";
81
+ return { classification: reclassified, providerQuota };
82
+ }
83
+
52
84
  /**
53
85
  * Force-terminate lane worker process trees tracked in batch state.
54
86
  * Reaps nested `pi` grandchildren, not only the tracked runner PID (SP-609 / #194).
@@ -99,6 +131,7 @@ function sleep(ms) {
99
131
  * @param {string} [params.taskId]
100
132
  * @param {string} [params.laneCorrelationId]
101
133
  * @param {object} [params.config]
134
+ * @param {string} [params.workerModel] Effective worker model (SP-808).
102
135
  * @param {number} [params.stallDeadline]
103
136
  * @param {object} [params.signals]
104
137
  */
@@ -114,6 +147,7 @@ function buildWorkerFailureResult({
114
147
  taskId,
115
148
  laneCorrelationId,
116
149
  config,
150
+ workerModel,
117
151
  stallDeadline,
118
152
  signals,
119
153
  }) {
@@ -131,6 +165,8 @@ function buildWorkerFailureResult({
131
165
  signals,
132
166
  config,
133
167
  });
168
+ // SP-806 (#329): post-finalize reclassification (see helper doc).
169
+ const quotaOutcome = applyProviderQuotaClassification({ classification, rawOutput, workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId });
134
170
  return {
135
171
  ok: false,
136
172
  exitCode,
@@ -138,8 +174,9 @@ function buildWorkerFailureResult({
138
174
  output: finalized.output,
139
175
  workerOutputLogPath: finalized.logPath,
140
176
  workerOutputLogRef: finalized.logRef,
141
- classification,
177
+ classification: quotaOutcome.classification,
142
178
  doneFound,
179
+ ...(quotaOutcome.providerQuota ? { providerQuota: quotaOutcome.providerQuota } : {}),
143
180
  };
144
181
  }
145
182
 
@@ -183,10 +220,15 @@ export async function runWorker({
183
220
  return { ok: true, exitCode: 0, mode: "already-done" };
184
221
  }
185
222
 
186
- const useStub =
187
- process.env.SPINE_WORKER_STUB === "1" ||
188
- process.env.SPINE_WORKER_STUB === "true" ||
189
- (!commandExists("pi") && resolveWorkerBackend(config) !== "agentSession");
223
+ // SP-808 (#329): sticky quota fallback — read-only load; caller extraEnv wins.
224
+ const quotaCtx = resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv });
225
+
226
+ const stubExplicit =
227
+ process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
228
+ // #299 (SP-801): the stub is opt-in only. The old implicit fallback
229
+ // (missing `pi` → stub) could mark review-level-0 tasks done with no work
230
+ // when PATH lacked `pi`; the fail-closed guard below replaces it.
231
+ const useStub = stubExplicit;
190
232
 
191
233
  const workerBackend = useStub ? "subprocess" : resolveWorkerBackend(config);
192
234
  const workerMode = useStub ? "stub" : workerBackend === "agentSession" ? "agentSession" : "pi";
@@ -229,6 +271,32 @@ export async function runWorker({
229
271
  const isExecute = parsedPrompt?.type === "execute";
230
272
  const runCommand = contract.runCommand || contract.testCommand;
231
273
 
274
+ // #299 (SP-801): fail closed when the pi CLI is missing rather than silently
275
+ // falling back to the stub. Placed after the review gate so review-tool
276
+ // unavailability keeps its `review_failed` precedence, and scoped to
277
+ // non-execute tasks (execute-only runs the contract command, never `pi`);
278
+ // agentSession workers spawn in-process and never consult PATH for `pi`.
279
+ if (!stubExplicit && !isExecute && workerBackend !== "agentSession" && !commandExists("pi")) {
280
+ if (projectRoot && batchId) {
281
+ appendJournalEvent(projectRoot, batchId, "worker.spawn_failed", {
282
+ taskId,
283
+ laneNumber,
284
+ correlationId: laneCorrelationId,
285
+ reason: "pi_missing",
286
+ phase: "preflight",
287
+ });
288
+ }
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
+ };
298
+ }
299
+
232
300
  const child = isExecute
233
301
  ? spawnExecutionOnlyHandle({
234
302
  worktreePath,
@@ -256,7 +324,7 @@ export async function runWorker({
256
324
  fileScopePaths,
257
325
  config,
258
326
  workerBackendDeps,
259
- extraEnv,
327
+ extraEnv: quotaCtx.extraEnv,
260
328
  });
261
329
  const workerChild = /** @type {WorkerChildHandle} */ (child);
262
330
  let childPastPreflight = isExecute ? true : !useLaunchScript;
@@ -309,6 +377,7 @@ export async function runWorker({
309
377
  taskId,
310
378
  laneCorrelationId,
311
379
  config,
380
+ workerModel: quotaCtx.workerModel,
312
381
  }),
313
382
  });
314
383
 
@@ -361,6 +430,7 @@ export async function runWorker({
361
430
  taskId,
362
431
  laneCorrelationId,
363
432
  config,
433
+ workerModel: quotaCtx.workerModel,
364
434
  });
365
435
  }
366
436
  // SP-738 (#273): the runner exits 124 when the `pi` spawn hit its wall-clock
@@ -412,6 +482,9 @@ export async function runWorker({
412
482
  config,
413
483
  });
414
484
 
485
+ // SP-806 (#329): main post-spawn failure path — post-finalize
486
+ // reclassification (see helper doc); only plain `failed` exits can match.
487
+ const quotaOutcome = applyProviderQuotaClassification({ classification, rawOutput: output, workerModel: quotaCtx.workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId });
415
488
  return {
416
489
  ok,
417
490
  exitCode,
@@ -419,7 +492,8 @@ export async function runWorker({
419
492
  output: finalized.output,
420
493
  workerOutputLogPath: finalized.logPath,
421
494
  workerOutputLogRef: finalized.logRef,
422
- classification,
495
+ classification: quotaOutcome.classification,
423
496
  doneFound,
497
+ ...(quotaOutcome.providerQuota ? { providerQuota: quotaOutcome.providerQuota } : {}),
424
498
  };
425
499
  }
@@ -7,7 +7,7 @@ import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
9
 
10
- import micromatch from "micromatch";
10
+ import picomatch from "picomatch";
11
11
 
12
12
  import { writeJsonAtomic } from "../../fs/atomic-write.mjs";
13
13
 
@@ -97,7 +97,7 @@ export function getCursorRuleExclusionReason(discovery, relPath) {
97
97
  }
98
98
 
99
99
  for (const target of matchTargets) {
100
- if (micromatch.isMatch(target, discovery.excludePatterns)) {
100
+ if (picomatch(discovery.excludePatterns)(target)) {
101
101
  return "excludePattern";
102
102
  }
103
103
  }
@@ -1,9 +1,9 @@
1
1
  // @ts-nocheck
2
2
  /**
3
- * Micromatch helpers for PROMPT File Scope vs rule globs (SP-091).
3
+ * Glob helpers for PROMPT File Scope vs rule globs (SP-091).
4
4
  */
5
5
 
6
- import micromatch from "micromatch";
6
+ import picomatch from "picomatch";
7
7
 
8
8
  /** Synthetic extensions used when expanding directory or wildcard scope entries. */
9
9
  export const SYNTHETIC_PROBE_EXTENSIONS = Object.freeze([
@@ -120,11 +120,13 @@ export function ruleGlobsMatchFileScope(globs, fileScope) {
120
120
  return true;
121
121
  }
122
122
 
123
- if (scopeEntries.some((entry) => micromatch.isMatch(entry, glob))) {
123
+ const isMatch = picomatch(glob);
124
+
125
+ if (scopeEntries.some((entry) => isMatch(entry))) {
124
126
  return true;
125
127
  }
126
128
 
127
- if (probes.some((probe) => micromatch.isMatch(probe, glob))) {
129
+ if (probes.some((probe) => isMatch(probe))) {
128
130
  return true;
129
131
  }
130
132
  }
@@ -38,9 +38,23 @@ export const CONTRACT_DEFAULTS = Object.freeze({
38
38
  legacyTaskIdPrefixes: Object.freeze(["TP-"]),
39
39
  });
40
40
 
41
- /** @type {Readonly<{ cleanupWorktreesOnComplete: boolean }>} */
41
+ /**
42
+ * Conflicted paths outside a lane File Scope that keep prefer-orch auto-resolution
43
+ * (SP-798 / #304). A conflicted path outside File Scope is only auto-resolved when
44
+ * it matches one of these globs — and the discarded lane blob is journaled; every
45
+ * other out-of-scope conflict fails closed so lane-committed work is never silently
46
+ * discarded.
47
+ */
48
+ const OUT_OF_SCOPE_MERGE_ALLOW_LIST_DEFAULT = Object.freeze([
49
+ ".spine/rules-manifest.json",
50
+ "package-lock.json",
51
+ "**/package-lock.json",
52
+ ]);
53
+
54
+ /** @type {Readonly<{ cleanupWorktreesOnComplete: boolean; outOfScopeMergeAllowList: readonly string[] }>} */
42
55
  export const LANES_DEFAULTS = Object.freeze({
43
56
  cleanupWorktreesOnComplete: true,
57
+ outOfScopeMergeAllowList: OUT_OF_SCOPE_MERGE_ALLOW_LIST_DEFAULT,
44
58
  });
45
59
 
46
60
  /** @type {Readonly<{ isolatedWorktree: boolean; allowHumanOnBaseBranch: "warn" | "block" | "allow" }>} */