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,202 @@
1
+ /**
2
+ * Persisted quota-fallback state helpers (SP-808, partial #329).
3
+ *
4
+ * SP-807 (`../quota-fallback.mjs`) decides and shapes the single-hop fallback;
5
+ * this module owns the side effects the engine lane paths need (SP-809 wires
6
+ * the calls):
7
+ *
8
+ * - `applyQuotaFallback` persists `state.resilience.quotaFallback` and
9
+ * journals `batch.quota_fallback_applied` exactly once per hop;
10
+ * - `recordQuotaFallbackRetry` appends the retried task and journals
11
+ * `task.quota_fallback_retry`;
12
+ * - `recordQuotaFallbackExhausted` journals `batch.quota_fallback_exhausted`
13
+ * with every exhausted pool and its reset text;
14
+ * - `quotaFallbackWorkerEnv` / `resolveEffectiveWorkerModel` /
15
+ * `loadQuotaFallbackForWorker` let `runWorker` re-apply the persisted hop to
16
+ * every later worker spawn (sticky override) and report the model actually
17
+ * used, all read-only.
18
+ *
19
+ * Persistence uses `saveEngineBatchState` — the same saver the engine lane
20
+ * paths use (`engine-lanes/matrix-run.mjs`) — so an operator pause already on
21
+ * disk or in the journal is never clobbered by the whole-file write.
22
+ */
23
+
24
+ import { appendJournalEvent } from "../journal.mjs";
25
+ import { saveEngineBatchState } from "../pause.mjs";
26
+ import { buildQuotaFallbackState, markQuotaFallbackRetry } from "../quota-fallback.mjs";
27
+ import { loadSpineBatchState } from "../state-io.mjs";
28
+
29
+ /** @typedef {import("../quota-fallback.mjs").QuotaFallbackState} QuotaFallbackState */
30
+ /** @typedef {import("../quota-fallback.mjs").QuotaFallbackApplyResult} QuotaFallbackApplyResult */
31
+ /** @typedef {import("../quota-fallback.mjs").QuotaFallbackStopResult} QuotaFallbackStopResult */
32
+ /** @typedef {import("../provider-quota.mjs").ProviderQuotaError} ProviderQuotaError */
33
+
34
+ /**
35
+ * Applies the single quota-fallback hop: builds the persisted state from the
36
+ * SP-807 `apply` decision, stores it at `state.resilience.quotaFallback`,
37
+ * persists the batch state, and journals `batch.quota_fallback_applied`. The
38
+ * hop is sticky — callers must invoke this at most once per batch (the SP-807
39
+ * decision layer refuses a second hop while a fallback state exists).
40
+ *
41
+ * @param {object} params
42
+ * @param {string} params.projectRoot
43
+ * @param {string} params.batchId
44
+ * @param {Record<string, any>} params.state Live batch state (mutated in place, then persisted).
45
+ * @param {QuotaFallbackApplyResult} params.decision An `apply` result from `decideQuotaFallback`.
46
+ * @param {ProviderQuotaError} params.classification Classification that produced the decision.
47
+ * @param {string} params.taskId Task whose failure triggered the hop.
48
+ * @param {Date|number} params.now Clock injection point.
49
+ * @returns {Promise<QuotaFallbackState>} The persisted fallback state.
50
+ */
51
+ export async function applyQuotaFallback({ projectRoot, batchId, state, decision, classification, taskId, now }) {
52
+ const fallbackState = buildQuotaFallbackState(decision, { classification, taskId, now });
53
+ if (!state.resilience || typeof state.resilience !== "object") {
54
+ state.resilience = {};
55
+ }
56
+ state.resilience.quotaFallback = fallbackState;
57
+ await saveEngineBatchState(projectRoot, state);
58
+ appendJournalEvent(projectRoot, batchId, "batch.quota_fallback_applied", {
59
+ fromProfile: fallbackState.fromProfile,
60
+ toProfile: fallbackState.toProfile,
61
+ fromModel: fallbackState.fromModel,
62
+ toModel: fallbackState.toModel,
63
+ exhaustedPool: fallbackState.exhaustedPool,
64
+ resetAtRaw: fallbackState.resetAtRaw,
65
+ taskIds: [taskId],
66
+ });
67
+ return fallbackState;
68
+ }
69
+
70
+ /**
71
+ * Records that a task consumed its one auto-retry onto the fallback pool:
72
+ * appends the taskId to the persisted state (SP-807 `markQuotaFallbackRetry`,
73
+ * idempotent), persists, and journals `task.quota_fallback_retry` with the
74
+ * fallback destination.
75
+ *
76
+ * @param {object} params
77
+ * @param {string} params.projectRoot
78
+ * @param {string} params.batchId
79
+ * @param {Record<string, any>} params.state Live batch state carrying `resilience.quotaFallback`.
80
+ * @param {string} params.taskId Task that was retried.
81
+ * @returns {Promise<QuotaFallbackState>} The evolved fallback state.
82
+ */
83
+ export async function recordQuotaFallbackRetry({ projectRoot, batchId, state, taskId }) {
84
+ if (!state.resilience || typeof state.resilience !== "object") {
85
+ state.resilience = {};
86
+ }
87
+ const fallbackState = markQuotaFallbackRetry(state.resilience.quotaFallback, taskId);
88
+ state.resilience.quotaFallback = fallbackState;
89
+ await saveEngineBatchState(projectRoot, state);
90
+ appendJournalEvent(projectRoot, batchId, "task.quota_fallback_retry", {
91
+ taskId,
92
+ toProfile: fallbackState.toProfile,
93
+ toModel: fallbackState.toModel,
94
+ });
95
+ return fallbackState;
96
+ }
97
+
98
+ /**
99
+ * Journals `batch.quota_fallback_exhausted` for a SP-807 `stop` decision. The
100
+ * payload carries every exhausted pool and its index-aligned raw reset text
101
+ * (#329: the operator must see both reset windows when the fallback pool dies
102
+ * too). Pure journal side effect — no state mutation.
103
+ *
104
+ * @param {object} params
105
+ * @param {string} params.projectRoot
106
+ * @param {string} params.batchId
107
+ * @param {QuotaFallbackStopResult} params.decision A `stop` result from `decideQuotaFallback`.
108
+ * @param {string} params.taskId Task whose failure produced the stop.
109
+ */
110
+ export function recordQuotaFallbackExhausted({ projectRoot, batchId, decision, taskId }) {
111
+ appendJournalEvent(projectRoot, batchId, "batch.quota_fallback_exhausted", {
112
+ taskId,
113
+ reason: decision.reason,
114
+ exhaustedPools: Array.isArray(decision.exhaustedPools) ? [...decision.exhaustedPools] : [],
115
+ resetAtRaw: Array.isArray(decision.resetAtRaw) ? [...decision.resetAtRaw] : [],
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Maps a persisted fallback state to the child-env override every later worker
121
+ * spawn must receive (SP-805 resolves `SPINE_AGENT_PROFILE_OVERRIDE` at config
122
+ * load). Returns `{}` when no hop is active so callers can merge blindly.
123
+ *
124
+ * @param {QuotaFallbackState|null|undefined} fallbackState
125
+ * @returns {Record<string, string>}
126
+ */
127
+ export function quotaFallbackWorkerEnv(fallbackState) {
128
+ const toProfile = typeof fallbackState?.toProfile === "string" ? fallbackState.toProfile.trim() : "";
129
+ if (!toProfile) return {};
130
+ return { SPINE_AGENT_PROFILE_OVERRIDE: toProfile };
131
+ }
132
+
133
+ /**
134
+ * Resolves the worker model that is actually in effect: when a fallback hop is
135
+ * active, the fallback profile's worker model; otherwise the configured worker
136
+ * model. Used for quota classification and for the journaled `model` field so
137
+ * both tell the truth after a hop. Returns `undefined` when neither source
138
+ * yields a string (matching the pre-SP-808 `typeof === "string"` contract).
139
+ *
140
+ * @param {object|undefined} config Resolved spine config.
141
+ * @param {QuotaFallbackState|null|undefined} fallbackState
142
+ * @returns {string|undefined}
143
+ */
144
+ export function resolveEffectiveWorkerModel(config, fallbackState) {
145
+ // The config arrives untyped; read the narrow slice this helper needs.
146
+ const cfg = /** @type {{ agents?: { profiles?: Record<string, any>, worker?: { model?: unknown } } }} */ (config ?? {});
147
+ const toProfile = typeof fallbackState?.toProfile === "string" ? fallbackState.toProfile.trim() : "";
148
+ if (toProfile) {
149
+ const profileModel = cfg.agents?.profiles?.[toProfile]?.worker?.model;
150
+ if (typeof profileModel === "string" && profileModel !== "") {
151
+ return profileModel;
152
+ }
153
+ }
154
+ const configured = cfg.agents?.worker?.model;
155
+ return typeof configured === "string" ? configured : undefined;
156
+ }
157
+
158
+ /**
159
+ * Read-only load of the persisted quota fallback for a worker spawn
160
+ * (`runWorker` must never write batch state). Returns the fallback state when
161
+ * the on-disk batch state belongs to `batchId` and carries one; `null` when
162
+ * the state file is missing, unreadable, stale (different batch), or has no
163
+ * active hop — in every case the caller behaves as if no override exists.
164
+ *
165
+ * @param {object} params
166
+ * @param {string} params.projectRoot
167
+ * @param {string} params.batchId
168
+ * @returns {QuotaFallbackState|null}
169
+ */
170
+ export function loadQuotaFallbackForWorker({ projectRoot, batchId }) {
171
+ if (!projectRoot || !batchId) return null;
172
+ const loaded = loadSpineBatchState(projectRoot);
173
+ const state = loaded.raw;
174
+ if (!state || typeof state !== "object") return null;
175
+ if (String(state.batchId ?? "") !== String(batchId)) return null;
176
+ const fallback = state.resilience?.quotaFallback;
177
+ return fallback && typeof fallback === "object" ? fallback : null;
178
+ }
179
+
180
+ /**
181
+ * One-call resolution of everything `runWorker` needs for the sticky
182
+ * override: the persisted fallback (read-only), the effective worker model
183
+ * (fallback profile model when a hop is active, else the configured worker
184
+ * model), and the child env with the profile override merged UNDER the
185
+ * caller's `extraEnv` (caller keys win — e.g. matrix row identity, #229).
186
+ * Kept here so `worker-host.mjs` stays under its 500-LOC module cap.
187
+ *
188
+ * @param {object} params
189
+ * @param {string} [params.projectRoot]
190
+ * @param {string} [params.batchId]
191
+ * @param {object|undefined} params.config Resolved spine config.
192
+ * @param {Record<string, string>} [params.extraEnv] Caller-supplied child env.
193
+ * @returns {{ fallback: QuotaFallbackState|null, workerModel: string|undefined, extraEnv: Record<string, string> }}
194
+ */
195
+ export function resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv }) {
196
+ const fallback = projectRoot && batchId ? loadQuotaFallbackForWorker({ projectRoot, batchId }) : null;
197
+ return {
198
+ fallback,
199
+ workerModel: resolveEffectiveWorkerModel(config, fallback),
200
+ extraEnv: { ...quotaFallbackWorkerEnv(fallback), ...(extraEnv ?? {}) },
201
+ };
202
+ }
@@ -218,6 +218,7 @@ export async function runCodeReviewPhase({
218
218
  laneCorrelationId,
219
219
  taskFolder: taskFolderInWorktree,
220
220
  journalEvents,
221
+ worktreePath: wt,
221
222
  });
222
223
  if (honoredResult) return honoredResult;
223
224
 
@@ -260,6 +260,77 @@ export async function runFinalReviewPhase({
260
260
  const stubVerdicts = shouldUseReviewStub() ? createPhaseStubVerdictQueue("final") : null;
261
261
 
262
262
  const journalEvents = readJournalEvents(projectRoot, batchId);
263
+
264
+ // SP-813 / #328: contract verification must run before the honor fast path
265
+ // so a task can never complete through an honored final-review verdict
266
+ // without `contract.verified` in the journal. The result computed here is
267
+ // consumed by the first poll-loop iteration (contractVerifiedPending) so
268
+ // the contract is verified exactly once per phase entry; rework iterations
269
+ // re-verify as before. Respects shouldRunContractVerifyForWorker, so stub
270
+ // batches (and contracts without verifiable fields) keep skipping.
271
+ let contractVerifyResult =
272
+ /** @type {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number } | null} */ (
273
+ null
274
+ );
275
+ let contractVerifiedPending = false;
276
+ const runContractVerifyGate = async () => {
277
+ contractVerifyResult = null;
278
+ contractVerifiedPending = true;
279
+ const promptMarkdown = fs.readFileSync(path.join(taskFolderInWorktree, "PROMPT.md"), "utf-8");
280
+ const parsedContract = parseContract(promptMarkdown);
281
+ if (shouldRunContractVerifyForWorker(promptMarkdown, parsedContract, config)) {
282
+ const events = readJournalEvents(projectRoot, batchId);
283
+ const sinceCommit = resolveTaskStartCommit({
284
+ journal: events,
285
+ taskId,
286
+ laneId: lane.laneId,
287
+ batchId,
288
+ worktreePath: wt,
289
+ });
290
+ const result = await verifyContract(wt, parsedContract, {
291
+ ...config,
292
+ baseBranch,
293
+ sinceCommit: sinceCommit ?? undefined,
294
+ projectRoot,
295
+ batchId,
296
+ taskId,
297
+ taskFolder: taskFolderInWorktree,
298
+ });
299
+ contractVerifyResult = result;
300
+ task.contractOk = result.ok;
301
+ saveSpineBatchState(projectRoot, state);
302
+ appendJournalEvent(projectRoot, batchId, "contract.verified", {
303
+ taskId,
304
+ laneNumber,
305
+ laneId: lane.laneId,
306
+ correlationId: laneCorrelationId,
307
+ ok: result.ok,
308
+ checks: result.checks,
309
+ });
310
+ if (!result.ok) {
311
+ removeDoneFile(taskFolderInWorktree);
312
+ recordContractVerifyTaskFailure({
313
+ projectRoot,
314
+ state,
315
+ batchId,
316
+ task,
317
+ lane,
318
+ laneCorrelationId,
319
+ contractVerifyResult: result,
320
+ config,
321
+ taskFolder: taskFolderInWorktree,
322
+ });
323
+ return { contractFailed: true };
324
+ }
325
+ }
326
+ return { contractFailed: false };
327
+ };
328
+
329
+ const preHonorContractGate = await runContractVerifyGate();
330
+ if (preHonorContractGate.contractFailed) {
331
+ return { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" };
332
+ }
333
+
263
334
  const honoredResult = honorCompletedReview({
264
335
  reviewType: "final",
265
336
  passVerdict: "PASS",
@@ -274,6 +345,7 @@ export async function runFinalReviewPhase({
274
345
  laneCorrelationId,
275
346
  taskFolder: taskFolderInWorktree,
276
347
  journalEvents,
348
+ worktreePath: wt,
277
349
  });
278
350
  if (honoredResult) return honoredResult;
279
351
 
@@ -289,52 +361,17 @@ export async function runFinalReviewPhase({
289
361
  invalidVerdictOutput: "final review artifact missing PASS, REVISE, or REPLAN verdict",
290
362
  allowReplan: true,
291
363
  beforeReview: async () => {
292
- let contractVerifyResult = null;
293
- const promptMarkdown = fs.readFileSync(path.join(taskFolderInWorktree, "PROMPT.md"), "utf-8");
294
- const parsedContract = parseContract(promptMarkdown);
295
- if (shouldRunContractVerifyForWorker(promptMarkdown, parsedContract, config)) {
296
- const events = readJournalEvents(projectRoot, batchId);
297
- const sinceCommit = resolveTaskStartCommit({
298
- journal: events,
299
- taskId,
300
- laneId: lane.laneId,
301
- batchId,
302
- worktreePath: wt,
303
- });
304
- contractVerifyResult = verifyContract(wt, parsedContract, {
305
- ...config,
306
- baseBranch,
307
- sinceCommit: sinceCommit ?? undefined,
308
- projectRoot,
309
- batchId,
310
- taskId,
311
- taskFolder: taskFolderInWorktree,
312
- });
313
- task.contractOk = contractVerifyResult.ok;
314
- saveSpineBatchState(projectRoot, state);
315
- appendJournalEvent(projectRoot, batchId, "contract.verified", {
316
- taskId,
317
- laneNumber,
318
- laneId: lane.laneId,
319
- correlationId: laneCorrelationId,
320
- ok: contractVerifyResult.ok,
321
- checks: contractVerifyResult.checks,
322
- });
323
- if (!contractVerifyResult.ok) {
324
- removeDoneFile(taskFolderInWorktree);
325
- recordContractVerifyTaskFailure({
326
- projectRoot,
327
- state,
328
- batchId,
329
- task,
330
- lane,
331
- laneCorrelationId,
332
- contractVerifyResult,
333
- config,
334
- taskFolder: taskFolderInWorktree,
335
- });
336
- return { abort: { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" } };
337
- }
364
+ if (contractVerifiedPending) {
365
+ // Consume the phase-entry verification so the first poll iteration
366
+ // does not double-verify; later rework iterations run the full gate.
367
+ contractVerifiedPending = false;
368
+ return { extraReviewParams: { contractVerifyResult } };
369
+ }
370
+ const gate = await runContractVerifyGate();
371
+ if (gate.contractFailed) {
372
+ return {
373
+ abort: { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" },
374
+ };
338
375
  }
339
376
  return { extraReviewParams: { contractVerifyResult } };
340
377
  },
@@ -23,6 +23,7 @@ import {
23
23
  readReviewLevel,
24
24
  runStepReview,
25
25
  } from "../review.mjs";
26
+ import { isHonorableReviewEvent } from "../review-artifacts.mjs";
26
27
  import { honorCompletedReview, runReviewPollLoop } from "./review-poll.mjs";
27
28
  import {
28
29
  createPhaseStubVerdictQueue,
@@ -52,15 +53,26 @@ function findPlanReviewStepNumber(taskFolder) {
52
53
 
53
54
  /**
54
55
  * Resolve an existing worker or lane plan review from journal and/or artifacts.
55
- * Mirrors findCompletedCodeReview with reviewType "plan" (SP-695).
56
+ * Mirrors findCompletedCodeReview with reviewType "plan" (SP-695), including
57
+ * the honor guard for untrusted journal verdicts (SP-813 / #328).
56
58
  *
57
59
  * @param {object} params
58
60
  * @param {string} params.taskFolder
59
61
  * @param {Array<Record<string, any>>} [params.journalEvents]
60
62
  * @param {string} [params.taskId]
63
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
64
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
65
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
61
66
  * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
62
67
  */
63
- function findCompletedPlanReview({ taskFolder, journalEvents = [], taskId }) {
68
+ function findCompletedPlanReview({
69
+ taskFolder,
70
+ journalEvents = [],
71
+ taskId,
72
+ worktreePath,
73
+ stubMode,
74
+ onReject,
75
+ }) {
64
76
  /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
65
77
  let journalMatch = null;
66
78
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -71,6 +83,13 @@ function findCompletedPlanReview({ taskFolder, journalEvents = [], taskId }) {
71
83
  if (payload.reviewType !== "plan") continue;
72
84
  const verdict = normalizeCodeVerdict(payload.verdict);
73
85
  if (!verdict) continue;
86
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
87
+ if (!honorGuard.ok) {
88
+ // Untrusted event: skip it exactly as if it were absent so the scan
89
+ // still honors a later trustworthy event or the artifact fallback.
90
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
91
+ continue;
92
+ }
74
93
  journalMatch = {
75
94
  verdict,
76
95
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -313,6 +332,7 @@ export async function runPlanReviewPhase({
313
332
  laneCorrelationId,
314
333
  taskFolder: taskFolderInWorktree,
315
334
  journalEvents,
335
+ worktreePath: wt,
316
336
  });
317
337
  if (honoredResult) return honoredResult;
318
338
 
@@ -22,6 +22,7 @@ import {
22
22
  resolveReviewPassKind,
23
23
  shouldEmitReviewResumed,
24
24
  } from "../review.mjs";
25
+ import { shouldUseReviewStub } from "./review-stub.mjs";
25
26
 
26
27
  /**
27
28
  * @param {string} taskFolder
@@ -112,6 +113,7 @@ export function appendReviewHonorJournalEvents({
112
113
  * @param {string} params.laneCorrelationId
113
114
  * @param {string} params.taskFolder
114
115
  * @param {Array<Record<string, any>>} params.journalEvents
116
+ * @param {string} [params.worktreePath] Lane worktree; resolves relative journal artifact paths for the honor guard.
115
117
  * @returns {{ ok: boolean, [key: string]: any } | null}
116
118
  */
117
119
  export function honorCompletedReview({
@@ -128,11 +130,55 @@ export function honorCompletedReview({
128
130
  laneCorrelationId,
129
131
  taskFolder,
130
132
  journalEvents,
133
+ worktreePath,
131
134
  }) {
132
135
  const taskId = task.taskId;
133
136
  const laneNumber = lane.laneNumber;
134
137
  const reviewAttempt = task[attemptField] ?? 0;
135
- const honored = findCompletedReview({ taskFolder, journalEvents, taskId });
138
+ // #328: only honor verdicts the batch can trust. stubMode is computed once
139
+ // here (the caller of the finders) and passed down, covering both
140
+ // SPINE_WORKER_STUB and SPINE_REVIEW_STUB engine-stub modes.
141
+ const stubMode = shouldUseReviewStub();
142
+ const rejectedSourceIds = new Set(
143
+ journalEvents
144
+ .filter(
145
+ (event) =>
146
+ event.type === "review.honor_rejected" &&
147
+ (event.taskId === undefined || event.taskId === taskId),
148
+ )
149
+ .map((event) => event.payload?.sourceEventId)
150
+ .filter((id) => typeof id === "string" && id),
151
+ );
152
+ const honored = findCompletedReview({
153
+ taskFolder,
154
+ journalEvents,
155
+ taskId,
156
+ worktreePath,
157
+ stubMode,
158
+ onReject: (
159
+ /** @type {Record<string, any>} */ event,
160
+ /** @type {string} */ reason,
161
+ ) => {
162
+ const payload =
163
+ event.payload && typeof event.payload === "object" ? event.payload : {};
164
+ const sourceEventId =
165
+ typeof event.eventId === "string" && event.eventId ? event.eventId : event.timestamp;
166
+ // Dedupe by source event id so a rejected event journals once, not on
167
+ // every phase entry that rescans the journal.
168
+ if (rejectedSourceIds.has(sourceEventId)) return;
169
+ rejectedSourceIds.add(sourceEventId);
170
+ appendJournalEvent(projectRoot, batchId, "review.honor_rejected", {
171
+ taskId,
172
+ laneNumber,
173
+ laneId: lane.laneId,
174
+ correlationId: laneCorrelationId,
175
+ reviewType,
176
+ reason,
177
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
178
+ sourceEventId,
179
+ });
180
+ },
181
+ });
136
182
  if (honored?.verdict !== passVerdict) return null;
137
183
 
138
184
  const honorJournalEvent = resolveReviewHonorJournalEvent({
@@ -31,12 +31,10 @@ import { runWorker } from "./worker-host.mjs";
31
31
  import { runCodeReviewPhase, runFinalReviewPhase, runPlanReviewPhase } from "./engine-lanes/review.mjs";
32
32
  import { ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
33
33
  import { resolveWorktreeSetupIgnorePaths } from "../config/spine-config-load.mjs";
34
- import {
35
- acquireLaneSlot,
36
- loadMatrixTaskRows,
37
- releaseLaneSlot,
38
- } from "./engine-lanes/matrix.mjs";
34
+ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
35
+ import { acquireLaneSlot, loadMatrixTaskRows, releaseLaneSlot } from "./engine-lanes/matrix.mjs";
39
36
  import { runMatrixTaskOnLane } from "./engine-lanes/matrix-run.mjs";
37
+ import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
40
38
 
41
39
  export {
42
40
  buildTasksAndLanesFromPlan,
@@ -160,7 +158,8 @@ export async function runTaskOnLane({
160
158
 
161
159
  const laneSlot = await acquireLaneSlot(state, config?.lanes?.maxParallel ?? 1);
162
160
  try {
163
- return await runNonMatrixTaskOnLane({
161
+ // SP-809 (#329): single-hop quota fallback retry wraps the lane run.
162
+ return await runWithQuotaFallback(() => runNonMatrixTaskOnLane({
164
163
  projectRoot,
165
164
  state,
166
165
  batchId,
@@ -171,7 +170,7 @@ export async function runTaskOnLane({
171
170
  taskFolderRel,
172
171
  laneCorrelationId,
173
172
  fileScopePaths,
174
- });
173
+ }), { projectRoot, batchId, state, taskId: task.taskId, config, workerBackend: resolveWorkerBackend(config) });
175
174
  } finally {
176
175
  releaseLaneSlot(state, laneSlot);
177
176
  }
@@ -226,7 +225,7 @@ async function runNonMatrixTaskOnLane({
226
225
  if (!task.startedAt) task.startedAt = Date.now();
227
226
  updateSegmentForTask(state, taskId, "failed");
228
227
  recomputeTaskCounters(state);
229
- saveEngineBatchState(projectRoot, state);
228
+ await saveEngineBatchState(projectRoot, state);
230
229
  appendJournalEvent(projectRoot, batchId, "lane.orch_sync_failed", {
231
230
  taskId,
232
231
  laneNumber,
@@ -276,7 +275,7 @@ async function runNonMatrixTaskOnLane({
276
275
  task.status = "running";
277
276
  if (!task.startedAt) task.startedAt = Date.now();
278
277
  updateSegmentForTask(state, taskId, "running");
279
- saveEngineBatchState(projectRoot, state);
278
+ await saveEngineBatchState(projectRoot, state);
280
279
  appendJournalEvent(projectRoot, batchId, "task.started", {
281
280
  taskId,
282
281
  laneNumber,
@@ -295,14 +294,16 @@ async function runNonMatrixTaskOnLane({
295
294
  laneCorrelationId,
296
295
  fileScopePaths,
297
296
  config,
298
- onHeartbeat: (timestamp) => {
297
+ // Fire-and-forget saves (SP-797 / #302): the host never awaits these callbacks.
298
+ // Safe — the save serializes live state at lock-acquire time, never a stale snapshot.
299
+ onHeartbeat: async (timestamp) => {
299
300
  lane.lastHeartbeatAt = timestamp;
300
- saveEngineBatchState(projectRoot, state);
301
+ await saveEngineBatchState(projectRoot, state);
301
302
  },
302
- onWorkerPid: (pid) => {
303
+ onWorkerPid: async (pid) => {
303
304
  if (pid > 0) {
304
305
  lane.workerPid = pid;
305
- saveEngineBatchState(projectRoot, state);
306
+ await saveEngineBatchState(projectRoot, state);
306
307
  }
307
308
  },
308
309
  }));
@@ -323,7 +324,7 @@ async function runNonMatrixTaskOnLane({
323
324
  });
324
325
  if (lane.workerPid) {
325
326
  delete lane.workerPid;
326
- saveEngineBatchState(projectRoot, state);
327
+ await saveEngineBatchState(projectRoot, state);
327
328
  }
328
329
  } else {
329
330
  const aborted = workerResult.classification === "aborted";
@@ -339,7 +340,7 @@ async function runNonMatrixTaskOnLane({
339
340
  task.exitReason = workerResult.classification ?? "worker_failed";
340
341
  updateSegmentForTask(state, taskId, aborted ? "aborted" : "failed");
341
342
  recomputeTaskCounters(state);
342
- saveEngineBatchState(projectRoot, state);
343
+ await saveEngineBatchState(projectRoot, state);
343
344
  if (!aborted) {
344
345
  const salvageFields = recordTaskFailureSalvage({
345
346
  projectRoot,
@@ -378,7 +379,7 @@ async function runNonMatrixTaskOnLane({
378
379
 
379
380
  if (lane.workerPid) {
380
381
  delete lane.workerPid;
381
- saveEngineBatchState(projectRoot, state);
382
+ await saveEngineBatchState(projectRoot, state);
382
383
  }
383
384
 
384
385
  appendJournalEvent(projectRoot, batchId, "lane.completed", {
@@ -193,7 +193,7 @@ export async function startBatch({
193
193
  });
194
194
 
195
195
  recordBatchBaseSnapshotOnStart(projectRoot, state);
196
- saveEngineBatchState(projectRoot, state);
196
+ await saveEngineBatchState(projectRoot, state);
197
197
  persistBatchMetaFromStartState(projectRoot, state, /** @type {string} */ (tasksRoot));
198
198
 
199
199
  try {
@@ -201,7 +201,7 @@ export async function startBatch({
201
201
  transitionPhase(state, "running", { projectRoot, batchId });
202
202
  recordBatchEnginePid(state, process.pid);
203
203
  installAttachedEngineShutdownHandlers({ projectRoot });
204
- saveEngineBatchState(projectRoot, state);
204
+ await saveEngineBatchState(projectRoot, state);
205
205
 
206
206
  for (const lane of state.lanes) {
207
207
  lane.correlationId = crypto.randomUUID();
@@ -258,21 +258,21 @@ export async function startBatch({
258
258
  correlationId: lane.correlationId,
259
259
  });
260
260
  }
261
- saveEngineBatchState(projectRoot, state);
261
+ await saveEngineBatchState(projectRoot, state);
262
262
 
263
263
  let batchAborted = false;
264
264
 
265
265
  for (const wave of effectivePlan.waves) {
266
- const pauseAtWave = adoptPauseIfRequested({ projectRoot, state, batchId });
266
+ const pauseAtWave = await adoptPauseIfRequested({ projectRoot, state, batchId });
267
267
  if (pauseAtWave.stop) {
268
268
  return buildEnginePausedResult(batchId);
269
269
  }
270
270
 
271
271
  state.currentWaveIndex = wave.index;
272
- saveEngineBatchState(projectRoot, state);
272
+ await saveEngineBatchState(projectRoot, state);
273
273
 
274
274
  for (const tick of wave.ticks ?? []) {
275
- const pauseAtTick = adoptPauseIfRequested({ projectRoot, state, batchId });
275
+ const pauseAtTick = await adoptPauseIfRequested({ projectRoot, state, batchId });
276
276
  if (pauseAtTick.stop) {
277
277
  return buildEnginePausedResult(batchId);
278
278
  }
@@ -359,7 +359,7 @@ export async function startBatch({
359
359
  await Promise.all(laneExecutions);
360
360
  if (batchAborted) break;
361
361
 
362
- const pauseAfterTick = adoptPauseIfRequested({ projectRoot, state, batchId });
362
+ const pauseAfterTick = await adoptPauseIfRequested({ projectRoot, state, batchId });
363
363
  if (pauseAfterTick.stop) {
364
364
  return buildEnginePausedResult(batchId);
365
365
  }
@@ -374,7 +374,7 @@ export async function startBatch({
374
374
  batchId,
375
375
  extra: { taskId: abortedTask?.taskId },
376
376
  });
377
- saveEngineBatchState(projectRoot, state);
377
+ await saveEngineBatchState(projectRoot, state);
378
378
  return {
379
379
  ok: false,
380
380
  exitCode: 1,
@@ -398,7 +398,7 @@ export async function startBatch({
398
398
  reason: "mixed_outcome",
399
399
  },
400
400
  });
401
- saveEngineBatchState(projectRoot, state);
401
+ await saveEngineBatchState(projectRoot, state);
402
402
  appendJournalEvent(projectRoot, batchId, "batch.merge_blocked", {
403
403
  waveIndex: wave.index,
404
404
  failedTaskIds: mergeEligibility.failedTaskIds,
@@ -481,7 +481,7 @@ export async function startBatch({
481
481
  batchId,
482
482
  extra: { error: message },
483
483
  });
484
- saveEngineBatchState(projectRoot, state);
484
+ await saveEngineBatchState(projectRoot, state);
485
485
  removeAllMatrixSubLaneWorktrees(projectRoot, batchId);
486
486
  removeLaneWorktrees(projectRoot, batchId, maxLaneNumber);
487
487
  return { ok: false, exitCode: 1, batchId, error: message };