@juicesharp/rpiv-workflow 1.19.1 → 2.0.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/README.md +81 -8
- package/api.ts +18 -703
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +154 -0
- package/audit.ts +158 -190
- package/built-ins.ts +40 -45
- package/chain-state.ts +220 -0
- package/command-run.ts +64 -31
- package/command.ts +123 -21
- package/docs/workflow-authoring.md +356 -63
- package/{lifecycle.ts → events.ts} +161 -37
- package/execution-host.ts +75 -0
- package/host.ts +149 -64
- package/index.ts +25 -81
- package/internal-utils.ts +171 -71
- package/internal.ts +22 -1
- package/judge.ts +241 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +27 -106
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +24 -0
- package/loop-def.ts +285 -0
- package/loop-kinds.ts +750 -0
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +330 -0
- package/loops/constructors.ts +334 -0
- package/loops/derivations.ts +65 -0
- package/loops/introspection.ts +184 -0
- package/loops/panel.ts +196 -0
- package/loops/verify.ts +99 -0
- package/messages.ts +249 -156
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +4 -18
- package/outcomes/collectors/union.ts +30 -10
- package/outcomes/collectors/url.ts +9 -14
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.ts +190 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +98 -20
- package/package.json +27 -11
- package/predicates.ts +11 -8
- package/preview.ts +81 -21
- package/registration.ts +117 -36
- package/routing-dsl.ts +322 -0
- package/routing.ts +48 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +84 -56
- package/runner/errors.ts +10 -0
- package/runner/failure.ts +163 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +16 -23
- package/runner/preflight.ts +169 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +121 -0
- package/runner/resume-loop.ts +131 -0
- package/runner/resume.ts +368 -262
- package/runner/run-context.ts +165 -0
- package/runner/run-stage.ts +490 -0
- package/runner/runner.ts +202 -449
- package/runner/script-stage.ts +104 -112
- package/schema-compat.ts +12 -1
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +146 -81
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +3 -1
- package/sessions/locate.ts +141 -0
- package/sessions/reattach.ts +71 -0
- package/sessions/sessions.ts +114 -199
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +86 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +4 -4
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +595 -0
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +4 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +20 -0
- package/state/raw.ts +77 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +135 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +290 -78
- package/validate/contract-compat.ts +198 -0
- package/validate/graph.ts +134 -0
- package/validate/issue.ts +328 -0
- package/validate/stage-rules.ts +499 -0
- package/validate-output.ts +82 -7
- package/validate-workflow.ts +57 -759
- package/validation-bounds.ts +35 -0
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -74
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -110
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -59
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -107
- package/outcomes/git-commit.test.ts +0 -194
- package/outcomes/parsers/json-body.test.ts +0 -80
- package/runner/by-name.test.ts +0 -95
- package/runner/by-run-id.test.ts +0 -115
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- package/runner/resume.test.ts +0 -1130
- package/runner/stage-lifecycle.ts +0 -500
package/loop-kinds.ts
ADDED
|
@@ -0,0 +1,750 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* loop-kinds.ts — the per-loop-kind vocabulary and strategy table.
|
|
3
|
+
*
|
|
4
|
+
* Everything that varies BY KIND across the loop machinery lives here, in one
|
|
5
|
+
* `Record<LoopDef["kind"], LoopKindStrategy>`. The contract is split by
|
|
6
|
+
* parallelizability: the base `LoopKindStrategy` carries only `parallelizable`,
|
|
7
|
+
* and the SEQUENTIAL kinds (iterate/assess) add — via `SequentialStrategy` —
|
|
8
|
+
* the three methods only their path reaches:
|
|
9
|
+
* - `pull` — the live driver's next-step rule (loop.ts `step`);
|
|
10
|
+
* - `guardExpectation` — the resume fold's per-row determinism re-check
|
|
11
|
+
* (runner/resume.ts `guardRow`);
|
|
12
|
+
* - `hasPending` — the resume re-entry announce probe
|
|
13
|
+
* (runner/resume-loop.ts).
|
|
14
|
+
* Fanout (parallelizable) implements NONE of those — its live entry, resume
|
|
15
|
+
* re-dispatch, and pending probe are index-addressed and reached first; the
|
|
16
|
+
* sequential callers go through `sequentialStrategyOf`. A new loop kind extends
|
|
17
|
+
* the `LoopDef` union and this table — the `Record`/`satisfies` shape makes a
|
|
18
|
+
* missing strategy a compile error — and touches nothing else: dispatch,
|
|
19
|
+
* persistence, cap policy, projection, and completion are kind-agnostic in loop.ts.
|
|
20
|
+
*
|
|
21
|
+
* Also home to the kind-agnostic cursor vocabulary the live driver and the
|
|
22
|
+
* fold share: `LoopCursor`, `advanceCursor` (THE cursor state machine),
|
|
23
|
+
* `unitTagOf`, `judgeStageDef`, `LoopEntry`, `NextStep`.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { AssessLoop, IterateLoop, LoopDef, StageDef, Unit, UnitRole } from "./api.js";
|
|
27
|
+
import { decorateStage, runIdentityOf } from "./audit.js";
|
|
28
|
+
// Fanout completion is INDEX-ADDRESSED (place-by-unitIndex), the
|
|
29
|
+
// shared authority for the live parallel fold AND the resume fold so the two
|
|
30
|
+
// reconstruct byte-identical declared-order state regardless of
|
|
31
|
+
// completion/resume order. iterate/assess keep advanceCursor (sequential).
|
|
32
|
+
import { placeFanoutOutput, resolveStagePrompt } from "./chain-state.js";
|
|
33
|
+
import { type Artifact, handleToString } from "./handle.js";
|
|
34
|
+
import { isPanel, type Judge, type PanelJudge, panelMembers, resolveJudgePrompt } from "./judge.js";
|
|
35
|
+
import { MSG_LOOP_CURSOR_CORRUPT } from "./messages.js";
|
|
36
|
+
import { finalizeOutput, isFailedOutput, type Output, type OutputMeta } from "./output.js";
|
|
37
|
+
import { invariantPreflight } from "./stage-errors.js";
|
|
38
|
+
import type { RunContext, RunState, StageSession, UnitRef, WorkflowHostContext } from "./types.js";
|
|
39
|
+
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
// Cursor + entry vocabulary (kind-agnostic, shared live + fold)
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Frozen per-invocation loop identity, built by the caller (`runLoopStage`
|
|
46
|
+
* live; `resume-loop` on resume). `entryArtifact`/`entryArgs`/`entryPair`
|
|
47
|
+
* are captured BEFORE unit 1 and never change.
|
|
48
|
+
*/
|
|
49
|
+
export interface LoopEntry {
|
|
50
|
+
stageIdx: number;
|
|
51
|
+
/** Loop stage record key (routing + row `parent` + event refs). */
|
|
52
|
+
name: string;
|
|
53
|
+
/** Parent stage's resolved skill body (produce units dispatch it). */
|
|
54
|
+
skill: string;
|
|
55
|
+
/** Parent stage def — produce units run with its knobs. */
|
|
56
|
+
def: StageDef;
|
|
57
|
+
loop: LoopDef;
|
|
58
|
+
/** Stage-entry primary, FROZEN (IterateContext.artifact / JudgeContext.entryArtifact). */
|
|
59
|
+
entryArtifact: Artifact | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Round-0 producer arg (assess) — precomputed via `inputForStage`. `""` for
|
|
62
|
+
* a prompt-dispatch stage (its round-0 message is the stage's own resolved
|
|
63
|
+
* `prompt`, re-resolved at dispatch time — never frozen here).
|
|
64
|
+
*/
|
|
65
|
+
entryArgs: string;
|
|
66
|
+
/** {output, primaryArtifact} captured at loop entry — the "entry" projection. */
|
|
67
|
+
entryPair: { output: Output | undefined; primaryArtifact: Artifact | undefined };
|
|
68
|
+
/** Precomputed unit list — fanout only (computed by runLoopStage / verified by the resume fold). */
|
|
69
|
+
units?: readonly Unit[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Assemble a `LoopEntry` from its stage identity + the frozen per-invocation
|
|
74
|
+
* inputs. THE single construction site for both the live entry (`runLoopStage`,
|
|
75
|
+
* which derives the frozen inputs from current `RunState`) and the resume
|
|
76
|
+
* re-entry (`resumeLoopStage`, which replays them off the `LoopResumePoint`) —
|
|
77
|
+
* so a new `LoopEntry` field is added once here instead of being rebuilt by hand
|
|
78
|
+
* in both. The two paths legitimately differ ONLY in how they obtain `frozen`
|
|
79
|
+
* (compute vs replay); the envelope shape is shared.
|
|
80
|
+
*/
|
|
81
|
+
export function buildLoopEntry(
|
|
82
|
+
id: Pick<LoopEntry, "stageIdx" | "name" | "skill" | "def" | "loop">,
|
|
83
|
+
frozen: Pick<LoopEntry, "entryArtifact" | "entryArgs" | "entryPair" | "units">,
|
|
84
|
+
): LoopEntry {
|
|
85
|
+
return { ...id, ...frozen };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The dependency-injection contract every loop driver runs against — the engine
|
|
90
|
+
* primitives (`runner/run-stage.ts` `buildLoopDeps`) handed to the sequential
|
|
91
|
+
* (`loop.ts`), parallel (`loop-parallel.ts`), and resume (`runner/resume-loop.ts`)
|
|
92
|
+
* paths so none of them imports the engine back (cycle-free). Homed HERE beside
|
|
93
|
+
* `LoopEntry` — the type it references — so it is a leaf shared by all consumers
|
|
94
|
+
* with no module owning a back-edge to declare it.
|
|
95
|
+
*/
|
|
96
|
+
export interface LoopDeps {
|
|
97
|
+
/** Dispatch one unit through the standard stage-session path. */
|
|
98
|
+
runStageSession: (ctx: WorkflowHostContext, s: StageSession) => Promise<void>;
|
|
99
|
+
/**
|
|
100
|
+
* Resume the chain after the loop finishes — receives the loop node's REAL
|
|
101
|
+
* name. `Promise<unknown>` so the walk's `ChainOutcome`-returning composed
|
|
102
|
+
* advance plugs in directly (the driver only awaits settlement).
|
|
103
|
+
*/
|
|
104
|
+
advanceAfter: (
|
|
105
|
+
curCtx: WorkflowHostContext,
|
|
106
|
+
completedName: string,
|
|
107
|
+
completedIdx: number,
|
|
108
|
+
run: RunContext,
|
|
109
|
+
) => Promise<unknown>;
|
|
110
|
+
/** Re-capture the outcome's pre-stage snapshot per unit (ctx + stage name for the fail-soft warning). */
|
|
111
|
+
captureSnapshot: (
|
|
112
|
+
curCtx: WorkflowHostContext,
|
|
113
|
+
stageName: string,
|
|
114
|
+
def: StageDef,
|
|
115
|
+
idx: number,
|
|
116
|
+
run: RunContext,
|
|
117
|
+
) => Promise<unknown>;
|
|
118
|
+
/** Record the terminal failure when `onCap: "halt"` trips — verify-worded for verify stages. */
|
|
119
|
+
haltLoop: (
|
|
120
|
+
curCtx: WorkflowHostContext,
|
|
121
|
+
run: RunContext,
|
|
122
|
+
e: Pick<LoopEntry, "name" | "def">,
|
|
123
|
+
count: number,
|
|
124
|
+
cap: number,
|
|
125
|
+
) => Promise<void>;
|
|
126
|
+
/** Record a mid-flight run abort at the loop seam (FAIL_WORKFLOW_ABORTED).
|
|
127
|
+
* Keeps the drivers free of engine imports; wired to `recordAbortedAtSeam`. */
|
|
128
|
+
recordAborted: (curCtx: WorkflowHostContext, name: string, run: RunContext) => Promise<void>;
|
|
129
|
+
/** Funnel an UNEXPECTED worker rejection (not a workflow halt) to a
|
|
130
|
+
* terminal-failure row + onStageError, terminating state WITHOUT re-throwing,
|
|
131
|
+
* so entry() resolves and onWorkflowEnd still fires. Wraps recordEntryThrow.
|
|
132
|
+
* The unit's identity (`unit` + its `skill`) lands as STRUCTURED row fields —
|
|
133
|
+
* the row's `stage` stays the parent graph identity. */
|
|
134
|
+
recordWorkerThrow: (
|
|
135
|
+
curCtx: WorkflowHostContext,
|
|
136
|
+
unit: UnitRef,
|
|
137
|
+
skill: string,
|
|
138
|
+
run: RunContext,
|
|
139
|
+
err: unknown,
|
|
140
|
+
) => Promise<void>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Mutable generation cursor threaded through the continuation self-calls. */
|
|
144
|
+
export interface LoopCursor {
|
|
145
|
+
/** 0-based index of the NEXT unit (== the round for assess). */
|
|
146
|
+
index: number;
|
|
147
|
+
/** This generation's completed produce Outputs, in order (the iterate pull prefix). */
|
|
148
|
+
accumulated: Output[];
|
|
149
|
+
/** Last completed produce unit's pair — "last" projection + judge input. */
|
|
150
|
+
lastProduce?: { output: Output; artifact: Artifact | undefined };
|
|
151
|
+
/** Last judge verdict — feedForward input + done fast-path. */
|
|
152
|
+
lastVerdict?: Output;
|
|
153
|
+
/** Which assess sub-step is next ("produce" for non-assess loops). */
|
|
154
|
+
phase: "produce" | "judge";
|
|
155
|
+
/**
|
|
156
|
+
* Mid-flight panel sub-state — present ONLY while a multi-member judge phase
|
|
157
|
+
* is in progress (a single judge never sets it; a panel clears it the moment
|
|
158
|
+
* its last member folds). `memberIndex` is the NEXT member to dispatch;
|
|
159
|
+
* `verdicts` accumulates the graded member Outputs the fold reduces. Both the
|
|
160
|
+
* live driver and the resume fold rebuild it through `advanceCursor`, so the
|
|
161
|
+
* two paths fold byte-identically (THE REPLAY CONTRACT).
|
|
162
|
+
*/
|
|
163
|
+
panel?: { memberIndex: number; verdicts: Output[] };
|
|
164
|
+
/** Units dispatched by THIS driver invocation — the resume silence rule. */
|
|
165
|
+
ranThisInvocation: number;
|
|
166
|
+
/** Fanout only — declared-index slot array (length = units.length). A unit's
|
|
167
|
+
* output lands at slots[unitIndex]; `undefined` = still pending. */
|
|
168
|
+
slots?: (Output | undefined)[];
|
|
169
|
+
/** Fanout only — count of filled slots (completion bookkeeping), derived from
|
|
170
|
+
* `slots` by `foldFanoutCompletion`. Distinct from `index` (the next-unit
|
|
171
|
+
* pointer): parallel completion fills slots out of order, so this count is NOT
|
|
172
|
+
* a position. `undefined` until the first unit folds. */
|
|
173
|
+
filledCount?: number;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Pristine cursor for a live (non-resume) loop entry. */
|
|
177
|
+
export function freshCursor(): LoopCursor {
|
|
178
|
+
return { index: 0, accumulated: [], phase: "produce", ranThisInvocation: 0 };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Stable unit identity — `row.unitId`, the display tag, and the resume guard's join key. */
|
|
182
|
+
export const unitTagOf = (u: Unit): string => u.id ?? u.label;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* THE cursor state machine — the ONE place a completed unit's output advances
|
|
186
|
+
* a `LoopCursor`. Shared by the live driver (`dispatchUnit.onSuccess`) and the
|
|
187
|
+
* resume fold (`foldUnitRow`); THE REPLAY CONTRACT requires the two paths to
|
|
188
|
+
* advance byte-identically, so neither may hand-roll the transition again.
|
|
189
|
+
* `ranThisInvocation` is deliberately NOT advanced here: it is live-dispatch
|
|
190
|
+
* accounting (the resume silence rule), not replayed state.
|
|
191
|
+
*
|
|
192
|
+
* Takes the whole `LoopDef` (not just its `kind`) so the judge arm can read the
|
|
193
|
+
* assess loop's judge SLOT: a single judge sets `lastVerdict` directly (today's
|
|
194
|
+
* transition, byte-for-byte); a panel accumulates each member verdict and, on
|
|
195
|
+
* the LAST member, folds the N verdicts into the one decision the produce phase
|
|
196
|
+
* reads. The fold + `finalizeOutput` are pure, so live and resume — both of which
|
|
197
|
+
* call this from the durable member rows — manufacture an identical verdict.
|
|
198
|
+
*/
|
|
199
|
+
export function advanceCursor(cursor: LoopCursor, role: UnitRole, output: Output, loop: LoopDef): void {
|
|
200
|
+
if (role === "produce") {
|
|
201
|
+
advanceProduce(cursor, output, loop);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
advanceJudge(cursor, output, loop);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Produce arm of `advanceCursor`. A failed sentinel advances the index but is
|
|
209
|
+
* NOT the "last" produce, so `result:"last"` projects the last SUCCESSFUL
|
|
210
|
+
* output. DEFENSIVE only: ALL fanout (the sole producer of `failedOutput`)
|
|
211
|
+
* routes through `foldFanoutCompletion`, never `advanceCursor`, at every
|
|
212
|
+
* concurrency including 1 and on both live + resume; iterate/assess (which DO
|
|
213
|
+
* use advanceCursor) never collect-all. Keeps a future collect-all iterate kind
|
|
214
|
+
* from silently corrupting `lastProduce`.
|
|
215
|
+
*/
|
|
216
|
+
function advanceProduce(cursor: LoopCursor, output: Output, loop: LoopDef): void {
|
|
217
|
+
cursor.accumulated.push(output);
|
|
218
|
+
if (!isFailedOutput(output)) cursor.lastProduce = { output, artifact: output.artifacts[0] };
|
|
219
|
+
if (loop.kind === "assess") cursor.phase = "judge";
|
|
220
|
+
else cursor.index++;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Judge/verify arm of `advanceCursor` — assess loops only (the only kind with a judge phase). */
|
|
224
|
+
function advanceJudge(cursor: LoopCursor, output: Output, loop: LoopDef): void {
|
|
225
|
+
const slot = (loop as AssessLoop).judge;
|
|
226
|
+
if (isPanel(slot)) {
|
|
227
|
+
const verdicts = cursor.panel?.verdicts ?? [];
|
|
228
|
+
verdicts.push(output);
|
|
229
|
+
const memberIndex = cursor.panel?.memberIndex ?? 0;
|
|
230
|
+
if (memberIndex + 1 < slot.members.length) {
|
|
231
|
+
advancePanelMember(cursor, verdicts, memberIndex);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
foldPanelClose(cursor, slot, verdicts, output);
|
|
235
|
+
} else {
|
|
236
|
+
cursor.lastVerdict = output;
|
|
237
|
+
}
|
|
238
|
+
cursor.phase = "produce";
|
|
239
|
+
cursor.index++;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** More members to grade — stay in the judge phase, advance the member, keep the round (`index`) + `lastVerdict` untouched. */
|
|
243
|
+
function advancePanelMember(cursor: LoopCursor, verdicts: Output[], memberIndex: number): void {
|
|
244
|
+
cursor.panel = { memberIndex: memberIndex + 1, verdicts };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Last panel member — fold the N verdicts to the panel's decision (pure) and
|
|
249
|
+
* clear the sub-state. The folded verdict is what the produce phase's `done`
|
|
250
|
+
* reads, exactly where a single judge's verdict would sit.
|
|
251
|
+
*/
|
|
252
|
+
function foldPanelClose(cursor: LoopCursor, slot: PanelJudge, verdicts: readonly Output[], output: Output): void {
|
|
253
|
+
cursor.lastVerdict = foldPanelVerdict(slot, verdicts, output.meta);
|
|
254
|
+
cursor.panel = undefined;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Manufactured `Output.kind` for a panel's folded verdict — data-only, no artifact. */
|
|
258
|
+
const PANEL_VERDICT_KIND = "panel-verdict";
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Reduce a panel's N member verdicts to the single decision the produce phase
|
|
262
|
+
* reads. PURE (the author fold + `finalizeOutput` are pure) and DETERMINISTIC:
|
|
263
|
+
* reusing the last member's `meta` keeps the manufactured verdict byte-identical
|
|
264
|
+
* across live + resume (the member rows are the durable, replayed trail; a fresh
|
|
265
|
+
* `nowIso()` would break the replay contract). The folded Output carries NO
|
|
266
|
+
* artifact — it is routable decision DATA, not a file the loop projects (the
|
|
267
|
+
* fold publishes data, member reasoning lives on member channels).
|
|
268
|
+
*/
|
|
269
|
+
function foldPanelVerdict(panel: PanelJudge, verdicts: readonly Output[], meta: OutputMeta): Output {
|
|
270
|
+
return finalizeOutput({ kind: PANEL_VERDICT_KIND, artifacts: [], data: panel.fold(verdicts) }, meta);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Defensive read of `cursor.lastProduce` for cursor states that PROVE a
|
|
275
|
+
* completed produce precedes them (`phase === "judge"`, or `lastVerdict` set —
|
|
276
|
+
* both only reachable through `advanceCursor`, which assigns `lastProduce`
|
|
277
|
+
* first). The resume fold's deep shape guards (`readAllStagesForResume`,
|
|
278
|
+
* `guardRow`) refuse corrupted trails before they can rebuild such a cursor,
|
|
279
|
+
* so a miss here is an internal bug — surfaced as the runner's typed
|
|
280
|
+
* preflight error (stage-attributed JSONL row) instead of a bare `TypeError`.
|
|
281
|
+
*/
|
|
282
|
+
function lastProduceOf(cursor: LoopCursor, stage: string): NonNullable<LoopCursor["lastProduce"]> {
|
|
283
|
+
const lp = cursor.lastProduce;
|
|
284
|
+
if (!lp) {
|
|
285
|
+
const msg = MSG_LOOP_CURSOR_CORRUPT(stage, "no completed produce on the cursor");
|
|
286
|
+
throw invariantPreflight(stage, msg);
|
|
287
|
+
}
|
|
288
|
+
return lp;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Synthetic `produces` def a judge unit runs on: the verdict is validated +
|
|
293
|
+
* published by `judge.outcome`; `sessionPolicy: "fresh"` so it never replays
|
|
294
|
+
* the producer's branch. Parent validation knobs are DELIBERATELY not copied
|
|
295
|
+
* (judge sessions use framework defaults; a skill judge still picks up its
|
|
296
|
+
* own declared contract via `effectiveOutputSchema`). The ONE construction
|
|
297
|
+
* site — the resume fold reuses it for verdict publishing.
|
|
298
|
+
*/
|
|
299
|
+
export function judgeStageDef(judge: Judge): StageDef {
|
|
300
|
+
return { kind: "produces", outcome: judge.outcome, sessionPolicy: "fresh" };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Judge-unit display label + identity tag. A single judge keeps the bare
|
|
305
|
+
* `r{round}·judge` / `a{round}·verify` form (its identity is `(role, round)`, no
|
|
306
|
+
* `unitId`); a panel member appends `#{memberIndex}` so each member row is
|
|
307
|
+
* identity-bearing — the `(round, memberIndex)` key the resume drift join reads
|
|
308
|
+
* to tell members of the same round apart. The ONE construction site for both
|
|
309
|
+
* the live dispatch tag and the resume guard's expectation, so they can't drift.
|
|
310
|
+
*/
|
|
311
|
+
export function judgeUnitLabel(round: number, isVerify: boolean, memberIndex: number | undefined): string {
|
|
312
|
+
const base = isVerify ? `a${round}·verify` : `r${round}·judge`;
|
|
313
|
+
return memberIndex === undefined ? base : `${base}#${memberIndex}`;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The kind a loop PRESENTS to listeners and wording — `"verify"` for a
|
|
318
|
+
* verify-bearing stage (the author declared a post-condition, not a loop),
|
|
319
|
+
* the loop's own kind otherwise. Derived from the parent def, never from the
|
|
320
|
+
* loop object (the verify synthesis carries no marker), so live and resume
|
|
321
|
+
* can't disagree about flavoring.
|
|
322
|
+
*/
|
|
323
|
+
export const presentedKindOf = (def: StageDef, loop: LoopDef): "verify" | LoopDef["kind"] =>
|
|
324
|
+
def.verify ? "verify" : loop.kind;
|
|
325
|
+
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
// Strategy table
|
|
328
|
+
// ---------------------------------------------------------------------------
|
|
329
|
+
|
|
330
|
+
/** What the driver does next — produced by a strategy's `pull`. */
|
|
331
|
+
export type NextStep =
|
|
332
|
+
| { kind: "complete" }
|
|
333
|
+
| { kind: "cap"; count: number }
|
|
334
|
+
| {
|
|
335
|
+
kind: "unit";
|
|
336
|
+
role: UnitRole;
|
|
337
|
+
/** Display + identity tag (`unitId` for fanout/iterate; `r{n}·{phase}` display-only for assess). */
|
|
338
|
+
tag: string;
|
|
339
|
+
id?: string;
|
|
340
|
+
label: string;
|
|
341
|
+
skill: string;
|
|
342
|
+
prompt: string;
|
|
343
|
+
def: StageDef;
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* The slice of the fold's open generation a guard strategy reads — the
|
|
348
|
+
* fold's `OpenGeneration` satisfies it structurally. `expected` is the
|
|
349
|
+
* iterate strategy's pull-once-per-index cache (a failed row followed by its
|
|
350
|
+
* resumed re-run row re-checks the same expectation without double-pulling
|
|
351
|
+
* the generator); the strategy owns the field. `memberIndex` extends the join
|
|
352
|
+
* key to `(index, memberIndex)` for assess panels — within one round all member
|
|
353
|
+
* rows share `index`, so the member dimension is what tells them apart.
|
|
354
|
+
*/
|
|
355
|
+
export interface GenerationGuardCtx {
|
|
356
|
+
loop: LoopDef;
|
|
357
|
+
entryArtifact: Artifact | undefined;
|
|
358
|
+
cursor: LoopCursor;
|
|
359
|
+
units?: readonly Unit[];
|
|
360
|
+
expected?: { index: number; memberIndex?: number; tag: string | undefined };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** The unit-row facts a guard strategy compares against (a `WorkflowStage` row satisfies it). */
|
|
364
|
+
export interface UnitRowFacts {
|
|
365
|
+
role?: UnitRole;
|
|
366
|
+
unitId?: string;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** The resume point facts the announce probe reads (a `LoopResumePoint` satisfies it). */
|
|
370
|
+
export interface ResumeProbe {
|
|
371
|
+
cursor: LoopCursor;
|
|
372
|
+
entryArtifact: Artifact | undefined;
|
|
373
|
+
units?: readonly Unit[];
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The kind-invariant constants every loop strategy carries. Parallelizable
|
|
378
|
+
* kinds (fanout) implement ONLY this — their live entry, resume re-dispatch,
|
|
379
|
+
* and pending probe are all index-addressed (`runFanoutParallel` /
|
|
380
|
+
* `runFanoutResume` / `pendingFanoutIndices`), reached BEFORE any sequential
|
|
381
|
+
* method. The `SequentialStrategy` methods below are reached only on the
|
|
382
|
+
* non-parallelizable path, so giving fanout dead stubs for them "to keep the
|
|
383
|
+
* Record total" was an LSP/ISP smell — the split deletes the stubs and lets the
|
|
384
|
+
* compiler refuse `pull`/`guardExpectation`/`hasPending` on a parallel kind.
|
|
385
|
+
*/
|
|
386
|
+
export interface LoopKindStrategy {
|
|
387
|
+
/** Whether this kind's units are mutually independent and may be dispatched
|
|
388
|
+
* in bounded parallel (fanout only — iterate/assess consume the prior). When
|
|
389
|
+
* true, the kind routes through the index-addressed parallel path and NONE of
|
|
390
|
+
* the `SequentialStrategy` methods apply. */
|
|
391
|
+
parallelizable: boolean;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* The sequential (one-unit-per-pull) loop kinds — iterate and assess. They own
|
|
396
|
+
* the live next-step rule, the resume determinism re-check, and the resume
|
|
397
|
+
* announce probe; all three are entered only after fanout has routed to the
|
|
398
|
+
* parallel dispatcher (`step`, `guardRow`, and the announce all narrow fanout
|
|
399
|
+
* away first), so they live on this narrower contract, not on the base.
|
|
400
|
+
*/
|
|
401
|
+
export interface SequentialStrategy extends LoopKindStrategy {
|
|
402
|
+
parallelizable: false;
|
|
403
|
+
/**
|
|
404
|
+
* The live driver's next-step rule. Cap-check positions preserve pinned
|
|
405
|
+
* semantics: iterate checks POST-pull (the null terminator wins; the
|
|
406
|
+
* generator gets one extra discarded call), assess checks pre-round. For
|
|
407
|
+
* assess, a `done` verdict wins over the cap (a done loop is a normal
|
|
408
|
+
* completion, never a cap event).
|
|
409
|
+
*/
|
|
410
|
+
pull(e: LoopEntry, cursor: LoopCursor, cap: number, run: RunContext): Promise<NextStep>;
|
|
411
|
+
/**
|
|
412
|
+
* The resume fold's per-row determinism re-check, AFTER the kind-agnostic
|
|
413
|
+
* (role, unitIndex) arithmetic matched. Returns false on drift. May invoke
|
|
414
|
+
* user fns — a throw becomes drift in the caller (`guarded`).
|
|
415
|
+
*/
|
|
416
|
+
guardExpectation(gen: GenerationGuardCtx, row: UnitRowFacts, cwd: string, state: RunState): Promise<boolean>;
|
|
417
|
+
/**
|
|
418
|
+
* Resume re-entry pending-work probe — never dispatches; gates the
|
|
419
|
+
* announce only. The iterate arm re-pulls `next()` at the cursor (the
|
|
420
|
+
* driver pulls the same index again right after) — the harmless
|
|
421
|
+
* double-pull is safe because the resume contract requires generators to
|
|
422
|
+
* be deterministic.
|
|
423
|
+
*/
|
|
424
|
+
hasPending(loop: LoopDef, probe: ResumeProbe, run: RunContext): Promise<boolean>;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Place a fanout unit's output at its DECLARED index in both the cursor and the
|
|
428
|
+
* named channel. `cursor.filledCount` becomes the filled-slot count (completion);
|
|
429
|
+
* `cursor.index` is left untouched — it stays the next-unit pointer. `lastProduce`
|
|
430
|
+
* is the highest-index non-failed slot (deterministic — order-free, so live +
|
|
431
|
+
* resume + re-dispatch agree). */
|
|
432
|
+
export function foldFanoutCompletion(
|
|
433
|
+
state: RunState,
|
|
434
|
+
cursor: LoopCursor,
|
|
435
|
+
def: StageDef,
|
|
436
|
+
stageName: string,
|
|
437
|
+
index: number,
|
|
438
|
+
total: number,
|
|
439
|
+
output: Output,
|
|
440
|
+
): void {
|
|
441
|
+
if (!cursor.slots) cursor.slots = new Array<Output | undefined>(total);
|
|
442
|
+
cursor.slots[index] = output;
|
|
443
|
+
cursor.filledCount = cursor.slots.reduce<number>((n, s) => (s !== undefined ? n + 1 : n), 0);
|
|
444
|
+
cursor.lastProduce = lastNonFailedSlot(cursor.slots);
|
|
445
|
+
placeFanoutOutput(state, def, stageName, index, total, output);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Highest-index non-failed slot — the deterministic `result:"last"` source. */
|
|
449
|
+
function lastNonFailedSlot(slots: readonly (Output | undefined)[]): LoopCursor["lastProduce"] {
|
|
450
|
+
for (let i = slots.length - 1; i >= 0; i--) {
|
|
451
|
+
const o = slots[i];
|
|
452
|
+
if (o && !isFailedOutput(o)) return { output: o, artifact: o.artifacts[0] };
|
|
453
|
+
}
|
|
454
|
+
return undefined;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** THE fanout fail-fast narrow — `true` when a fanout loop opted out of the
|
|
458
|
+
* default collect-all via `fanout({ failFast: true })`. The ONE spelling of the
|
|
459
|
+
* kind+field guard the dispatcher (sibling-cancel) and `buildUnitSession`
|
|
460
|
+
* (`collectAll`) both read, so the narrow can't drift across its read sites. */
|
|
461
|
+
export const isFailFast = (loop: LoopDef): boolean => loop.kind === "fanout" && loop.failFast === true;
|
|
462
|
+
|
|
463
|
+
/** fanout units collect-all by default (opt out via fanout({ failFast: true }));
|
|
464
|
+
* the `kind === "fanout"` guard is LOAD-BEARING: iterate/assess units MUST NOT
|
|
465
|
+
* collect-all — they advance the cursor (advanceCursor), so a soft-halt sentinel
|
|
466
|
+
* would land in `accumulated` AND diverge live/resume (the resume fold skips the
|
|
467
|
+
* collected:true row). See `advanceProduce`'s defensive invariant. */
|
|
468
|
+
const shouldCollectAll = (loop: LoopDef): boolean => loop.kind === "fanout" && !isFailFast(loop);
|
|
469
|
+
|
|
470
|
+
/** Only fan-out units become individually-addressable lane sub-rows. A
|
|
471
|
+
* sequential loop unit (iterate/assess) leaves this undefined, so the host keys
|
|
472
|
+
* its live session on the single-unit slot — the lane (parent) row keeps showing
|
|
473
|
+
* it, exactly as the pre-change single slot did. `index` is the unit's declared
|
|
474
|
+
* fan-out index (the same value `unit.index` carries). */
|
|
475
|
+
const laneIndexFor = (loop: LoopDef, index: number): number | undefined => (loop.kind === "fanout" ? index : undefined);
|
|
476
|
+
|
|
477
|
+
/** Factored unit StageSession — shared by the sequential `dispatchUnit` (loop.ts)
|
|
478
|
+
* and the parallel `dispatchUnitDetached` (loop-parallel.ts); differs only in
|
|
479
|
+
* `onSuccess` and the threaded `signal`. Populates the per-child execution
|
|
480
|
+
* controls (lane/model/signal). The sequential path passes `run.signal`
|
|
481
|
+
* (run-level abort only); the detached path passes the per-generation
|
|
482
|
+
* `genAbort.signal` (run-level abort OR fail-fast sibling cancel). */
|
|
483
|
+
export function buildUnitSession(
|
|
484
|
+
e: LoopEntry,
|
|
485
|
+
u: Extract<NextStep, { kind: "unit" }>,
|
|
486
|
+
index: number,
|
|
487
|
+
run: RunContext,
|
|
488
|
+
snapshot: unknown,
|
|
489
|
+
signal: AbortSignal | undefined,
|
|
490
|
+
onSuccess: StageSession["onSuccess"],
|
|
491
|
+
): StageSession {
|
|
492
|
+
return {
|
|
493
|
+
cwd: run.cwd,
|
|
494
|
+
runId: run.runId,
|
|
495
|
+
state: run.state,
|
|
496
|
+
prompt: u.prompt,
|
|
497
|
+
stageName: decorateStage(e.name, u.tag), // DISPLAY only — machine identity is `unit`
|
|
498
|
+
skill: u.skill,
|
|
499
|
+
lifecycle: run.lifecycle,
|
|
500
|
+
runIdentity: runIdentityOf(run),
|
|
501
|
+
stage: u.def,
|
|
502
|
+
skillContracts: run.skillContracts,
|
|
503
|
+
stageIndex: e.stageIdx,
|
|
504
|
+
snapshot,
|
|
505
|
+
branchOffset: undefined,
|
|
506
|
+
unit: { parent: e.name, role: u.role, index, id: u.id, label: u.label },
|
|
507
|
+
model: run.resolveModel?.({ stage: e.name, skill: u.skill }),
|
|
508
|
+
signal,
|
|
509
|
+
collectAll: shouldCollectAll(e.loop),
|
|
510
|
+
laneUnitIndex: laneIndexFor(e.loop, index),
|
|
511
|
+
onFailure: undefined,
|
|
512
|
+
onSuccess,
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** The fanout unit descriptor at `index` — the shape the parallel dispatcher builds.
|
|
517
|
+
* `promptSuffix` is the resolved dep-artifact injection (`depArtifactSuffix`), appended
|
|
518
|
+
* to the unit prompt; "" for a deps-free unit or a fanout with no `depArtifactFlag`. */
|
|
519
|
+
export function fanoutUnitAt(e: LoopEntry, index: number, promptSuffix = ""): Extract<NextStep, { kind: "unit" }> {
|
|
520
|
+
const u = e.units![index]!;
|
|
521
|
+
const tag = unitTagOf(u);
|
|
522
|
+
return {
|
|
523
|
+
kind: "unit",
|
|
524
|
+
role: "produce",
|
|
525
|
+
tag,
|
|
526
|
+
id: tag,
|
|
527
|
+
label: u.label,
|
|
528
|
+
skill: e.skill,
|
|
529
|
+
// `promptSuffix` is produced by `depArtifactSuffix` (loop-parallel.ts:187) and
|
|
530
|
+
// appends `<depArtifactFlag> <dep-artifact-path>` for a deps-bearing fanout unit
|
|
531
|
+
// ("" otherwise). The flag itself is double-gated upstream: `checkedDepArtifactFlag`
|
|
532
|
+
// at construction (loop-constructors.ts:293) and `loop-dep-flag-invalid` at load
|
|
533
|
+
// (validate/stage-rules.ts:85, defined validate/issue.ts:121).
|
|
534
|
+
prompt: `/skill:${e.skill} ${u.prompt}${promptSuffix}`,
|
|
535
|
+
def: e.def,
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// Fanout carries ONLY `parallelizable`: its live entry (`runFanoutParallel`),
|
|
540
|
+
// resume re-dispatch (`runFanoutResume`), and pending probe
|
|
541
|
+
// (`pendingFanoutIndices`) are all index-addressed and reached before any
|
|
542
|
+
// sequential method — `step`/`guardRow`/the resume announce each route fanout to
|
|
543
|
+
// the parallel path first. The former `pull`/`guardExpectation`/`hasPending`
|
|
544
|
+
// stubs were dead at runtime; they're gone with the interface split.
|
|
545
|
+
const fanoutStrategy: LoopKindStrategy = {
|
|
546
|
+
parallelizable: true,
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
const iterateStrategy: SequentialStrategy = {
|
|
550
|
+
parallelizable: false,
|
|
551
|
+
async pull(e, cursor, cap, run) {
|
|
552
|
+
const loop = e.loop as IterateLoop;
|
|
553
|
+
const u = await loop.next({
|
|
554
|
+
cwd: run.cwd,
|
|
555
|
+
artifact: e.entryArtifact,
|
|
556
|
+
state: run.state,
|
|
557
|
+
accumulated: cursor.accumulated,
|
|
558
|
+
index: cursor.index,
|
|
559
|
+
});
|
|
560
|
+
if (!u) return { kind: "complete" };
|
|
561
|
+
if (cursor.accumulated.length >= cap) return { kind: "cap", count: cursor.accumulated.length };
|
|
562
|
+
const tag = unitTagOf(u);
|
|
563
|
+
return {
|
|
564
|
+
kind: "unit",
|
|
565
|
+
role: "produce",
|
|
566
|
+
tag,
|
|
567
|
+
id: tag,
|
|
568
|
+
label: u.label,
|
|
569
|
+
skill: e.skill,
|
|
570
|
+
prompt: `/skill:${e.skill} ${u.prompt}`,
|
|
571
|
+
def: e.def,
|
|
572
|
+
};
|
|
573
|
+
},
|
|
574
|
+
async guardExpectation(gen, row, cwd, state) {
|
|
575
|
+
if (!gen.expected || gen.expected.index !== gen.cursor.index) {
|
|
576
|
+
const u = await (gen.loop as IterateLoop).next({
|
|
577
|
+
cwd,
|
|
578
|
+
artifact: gen.entryArtifact,
|
|
579
|
+
state,
|
|
580
|
+
accumulated: gen.cursor.accumulated,
|
|
581
|
+
index: gen.cursor.index,
|
|
582
|
+
});
|
|
583
|
+
gen.expected = { index: gen.cursor.index, tag: u ? unitTagOf(u) : undefined };
|
|
584
|
+
}
|
|
585
|
+
// `tag: undefined` = the generator now terminates here, but a row exists — drift.
|
|
586
|
+
return gen.expected.tag === row.unitId;
|
|
587
|
+
},
|
|
588
|
+
async hasPending(loop, probe, run) {
|
|
589
|
+
const u = await (loop as IterateLoop).next({
|
|
590
|
+
cwd: run.cwd,
|
|
591
|
+
artifact: probe.entryArtifact,
|
|
592
|
+
state: run.state,
|
|
593
|
+
accumulated: probe.cursor.accumulated,
|
|
594
|
+
index: probe.cursor.index,
|
|
595
|
+
});
|
|
596
|
+
return u !== null && u !== undefined;
|
|
597
|
+
},
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
const assessStrategy: SequentialStrategy = {
|
|
601
|
+
parallelizable: false,
|
|
602
|
+
// Including a synthesized verify loop. Verify-ness is derived from the
|
|
603
|
+
// parent def (`e.def.verify`), never from the loop object: the synthesis
|
|
604
|
+
// carries no marker, so live and resume can't disagree about flavoring.
|
|
605
|
+
async pull(e, cursor, cap, run) {
|
|
606
|
+
const loop = e.loop as AssessLoop;
|
|
607
|
+
const isVerify = e.def.verify !== undefined;
|
|
608
|
+
if (cursor.phase === "judge") {
|
|
609
|
+
const lp = lastProduceOf(cursor, e.name); // a judge step always follows a completed produce
|
|
610
|
+
// Expand the judge slot to its members and dispatch the member the
|
|
611
|
+
// panel sub-state points at. A single judge is the panel of one
|
|
612
|
+
// (`memberIndex` undefined, member 0 the only member), so its transition
|
|
613
|
+
// is byte-identical to today; a panel walks member 0..N-1 across
|
|
614
|
+
// successive judge-phase pulls, `advanceCursor` bumping
|
|
615
|
+
// `cursor.panel.memberIndex` between them.
|
|
616
|
+
const memberIndex = isPanel(loop.judge) ? (cursor.panel?.memberIndex ?? 0) : undefined;
|
|
617
|
+
const judge = panelMembers(loop.judge)[memberIndex ?? 0]!;
|
|
618
|
+
const judgeSkill = judge.skill ?? (isVerify ? `${e.name}-verify` : `${e.name}-judge`);
|
|
619
|
+
let prompt: string;
|
|
620
|
+
if (judge.skill !== undefined) {
|
|
621
|
+
// produces-validation guarantees the producer emitted an artifact —
|
|
622
|
+
// a miss is the same corrupted-cursor class as a missing produce.
|
|
623
|
+
if (!lp.artifact) {
|
|
624
|
+
const msg = MSG_LOOP_CURSOR_CORRUPT(e.name, "judge skill dispatch found no produced artifact");
|
|
625
|
+
throw invariantPreflight(e.name, msg);
|
|
626
|
+
}
|
|
627
|
+
prompt = `/skill:${judge.skill} ${handleToString(lp.artifact.handle)}`;
|
|
628
|
+
} else {
|
|
629
|
+
prompt = await resolveJudgePrompt(judge.prompt!, {
|
|
630
|
+
cwd: run.cwd,
|
|
631
|
+
output: lp.output,
|
|
632
|
+
entryArtifact: e.entryArtifact,
|
|
633
|
+
state: run.state,
|
|
634
|
+
round: cursor.index,
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
const label = judgeUnitLabel(cursor.index, isVerify, memberIndex);
|
|
638
|
+
return {
|
|
639
|
+
kind: "unit",
|
|
640
|
+
role: isVerify ? "verify" : "judge",
|
|
641
|
+
tag: label,
|
|
642
|
+
// Panel member rows carry an `id` so they are identity-bearing for the
|
|
643
|
+
// resume join (`unitId` = the `#{memberIndex}` tag); a single judge keeps
|
|
644
|
+
// identity `(role, round)` with no `id`, exactly as before.
|
|
645
|
+
id: memberIndex === undefined ? undefined : label,
|
|
646
|
+
label,
|
|
647
|
+
skill: judgeSkill,
|
|
648
|
+
prompt,
|
|
649
|
+
def: judgeStageDef(judge),
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// produce — done wins over cap (one code path for live + resume fast-advance)
|
|
654
|
+
if (cursor.lastVerdict !== undefined && loop.done(cursor.lastVerdict)) return { kind: "complete" };
|
|
655
|
+
if (cursor.index >= cap) return { kind: "cap", count: cursor.index };
|
|
656
|
+
// Producer dispatch is skill XOR prompt (the judge arm's posture). For
|
|
657
|
+
// prompt dispatch the message is sent raw: round 0 resolves the stage's own
|
|
658
|
+
// `prompt` at dispatch time (re-resolved on resume — the PromptFn joins the
|
|
659
|
+
// loop determinism contract), and retry rounds send feedForward's output as
|
|
660
|
+
// the COMPLETE message (there is no skill to prefix an arg onto).
|
|
661
|
+
const isPrompt = e.def.prompt !== undefined;
|
|
662
|
+
// `lastVerdict` is only set by a completed judge, which also bumps `index` —
|
|
663
|
+
// so `index - 1 ≥ 0` whenever feedForward runs (round 0 takes entryArgs).
|
|
664
|
+
const arg =
|
|
665
|
+
cursor.lastVerdict !== undefined
|
|
666
|
+
? loop.feedForward({
|
|
667
|
+
cwd: run.cwd,
|
|
668
|
+
output: lastProduceOf(cursor, e.name).output,
|
|
669
|
+
verdict: cursor.lastVerdict,
|
|
670
|
+
round: cursor.index - 1,
|
|
671
|
+
state: run.state,
|
|
672
|
+
})
|
|
673
|
+
: isPrompt
|
|
674
|
+
? await resolveStagePrompt(e.def.prompt!, run.cwd, run.state)
|
|
675
|
+
: e.entryArgs;
|
|
676
|
+
const label = isVerify ? `a${cursor.index}·attempt` : `r${cursor.index}·produce`;
|
|
677
|
+
return {
|
|
678
|
+
kind: "unit",
|
|
679
|
+
role: "produce",
|
|
680
|
+
tag: label,
|
|
681
|
+
label,
|
|
682
|
+
skill: e.skill,
|
|
683
|
+
prompt: isPrompt ? arg : `/skill:${e.skill} ${arg}`,
|
|
684
|
+
def: e.def,
|
|
685
|
+
};
|
|
686
|
+
},
|
|
687
|
+
// The kind-agnostic (role, unitIndex) arithmetic already matched in the
|
|
688
|
+
// caller. Full-check extras:
|
|
689
|
+
// - a produce row for round n>0 implies done(verdict n-1) was false on the
|
|
690
|
+
// live run — a now-true done means the predicate drifted;
|
|
691
|
+
// - a PANEL judge/verify row carries its member index in `unitId`, the
|
|
692
|
+
// dimension the (role, unitIndex) check can't see — verify it matches the
|
|
693
|
+
// member the rebuilt sub-state expects, so a missing/reordered member row
|
|
694
|
+
// is drift, not a silently mis-folded verdict.
|
|
695
|
+
async guardExpectation(gen, row) {
|
|
696
|
+
const loop = gen.loop as AssessLoop; // assessStrategy ⇒ gen.loop is the assess arm by construction
|
|
697
|
+
if (row.role === "produce" && gen.cursor.lastVerdict !== undefined) {
|
|
698
|
+
return !loop.done(gen.cursor.lastVerdict);
|
|
699
|
+
}
|
|
700
|
+
const slot = loop.judge;
|
|
701
|
+
if ((row.role === "judge" || row.role === "verify") && isPanel(slot)) {
|
|
702
|
+
const memberIndex = gen.cursor.panel?.memberIndex ?? 0;
|
|
703
|
+
gen.expected = {
|
|
704
|
+
index: gen.cursor.index,
|
|
705
|
+
memberIndex,
|
|
706
|
+
tag: judgeUnitLabel(gen.cursor.index, row.role === "verify", memberIndex),
|
|
707
|
+
};
|
|
708
|
+
return gen.expected.tag === row.unitId;
|
|
709
|
+
}
|
|
710
|
+
return true;
|
|
711
|
+
},
|
|
712
|
+
// A pending judge always runs; a pending produce runs unless the
|
|
713
|
+
// recovered verdict is done (the driver's fast-advance path).
|
|
714
|
+
async hasPending(loop, probe) {
|
|
715
|
+
if (probe.cursor.phase === "judge") return true;
|
|
716
|
+
return !(probe.cursor.lastVerdict !== undefined && (loop as AssessLoop).done(probe.cursor.lastVerdict));
|
|
717
|
+
},
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* One strategy per kind — the `Record` shape turns "added a `LoopDef` arm,
|
|
722
|
+
* forgot the strategy" into a compile error. Keyed value types are preserved
|
|
723
|
+
* (fanout: base `LoopKindStrategy`; iterate/assess: `SequentialStrategy`) so
|
|
724
|
+
* `sequentialStrategyOf` hands back the narrower contract.
|
|
725
|
+
*/
|
|
726
|
+
export const LOOP_STRATEGIES = {
|
|
727
|
+
fanout: fanoutStrategy,
|
|
728
|
+
iterate: iterateStrategy,
|
|
729
|
+
assess: assessStrategy,
|
|
730
|
+
} satisfies Record<LoopDef["kind"], LoopKindStrategy>;
|
|
731
|
+
|
|
732
|
+
/** Base-contract accessor — all `parallelizable` reads (loop.ts route choice). */
|
|
733
|
+
export const loopStrategyOf = (kind: LoopDef["kind"]): LoopKindStrategy => LOOP_STRATEGIES[kind];
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* Sequential-contract accessor for the live `step()` next-step rule, the resume
|
|
737
|
+
* `guardRow` re-check, and the resume announce probe — paths reached ONLY after
|
|
738
|
+
* fanout has routed to the index-addressed parallel dispatcher. The runtime
|
|
739
|
+
* guard makes a future routing regression fail loudly here instead of silently
|
|
740
|
+
* mis-typing a parallelizable strategy; the cast is the one place the
|
|
741
|
+
* never-fanout invariant is asserted (replacing the dead per-method stubs).
|
|
742
|
+
*/
|
|
743
|
+
export function sequentialStrategyOf(kind: LoopDef["kind"]): SequentialStrategy {
|
|
744
|
+
const s = LOOP_STRATEGIES[kind];
|
|
745
|
+
if (s.parallelizable) {
|
|
746
|
+
const msg = MSG_LOOP_CURSOR_CORRUPT(kind, `sequential driver entered for parallelizable kind "${kind}"`);
|
|
747
|
+
throw invariantPreflight(kind, msg);
|
|
748
|
+
}
|
|
749
|
+
return s as SequentialStrategy;
|
|
750
|
+
}
|