@juicesharp/rpiv-workflow 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/runner/resume.ts CHANGED
@@ -126,24 +126,12 @@ export async function reconstructState(
126
126
  };
127
127
 
128
128
  for (const row of rows) {
129
- if (row.parent !== undefined) {
129
+ if (isUnitRow(row)) {
130
130
  const refusal = await foldUnitRow(acc, workflow, row);
131
131
  if (refusal) return refusal;
132
132
  continue;
133
133
  }
134
- // A non-completed, parent-unset row for the SAME stage as the open FANOUT
135
- // generation is that generation's own halt marker: a mid-flight abort
136
- // writes a stage-level `aborted` row (recordAbortedAtSeam) AFTER the
137
- // completed unit rows. Closing the generation on it would discard the
138
- // reconstructed cursor whose completed-unit slots are already filled,
139
- // forcing resume to cold-re-enter the loop and re-dispatch EVERY unit
140
- // (finding 7: the aborted-mid-flight fanout re-ran completed units,
141
- // duplicating the channel and collapsing the downstream fan-in). Keep the
142
- // generation open — `trailing` then carries the filled slots and
143
- // `pendingFanoutIndices` dispatches only the genuinely-pending units. A
144
- // COMPLETED parent row still closes+advances; a stage with no completed
145
- // units never opened a generation, so it falls through and re-runs whole.
146
- if (acc.gen?.parent === row.stage && acc.gen.loop.kind === "fanout" && row.status !== "completed") {
134
+ if (isOpenFanoutHaltMarker(acc, row)) {
147
135
  acc.visited.add(row.stage);
148
136
  acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
149
137
  continue;
@@ -153,7 +141,7 @@ export async function reconstructState(
153
141
  // Unknown key refuses — including LEGACY decorated rows (older
154
142
  // runs carry no `parent`, so their unit rows land here): stage-gone.
155
143
  if (!def) return { ok: false, reason: "stage-gone", detail: row.stage };
156
- noteChainNode(acc, row.stage, row.status !== "completed");
144
+ noteChainNode(acc, row.stage, !isCompletedRow(row));
157
145
  foldKnownStage(acc, def, row);
158
146
  }
159
147
 
@@ -215,6 +203,56 @@ interface FoldAcc {
215
203
  drift: { parent: string; errMsg: string } | undefined;
216
204
  }
217
205
 
206
+ // --- Fold predicates — single canonical spellings of the row-kind tests ---
207
+
208
+ /** Unit rows carry a `parent` (the structured machine channel) — the top-of-loop routing split. */
209
+ const isUnitRow = (row: WorkflowStage): boolean => row.parent !== undefined;
210
+
211
+ /** The ONE canonical "this row's stage ran to completion" test — every fold site routes through here. */
212
+ const isCompletedRow = (row: WorkflowStage): boolean => row.status === "completed";
213
+
214
+ /** A collected soft-halt (`status:"failed"` + `collected:true` + defined `errMsg`) — rebuilds the failedOutput sentinel and places it via `foldFanoutCompletion` ONLY. */
215
+ const isCollectedSoftHalt = (row: WorkflowStage): boolean => row.collected === true && row.errMsg !== undefined;
216
+
217
+ /** A panel/verify verdict row — the judge/verify arm guard. */
218
+ const isVerdictRow = (row: WorkflowStage): boolean => row.role === "judge" || row.role === "verify";
219
+
220
+ /**
221
+ * A non-completed, parent-unset row for the SAME stage as the open FANOUT
222
+ * generation is that generation's own halt marker: a mid-flight abort
223
+ * writes a stage-level `aborted` row (recordAbortedAtSeam) AFTER the
224
+ * completed unit rows. Closing the generation on it would discard the
225
+ * reconstructed cursor whose completed-unit slots are already filled,
226
+ * forcing resume to cold-re-enter the loop and re-dispatch EVERY unit
227
+ * (finding 7: the aborted-mid-flight fanout re-ran completed units,
228
+ * duplicating the channel and collapsing the downstream fan-in). Keep the
229
+ * generation open — `trailing` then carries the filled slots and
230
+ * `pendingFanoutIndices` dispatches only the genuinely-pending units. A
231
+ * COMPLETED parent row still closes+advances; a stage with no completed
232
+ * units never opened a generation, so it falls through and re-runs whole.
233
+ */
234
+ const isOpenFanoutHaltMarker = (acc: FoldAcc, row: WorkflowStage): boolean =>
235
+ acc.gen?.parent === row.stage && acc.gen.loop.kind === "fanout" && !isCompletedRow(row);
236
+
237
+ /**
238
+ * Rebuild the `failedOutput` sentinel from a collected soft-halt row's
239
+ * `errMsg` — byte-identical to the live `outputMetaFor` sentinel (decorated
240
+ * `row.stage`, `row.skill`, `row.stageNumber`). The live `softHaltUnit` runs
241
+ * no `applyStageSuccess`; the fold owns the single channel write.
242
+ */
243
+ function rebuildCollectedSentinel(row: WorkflowStage, runId: string): Output {
244
+ return failedOutput(
245
+ outputMeta({
246
+ stage: row.stage,
247
+ skill: row.skill,
248
+ stageNumber: row.stageNumber,
249
+ ts: row.ts,
250
+ runId,
251
+ }),
252
+ row.errMsg!, // defined: the single caller gates on isCollectedSoftHalt(row)
253
+ );
254
+ }
255
+
218
256
  /** Advance the chain index for one activation — unless the row continues the previous one. */
219
257
  function noteChainNode(acc: FoldAcc, stage: string, reentrant: boolean): void {
220
258
  if (!(acc.prevNode?.stage === stage && acc.prevNode.reentrant)) acc.chainIndex++;
@@ -229,7 +267,7 @@ function noteChainNode(acc: FoldAcc, stage: string, reentrant: boolean): void {
229
267
  function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): void {
230
268
  acc.visited.add(row.stage);
231
269
  acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
232
- if (row.status !== "completed") return;
270
+ if (!isCompletedRow(row)) return;
233
271
  applyStageSuccess(acc.state, def, row.stage, row.output);
234
272
  // Roll the predecessor session forward through the SAME authority the live
235
273
  // `recordStageSuccess` single-stage branch uses (`rollLastSession`) — so a
@@ -246,139 +284,166 @@ function closeGeneration(acc: FoldAcc): void {
246
284
  acc.gen = undefined;
247
285
  }
248
286
 
249
- async function foldUnitRow(
287
+ /**
288
+ * Open a generation for `row.parent` if none is active for it (first unit row,
289
+ * or a different parent / after a non-unit row). Returns a `stage-gone` refusal
290
+ * WITHOUT mutating `acc.gen` when the parent stage or its loop is missing;
291
+ * otherwise assigns `acc.gen` and returns `undefined`.
292
+ *
293
+ * Frozen HERE: replayed state at generation open is byte-identical to what the
294
+ * live driver saw at loop entry (THE REPLAY CONTRACT) — the only safe place to
295
+ * derive the round-0 arg. `reads` projections in particular must NOT be
296
+ * re-derived post-fold, where the generation's own appends have moved the
297
+ * `.at(-1)` cursors.
298
+ */
299
+ async function openGeneration(
250
300
  acc: FoldAcc,
251
301
  workflow: Workflow,
252
302
  row: WorkflowStage,
253
303
  ): Promise<Extract<ReconstructResult, { ok: false }> | undefined> {
254
- // New generation: different parent (or first unit row / after a non-unit row).
255
- if (!acc.gen || acc.gen.parent !== row.parent) {
256
- closeGeneration(acc);
257
- const def = workflow.stages[row.parent!];
258
- // `effectiveLoopOf` — a verify stage's unit rows recover their synthesized
259
- // loop here; without it every verify-stage trailer would refuse stage-gone.
260
- const loop = def ? effectiveLoopOf(def) : undefined;
261
- if (!def || !loop) return { ok: false, reason: "stage-gone", detail: row.stage };
262
- // One generation = one chain-node activation. Always reentrant: a halt
263
- // row for the parent or a resumed re-entry continues this activation.
264
- noteChainNode(acc, row.parent!, true);
265
- acc.gen = {
266
- parent: row.parent!,
267
- loop,
268
- def,
269
- entryArtifact: acc.state.primaryArtifact,
270
- entryPair: { output: acc.state.output, primaryArtifact: acc.state.primaryArtifact },
271
- // Frozen HERE: replayed state at generation open is byte-identical to
272
- // what the live driver saw at loop entry (THE REPLAY CONTRACT) — the
273
- // only safe place to derive the round-0 arg. `reads` projections in
274
- // particular must NOT be re-derived post-fold, where the generation's
275
- // own appends have moved the `.at(-1)` cursors.
276
- entryArgs: freezesEntryArgsOf(loop) ? stageEntryArgs(def, row.parent!, workflow.start, acc.state) : "",
277
- cursor: freshCursor(),
278
- units: undefined,
279
- };
280
- if (loop.kind === "fanout") {
281
- acc.gen.units = await guarded(acc, acc.gen.parent, () =>
282
- (loop as Extract<LoopDef, { kind: "fanout" }>).units({
283
- cwd: acc.cwd,
284
- artifact: acc.state.primaryArtifact,
285
- state: acc.state,
286
- }),
287
- );
288
- }
304
+ // Same generation as the active one — nothing to open.
305
+ if (acc.gen && acc.gen.parent === row.parent) return undefined;
306
+ closeGeneration(acc);
307
+ const def = workflow.stages[row.parent!];
308
+ // `effectiveLoopOf` — a verify stage's unit rows recover their synthesized
309
+ // loop here; without it every verify-stage trailer would refuse stage-gone.
310
+ const loop = def ? effectiveLoopOf(def) : undefined;
311
+ if (!def || !loop) return { ok: false, reason: "stage-gone", detail: row.stage };
312
+ // One generation = one chain-node activation. Always reentrant: a halt
313
+ // row for the parent or a resumed re-entry continues this activation.
314
+ noteChainNode(acc, row.parent!, true);
315
+ acc.gen = {
316
+ parent: row.parent!,
317
+ loop,
318
+ def,
319
+ entryArtifact: acc.state.primaryArtifact,
320
+ entryPair: { output: acc.state.output, primaryArtifact: acc.state.primaryArtifact },
321
+ entryArgs: freezesEntryArgsOf(loop) ? stageEntryArgs(def, row.parent!, workflow.start, acc.state) : "",
322
+ cursor: freshCursor(),
323
+ units: undefined,
324
+ };
325
+ if (loop.kind === "fanout") {
326
+ acc.gen.units = await guarded(acc, acc.gen.parent, () =>
327
+ (loop as Extract<LoopDef, { kind: "fanout" }>).units({
328
+ cwd: acc.cwd,
329
+ artifact: acc.state.primaryArtifact,
330
+ state: acc.state,
331
+ }),
332
+ );
333
+ }
334
+ return undefined;
335
+ }
336
+
337
+ /**
338
+ * Fanout index-placement arm: place-by-`unitIndex` (NOT trail order) so
339
+ * declared order survives a completion-ordered / out-of-order trail. A slot is
340
+ * FILLED — and so NOT re-dispatched on resume — only when the row is a
341
+ * COMPLETED unit or a COLLECTED soft-halt:
342
+ * • completed → `applyStageSuccess` (bookkeeping + state.output, mirroring the
343
+ * live `recordStageSuccess`) THEN the channel-owning `foldFanoutCompletion`;
344
+ * • collected (`status:"failed"` + `collected:true`) → rebuild the
345
+ * `failedOutput` sentinel from `errMsg` and place it via
346
+ * `foldFanoutCompletion` ONLY (the live `softHaltUnit` runs no
347
+ * `applyStageSuccess` — the fold owns the single channel write). The rebuilt
348
+ * meta is byte-identical to the live sentinel's (see `outputMetaFor`):
349
+ * decorated `row.stage`, `row.skill`, `row.stageNumber`.
350
+ * A hard `status:"failed"` row (no `collected`) or a genuinely pending row — and
351
+ * an aborted in-flight unit, which wrote NO row at all — leaves the slot
352
+ * unfilled so resume re-dispatches that unit. Resets `gen.expected` (consumed)
353
+ * on every fanout row.
354
+ */
355
+ function foldFanoutRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): void {
356
+ const units = gen.units!; // dispatcher gates this arm on gen.loop.kind === "fanout" && gen.units
357
+ if (isCompletedRow(row) && row.output) {
358
+ applyStageSuccess(acc.state, gen.def, row.stage, row.output);
359
+ foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, units.length, row.output);
360
+ } else if (isCollectedSoftHalt(row)) {
361
+ const sentinel = rebuildCollectedSentinel(row, acc.runId);
362
+ foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, units.length, sentinel);
289
363
  }
364
+ gen.expected = undefined; // consumed
365
+ }
366
+
367
+ /**
368
+ * Judge/verify arm — apply-then-project: each member verdict rolls the pair
369
+ * TRANSIENTLY (exactly like the live judge unit); projection at generation
370
+ * close restores. The member this row graded is the one the rebuilt sub-state
371
+ * currently points at — `cursor.panel.memberIndex` BEFORE `advanceCursor` bumps
372
+ * it (0 for a single judge, the panel of one). Using that member's own def
373
+ * publishes the verdict to the member's OWN channel, matching the live session
374
+ * path (`judgeStageDef(member)`) per member — `[0]` for every member would have
375
+ * mis-filed members 1..N-1 onto member 0's channel.
376
+ *
377
+ * `guardRow` already verified `row.unitIndex === cursor.index` (drift
378
+ * otherwise), so the shared transition lands the same cursor the live driver
379
+ * had — and, on the last member, the same folded verdict. `advanceCursor` runs
380
+ * the author fold on the LAST member (`panel.fold`, which a sugar fold's
381
+ * per-member `pred` reaches too), and `publishPanelVerdict` lands it — BOTH
382
+ * behind `guarded()`. A fold/pred throw must become drift (a recorded terminal
383
+ * failure), NOT an unguarded rejection: this fold runs in `reconstructState`,
384
+ * which `resumeWorkflow` awaits BEFORE `executeRun` brackets the lifecycle — an
385
+ * escape here yields no JSONL failure row and no `onWorkflowEnd`. The live
386
+ * driver's same `advanceCursor`+`publishPanelVerdict` pair runs under
387
+ * `dispatchStageOrRecordFailure`'s catch (loop.ts `dispatchUnit`); this is its
388
+ * resume-side error boundary. Does NOT reset `gen.expected` (current behavior —
389
+ * the judge arm never consumed it).
390
+ */
391
+ async function foldJudgeRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): Promise<void> {
392
+ const judgeSlot = (gen.loop as Extract<LoopDef, { kind: "assess" }>).judge;
393
+ const memberIndex = gen.cursor.panel?.memberIndex ?? 0;
394
+ applyStageSuccess(acc.state, judgeStageDef(panelMembers(judgeSlot)[memberIndex]!), row.stage, row.output);
395
+ const role = row.role!; // dispatcher gates this arm on isVerdictRow(row) — "judge" | "verify"
396
+ const verdict = row.output;
397
+ if (!verdict) return; // defensive — completed unit rows always carry output
398
+ await guarded(acc, gen.parent, () => {
399
+ advanceCursor(gen.cursor, role, verdict, gen.loop);
400
+ // Panel-close publish — the SAME call the live driver makes after the
401
+ // last member's advance, so the folded verdict lands byte-identically.
402
+ publishPanelVerdict(gen.loop, gen.parent, gen.cursor, acc.state);
403
+ });
404
+ }
405
+
406
+ /**
407
+ * Produce arm — iterate units and assess producers (fanout is placed by index
408
+ * above; a fanout row only reaches here when `gen.units` is absent because the
409
+ * units generator threw at open — already drift — so `advanceCursor` keeps the
410
+ * refused fold applying bookkeeping without a `length`-of-undefined). Resets
411
+ * `gen.expected` (consumed).
412
+ */
413
+ function foldProduceRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): void {
414
+ applyStageSuccess(acc.state, gen.def, row.stage, row.output);
415
+ if (!row.output) return; // defensive — completed unit rows always carry output
416
+ advanceCursor(gen.cursor, "produce", row.output, gen.loop);
417
+ gen.expected = undefined; // consumed
418
+ }
419
+
420
+ async function foldUnitRow(
421
+ acc: FoldAcc,
422
+ workflow: Workflow,
423
+ row: WorkflowStage,
424
+ ): Promise<Extract<ReconstructResult, { ok: false }> | undefined> {
425
+ const refusal = await openGeneration(acc, workflow, row);
426
+ if (refusal) return refusal;
427
+ const gen = acc.gen!;
290
428
 
291
- const gen = acc.gen;
292
429
  acc.visited.add(gen.parent);
293
430
  acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
294
431
 
295
432
  if (!acc.drift) await guardRow(acc, gen, row);
296
433
 
297
- // Fanout: place-by-`unitIndex` (NOT trail order) so declared order survives a
298
- // completion-ordered / out-of-order trail. A slot is FILLED — and so NOT
299
- // re-dispatched on resume — only when the row is a COMPLETED unit or a
300
- // COLLECTED soft-halt:
301
- // • completed → `applyStageSuccess` (bookkeeping + state.output, mirroring the
302
- // live `recordStageSuccess`) THEN the channel-owning `foldFanoutCompletion`;
303
- // • collected (`status:"failed"` + `collected:true`) → rebuild the `failedOutput`
304
- // sentinel from `errMsg` and place it via `foldFanoutCompletion` ONLY (the live
305
- // `softHaltUnit` runs no `applyStageSuccess` — the fold owns the single channel
306
- // write). The rebuilt meta is byte-identical to the live sentinel's (see
307
- // `outputMetaFor`): decorated `row.stage`, `row.skill`, `row.stageNumber`.
308
- // A hard `status:"failed"` row (no `collected`) or a genuinely pending row — and
309
- // an aborted in-flight unit, which wrote NO row at all — leaves the slot
310
- // unfilled so resume re-dispatches that unit. `gen.units` is absent only when the
311
- // units generator threw at open (already drift); fall through to the produce arm's
312
- // `advanceCursor` so the refused fold still applies bookkeeping.
434
+ // Four-way dispatch over the unit row's kind. Fanout rows are placed by
435
+ // `unitIndex` (foldFanoutRow); everything else is cursor-ordered — a pending
436
+ // unit short-circuits, a verdict row rolls the panel, a produce row advances.
313
437
  if (gen.loop.kind === "fanout" && gen.units) {
314
- if (row.status === "completed" && row.output) {
315
- applyStageSuccess(acc.state, gen.def, row.stage, row.output);
316
- foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, gen.units.length, row.output);
317
- } else if (row.collected && row.errMsg !== undefined) {
318
- const sentinel = failedOutput(
319
- outputMeta({
320
- stage: row.stage,
321
- skill: row.skill,
322
- stageNumber: row.stageNumber,
323
- ts: row.ts,
324
- runId: acc.runId,
325
- }),
326
- row.errMsg,
327
- );
328
- foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, gen.units.length, sentinel);
329
- }
330
- gen.expected = undefined; // consumed
438
+ foldFanoutRow(acc, gen, row);
331
439
  return undefined; // pending / hard-failed slots stay unfilled — resume re-dispatches them
332
440
  }
333
-
334
- if (row.status !== "completed") return undefined; // pending unit — cursor stays (resume re-runs it)
335
-
336
- if (row.role === "judge" || row.role === "verify") {
337
- // Apply-then-project: each member verdict rolls the pair TRANSIENTLY
338
- // (exactly like the live judge unit); projection at generation close
339
- // restores. The member this row graded is the one the rebuilt sub-state
340
- // currently points at — `cursor.panel.memberIndex` BEFORE `advanceCursor`
341
- // bumps it (0 for a single judge, the panel of one). Using that member's
342
- // own def publishes the verdict to the member's OWN channel, matching the
343
- // live session path (`judgeStageDef(member)`) per member — `[0]` for every
344
- // member would have mis-filed members 1..N-1 onto member 0's channel.
345
- const judgeSlot = (gen.loop as Extract<LoopDef, { kind: "assess" }>).judge;
346
- const memberIndex = gen.cursor.panel?.memberIndex ?? 0;
347
- applyStageSuccess(acc.state, judgeStageDef(panelMembers(judgeSlot)[memberIndex]!), row.stage, row.output);
348
- const role = row.role; // narrowed to "judge" | "verify" — captured for the closure below
349
- const verdict = row.output;
350
- if (!verdict) return undefined; // defensive — completed unit rows always carry output
351
- // `guardRow` already verified `row.unitIndex === cursor.index` (drift
352
- // otherwise), so the shared transition lands the same cursor the live
353
- // driver had — and, on the last member, the same folded verdict.
354
- //
355
- // `advanceCursor` runs the author fold on the LAST member (`panel.fold`,
356
- // which a sugar fold's per-member `pred` reaches too), and
357
- // `publishPanelVerdict` lands it — BOTH behind `guarded()`. A fold/pred
358
- // throw must become drift (a recorded terminal failure), NOT an unguarded
359
- // rejection: this fold runs in `reconstructState`, which `resumeWorkflow`
360
- // awaits BEFORE `executeRun` brackets the lifecycle — an escape here yields
361
- // no JSONL failure row and no `onWorkflowEnd`. The live driver's same
362
- // `advanceCursor`+`publishPanelVerdict` pair runs under
363
- // `dispatchStageOrRecordFailure`'s catch (loop.ts `dispatchUnit`); this is its
364
- // resume-side error boundary.
365
- await guarded(acc, gen.parent, () => {
366
- advanceCursor(gen.cursor, role, verdict, gen.loop);
367
- // Panel-close publish — the SAME call the live driver makes after the
368
- // last member's advance, so the folded verdict lands byte-identically.
369
- publishPanelVerdict(gen.loop, gen.parent, gen.cursor, acc.state);
370
- });
441
+ if (!isCompletedRow(row)) return undefined; // pending unit — cursor stays (resume re-runs it)
442
+ if (isVerdictRow(row)) {
443
+ await foldJudgeRow(acc, gen, row);
371
444
  return undefined;
372
445
  }
373
-
374
- // produce row — iterate units and assess producers (fanout is placed by index
375
- // above; a fanout row only reaches here when `gen.units` is absent because the
376
- // units generator threw at open — already drift — so `advanceCursor` keeps the
377
- // refused fold applying bookkeeping without a `length`-of-undefined).
378
- applyStageSuccess(acc.state, gen.def, row.stage, row.output);
379
- if (!row.output) return undefined; // defensive — completed unit rows always carry output
380
- advanceCursor(gen.cursor, "produce", row.output, gen.loop);
381
- gen.expected = undefined; // consumed
446
+ foldProduceRow(acc, gen, row);
382
447
  return undefined;
383
448
  }
384
449
 
@@ -45,9 +45,10 @@ import {
45
45
  reattachStageSession,
46
46
  } from "../sessions/index.js";
47
47
  import { forkChildSession, reattachChildSession } from "../sessions/spawn.js";
48
+ import type { SkillContractMap } from "../skill-contract.js";
48
49
  import { effectiveOutputSchemaOf } from "../stage-identity.js";
49
50
  import type { WorkflowStage } from "../state/index.js";
50
- import type { RunContext, StageSessionContext, WorkflowHostContext } from "../types.js";
51
+ import type { RunContext, RunState, StageSessionContext, WorkflowHostContext } from "../types.js";
51
52
  import { resolveDigest } from "../worktree-digest.js";
52
53
  import { advanceChain, type ChainDeps } from "./chain-advance.js";
53
54
  import { type ChainOutcome, haltChain, recordAbortedAtSeam, recordEntryThrow, withStageEntryGuard } from "./failure.js";
@@ -234,6 +235,33 @@ function announceSingleStageStart(
234
235
  );
235
236
  }
236
237
 
238
+ /** A `produces` stage carrying an effective output schema — the gate's
239
+ * qualifying predicate. Spelled through the shared `effectiveOutputSchemaOf`
240
+ * so the gate and the extraction retry loop agree on "schema-validated". */
241
+ const isSchemaValidatedProducesStage = (stage: ResolvedStage, skillContracts: SkillContractMap | undefined): boolean =>
242
+ stage.def.kind === "produces" && !!effectiveOutputSchemaOf(stage.def, stage.name, skillContracts);
243
+
244
+ /** The worktree digest and progress point match the last gated baseline for
245
+ * THIS stage — no observable fix ran between the two dispatches. The
246
+ * `digest !== undefined` term narrows the digest compare inside the body. */
247
+ const isUnchangedTreeRedispatch = (
248
+ baseline: { stage: string; digest: string; stagesCompleted: number } | undefined,
249
+ stage: ResolvedStage,
250
+ digest: string | undefined,
251
+ stagesCompleted: number,
252
+ ): boolean =>
253
+ baseline !== undefined &&
254
+ baseline.stage === stage.name &&
255
+ digest !== undefined &&
256
+ digest === baseline.digest &&
257
+ stagesCompleted === baseline.stagesCompleted;
258
+
259
+ /** Records this dispatch's worktree digest + progress point as the gate
260
+ * baseline, so the NEXT dispatch of this stage compares against it. */
261
+ const recordGatedDispatchBaseline = (state: RunState, stage: ResolvedStage, digest: string): void => {
262
+ state.lastGatedDispatch = { stage: stage.name, digest, stagesCompleted: state.stagesCompleted };
263
+ };
264
+
237
265
  /**
238
266
  * Validation-retry mechanism-2: fail-fast a re-dispatch of a schema-validated
239
267
  * produces stage against an UNCHANGED worktree (no observable fix since the last
@@ -261,33 +289,23 @@ export async function gateValidationRedispatch(
261
289
  run: RunContext,
262
290
  ): Promise<boolean> {
263
291
  const isOperatorResume = run.trigger.meta?.resumedFrom !== undefined;
264
- const qualifies =
265
- stage.def.kind === "produces" && !!effectiveOutputSchemaOf(stage.def, stage.name, run.skillContracts);
266
- if (!isOperatorResume && qualifies) {
267
- const digest = resolveDigest(run.worktreeDigest, run.cwd);
268
- const baseline = run.state.lastGatedDispatch;
269
- if (
270
- baseline &&
271
- baseline.stage === stage.name &&
272
- digest !== undefined &&
273
- digest === baseline.digest &&
274
- run.state.stagesCompleted === baseline.stagesCompleted
275
- ) {
276
- await recordFatalFailure(
277
- hostCtx,
278
- auditCtxFor(run, stage.name, stage.skill),
279
- failedArgs(FAIL_VALIDATE_GATE_SKIPPED(stage.skill)),
280
- );
281
- return true;
282
- }
283
- // Overwrite the baseline on every qualifying dispatch with a defined
284
- // digest, so the NEXT dispatch of this stage compares against the most
285
- // recent state (the "tree changed" / "fix ran" proceed arms both land
286
- // here after the non-matching halt check above).
287
- if (digest !== undefined) {
288
- run.state.lastGatedDispatch = { stage: stage.name, digest, stagesCompleted: run.state.stagesCompleted };
289
- }
292
+ // Qualify → read guard → write. An operator-resume run and a stage with no
293
+ // effective output schema both fall through, leaving `lastGatedDispatch` alone.
294
+ if (isOperatorResume || !isSchemaValidatedProducesStage(stage, run.skillContracts)) return false;
295
+ const digest = resolveDigest(run.worktreeDigest, run.cwd);
296
+ if (isUnchangedTreeRedispatch(run.state.lastGatedDispatch, stage, digest, run.state.stagesCompleted)) {
297
+ await recordFatalFailure(
298
+ hostCtx,
299
+ auditCtxFor(run, stage.name, stage.skill),
300
+ failedArgs(FAIL_VALIDATE_GATE_SKIPPED(stage.skill)),
301
+ );
302
+ return true;
290
303
  }
304
+ // Overwrite the baseline on every qualifying dispatch with a defined
305
+ // digest, so the NEXT dispatch of this stage compares against the most
306
+ // recent state (the "tree changed" / "fix ran" proceed arms both land
307
+ // here after the non-matching halt check above).
308
+ if (digest !== undefined) recordGatedDispatchBaseline(run.state, stage, digest);
291
309
  return false;
292
310
  }
293
311