@juicesharp/rpiv-workflow 2.3.0 → 2.3.1
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/loop-kinds.ts +122 -79
- package/loop.ts +22 -5
- package/package.json +2 -2
- package/runner/chain-advance.ts +28 -12
- package/runner/preflight.ts +17 -14
- package/runner/resume.ts +198 -133
- package/runner/run-stage.ts +45 -27
- package/sessions/extraction.ts +117 -66
- package/sessions/sessions.ts +66 -32
- package/validate/stage-rules.ts +42 -17
package/loop-kinds.ts
CHANGED
|
@@ -607,85 +607,8 @@ const assessStrategy: SequentialStrategy = {
|
|
|
607
607
|
// carries no marker, so live and resume can't disagree about flavoring.
|
|
608
608
|
async pull(e, cursor, cap, run) {
|
|
609
609
|
const loop = e.loop as AssessLoop;
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
const lp = lastProduceOf(cursor, e.name); // a judge step always follows a completed produce
|
|
613
|
-
// Expand the judge slot to its members and dispatch the member the
|
|
614
|
-
// panel sub-state points at. A single judge is the panel of one
|
|
615
|
-
// (`memberIndex` undefined, member 0 the only member), so its transition
|
|
616
|
-
// is byte-identical to today; a panel walks member 0..N-1 across
|
|
617
|
-
// successive judge-phase pulls, `advanceCursor` bumping
|
|
618
|
-
// `cursor.panel.memberIndex` between them.
|
|
619
|
-
const memberIndex = isPanel(loop.judge) ? (cursor.panel?.memberIndex ?? 0) : undefined;
|
|
620
|
-
const judge = panelMembers(loop.judge)[memberIndex ?? 0]!;
|
|
621
|
-
const judgeSkill = judge.skill ?? (isVerify ? `${e.name}-verify` : `${e.name}-judge`);
|
|
622
|
-
let prompt: string;
|
|
623
|
-
if (judge.skill !== undefined) {
|
|
624
|
-
// produces-validation guarantees the producer emitted an artifact —
|
|
625
|
-
// a miss is the same corrupted-cursor class as a missing produce.
|
|
626
|
-
if (!lp.artifact) {
|
|
627
|
-
const msg = MSG_LOOP_CURSOR_CORRUPT(e.name, "judge skill dispatch found no produced artifact");
|
|
628
|
-
throw invariantPreflight(e.name, msg);
|
|
629
|
-
}
|
|
630
|
-
prompt = `/skill:${judge.skill} ${handleToString(lp.artifact.handle)}`;
|
|
631
|
-
} else {
|
|
632
|
-
prompt = await resolveJudgePrompt(judge.prompt!, {
|
|
633
|
-
cwd: run.cwd,
|
|
634
|
-
output: lp.output,
|
|
635
|
-
entryArtifact: e.entryArtifact,
|
|
636
|
-
state: run.state,
|
|
637
|
-
round: cursor.index,
|
|
638
|
-
});
|
|
639
|
-
}
|
|
640
|
-
const label = judgeUnitLabel(cursor.index, isVerify, memberIndex);
|
|
641
|
-
return {
|
|
642
|
-
kind: "unit",
|
|
643
|
-
role: isVerify ? "verify" : "judge",
|
|
644
|
-
tag: label,
|
|
645
|
-
// Panel member rows carry an `id` so they are identity-bearing for the
|
|
646
|
-
// resume join (`unitId` = the `#{memberIndex}` tag); a single judge keeps
|
|
647
|
-
// identity `(role, round)` with no `id`, exactly as before.
|
|
648
|
-
id: memberIndex === undefined ? undefined : label,
|
|
649
|
-
label,
|
|
650
|
-
skill: judgeSkill,
|
|
651
|
-
prompt,
|
|
652
|
-
def: judgeStageDef(judge),
|
|
653
|
-
};
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
// produce — done wins over cap (one code path for live + resume fast-advance)
|
|
657
|
-
if (cursor.lastVerdict !== undefined && loop.done(cursor.lastVerdict)) return { kind: "complete" };
|
|
658
|
-
if (cursor.index >= cap) return { kind: "cap", count: cursor.index };
|
|
659
|
-
// Producer dispatch is skill XOR prompt (the judge arm's posture). For
|
|
660
|
-
// prompt dispatch the message is sent raw: round 0 resolves the stage's own
|
|
661
|
-
// `prompt` at dispatch time (re-resolved on resume — the PromptFn joins the
|
|
662
|
-
// loop determinism contract), and retry rounds send feedForward's output as
|
|
663
|
-
// the COMPLETE message (there is no skill to prefix an arg onto).
|
|
664
|
-
const isPrompt = e.def.prompt !== undefined;
|
|
665
|
-
// `lastVerdict` is only set by a completed judge, which also bumps `index` —
|
|
666
|
-
// so `index - 1 ≥ 0` whenever feedForward runs (round 0 takes entryArgs).
|
|
667
|
-
const arg =
|
|
668
|
-
cursor.lastVerdict !== undefined
|
|
669
|
-
? loop.feedForward({
|
|
670
|
-
cwd: run.cwd,
|
|
671
|
-
output: lastProduceOf(cursor, e.name).output,
|
|
672
|
-
verdict: cursor.lastVerdict,
|
|
673
|
-
round: cursor.index - 1,
|
|
674
|
-
state: run.state,
|
|
675
|
-
})
|
|
676
|
-
: isPrompt
|
|
677
|
-
? await resolveStagePrompt(e.def.prompt!, run.cwd, run.state)
|
|
678
|
-
: e.entryArgs;
|
|
679
|
-
const label = isVerify ? `a${cursor.index}·attempt` : `r${cursor.index}·produce`;
|
|
680
|
-
return {
|
|
681
|
-
kind: "unit",
|
|
682
|
-
role: "produce",
|
|
683
|
-
tag: label,
|
|
684
|
-
label,
|
|
685
|
-
skill: e.skill,
|
|
686
|
-
prompt: isPrompt ? arg : `/skill:${e.skill} ${arg}`,
|
|
687
|
-
def: e.def,
|
|
688
|
-
};
|
|
610
|
+
if (cursor.phase === "judge") return dispatchPanelMember(loop, cursor, e, run);
|
|
611
|
+
return dispatchProduce(loop, cursor, e, cap, run);
|
|
689
612
|
},
|
|
690
613
|
// The kind-agnostic (role, unitIndex) arithmetic already matched in the
|
|
691
614
|
// caller. Full-check extras:
|
|
@@ -720,6 +643,126 @@ const assessStrategy: SequentialStrategy = {
|
|
|
720
643
|
},
|
|
721
644
|
};
|
|
722
645
|
|
|
646
|
+
/**
|
|
647
|
+
* The produce phase's termination check — a set `lastVerdict` that the loop's
|
|
648
|
+
* `done` predicate accepts. Named so the done-wins-over-cap ordering in
|
|
649
|
+
* `dispatchProduce` reads as intent.
|
|
650
|
+
*/
|
|
651
|
+
const isDone = (loop: AssessLoop, cursor: LoopCursor): boolean =>
|
|
652
|
+
cursor.lastVerdict !== undefined && loop.done(cursor.lastVerdict);
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Judge/verify phase dispatch — the panel-member arm of `assessStrategy.pull`.
|
|
656
|
+
* Expand the judge slot to its members and dispatch the member the panel
|
|
657
|
+
* sub-state points at. A single judge is the panel of one (`memberIndex`
|
|
658
|
+
* undefined, member 0 the only member), so its transition is byte-identical to
|
|
659
|
+
* today; a panel walks member 0..N-1 across successive judge-phase pulls,
|
|
660
|
+
* `advanceCursor` bumping `cursor.panel.memberIndex` between them.
|
|
661
|
+
*/
|
|
662
|
+
async function dispatchPanelMember(
|
|
663
|
+
loop: AssessLoop,
|
|
664
|
+
cursor: LoopCursor,
|
|
665
|
+
e: LoopEntry,
|
|
666
|
+
run: RunContext,
|
|
667
|
+
): Promise<NextStep> {
|
|
668
|
+
const isVerify = e.def.verify !== undefined;
|
|
669
|
+
const lp = lastProduceOf(cursor, e.name); // a judge step always follows a completed produce
|
|
670
|
+
const memberIndex = isPanel(loop.judge) ? (cursor.panel?.memberIndex ?? 0) : undefined;
|
|
671
|
+
const judge = panelMembers(loop.judge)[memberIndex ?? 0]!;
|
|
672
|
+
const judgeSkill = judge.skill ?? (isVerify ? `${e.name}-verify` : `${e.name}-judge`);
|
|
673
|
+
let prompt: string;
|
|
674
|
+
if (judge.skill !== undefined) {
|
|
675
|
+
// produces-validation guarantees the producer emitted an artifact —
|
|
676
|
+
// a miss is the same corrupted-cursor class as a missing produce.
|
|
677
|
+
if (!lp.artifact) {
|
|
678
|
+
const msg = MSG_LOOP_CURSOR_CORRUPT(e.name, "judge skill dispatch found no produced artifact");
|
|
679
|
+
throw invariantPreflight(e.name, msg);
|
|
680
|
+
}
|
|
681
|
+
prompt = `/skill:${judge.skill} ${handleToString(lp.artifact.handle)}`;
|
|
682
|
+
} else {
|
|
683
|
+
prompt = await resolveJudgePrompt(judge.prompt!, {
|
|
684
|
+
cwd: run.cwd,
|
|
685
|
+
output: lp.output,
|
|
686
|
+
entryArtifact: e.entryArtifact,
|
|
687
|
+
state: run.state,
|
|
688
|
+
round: cursor.index,
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
const label = judgeUnitLabel(cursor.index, isVerify, memberIndex);
|
|
692
|
+
return {
|
|
693
|
+
kind: "unit",
|
|
694
|
+
role: isVerify ? "verify" : "judge",
|
|
695
|
+
tag: label,
|
|
696
|
+
// Panel member rows carry an `id` so they are identity-bearing for the
|
|
697
|
+
// resume join (`unitId` = the `#{memberIndex}` tag); a single judge keeps
|
|
698
|
+
// identity `(role, round)` with no `id`, exactly as before.
|
|
699
|
+
id: memberIndex === undefined ? undefined : label,
|
|
700
|
+
label,
|
|
701
|
+
skill: judgeSkill,
|
|
702
|
+
prompt,
|
|
703
|
+
def: judgeStageDef(judge),
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Produce phase dispatch — the producer arm of `assessStrategy.pull`. Done wins
|
|
709
|
+
* over cap (one code path for live + resume fast-advance). Producer dispatch is
|
|
710
|
+
* skill XOR prompt (the judge arm's posture). For prompt dispatch the message is
|
|
711
|
+
* sent raw: round 0 resolves the stage's own `prompt` at dispatch time
|
|
712
|
+
* (re-resolved on resume — the PromptFn joins the loop determinism contract),
|
|
713
|
+
* and retry rounds send feedForward's output as the COMPLETE message (there is no
|
|
714
|
+
* skill to prefix an arg onto).
|
|
715
|
+
*/
|
|
716
|
+
async function dispatchProduce(
|
|
717
|
+
loop: AssessLoop,
|
|
718
|
+
cursor: LoopCursor,
|
|
719
|
+
e: LoopEntry,
|
|
720
|
+
cap: number,
|
|
721
|
+
run: RunContext,
|
|
722
|
+
): Promise<NextStep> {
|
|
723
|
+
if (isDone(loop, cursor)) return { kind: "complete" };
|
|
724
|
+
if (cursor.index >= cap) return { kind: "cap", count: cursor.index };
|
|
725
|
+
const isPrompt = e.def.prompt !== undefined;
|
|
726
|
+
const arg = await resolveProduceArg(loop, cursor, e, run);
|
|
727
|
+
const isVerify = e.def.verify !== undefined;
|
|
728
|
+
const label = isVerify ? `a${cursor.index}·attempt` : `r${cursor.index}·produce`;
|
|
729
|
+
return {
|
|
730
|
+
kind: "unit",
|
|
731
|
+
role: "produce",
|
|
732
|
+
tag: label,
|
|
733
|
+
label,
|
|
734
|
+
skill: e.skill,
|
|
735
|
+
prompt: isPrompt ? arg : `/skill:${e.skill} ${arg}`,
|
|
736
|
+
def: e.def,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* The producer's next-round arg — the three-way verdict/retry/init resolution:
|
|
742
|
+
* a retry round (a completed judge set `lastVerdict`) runs `feedForward`; round 0
|
|
743
|
+
* of a prompt stage resolves the stage's own `prompt`; round 0 of a skill stage
|
|
744
|
+
* takes the loop's entryArgs. `lastVerdict` is only set by a completed judge,
|
|
745
|
+
* which also bumps `index` — so `index - 1 ≥ 0` whenever feedForward runs
|
|
746
|
+
* (round 0 takes entryArgs). The async wrap preserves the await asymmetry:
|
|
747
|
+
* `feedForward` is a sync `(ctx) => string` (its bare `return` is wrapped by
|
|
748
|
+
* this async helper into a resolved promise), while `resolveStagePrompt` is
|
|
749
|
+
* `Promise<string>` and is awaited.
|
|
750
|
+
*/
|
|
751
|
+
async function resolveProduceArg(loop: AssessLoop, cursor: LoopCursor, e: LoopEntry, run: RunContext): Promise<string> {
|
|
752
|
+
const isPrompt = e.def.prompt !== undefined;
|
|
753
|
+
return cursor.lastVerdict !== undefined
|
|
754
|
+
? loop.feedForward({
|
|
755
|
+
cwd: run.cwd,
|
|
756
|
+
output: lastProduceOf(cursor, e.name).output,
|
|
757
|
+
verdict: cursor.lastVerdict,
|
|
758
|
+
round: cursor.index - 1,
|
|
759
|
+
state: run.state,
|
|
760
|
+
})
|
|
761
|
+
: isPrompt
|
|
762
|
+
? await resolveStagePrompt(e.def.prompt!, run.cwd, run.state)
|
|
763
|
+
: e.entryArgs;
|
|
764
|
+
}
|
|
765
|
+
|
|
723
766
|
/**
|
|
724
767
|
* One strategy per kind — the `Record` shape turns "added a `LoopDef` arm,
|
|
725
768
|
* forgot the strategy" into a compile error. Keyed value types are preserved
|
package/loop.ts
CHANGED
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
* no-op (pinned behavior).
|
|
37
37
|
*/
|
|
38
38
|
|
|
39
|
-
import type { LoopDef } from "./api.js";
|
|
39
|
+
import type { AssessLoop, LoopDef } from "./api.js";
|
|
40
40
|
import { applyCompletedStage } from "./chain-state.js";
|
|
41
41
|
import { lifecycleCtxFor, skillStageRef } from "./events.js";
|
|
42
42
|
import { nowIso } from "./internal-utils.js";
|
|
43
|
-
import { isPanel } from "./judge.js";
|
|
43
|
+
import { type AnyJudge, isPanel, type PanelJudge } from "./judge.js";
|
|
44
44
|
import { panelVerdictChannel, panelVerdictDef } from "./loop-constructors.js";
|
|
45
45
|
import {
|
|
46
46
|
advanceCursor,
|
|
@@ -88,6 +88,23 @@ export async function announceLoopStart(
|
|
|
88
88
|
const isPristine = (cursor: LoopCursor): boolean =>
|
|
89
89
|
cursor.index === 0 && cursor.accumulated.length === 0 && cursor.slots === undefined;
|
|
90
90
|
|
|
91
|
+
/** Narrows `loop` to AssessLoop — the one bearing a `judge` field; the first
|
|
92
|
+
* publishPanelVerdict guard routes through this so `loop.judge` type-checks
|
|
93
|
+
* without a cast. */
|
|
94
|
+
const isAssessLoop = (loop: LoopDef): loop is AssessLoop => loop.kind === "assess";
|
|
95
|
+
|
|
96
|
+
/** The panel-closing transition — fires exactly once per round: the LAST member's
|
|
97
|
+
* judge advance clears `cursor.panel` and flips to `produce` with the folded
|
|
98
|
+
* verdict already on `lastVerdict`. The positive conjunction of the De Morgan
|
|
99
|
+
* dual of the original guard. */
|
|
100
|
+
const isPanelClosingTransition = (judge: AnyJudge, cursor: LoopCursor): judge is PanelJudge =>
|
|
101
|
+
isPanel(judge) && cursor.panel === undefined && cursor.phase === "produce";
|
|
102
|
+
|
|
103
|
+
/** A live empty pull (iterate) loop — no units ran this invocation and none
|
|
104
|
+
* accumulated — the one shape that earns the zero-unit warning. */
|
|
105
|
+
const isZeroUnitPullLoop = (cursor: LoopCursor, loop: LoopDef): boolean =>
|
|
106
|
+
cursor.ranThisInvocation === 0 && cursor.accumulated.length === 0 && loop.kind === "iterate";
|
|
107
|
+
|
|
91
108
|
/** Run (or resume) one loop generation. The caller fired onStageStart/onLoopStart. */
|
|
92
109
|
export async function runLoop(
|
|
93
110
|
hostCtx: WorkflowHostContext,
|
|
@@ -248,9 +265,9 @@ export function publishPanelVerdict(
|
|
|
248
265
|
cursor: LoopCursor,
|
|
249
266
|
state: RunContext["state"],
|
|
250
267
|
): void {
|
|
251
|
-
if (loop
|
|
268
|
+
if (!isAssessLoop(loop)) return;
|
|
252
269
|
const judge = loop.judge;
|
|
253
|
-
if (!
|
|
270
|
+
if (!isPanelClosingTransition(judge, cursor)) return;
|
|
254
271
|
if (cursor.lastVerdict === undefined) return; // defensive — the fold always set it
|
|
255
272
|
applyCompletedStage(
|
|
256
273
|
state,
|
|
@@ -303,7 +320,7 @@ async function finishLoop(
|
|
|
303
320
|
deps: LoopDeps,
|
|
304
321
|
): Promise<void> {
|
|
305
322
|
projectResult(e.loop, e.entryPair, cursor, run.state);
|
|
306
|
-
if (cursor
|
|
323
|
+
if (isZeroUnitPullLoop(cursor, e.loop)) {
|
|
307
324
|
hostCtx.ui.notify(MSG_LOOP_ZERO_UNITS(e.skill), "warning");
|
|
308
325
|
}
|
|
309
326
|
await deps.advanceAfter(hostCtx, e.name, e.stageIdx, run);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juicesharp/rpiv-workflow",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.1",
|
|
4
4
|
"description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -111,7 +111,7 @@
|
|
|
111
111
|
]
|
|
112
112
|
},
|
|
113
113
|
"dependencies": {
|
|
114
|
-
"@juicesharp/rpiv-config": "^2.3.
|
|
114
|
+
"@juicesharp/rpiv-config": "^2.3.1",
|
|
115
115
|
"jiti": "^2.7.0",
|
|
116
116
|
"typebox": "^1.1.24"
|
|
117
117
|
},
|
package/runner/chain-advance.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* spelled as a module cycle.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import { takeRouteNote } from "../api.js";
|
|
14
|
+
import { type EdgeTarget, takeRouteNote } from "../api.js";
|
|
15
15
|
import { auditCtxFor, failedArgs, recordFatalFailure } from "../audit.js";
|
|
16
16
|
import { resolveSkill } from "../chain-state.js";
|
|
17
17
|
import { lifecycleCtxFor, skillStageRef } from "../events.js";
|
|
@@ -65,19 +65,10 @@ export async function advanceChain(
|
|
|
65
65
|
const fromRef = skillStageRef(currentName, idx + 1, skill);
|
|
66
66
|
|
|
67
67
|
if (result.kind === "stop") {
|
|
68
|
-
|
|
69
|
-
// and a stop carrying a ROUTE_NOTE is `match`'s no-fallback termination:
|
|
70
|
-
// the gate found no branch for the value it read (typically a failed
|
|
71
|
-
// verdict on a pass-only gate). That run is BLOCKED awaiting
|
|
72
|
-
// intervention, not complete — record a terminal failure row so the
|
|
73
|
-
// trail and the lane show a stopped run instead of a silent ✓. A
|
|
74
|
-
// noteless decision stop (a custom edge deliberately returning STOP)
|
|
75
|
-
// and the ordinary end-of-chain stop remain completions.
|
|
76
|
-
const edge = run.workflow.edges[currentName];
|
|
77
|
-
const note = wasDecision && typeof edge === "function" ? takeRouteNote(edge) : undefined;
|
|
68
|
+
const note = stopRouteNote(wasDecision, run.workflow.edges[currentName]);
|
|
78
69
|
if (wasDecision) auditRoutingDecision(hostCtx, run, idx, currentName, "stop", note);
|
|
79
70
|
await run.lifecycle.fire(hostCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
|
|
80
|
-
if (note
|
|
71
|
+
if (isBlockedGateStop(note)) {
|
|
81
72
|
return haltChain(hostCtx, run, currentName, skill, failedArgs(FAIL_GATE_STOP(currentName, note)));
|
|
82
73
|
}
|
|
83
74
|
return finalizeWorkflow(hostCtx, run);
|
|
@@ -210,3 +201,28 @@ async function haltOnRoutingError(
|
|
|
210
201
|
);
|
|
211
202
|
return "halted";
|
|
212
203
|
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Read the ROUTE_NOTE a decision EdgeFn attached to its most recent pick,
|
|
207
|
+
* or undefined when the stop did not come from a decision edge function.
|
|
208
|
+
*
|
|
209
|
+
* Returns the note VALUE, not a boolean — `takeRouteNote` reads the
|
|
210
|
+
* `ROUTE_NOTE` symbol once then clears it (read-and-clear), so a boolean
|
|
211
|
+
* variant called twice would see undefined on the second read. The single
|
|
212
|
+
* returned note is threaded to both the audit row and the halt-vs-finalize
|
|
213
|
+
* decision. Non-decision stops and declarative edges (string / STOP) carry
|
|
214
|
+
* no note.
|
|
215
|
+
*/
|
|
216
|
+
const stopRouteNote = (wasDecision: boolean, edge: EdgeTarget): string | undefined =>
|
|
217
|
+
wasDecision && typeof edge === "function" ? takeRouteNote(edge) : undefined;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* A decision stop carrying a ROUTE_NOTE is `match`'s no-fallback
|
|
221
|
+
* termination: the gate found no branch for the value it read (typically
|
|
222
|
+
* a failed verdict on a pass-only gate). That run is BLOCKED awaiting
|
|
223
|
+
* intervention, not complete — halt via `haltChain` so the trail and the
|
|
224
|
+
* lane show a stopped run instead of a silent ✓. A noteless decision stop
|
|
225
|
+
* (a custom edge deliberately returning STOP) and the ordinary
|
|
226
|
+
* end-of-chain stop remain completions.
|
|
227
|
+
*/
|
|
228
|
+
const isBlockedGateStop = (note: string | undefined): note is string => note !== undefined;
|
package/runner/preflight.ts
CHANGED
|
@@ -122,22 +122,25 @@ function ensureSkillRegistered(stage: ResolvedStage, run: RunContext): void {
|
|
|
122
122
|
* The start node consumes the user's brief; subsequent stages MUST inherit
|
|
123
123
|
* an upstream artifactPath. Falling back to originalInput past the start
|
|
124
124
|
* would silently hand a downstream skill the raw feature description.
|
|
125
|
-
*
|
|
126
|
-
* Three opt-outs skip the check:
|
|
127
|
-
* - `inheritsArtifacts: false` (authored via `terminal()`) — stage consumes
|
|
128
|
-
* `originalInput` by design.
|
|
129
|
-
* - `reads: [...]` — stage builds its prompt from the named-publish
|
|
130
|
-
* registry instead of the rolling primary slot; `ensureNamedReads`
|
|
131
|
-
* enforces its own coverage rule.
|
|
132
|
-
* - prompt dispatch — the stage builds its own text and never consumes the
|
|
133
|
-
* rolling primary as an arg (a continue chat turn typically leans on
|
|
134
|
-
* session context, not a handle).
|
|
135
125
|
*/
|
|
126
|
+
|
|
127
|
+
/** The start node consumes the user's brief; it has no upstream artifact to inherit. */
|
|
128
|
+
const isStartStage = (stage: ResolvedStage, run: RunContext): boolean => stage.name === run.workflow.start;
|
|
129
|
+
|
|
130
|
+
/** Authored via `terminal()`: the stage consumes `originalInput` by design. */
|
|
131
|
+
const optsOutOfArtifactInheritance = (stage: ResolvedStage): boolean => stage.def.inheritsArtifacts === false;
|
|
132
|
+
|
|
133
|
+
/** Builds its prompt from the named-publish registry, not the rolling primary slot. */
|
|
134
|
+
const readsNamedChannels = (stage: ResolvedStage): boolean => !!stage.def.reads?.length;
|
|
135
|
+
|
|
136
|
+
/** Prompt dispatch builds its own text and never takes the rolling primary as an arg. */
|
|
137
|
+
const isPromptDispatch = (stage: ResolvedStage): boolean => stage.dispatch === "prompt";
|
|
138
|
+
|
|
136
139
|
function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
|
|
137
|
-
if (stage
|
|
138
|
-
if (stage
|
|
139
|
-
if (stage
|
|
140
|
-
if (stage
|
|
140
|
+
if (isStartStage(stage, run)) return;
|
|
141
|
+
if (optsOutOfArtifactInheritance(stage)) return;
|
|
142
|
+
if (readsNamedChannels(stage)) return;
|
|
143
|
+
if (isPromptDispatch(stage)) return;
|
|
141
144
|
if (currentPrimaryArtifact(run.state)) return;
|
|
142
145
|
const f = FAIL_MISSING_ARTIFACT(stage.skill, stage.stageNumber);
|
|
143
146
|
throw haltPreflight(stage.skill, f);
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
//
|
|
255
|
-
if (
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
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
|
-
//
|
|
298
|
-
//
|
|
299
|
-
//
|
|
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
|
-
|
|
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
|
|
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
|
|
package/runner/run-stage.ts
CHANGED
|
@@ -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
|
-
|
|
265
|
-
|
|
266
|
-
if (
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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
|
|
package/sessions/extraction.ts
CHANGED
|
@@ -234,12 +234,115 @@ function shouldValidateOutput(s: StageSessionContext, output: Output): boolean {
|
|
|
234
234
|
return !!(effectiveOutputSchemaOf(s.stage, s.stageName, s.skillContracts) && output.data !== undefined);
|
|
235
235
|
}
|
|
236
236
|
|
|
237
|
-
interface RetryDeps {
|
|
237
|
+
export interface RetryDeps {
|
|
238
238
|
outcome: Outcome;
|
|
239
239
|
collectCtx: CollectContext;
|
|
240
240
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output;
|
|
241
241
|
}
|
|
242
242
|
|
|
243
|
+
/**
|
|
244
|
+
* Validation-retry mechanism-1 gate: did the worktree stay byte-identical
|
|
245
|
+
* between the failed validate and the post-fix re-read? An UNCHANGED digest
|
|
246
|
+
* means the agent's fix touched nothing observable (tracked files OR
|
|
247
|
+
* gitignored artifacts under `.rpiv/artifacts/`, both hashed by
|
|
248
|
+
* `computeWorktreeDigest`), so the next `produce` → `validate` cycle would
|
|
249
|
+
* re-run the same failing validation — fail fast instead of looping.
|
|
250
|
+
*
|
|
251
|
+
* An `undefined` baseline (non-repo / git missing — `resolveDigest` degrades
|
|
252
|
+
* to `undefined`) ALWAYS proceeds: degrade on a missing signal, never skip.
|
|
253
|
+
*/
|
|
254
|
+
export const worktreeUnchangedSince = (baselineDigest: string | undefined, s: StageSessionContext): boolean =>
|
|
255
|
+
baselineDigest !== undefined && resolveDigest(s.worktreeDigest, s.cwd) === baselineDigest;
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The retry-loop `produce` hook: re-production of the stage's output.
|
|
259
|
+
*
|
|
260
|
+
* `attempt === 0` is the fast-path — the initial output was already produced
|
|
261
|
+
* and contract-checked before the retry loop opened (`produceAndValidateOutput`
|
|
262
|
+
* ran `runOutcome` + `enforceCompletionContract` once), so it returns the
|
|
263
|
+
* `initial` Output WITHOUT re-collection or re-checking the contract.
|
|
264
|
+
*
|
|
265
|
+
* `attempt > 0` re-reads the branch (the agent's fix landed as new messages),
|
|
266
|
+
* re-runs the collector → parser pipeline (`runOutcome`), and re-checks the
|
|
267
|
+
* completion contract. A fatal collector/parser/contract result maps onto
|
|
268
|
+
* the engine's `{ kind: "aborted" }` arm (the loop halts with that message).
|
|
269
|
+
*/
|
|
270
|
+
export async function produceAttempt(
|
|
271
|
+
ctx: WorkflowSessionContext,
|
|
272
|
+
s: StageSessionContext,
|
|
273
|
+
deps: RetryDeps,
|
|
274
|
+
initial: Output,
|
|
275
|
+
attempt: number,
|
|
276
|
+
): Promise<{ kind: "ok"; value: Output } | { kind: "aborted"; abort: Fatal }> {
|
|
277
|
+
if (attempt === 0) return { kind: "ok", value: initial };
|
|
278
|
+
const retryBranch = readBranch(ctx);
|
|
279
|
+
const retryCtx: CollectContext = { ...deps.collectCtx, branch: retryBranch };
|
|
280
|
+
const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
|
|
281
|
+
if (reRun.kind === "fatal") return { kind: "aborted", abort: reRun };
|
|
282
|
+
const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
|
|
283
|
+
if (contract.kind === "fatal") return { kind: "aborted", abort: contract };
|
|
284
|
+
return { kind: "ok", value: contract.output };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* The retry-loop `validate` hook: run the output schema against the produced
|
|
289
|
+
* data, guarded by `timeoutMs` (the same `validateTimeoutMs` budget that
|
|
290
|
+
* bounds `askAgentToFix`). Maps `validateOrFatal`'s `Fatal` outcome (a
|
|
291
|
+
* thrown/rejected/timed-out schema) onto the engine's `{ kind: "aborted" }`
|
|
292
|
+
* arm so a schema failure halts the loop instead of re-prompting the agent.
|
|
293
|
+
*/
|
|
294
|
+
export async function validateOutput(
|
|
295
|
+
schema: StageSchema,
|
|
296
|
+
skill: string,
|
|
297
|
+
timeoutMs: number,
|
|
298
|
+
output: Output,
|
|
299
|
+
): Promise<{ kind: "ok"; result: ValidationResult } | { kind: "aborted"; abort: Fatal }> {
|
|
300
|
+
const validation = await validateOrFatal(schema, output.data, skill, timeoutMs);
|
|
301
|
+
if (validation.kind === "fatal") return { kind: "aborted", abort: validation };
|
|
302
|
+
return { kind: "ok", result: validation.result };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* The retry-loop `onRetry` hook: fired between a failed validate and the next
|
|
307
|
+
* produce (`attempt` is 1-based). Sequence:
|
|
308
|
+
* 1. Capture the worktree digest AT THE FAILED VALIDATE — nothing mutates
|
|
309
|
+
* the tree between `validate` failing and `onRetry` opening, so this
|
|
310
|
+
* equals the digest at the failure. Captured per-retry (NOT once before
|
|
311
|
+
* the loop): a later retry's "before" state is the tree AFTER the prior
|
|
312
|
+
* retry's fix, so a single pre-loop baseline would compare against a
|
|
313
|
+
* stale tree and false-abort every later retry.
|
|
314
|
+
* 2. Fire `onStageRetry` before the agent is re-prompted (the ref shares the
|
|
315
|
+
* activation's allocator number via `currentStageRef` so listeners
|
|
316
|
+
* correlate retry ↔ end; graph position `stageIndex + 1` diverges past
|
|
317
|
+
* any loop).
|
|
318
|
+
* 3. Re-prompt the agent (`askAgentToFix`); a throw becomes an abort.
|
|
319
|
+
* 4. Gate on `worktreeUnchangedSince` — if the fix changed nothing
|
|
320
|
+
* observable, abort with the unchanged-worktree message instead of
|
|
321
|
+
* re-running the same failing validation.
|
|
322
|
+
*/
|
|
323
|
+
export async function handleRetry(
|
|
324
|
+
ctx: WorkflowSessionContext,
|
|
325
|
+
s: StageSessionContext,
|
|
326
|
+
attempt: number,
|
|
327
|
+
failures: SchemaValidationFailure[],
|
|
328
|
+
timeoutMs: number,
|
|
329
|
+
): Promise<{ kind: "ok" } | { kind: "aborted"; abort: Fatal }> {
|
|
330
|
+
const baselineDigest = resolveDigest(s.worktreeDigest, s.cwd);
|
|
331
|
+
await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
|
|
332
|
+
try {
|
|
333
|
+
await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
|
|
334
|
+
} catch (e) {
|
|
335
|
+
return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
|
|
336
|
+
}
|
|
337
|
+
if (worktreeUnchangedSince(baselineDigest, s)) {
|
|
338
|
+
return {
|
|
339
|
+
kind: "aborted",
|
|
340
|
+
abort: { kind: "fatal", message: ERR_VALIDATE_RETRY_UNCHANGED(s.skill) },
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
return { kind: "ok" };
|
|
344
|
+
}
|
|
345
|
+
|
|
243
346
|
async function retryUntilValid(
|
|
244
347
|
ctx: WorkflowSessionContext,
|
|
245
348
|
s: StageSessionContext,
|
|
@@ -260,78 +363,26 @@ async function retryUntilValid(
|
|
|
260
363
|
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
261
364
|
);
|
|
262
365
|
|
|
263
|
-
// The retry policy
|
|
366
|
+
// The retry policy delegates to the SHARED `runValidationRetryLoop` engine
|
|
264
367
|
// (validate-output.ts) — the same produce → validate → retry structure the
|
|
265
|
-
// script path runs. The
|
|
266
|
-
//
|
|
267
|
-
//
|
|
268
|
-
//
|
|
269
|
-
//
|
|
270
|
-
//
|
|
271
|
-
// - `
|
|
272
|
-
//
|
|
273
|
-
// - `onRetry` → `onStageRetry` + `askAgentToFix`; a throw becomes an abort.
|
|
368
|
+
// script path runs. The three hooks are short named delegations:
|
|
369
|
+
// - `produceAttempt` — `produce(0)` returns the already-produced `initial`;
|
|
370
|
+
// `produce(n>0)` re-reads the branch, re-runs the collector/parser, and
|
|
371
|
+
// re-checks the completion contract.
|
|
372
|
+
// - `validateOutput` — `validateOrFatal`, mapping its `Fatal` onto the
|
|
373
|
+
// engine's `{ kind: "aborted" }` abort arm.
|
|
374
|
+
// - `handleRetry` — `onStageRetry` + `askAgentToFix`; a throw becomes an
|
|
375
|
+
// abort, and the `worktreeUnchangedSince` gate aborts a no-op fix.
|
|
274
376
|
// `failFast` mirrors the script path's stop-flag polarity —
|
|
275
377
|
// `(onInvalid ?? "retry") === "halt"` is byte-identical to today's
|
|
276
378
|
// `onInvalid !== "halt"` loop-continue condition, just expressed as the
|
|
277
379
|
// engine's stop flag. Total productions stay bounded by `maxRetries + 1`.
|
|
278
380
|
const outcome = await runValidationRetryLoop<Output, Fatal>(
|
|
381
|
+
{ maxRetries, failFast: (s.stage.onInvalid ?? "retry") === "halt" },
|
|
279
382
|
{
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
{
|
|
284
|
-
produce: async (attempt) => {
|
|
285
|
-
// `produce(0)` returns the already-produced initial — no re-collection,
|
|
286
|
-
// no contract re-check (both ran before the loop opened).
|
|
287
|
-
if (attempt === 0) return { kind: "ok", value: initial };
|
|
288
|
-
const retryBranch = readBranch(ctx);
|
|
289
|
-
const retryCtx: CollectContext = { ...deps.collectCtx, branch: retryBranch };
|
|
290
|
-
const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
|
|
291
|
-
if (reRun.kind === "fatal") return { kind: "aborted", abort: reRun };
|
|
292
|
-
const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
|
|
293
|
-
if (contract.kind === "fatal") return { kind: "aborted", abort: contract };
|
|
294
|
-
return { kind: "ok", value: contract.output };
|
|
295
|
-
},
|
|
296
|
-
validate: async (output) => {
|
|
297
|
-
const validation = await validateOrFatal(schema, output.data, s.skill, timeoutMs);
|
|
298
|
-
if (validation.kind === "fatal") return { kind: "aborted", abort: validation };
|
|
299
|
-
return { kind: "ok", result: validation.result };
|
|
300
|
-
},
|
|
301
|
-
onRetry: async (attempt, failures) => {
|
|
302
|
-
// Validation-retry mechanism-1: capture the worktree digest AT THE FAILED
|
|
303
|
-
// VALIDATE before the agent is re-prompted. Nothing mutates the tree
|
|
304
|
-
// between `validate` failing and `onRetry` opening, so this equals
|
|
305
|
-
// the digest at the failure. Captured per-retry (NOT once before the
|
|
306
|
-
// loop): a later retry's "before" state is the tree AFTER the prior
|
|
307
|
-
// retry's fix, so a single pre-loop baseline would compare against a
|
|
308
|
-
// stale tree and false-abort every later retry.
|
|
309
|
-
const baselineDigest = resolveDigest(s.worktreeDigest, s.cwd);
|
|
310
|
-
// onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
|
|
311
|
-
// Ref shares the activation's ALLOCATOR number (currentStageRef) so
|
|
312
|
-
// listeners can correlate this retry with the end/error event it
|
|
313
|
-
// belongs to — graph position (`stageIndex + 1`) diverges past any loop.
|
|
314
|
-
await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
|
|
315
|
-
try {
|
|
316
|
-
await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
|
|
317
|
-
} catch (e) {
|
|
318
|
-
return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
|
|
319
|
-
}
|
|
320
|
-
// The agent was asked to fix but changed nothing observable in the
|
|
321
|
-
// worktree (tracked files OR gitignored artifacts under
|
|
322
|
-
// `.rpiv/artifacts/`, both hashed by `computeWorktreeDigest`), so the
|
|
323
|
-
// `produce(attempt)` re-read + re-validate cycle would just re-run the
|
|
324
|
-
// same failing validation — fail fast instead of looping. An unchanged
|
|
325
|
-
// `undefined` digest (non-repo / git missing) ALWAYS proceeds: degrade
|
|
326
|
-
// on a missing signal, never skip.
|
|
327
|
-
if (baselineDigest !== undefined && resolveDigest(s.worktreeDigest, s.cwd) === baselineDigest) {
|
|
328
|
-
return {
|
|
329
|
-
kind: "aborted",
|
|
330
|
-
abort: { kind: "fatal", message: ERR_VALIDATE_RETRY_UNCHANGED(s.skill) },
|
|
331
|
-
};
|
|
332
|
-
}
|
|
333
|
-
return { kind: "ok" };
|
|
334
|
-
},
|
|
383
|
+
produce: (attempt) => produceAttempt(ctx, s, deps, initial, attempt),
|
|
384
|
+
validate: (output) => validateOutput(schema, s.skill, timeoutMs, output),
|
|
385
|
+
onRetry: (attempt, failures) => handleRetry(ctx, s, attempt, failures, timeoutMs),
|
|
335
386
|
},
|
|
336
387
|
);
|
|
337
388
|
|
package/sessions/sessions.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
import { WorkflowAbortError } from "../internal-utils.js";
|
|
27
|
+
import type { SessionRef } from "../state/index.js";
|
|
27
28
|
import { type BranchEntry, classifyStop, readBranch, readSessionRef, type StopSignal } from "../transcript.js";
|
|
28
29
|
import type { StageSessionContext, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
|
|
29
30
|
import { bashStrikesRemaining, bashTimeoutSteeringMessage, consumeBashStrike } from "./bash-strikes.js";
|
|
@@ -100,36 +101,10 @@ export async function postStage(
|
|
|
100
101
|
): Promise<void> {
|
|
101
102
|
const session = readSessionRef(child, offset);
|
|
102
103
|
const outcome = readSessionOutcome(child, offset);
|
|
103
|
-
// Abort
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
|
|
107
|
-
// (a) no `collected:true` row is written (else the resume fold marks the unit
|
|
108
|
-
// "don't re-dispatch" → permanent work loss), (b) the parallel fold's
|
|
109
|
-
// `isAbortError` branch leaves the slot unfilled, and (c) resume re-dispatches
|
|
110
|
-
// the unit cleanly.
|
|
111
|
-
//
|
|
112
|
-
// A genuine run/user abort (`s.signal` fired) ALWAYS re-dispatches on resume, so it
|
|
113
|
-
// takes the throw unconditionally. An `aborted` stop with the signal cold is examined
|
|
114
|
-
// for a watchdog tool-timeout (`child.toolTimeout`): the host aborted a runaway bash,
|
|
115
|
-
// which must route to the soft-halt gate (collect-all unit survives; else terminal
|
|
116
|
-
// fail) — NOT WorkflowAbortError, which would re-run the same runaway command on resume.
|
|
117
|
-
if (s.signal?.aborted) throw new WorkflowAbortError();
|
|
118
|
-
if (outcome.stop === "aborted") {
|
|
119
|
-
const timeout = child.toolTimeout?.();
|
|
120
|
-
if (timeout) {
|
|
121
|
-
// Strike-based recovery: a watchdog tool-timeout is a recoverable tool
|
|
122
|
-
// event INSIDE the live child. While strikes remain, the single-caller
|
|
123
|
-
// helper resets → re-prompts → tail-recurses postStage (offset threaded
|
|
124
|
-
// verbatim); exhaustion falls through to the UNCHANGED soft-halt/terminal
|
|
125
|
-
// seam below, where the failure-row writers (memo + death-scene) fire for free.
|
|
126
|
-
if (consumeBashStrike(s, timeout.reason)) {
|
|
127
|
-
return retryStageAfterBashStrike(observerCtx, child, s, offset, timeout.reason);
|
|
128
|
-
}
|
|
129
|
-
return haltStageOrSoftHalt(observerCtx, s, { kind: "timeout", reason: timeout.reason }, session);
|
|
130
|
-
}
|
|
131
|
-
throw new WorkflowAbortError();
|
|
132
|
-
}
|
|
104
|
+
// Abort classification and strike recovery are owned by a single helper that
|
|
105
|
+
// returns "continue" when it has handled the turn (strike retry or soft-halt),
|
|
106
|
+
// so postStage reaches its happy-path switch only for a clean stop.
|
|
107
|
+
if ((await classifyAndHandleAbort(observerCtx, child, s, outcome, session, offset)) === "continue") return;
|
|
133
108
|
// Every halt below routes through the single `haltStageOrSoftHalt` gate: a
|
|
134
109
|
// fanout unit marked `collectAll` records a NON-terminal failed row + a sentinel
|
|
135
110
|
// slot instead of halting the run; everything else takes the arm's fail-fast
|
|
@@ -157,7 +132,66 @@ export async function postStage(
|
|
|
157
132
|
}
|
|
158
133
|
|
|
159
134
|
// ===========================================================================
|
|
160
|
-
//
|
|
135
|
+
// ABORT CLASSIFIER — postStage's single abort dispatch + its predicates
|
|
136
|
+
// ===========================================================================
|
|
137
|
+
|
|
138
|
+
/** An `aborted` stop classification (the SDK resolves `prompt()` with `stopReason:"aborted"`). */
|
|
139
|
+
const isAbortedStop = (outcome: SessionOutcome): boolean => outcome.stop === "aborted";
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The watchdog tool-timeout verdict, if any. Read ONCE and returned so the
|
|
143
|
+
* `reason` threads through without a second read (the strike arm clears the
|
|
144
|
+
* verdict, so a re-read would see `undefined`).
|
|
145
|
+
*/
|
|
146
|
+
const watchdogTimeoutOf = (child: WorkflowSessionContext): { reason: string } | undefined => child.toolTimeout?.();
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Classify and route an abort. Abort surfaces as a STOP CLASSIFICATION, not a
|
|
150
|
+
* promise rejection: `session.abort()` makes the SDK RESOLVE `prompt()` with a
|
|
151
|
+
* `stopReason:"aborted"` transcript message, so an aborted in-flight child runs
|
|
152
|
+
* straight into here. A genuine abort throws BEFORE haltStage/softHaltUnit/any
|
|
153
|
+
* row write so: (a) no `collected:true` row is written (else the resume fold
|
|
154
|
+
* marks the unit "don't re-dispatch" → permanent work loss), (b) the parallel
|
|
155
|
+
* fold's `isAbortError` branch leaves the slot unfilled, and (c) resume
|
|
156
|
+
* re-dispatches the unit cleanly.
|
|
157
|
+
*
|
|
158
|
+
* Returns `"continue"` once the turn is owned (strike retry or soft-halt),
|
|
159
|
+
* telling the caller to stop; returns `void` (no abort) so the caller proceeds
|
|
160
|
+
* to the happy-path switch.
|
|
161
|
+
*
|
|
162
|
+
* Exported ONLY for the co-located direct tests (`sessions/sessions.test.ts` —
|
|
163
|
+
* a non-exported member cannot be imported there; the `extraction.ts` retry
|
|
164
|
+
* hooks set the precedent). Absent from the `sessions/index.ts` barrel, so the
|
|
165
|
+
* package surface is unchanged.
|
|
166
|
+
*/
|
|
167
|
+
export async function classifyAndHandleAbort(
|
|
168
|
+
observerCtx: WorkflowHostContext,
|
|
169
|
+
child: WorkflowSessionContext,
|
|
170
|
+
s: StageSessionContext,
|
|
171
|
+
outcome: SessionOutcome,
|
|
172
|
+
session: SessionRef | null,
|
|
173
|
+
offset: number | undefined,
|
|
174
|
+
): Promise<"continue" | undefined> {
|
|
175
|
+
// Level 1 — genuine run/user abort: the signal fired, so always re-dispatch on resume.
|
|
176
|
+
if (s.signal?.aborted) throw new WorkflowAbortError();
|
|
177
|
+
// Level 2 — not an abort stop: hand back to the caller's happy-path switch.
|
|
178
|
+
if (!isAbortedStop(outcome)) return;
|
|
179
|
+
// Level 3 — examine a watchdog tool-timeout; an aborted stop with the signal cold
|
|
180
|
+
// and no watchdog is a genuine abort that re-dispatches on resume.
|
|
181
|
+
const timeout = watchdogTimeoutOf(child);
|
|
182
|
+
if (!timeout) throw new WorkflowAbortError();
|
|
183
|
+
// Level 4 — a watchdog tool-timeout is recoverable: consume a strike and retry, or
|
|
184
|
+
// route exhaustion through the soft-halt gate (collect-all survives; else terminal).
|
|
185
|
+
if (consumeBashStrike(s, timeout.reason)) {
|
|
186
|
+
await retryStageAfterBashStrike(observerCtx, child, s, offset, timeout.reason);
|
|
187
|
+
} else {
|
|
188
|
+
await haltStageOrSoftHalt(observerCtx, s, { kind: "timeout", reason: timeout.reason }, session);
|
|
189
|
+
}
|
|
190
|
+
return "continue";
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ===========================================================================
|
|
194
|
+
// STRIKE-ARM RECOVERY — single-caller helper for the abort classifier's watchdog arm
|
|
161
195
|
// ===========================================================================
|
|
162
196
|
|
|
163
197
|
/**
|
|
@@ -166,7 +200,7 @@ export async function postStage(
|
|
|
166
200
|
* verbatim — the exact shape the continue body uses). Called ONLY when
|
|
167
201
|
* `consumeBashStrike(s, reason)` returned true, so this helper performs the
|
|
168
202
|
* reset → re-prompt → tail-recurse sequence byte-identically to the inline arm
|
|
169
|
-
* it replaces; strike exhaustion stays routed by the caller (`
|
|
203
|
+
* it replaces; strike exhaustion stays routed by the caller (`classifyAndHandleAbort`) to
|
|
170
204
|
* the UNCHANGED `haltStageOrSoftHalt({ kind: "timeout" })` seam, where the
|
|
171
205
|
* failure-row writers (memo + death-scene artifact) fire for free.
|
|
172
206
|
*/
|
package/validate/stage-rules.ts
CHANGED
|
@@ -11,7 +11,16 @@
|
|
|
11
11
|
* (different dependency footprint entirely).
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
type FanoutLoop,
|
|
16
|
+
LOOP_KINDS,
|
|
17
|
+
type LoopDef,
|
|
18
|
+
ON_INVALID_VALUES,
|
|
19
|
+
SESSION_POLICIES,
|
|
20
|
+
STAGE_KINDS,
|
|
21
|
+
type StageDef,
|
|
22
|
+
type Workflow,
|
|
23
|
+
} from "../api.js";
|
|
15
24
|
import { type AnyJudge, isPanel } from "../judge.js";
|
|
16
25
|
import {
|
|
17
26
|
forEachJudgeChannel,
|
|
@@ -70,30 +79,17 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
|
|
|
70
79
|
if (loop.max !== undefined && (!Number.isInteger(loop.max) || loop.max < 1)) {
|
|
71
80
|
report("loop-max-invalid", { max: loop.max });
|
|
72
81
|
}
|
|
73
|
-
if (
|
|
74
|
-
loop.kind === "fanout" &&
|
|
75
|
-
loop.concurrency !== undefined &&
|
|
76
|
-
(!Number.isInteger(loop.concurrency) || loop.concurrency < 1)
|
|
77
|
-
) {
|
|
82
|
+
if (isInvalidConcurrency(loop)) {
|
|
78
83
|
report("loop-concurrency-invalid", { concurrency: loop.concurrency });
|
|
79
84
|
}
|
|
80
|
-
if (
|
|
81
|
-
loop.kind === "fanout" &&
|
|
82
|
-
loop.depArtifactFlag !== undefined &&
|
|
83
|
-
(typeof loop.depArtifactFlag !== "string" || loop.depArtifactFlag.trim().length === 0)
|
|
84
|
-
) {
|
|
85
|
+
if (isInvalidDepArtifactFlag(loop)) {
|
|
85
86
|
report("loop-dep-flag-invalid", { depArtifactFlag: loop.depArtifactFlag });
|
|
86
87
|
}
|
|
87
88
|
// Pull loops + assess run the stage's outcome collector per unit.
|
|
88
89
|
if ((loop.kind === "iterate" || loop.kind === "assess") && stage.kind !== "produces") {
|
|
89
90
|
report("loop-requires-produces", { kind: loop.kind });
|
|
90
91
|
}
|
|
91
|
-
|
|
92
|
-
// produces collector), fanout when COLLECTING (produces kind) — the decorated
|
|
93
|
-
// display string must never split the accumulation slot.
|
|
94
|
-
const needsName =
|
|
95
|
-
loop.kind === "iterate" || loop.kind === "assess" || (loop.kind === "fanout" && stage.kind === "produces");
|
|
96
|
-
if (needsName && !stage.outcome?.name) {
|
|
92
|
+
if (requiresOutcomeName(loop, stage) && !stage.outcome?.name) {
|
|
97
93
|
report("loop-outcome-name-required");
|
|
98
94
|
}
|
|
99
95
|
|
|
@@ -129,6 +125,35 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
|
|
|
129
125
|
checkVerdictChannels(slot, name, stage, "assess-verdict-channel-collision", report);
|
|
130
126
|
}
|
|
131
127
|
|
|
128
|
+
/**
|
|
129
|
+
* A fanout's `concurrency` ceiling is present and out of range — not an
|
|
130
|
+
* integer or below 1. The type guard narrows to `FanoutLoop &
|
|
131
|
+
* { concurrency: number }` so the report call reads the field without a cast
|
|
132
|
+
* or non-null assertion.
|
|
133
|
+
*/
|
|
134
|
+
const isInvalidConcurrency = (loop: LoopDef): loop is FanoutLoop & { concurrency: number } =>
|
|
135
|
+
loop.kind === "fanout" &&
|
|
136
|
+
loop.concurrency !== undefined &&
|
|
137
|
+
(!Number.isInteger(loop.concurrency) || loop.concurrency < 1);
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* A fanout's `depArtifactFlag` is present but not a non-empty string. The type
|
|
141
|
+
* guard narrows to `FanoutLoop & { depArtifactFlag: string }` so the report
|
|
142
|
+
* call reads the field without a cast or non-null assertion.
|
|
143
|
+
*/
|
|
144
|
+
const isInvalidDepArtifactFlag = (loop: LoopDef): loop is FanoutLoop & { depArtifactFlag: string } =>
|
|
145
|
+
loop.kind === "fanout" &&
|
|
146
|
+
loop.depArtifactFlag !== undefined &&
|
|
147
|
+
(typeof loop.depArtifactFlag !== "string" || loop.depArtifactFlag.trim().length === 0);
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A stable named slot: iterate and assess always (every unit/round runs the
|
|
151
|
+
* produces collector), fanout when COLLECTING (produces kind) — the decorated
|
|
152
|
+
* display string must never split the accumulation slot.
|
|
153
|
+
*/
|
|
154
|
+
const requiresOutcomeName = (loop: LoopDef, stage: StageDef): boolean =>
|
|
155
|
+
loop.kind === "iterate" || loop.kind === "assess" || (loop.kind === "fanout" && stage.kind === "produces");
|
|
156
|
+
|
|
132
157
|
/**
|
|
133
158
|
* Verdict-channel collisions for a judge SLOT (`AnyJudge`) — workflow-level
|
|
134
159
|
* because it needs the producer's publish identity
|