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
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Pure decision and state helpers for single-hop provider quota fallback
3
+ * (SP-807, partial #329).
4
+ *
5
+ * `decideQuotaFallback` encodes the #329 fallback rules as a truth table over
6
+ * the resolved config, the batch's `state.resilience.quotaFallback` state, the
7
+ * SP-804 classification, and the worker backend:
8
+ *
9
+ * - at most one hop per batch (sticky once applied — a second exhaustion can
10
+ * only re-route lanes still pinned to the old pool, never pick a new pool);
11
+ * - one auto-retry per task (`retriedTaskIds`), so no task ping-pongs;
12
+ * - transient overload, an unset fallback key, and the in-process
13
+ * `agentSession` backend never fall back;
14
+ * - same-pool and probe-reported-exhausted fallback targets are refused.
15
+ *
16
+ * Everything here is pure: no state reads/writes, no journal, no probes, no
17
+ * clocks (the caller passes `now` in). The engine wiring lands in SP-809.
18
+ * `agents.escalatePolicy` is deliberately not consulted (#329 alternatives:
19
+ * fallback is not escalation) and only a single fallback profile is supported.
20
+ */
21
+ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
22
+
23
+ /**
24
+ * @typedef {import("./provider-quota.mjs").ProviderQuotaError} ProviderQuotaError
25
+ */
26
+
27
+ /** @typedef {"apply"|"retry"|"stop"|"none"} QuotaFallbackAction */
28
+
29
+ /**
30
+ * Persisted fallback hop for a batch, stored by the engine at
31
+ * `state.resilience.quotaFallback`. Its presence alone means the hop already
32
+ * happened — no second hop is ever decided.
33
+ *
34
+ * @typedef {object} QuotaFallbackState
35
+ * @property {string|null} fromProfile Profile active when the hop was applied.
36
+ * @property {string} toProfile Fallback profile the batch moved to.
37
+ * @property {string|null} fromModel Worker model before the hop.
38
+ * @property {string} toModel Worker model after the hop.
39
+ * @property {string} exhaustedPool Pool whose exhaustion triggered the hop.
40
+ * @property {string|null} resetAtRaw Raw provider reset text for that pool, when it had one.
41
+ * @property {string} triggerTaskId Task whose failure triggered the hop.
42
+ * @property {string} at ISO timestamp of the hop.
43
+ * @property {string[]} retriedTaskIds Tasks already auto-retried onto the fallback pool.
44
+ */
45
+
46
+ /**
47
+ * Early-out result: the batch must keep running as configured.
48
+ *
49
+ * @typedef {object} QuotaFallbackNoneResult
50
+ * @property {"none"} action
51
+ * @property {"disabled"|"not_quota"|"backend_unsupported"} reason
52
+ */
53
+
54
+ /**
55
+ * Terminal result: the fallback chain is exhausted (or misconfigured); no hop
56
+ * and no retry. Carries every pool exhausted so far so the caller can report
57
+ * both reset times (#329 wants the operator to see each window).
58
+ *
59
+ * @typedef {object} QuotaFallbackStopResult
60
+ * @property {"stop"} action
61
+ * @property {"profile_missing"|"task_retry_spent"|"fallback_pool_exhausted"|"fallback_model_unresolved"|"same_pool"|"probe_exhausted"} reason
62
+ * @property {string[]} exhaustedPools Pools exhausted so far — recorded hop pool first (when present), current classification last.
63
+ * @property {(string|null)[]} resetAtRaw Reset text per pool, index-aligned with `exhaustedPools`.
64
+ */
65
+
66
+ /**
67
+ * Re-route result: a lane still pinned to the old pool hit the same
68
+ * exhaustion; retry it onto the already-applied fallback (no new hop).
69
+ *
70
+ * @typedef {object} QuotaFallbackRetryResult
71
+ * @property {"retry"} action
72
+ * @property {string} toProfile
73
+ * @property {string} toModel
74
+ */
75
+
76
+ /**
77
+ * Apply result: move the batch to the fallback profile (the single hop).
78
+ *
79
+ * @typedef {object} QuotaFallbackApplyResult
80
+ * @property {"apply"} action
81
+ * @property {string|null} fromProfile
82
+ * @property {string} toProfile
83
+ * @property {string|null} fromModel
84
+ * @property {string} toModel
85
+ * @property {string} exhaustedPool
86
+ * @property {string} toPool
87
+ */
88
+
89
+ /** @typedef {QuotaFallbackApplyResult|QuotaFallbackRetryResult|QuotaFallbackStopResult|QuotaFallbackNoneResult} QuotaFallbackDecision */
90
+
91
+ /**
92
+ * Structural slice of the resolved spine config this module reads. The config
93
+ * arrives untyped from config loading; this keeps checkJs honest without
94
+ * pulling in the full config schema.
95
+ *
96
+ * @typedef {{ agents?: { activeProfile?: unknown, worker?: { model?: unknown }, profiles?: Record<string, any>, quotaFallbackProfile?: unknown } }} QuotaFallbackConfig
97
+ */
98
+
99
+ /**
100
+ * Reads `agents.quotaFallbackProfile` from a resolved config. An unset,
101
+ * non-string, or blank value disables fallback entirely (SP-805 lets `""`
102
+ * clear the key).
103
+ *
104
+ * @param {QuotaFallbackConfig|undefined} config
105
+ * @returns {string|null} Profile name, or null when fallback is disabled.
106
+ */
107
+ function readFallbackProfileName(config) {
108
+ const raw = config?.agents?.quotaFallbackProfile;
109
+ if (typeof raw !== "string") return null;
110
+ const trimmed = raw.trim();
111
+ return trimmed === "" ? null : trimmed;
112
+ }
113
+
114
+ /**
115
+ * Looks up a profile by name using the same membership rule as the config
116
+ * schema (`Object.prototype.hasOwnProperty` on a plain object), so inherited
117
+ * or malformed entries cannot fabricate a fallback target.
118
+ *
119
+ * @param {QuotaFallbackConfig|undefined} config
120
+ * @param {string} name
121
+ * @returns {{ worker?: { model?: unknown } } | null}
122
+ */
123
+ function lookupProfile(config, name) {
124
+ const profiles = config?.agents?.profiles;
125
+ if (!profiles || typeof profiles !== "object") return null;
126
+ if (!Object.prototype.hasOwnProperty.call(profiles, name)) return null;
127
+ const profile = profiles[name];
128
+ return profile && typeof profile === "object" ? /** @type {{ worker?: { model?: unknown } }} */ (profile) : null;
129
+ }
130
+
131
+ /**
132
+ * Builds the parallel `exhaustedPools`/`resetAtRaw` report carried by every
133
+ * stop result: the pool/reset recorded in the fallback state (when a hop
134
+ * already happened), then the current classification's. Entries are appended
135
+ * verbatim — a same-pool repeat keeps both reset readings, the later one
136
+ * being the newer window — and stay index-aligned.
137
+ *
138
+ * @param {QuotaFallbackState|null} fallbackState
139
+ * @param {ProviderQuotaError} classification
140
+ * @returns {{exhaustedPools: string[], resetAtRaw: (string|null)[]}}
141
+ */
142
+ function buildExhaustedReport(fallbackState, classification) {
143
+ const exhaustedPools = [];
144
+ const resetAtRaw = [];
145
+ if (fallbackState) {
146
+ exhaustedPools.push(fallbackState.exhaustedPool);
147
+ resetAtRaw.push(typeof fallbackState.resetAtRaw === "string" ? fallbackState.resetAtRaw : null);
148
+ }
149
+ exhaustedPools.push(classification.poolId);
150
+ resetAtRaw.push(typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null);
151
+ return { exhaustedPools, resetAtRaw };
152
+ }
153
+
154
+ /**
155
+ * Decides what the engine should do about a provider quota exhaustion, as a
156
+ * pure function of its arguments. Precedence (first match wins):
157
+ *
158
+ * 1. `none/disabled` — `agents.quotaFallbackProfile` unset or blank.
159
+ * 2. `none/not_quota` — no classification, or not `quota_exhausted`
160
+ * (transient overload never falls back, even mid-fallback).
161
+ * 3. `none/backend_unsupported` — `agentSession` workers run in-process and
162
+ * ignore child env pins, so fallback cannot reach them.
163
+ * 4. `stop/profile_missing` — fallback profile absent from `agents.profiles`
164
+ * (defensive: the schema normally rejects this; fail closed on drift).
165
+ * 5. Fallback already applied (sticky, one hop per batch):
166
+ * `stop/task_retry_spent` when the task already used its auto-retry;
167
+ * `retry` when the classification hits the original pool (a lane still
168
+ * pinned there) — re-route it, no new hop; otherwise
169
+ * `stop/fallback_pool_exhausted` (the fallback pool died too).
170
+ * 6. `stop/fallback_model_unresolved` — fallback profile has no usable
171
+ * worker model (`missing`/`inherit`).
172
+ * 7. `stop/same_pool` — fallback model shares the exhausted pool.
173
+ * 8. `stop/probe_exhausted` — a live probe already reported the fallback
174
+ * pool exhausted.
175
+ * 9. `apply` — perform the single hop.
176
+ *
177
+ * @param {object} [params]
178
+ * @param {QuotaFallbackConfig} [params.config] Resolved spine config.
179
+ * @param {QuotaFallbackState|null} [params.fallbackState] `state.resilience.quotaFallback ?? null`.
180
+ * @param {ProviderQuotaError|null} [params.classification] SP-804 result.
181
+ * @param {string} [params.taskId] Task the classification came from.
182
+ * @param {string} [params.workerBackend] Resolved worker backend.
183
+ * @param {string[]} [params.probeExhaustedPools] Pools a live probe reported exhausted.
184
+ * @returns {QuotaFallbackDecision}
185
+ */
186
+ export function decideQuotaFallback({
187
+ config,
188
+ fallbackState = null,
189
+ classification = null,
190
+ taskId,
191
+ workerBackend,
192
+ probeExhaustedPools,
193
+ } = {}) {
194
+ // Row 1 — no fallback target configured.
195
+ const toProfileName = readFallbackProfileName(config);
196
+ if (toProfileName === null) {
197
+ return { action: "none", reason: "disabled" };
198
+ }
199
+
200
+ // Row 2 — transient overload and everything non-quota stays on the active profile.
201
+ if (!classification || classification.kind !== "quota_exhausted") {
202
+ return { action: "none", reason: "not_quota" };
203
+ }
204
+
205
+ // Row 3 — the in-process backend ignores child env, so a hop could not take effect.
206
+ if (workerBackend === "agentSession") {
207
+ return { action: "none", reason: "backend_unsupported" };
208
+ }
209
+
210
+ /** Stop results report every pool exhausted so far so callers can show both reset times. */
211
+ /**
212
+ * @param {QuotaFallbackStopResult["reason"]} reason
213
+ * @returns {QuotaFallbackStopResult}
214
+ */
215
+ const stop = (reason) => ({
216
+ action: "stop",
217
+ reason,
218
+ ...buildExhaustedReport(fallbackState, classification),
219
+ });
220
+
221
+ // Row 4 — fail closed on config drift instead of guessing a target.
222
+ const targetProfile = lookupProfile(config, toProfileName);
223
+ if (targetProfile === null) {
224
+ return stop("profile_missing");
225
+ }
226
+
227
+ // Row 5 — sticky: once the hop happened, no second hop is ever decided.
228
+ if (fallbackState) {
229
+ const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
230
+ if (taskId !== undefined && taskId !== null && retriedTaskIds.includes(taskId)) {
231
+ return stop("task_retry_spent");
232
+ }
233
+ if (classification.poolId === fallbackState.exhaustedPool) {
234
+ // A lane pinned to the old pool hit the same exhaustion: re-route it
235
+ // to the fallback that is already applied (recorded in the state, so
236
+ // later config edits cannot change the destination mid-batch).
237
+ return { action: "retry", toProfile: fallbackState.toProfile, toModel: fallbackState.toModel };
238
+ }
239
+ return stop("fallback_pool_exhausted");
240
+ }
241
+
242
+ // Row 6 — `inherit`/missing resolves to the "unknown" pool, which can never
243
+ // be a real destination, so it is refused before any pool comparison.
244
+ const toModel = typeof targetProfile.worker?.model === "string" ? targetProfile.worker.model : null;
245
+ if (toModel === null || toModel === "inherit") {
246
+ return stop("fallback_model_unresolved");
247
+ }
248
+
249
+ // Row 7 — a fallback inside the exhausted pool buys nothing.
250
+ const toPool = resolvePoolId(toModel);
251
+ if (toPool === classification.poolId) {
252
+ return stop("same_pool");
253
+ }
254
+
255
+ // Row 8 — trust the live probe over blind configuration.
256
+ const probes = Array.isArray(probeExhaustedPools) ? probeExhaustedPools : [];
257
+ if (probes.includes(toPool)) {
258
+ return stop("probe_exhausted");
259
+ }
260
+
261
+ // Row 9 — the single hop.
262
+ return {
263
+ action: "apply",
264
+ fromProfile: typeof config?.agents?.activeProfile === "string" ? config.agents.activeProfile : null,
265
+ toProfile: toProfileName,
266
+ fromModel: typeof config?.agents?.worker?.model === "string" ? config.agents.worker.model : null,
267
+ toModel,
268
+ exhaustedPool: classification.poolId,
269
+ toPool,
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Builds the persisted fallback state from an `apply` decision. Pure: the
275
+ * timestamp comes from the injected `now`, and the returned object shares no
276
+ * references with the decision or classification.
277
+ *
278
+ * @param {QuotaFallbackApplyResult} decision An `apply` result from {@link decideQuotaFallback}.
279
+ * @param {object} params
280
+ * @param {ProviderQuotaError} params.classification The classification that produced the decision.
281
+ * @param {string} params.taskId Task whose failure triggered the hop.
282
+ * @param {Date|number} params.now Injection point for the clock.
283
+ * @returns {QuotaFallbackState}
284
+ */
285
+ export function buildQuotaFallbackState(decision, { classification, taskId, now }) {
286
+ return {
287
+ fromProfile: decision.fromProfile,
288
+ toProfile: decision.toProfile,
289
+ fromModel: decision.fromModel,
290
+ toModel: decision.toModel,
291
+ exhaustedPool: decision.exhaustedPool,
292
+ resetAtRaw: typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null,
293
+ triggerTaskId: taskId,
294
+ at: new Date(now).toISOString(),
295
+ retriedTaskIds: [],
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Records that a task consumed its one auto-retry onto the fallback pool.
301
+ * Pure: returns a new state object and never mutates the input; appending an
302
+ * already-recorded task is a no-op duplicate-wise (idempotent).
303
+ *
304
+ * @param {QuotaFallbackState} fallbackState State to evolve (must be an object).
305
+ * @param {string} taskId Task that was retried.
306
+ * @returns {QuotaFallbackState}
307
+ * @throws {TypeError} When `fallbackState` is not an object, so a missing hop
308
+ * cannot silently produce an empty-looking state.
309
+ */
310
+ export function markQuotaFallbackRetry(fallbackState, taskId) {
311
+ if (!fallbackState || typeof fallbackState !== "object") {
312
+ throw new TypeError("markQuotaFallbackRetry requires a QuotaFallbackState object");
313
+ }
314
+ const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
315
+ if (retriedTaskIds.includes(taskId)) {
316
+ return { ...fallbackState, retriedTaskIds: [...retriedTaskIds] };
317
+ }
318
+ return { ...fallbackState, retriedTaskIds: [...retriedTaskIds, taskId] };
319
+ }
@@ -42,6 +42,26 @@ export function buildReconcileDiagnosisContext(params) {
42
42
 
43
43
  const pendingLaneLandTasks = findPendingLaneLandTasks(classifiedTasks);
44
44
 
45
+ // SP-810 (partial #329): surface the persisted quota-fallback hop and the
46
+ // latest quota-exhaustion journal payload so SBAR Background/Assessment can
47
+ // tell operators the real quota situation. Journal events are reused from
48
+ // signals.journalEvents (reconcileBatch already read them) — never a second
49
+ // journal read here. Payloads follow the SP-808 shapes: worker.quota_exhausted
50
+ // carries a single poolId/resetAtRaw; batch.quota_fallback_exhausted carries
51
+ // parallel exhaustedPools[]/resetAtRaw[] arrays.
52
+ const quotaFallbackRaw = signals.raw?.resilience?.quotaFallback;
53
+ const quotaFallback = quotaFallbackRaw && typeof quotaFallbackRaw === "object" ? quotaFallbackRaw : null;
54
+ const journalEvents = Array.isArray(signals.journalEvents) ? signals.journalEvents : [];
55
+ let lastQuotaExhausted = null;
56
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
57
+ const event = journalEvents[index];
58
+ if (event?.type !== "worker.quota_exhausted" && event?.type !== "batch.quota_fallback_exhausted") {
59
+ continue;
60
+ }
61
+ lastQuotaExhausted = event.payload && typeof event.payload === "object" ? event.payload : {};
62
+ break;
63
+ }
64
+
45
65
  return {
46
66
  batchId: batch.batchId,
47
67
  baseBranch: batch.baseBranch ?? git.baseBranch ?? "main",
@@ -49,6 +69,8 @@ export function buildReconcileDiagnosisContext(params) {
49
69
  phase: batch.phase,
50
70
  failedTasks: signals.failedTasks,
51
71
  failedTaskId,
72
+ quotaFallback,
73
+ lastQuotaExhausted,
52
74
  driftTaskStatus,
53
75
  exitReason,
54
76
  launchFailureKind: resolvedLaunchFailureKind,
@@ -5,13 +5,19 @@
5
5
  */
6
6
 
7
7
  import { reopenIntegrateGateForCompletedBatch } from "./gate.mjs";
8
- import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
8
+ import { updateSpineBatchState } from "./state.mjs";
9
9
 
10
10
  /**
11
11
  * When `resumeCheck.gateReopen` is set, re-open the integrate gate and return
12
12
  * a resumeBatch-shaped result. Caller must release the resume lock via the
13
13
  * returned path (this helper releases it).
14
14
  *
15
+ * The reopen decision and the state persist run in one `updateSpineBatchState`
16
+ * critical section (SP-793 / #301): the phase is re-read under the lock from the
17
+ * latest committed state instead of a stale pre-load, and the persist goes
18
+ * through the write guard with no owner bypass — a completed batch has no live
19
+ * engine owner, so a guard rejection here is a real signal, not an obstacle.
20
+ *
15
21
  * @param {{
16
22
  * projectRoot: string,
17
23
  * resumeCheck: { batchId: string, gateReopen?: boolean },
@@ -24,14 +30,24 @@ export function tryResumeCompletedGateReopen({ projectRoot, resumeCheck, release
24
30
  return null;
25
31
  }
26
32
 
27
- const reopenState = loadSpineBatchState(projectRoot).raw;
28
- const reopenResult = reopenIntegrateGateForCompletedBatch({
29
- projectRoot,
30
- batchId: resumeCheck.batchId,
31
- batchState: reopenState,
33
+ let reopenResult = null;
34
+ updateSpineBatchState(projectRoot, (draft) => {
35
+ reopenResult = reopenIntegrateGateForCompletedBatch({
36
+ projectRoot,
37
+ batchId: resumeCheck.batchId,
38
+ batchState: draft,
39
+ });
40
+ // The gate record is written by the reopen itself; persisting the draft
41
+ // keeps parity with the prior unconditional save (refreshes updatedAt).
42
+ return true;
32
43
  });
33
- if (reopenState) {
34
- saveSpineBatchState(projectRoot, reopenState, { bypassWriteGuard: true });
44
+ if (!reopenResult) {
45
+ // Missing or corrupt batch-state on disk: evaluate reopen without state
46
+ // so the CLI reports the same batch_not_completed result as before.
47
+ reopenResult = reopenIntegrateGateForCompletedBatch({
48
+ projectRoot,
49
+ batchId: resumeCheck.batchId,
50
+ });
35
51
  }
36
52
  releaseResumeLock?.();
37
53
  const output = reopenResult.reopened
@@ -17,6 +17,8 @@ import {
17
17
  markTaskCompleteFromDisk,
18
18
  runResumedTaskOnLane,
19
19
  } from "./resume-multi-lanes.mjs";
20
+ import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
21
+ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
20
22
 
21
23
  /**
22
24
  * Build lane queues and run all tasks in a resume wave.
@@ -113,17 +115,30 @@ export async function executeResumeWave({
113
115
 
114
116
  laneQueue.runs.push({
115
117
  taskId,
118
+ // SP-809 (#329): the resumed path gets the same single-hop quota
119
+ // fallback retry as the normal lane path.
116
120
  run: () =>
117
- runResumedTaskOnLane({
118
- projectRoot,
119
- state,
120
- batchId,
121
- config,
122
- task,
123
- lane,
124
- taskFolderRel,
125
- laneCorrelationId,
126
- }).then((result) => {
121
+ runWithQuotaFallback(
122
+ () =>
123
+ runResumedTaskOnLane({
124
+ projectRoot,
125
+ state,
126
+ batchId,
127
+ config,
128
+ task,
129
+ lane,
130
+ taskFolderRel,
131
+ laneCorrelationId,
132
+ }),
133
+ {
134
+ projectRoot,
135
+ batchId,
136
+ state,
137
+ taskId,
138
+ config,
139
+ workerBackend: resolveWorkerBackend(config),
140
+ },
141
+ ).then((result) => {
127
142
  if (result.aborted) batchAborted = true;
128
143
  return result;
129
144
  }),
@@ -74,7 +74,7 @@ export async function resumeMultiTaskBatch({ projectRoot, force = false, resumeC
74
74
  batchId,
75
75
  fromPhase: phase,
76
76
  });
77
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
77
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
78
78
  return finalizeResumedBatchForIntegrate({
79
79
  projectRoot,
80
80
  state,
@@ -452,7 +452,7 @@ export async function resumeBatch({ projectRoot, force = false }) {
452
452
  taskBranch,
453
453
  orchBranch,
454
454
  });
455
- const merge = mergeLaneToOrch({ projectRoot, baseBranch, orchBranch, taskBranch, batchId });
455
+ const merge = mergeLaneToOrch({ projectRoot, baseBranch, orchBranch, taskBranch, batchId, laneFileScopePaths: fileScopePaths });
456
456
  if (!merge.ok) {
457
457
  state.endedAt = Date.now();
458
458
  state.lastError = merge.error ?? "merge failed";
@@ -1,14 +1,11 @@
1
1
  // @ts-nocheck
2
- /**
3
- * Review artifact discovery, level parsing, and honor-signal helpers.
4
- * SP-579 extraction from review.mjs; spawn wiring stays in review.mjs (SP-597).
5
- */
6
-
2
+ /* Review artifact discovery, level parsing, honor signals. SP-579 extraction from review.mjs. */
7
3
  import fs from "node:fs";
8
4
  import path from "node:path";
9
5
  import { detectOrphanedReviewStarted } from "./journal-rebuild.mjs";
10
6
  import { NESTED_REVIEW_SPAWN_REASON } from "./review-spawn.mjs";
11
7
  import { normalizeVerdict, parseReviewLevel, parseReviewVerdict } from "./review-shared.mjs";
8
+ import { shouldUseReviewStub } from "./engine-lanes/review-stub.mjs";
12
9
 
13
10
  /**
14
11
  * @param {string} taskFolder
@@ -70,16 +67,82 @@ export function findLatestStepReviewArtifact(taskFolder, stepNumber) {
70
67
  return candidates[0] ?? null;
71
68
  }
72
69
 
70
+ /**
71
+ * Realpath with a lexical fallback for missing targets — the guard must still
72
+ * classify a vanished foreign artifact, not crash on it.
73
+ * @param {string} candidatePath
74
+ */
75
+ function resolveRealPath(candidatePath) {
76
+ try {
77
+ return fs.realpathSync(candidatePath);
78
+ } catch {
79
+ return path.resolve(candidatePath);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * True when candidatePath is inside folderPath. Both sides are realpath-resolved
85
+ * so symlinks and /var vs /private/var aliases cannot smuggle a foreign artifact.
86
+ * @param {string} candidatePath
87
+ * @param {string} folderPath
88
+ */
89
+ function isPathInsideFolder(candidatePath, folderPath) {
90
+ if (!folderPath) return true;
91
+ const candidate = resolveRealPath(candidatePath);
92
+ const folder = resolveRealPath(folderPath);
93
+ return candidate === folder || candidate.startsWith(`${folder}${path.sep}`);
94
+ }
95
+
96
+ /**
97
+ * Trust predicate for journaled `review.completed` honors (SP-813 / #328).
98
+ * A live batch never honors: (a) `payload.stub === true` without
99
+ * `payload.honored === true` — a foreign stub verdict leaked into the live
100
+ * journal; the spawn-timeout honor (`honorReason: "spawn_timeout_with_done"`)
101
+ * journals `honored: true` in real batches and stays honorable. (b) an
102
+ * absolute `payload.artifactPath` outside the task folder. Relative paths are
103
+ * worker-relative to the lane worktree and always accepted. `stubMode` comes
104
+ * from the engine caller via `shouldUseReviewStub(env)`; when omitted it
105
+ * defaults to the process env so callers that predate the guard
106
+ * (review-step-run.mjs) keep their stub-batch behavior.
107
+ * @param {Record<string, any>} event
108
+ * @param {object} params
109
+ * @param {string} params.taskFolder
110
+ * @param {string} [params.worktreePath] Accepted for caller symmetry; relative artifact paths are worker-relative and always trusted.
111
+ * @param {boolean} [params.stubMode]
112
+ * @returns {{ ok: true } | { ok: false, reason: "stub_verdict_in_live_batch" | "artifact_outside_task_folder" }}
113
+ */
114
+ export function isHonorableReviewEvent(event, { taskFolder, worktreePath: _worktreePath, stubMode } = {}) {
115
+ const payload = event?.payload && typeof event.payload === "object" ? event.payload : {};
116
+ const effectiveStubMode = stubMode ?? shouldUseReviewStub();
117
+ if (payload.stub === true && payload.honored !== true && !effectiveStubMode) {
118
+ return { ok: false, reason: "stub_verdict_in_live_batch" };
119
+ }
120
+ const artifactPath = typeof payload.artifactPath === "string" ? payload.artifactPath : "";
121
+ if (artifactPath && path.isAbsolute(artifactPath) && !isPathInsideFolder(artifactPath, taskFolder)) {
122
+ return { ok: false, reason: "artifact_outside_task_folder" };
123
+ }
124
+ return { ok: true };
125
+ }
126
+
73
127
  /**
74
128
  * Resolve an existing worker or lane code review from journal and/or artifacts.
75
- *
76
129
  * @param {object} params
77
130
  * @param {string} params.taskFolder
78
131
  * @param {object[]} [params.journalEvents]
79
132
  * @param {string} [params.taskId]
133
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
134
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
135
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
80
136
  * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
81
137
  */
82
- export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId }) {
138
+ export function findCompletedCodeReview({
139
+ taskFolder,
140
+ journalEvents = [],
141
+ taskId,
142
+ worktreePath,
143
+ stubMode,
144
+ onReject,
145
+ }) {
83
146
  /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
84
147
  let journalMatch = null;
85
148
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -90,6 +153,12 @@ export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId
90
153
  if (payload.reviewType !== "code") continue;
91
154
  const verdict = normalizeVerdict(payload.verdict, "code");
92
155
  if (!verdict) continue;
156
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
157
+ if (!honorGuard.ok) {
158
+ // Skip untrusted events as if absent; later candidates still honor.
159
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
160
+ continue;
161
+ }
93
162
  journalMatch = {
94
163
  verdict,
95
164
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -135,7 +204,6 @@ export const REVIEW_HONOR_JOURNAL_EVENTS = {
135
204
 
136
205
  /**
137
206
  * True when operator retry or reconcile re-enters review with a still-valid prior verdict.
138
- *
139
207
  * @param {object} params
140
208
  * @param {object[]} params.journalEvents
141
209
  * @param {string} params.taskId
@@ -186,7 +254,6 @@ export function isRetryReconcileFreshReview({
186
254
 
187
255
  /**
188
256
  * True when journal shows a review spawn crash/failure that warrants crash_recovered.
189
- *
190
257
  * @param {object} params
191
258
  * @param {object[]} params.journalEvents
192
259
  * @param {string} params.taskId
@@ -222,7 +289,6 @@ export function hasReviewSpawnFailureForHonor({ journalEvents = [], taskId, revi
222
289
 
223
290
  /**
224
291
  * Resolve explicit journal event for honoring a completed review artifact.
225
- *
226
292
  * @param {object} params
227
293
  * @param {object[]} params.journalEvents
228
294
  * @param {string} params.taskId
@@ -255,7 +321,6 @@ export function resolveReviewHonorJournalEvent({
255
321
 
256
322
  /**
257
323
  * Map honor journal event to task.verdict_recorded reviewPassKind.
258
- *
259
324
  * @param {"review.crash_recovered"|"review.skipped_fresh_artifact"|null} honorJournalEvent
260
325
  * @returns {"recovered"|"fresh_skip"|"normal"}
261
326
  */
@@ -271,7 +336,6 @@ export function resolveReviewPassKind(honorJournalEvent) {
271
336
 
272
337
  /**
273
338
  * True when review should emit review.resumed before spawning after operator retry.
274
- *
275
339
  * @param {object} params
276
340
  * @param {object[]} params.journalEvents
277
341
  * @param {string} params.taskId
@@ -291,7 +355,6 @@ export function shouldEmitReviewResumed({ journalEvents = [], taskId }) {
291
355
 
292
356
  /**
293
357
  * Latest review honor/resume signal for diagnose and dashboard surfaces.
294
- *
295
358
  * @param {object[]} journalEvents
296
359
  * @param {string|null} [activeTaskId]
297
360
  * @returns {{ taskId: string, reviewType: string, kind: string, honorSource?: string, reviewPassKind?: string }|null}
@@ -365,14 +428,23 @@ export function findLatestFinalReviewArtifact(taskFolder) {
365
428
  /**
366
429
  * Resolve an existing worker or lane final review from journal and/or artifacts.
367
430
  * Honors PASS from journal `review.completed` or latest final artifact.
368
- *
369
431
  * @param {object} params
370
432
  * @param {string} params.taskFolder
371
433
  * @param {object[]} [params.journalEvents]
372
434
  * @param {string} [params.taskId]
435
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
436
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
437
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
373
438
  * @returns {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
374
439
  */
375
- export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskId }) {
440
+ export function findCompletedFinalReview({
441
+ taskFolder,
442
+ journalEvents = [],
443
+ taskId,
444
+ worktreePath,
445
+ stubMode,
446
+ onReject,
447
+ }) {
376
448
  /** @type {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
377
449
  let journalMatch = null;
378
450
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -383,6 +455,12 @@ export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskI
383
455
  if (payload.reviewType !== "final") continue;
384
456
  const verdict = normalizeVerdict(payload.verdict, "final");
385
457
  if (!verdict) continue;
458
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
459
+ if (!honorGuard.ok) {
460
+ // Skip untrusted events as if absent; later candidates still honor.
461
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
462
+ continue;
463
+ }
386
464
  journalMatch = {
387
465
  verdict,
388
466
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",