@juicesharp/rpiv-workflow 1.20.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +98 -545
  2. package/api.ts +1 -1
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +18 -0
  5. package/audit.ts +119 -164
  6. package/built-ins.ts +26 -6
  7. package/chain-state.ts +119 -68
  8. package/command-run.ts +35 -30
  9. package/command.ts +10 -4
  10. package/docs/embedding.md +341 -0
  11. package/docs/workflow-authoring.md +70 -16
  12. package/docs/workflow-basics.md +125 -10
  13. package/events.ts +44 -4
  14. package/execution-host.ts +75 -0
  15. package/host.ts +137 -82
  16. package/internal-utils.ts +89 -3
  17. package/internal.ts +1 -0
  18. package/judge.ts +23 -11
  19. package/load/alias.ts +3 -3
  20. package/load/index.ts +15 -1
  21. package/load/issues.ts +2 -2
  22. package/load/legacy.ts +2 -2
  23. package/load/resolve-default.ts +3 -4
  24. package/load/skill-contract-phase.ts +1 -1
  25. package/loop-constructors.ts +19 -618
  26. package/loop-def.ts +60 -15
  27. package/loop-kinds.ts +319 -62
  28. package/loop-parallel.ts +250 -0
  29. package/loop-waves.ts +99 -0
  30. package/loop.ts +106 -80
  31. package/loops/constructors.ts +334 -0
  32. package/loops/derivations.ts +65 -0
  33. package/loops/introspection.ts +184 -0
  34. package/loops/panel.ts +196 -0
  35. package/loops/verify.ts +99 -0
  36. package/messages.ts +58 -33
  37. package/outcomes/collectors/index.ts +1 -0
  38. package/outcomes/collectors/text-scan.ts +47 -0
  39. package/outcomes/collectors/transcript-path.ts +2 -15
  40. package/outcomes/collectors/union.ts +2 -1
  41. package/outcomes/collectors/url.ts +2 -14
  42. package/outcomes/collectors/workspace-diff.ts +1 -1
  43. package/outcomes/git-commit.ts +57 -6
  44. package/output-spec.ts +1 -1
  45. package/output.ts +59 -1
  46. package/package.json +19 -6
  47. package/preview.ts +18 -18
  48. package/registration.ts +11 -4
  49. package/routing-dsl.ts +53 -41
  50. package/routing.ts +46 -0
  51. package/runner/chain-advance.ts +30 -17
  52. package/runner/errors.ts +7 -30
  53. package/runner/failure.ts +67 -13
  54. package/runner/input-validation.ts +8 -5
  55. package/runner/preflight.ts +17 -21
  56. package/runner/resume-entry.ts +23 -3
  57. package/runner/resume-loop.ts +50 -29
  58. package/runner/resume.ts +96 -10
  59. package/runner/run-context.ts +20 -16
  60. package/runner/run-stage.ts +125 -91
  61. package/runner/runner.ts +163 -69
  62. package/runner/script-stage.ts +23 -29
  63. package/schema-compat.ts +1 -2
  64. package/semaphore.ts +55 -0
  65. package/sessions/extraction.ts +103 -60
  66. package/sessions/halt-routing.ts +195 -0
  67. package/sessions/index.ts +2 -2
  68. package/sessions/locate.ts +60 -9
  69. package/sessions/reattach.ts +28 -20
  70. package/sessions/sessions.ts +103 -191
  71. package/sessions/spawn.ts +132 -119
  72. package/sessions/success-persist.ts +89 -0
  73. package/skill-contracts/composition.ts +8 -10
  74. package/skill-contracts/harvest.ts +3 -2
  75. package/skill-contracts/registry.ts +1 -1
  76. package/stage-def.ts +115 -47
  77. package/stage-errors.ts +84 -0
  78. package/stage-identity.ts +56 -0
  79. package/startup.ts +1 -0
  80. package/state/paths.ts +11 -3
  81. package/state/raw.ts +2 -3
  82. package/state/resolve.ts +3 -3
  83. package/state/state.ts +26 -3
  84. package/state/writes.ts +1 -1
  85. package/types.ts +97 -43
  86. package/validate/contract-compat.ts +16 -11
  87. package/validate/graph.ts +10 -1
  88. package/validate/issue.ts +20 -6
  89. package/validate/stage-rules.ts +139 -60
  90. package/validate-output.ts +27 -20
  91. package/validate-workflow.ts +5 -3
  92. package/validation-bounds.ts +35 -0
  93. package/docs/cover.png +0 -0
  94. package/docs/cover.svg +0 -120
  95. package/load/cache.test.ts +0 -82
  96. package/load/shape-guards.test.ts +0 -77
  97. package/outcomes/collectors/directory-path.test.ts +0 -64
  98. package/outcomes/collectors/tool-call.test.ts +0 -112
  99. package/outcomes/collectors/transcript-path.test.ts +0 -70
  100. package/outcomes/collectors/union.test.ts +0 -113
  101. package/outcomes/collectors/url.test.ts +0 -67
  102. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  103. package/outcomes/git-commit.test.ts +0 -240
  104. package/outcomes/parsers/json-body.test.ts +0 -80
  105. package/runner/by-name.test.ts +0 -95
  106. package/runner/by-run-id.test.ts +0 -115
  107. package/runner/header-write-failure.test.ts +0 -64
  108. package/runner/resume-loop.test.ts +0 -1410
  109. package/runner/resume-session.test.ts +0 -400
  110. package/runner/resume.test.ts +0 -1805
  111. package/sessions/locate.test.ts +0 -77
package/loop-def.ts CHANGED
@@ -24,6 +24,16 @@ export interface Unit {
24
24
  prompt: string;
25
25
  label: string;
26
26
  id?: string;
27
+ /**
28
+ * Fanout only — the `id ?? label` identities of the units this unit depends
29
+ * on. The wave scheduler topologically orders dispatch over these directed
30
+ * edges: a unit dispatches only after every unit it lists here has completed
31
+ * (its slot filled). Absent/empty ⇒ a root (wave 0). A reference that matches
32
+ * no unit's `id ?? label`, or any cycle, halts the stage at the live entry
33
+ * (`validateUnitDeps`). Ignored by the sequential kinds (iterate/assess
34
+ * consume the prior unit, so ordering is implicit).
35
+ */
36
+ deps?: readonly string[];
27
37
  }
28
38
 
29
39
  /**
@@ -133,14 +143,16 @@ export interface JudgedRepetition {
133
143
  * would be byte-identical to the original and the model would have no
134
144
  * signal about why it failed); never called when `max` is 1.
135
145
  *
136
- * Runtime: the runner desugars the field into a degenerate assess loop
137
- * (`max: max ?? 1`, `onCap: "halt"`, `result: "last"`) run by the ONE loop
138
- * driver. Attempts and verdicts land as unit rows (`role: "produce"` /
139
- * `role: "verify"`, `unitIndex` = 0-based attempt); the verdict publishes
140
- * durably to `state.named[judge.outcome.name]` (so declarative fallback
141
- * routing over `EdgeContext.state.named` works); and `projectResult`
142
- * restores the last attempt's producer pair before the chain advances —
143
- * downstream stages never inherit the verdict.
146
+ * Runtime: the runner desugars the field into a degenerate assess loop run by
147
+ * the ONE loop driver. The desugar's gate-only defaults (`max`, `onCap`,
148
+ * `result`) are spelled ONCE in `VERIFY_LOOP_DEFAULTS` (loop-constructors.ts) —
149
+ * the named peer to `LOOP_DEFAULTS` (verify is not a `LoopDef["kind"]`) —
150
+ * and consulted by `synthesizeVerifyLoop`. Attempts and verdicts land as unit
151
+ * rows (`role: "produce"` / `role: "verify"`, `unitIndex` = 0-based attempt);
152
+ * the verdict publishes durably to `state.named[judge.outcome.name]` (so
153
+ * declarative fallback routing over `EdgeContext.state.named` works); and
154
+ * `projectResult` restores the last attempt's producer pair before the chain
155
+ * advances — downstream stages never inherit the verdict.
144
156
  */
145
157
  export type VerifySpec = JudgedRepetition;
146
158
 
@@ -163,12 +175,15 @@ export type CapPolicy = "halt" | "advance";
163
175
  /**
164
176
  * What the loop leaves in `{state.output, state.primaryArtifact}` — the PAIR
165
177
  * is governed as one (routing + downstream prompts read both):
166
- * `"entry"` — restore the pair captured at loop entry (fanout default;
167
- * reproduces routing-sees-upstream);
168
- * `"last"` — the last completed `role: "produce"` unit's pair (iterate /
169
- * assess default; zero produce units degrades to entry).
170
- * Applied at ONE point — loop advance — by the live driver and the resume
171
- * fold's generation close identically. Mid-loop transient rolls are accepted.
178
+ * `"entry"` — restore the pair captured at loop entry;
179
+ * `"last"` — the last completed `role: "produce"` unit's pair (zero produce
180
+ * units degrades to entry).
181
+ * The per-kind default (`entry` for fanout, `last` for iterate/assess) is
182
+ * spelled ONCE in `LOOP_DEFAULTS` (loop-constructors.ts) and consulted by each
183
+ * constructor via `firstDefined` — see that table rather than re-stating the
184
+ * per-kind literal here. Applied at ONE point — loop advance — by the live
185
+ * driver and the resume fold's generation close identically. Mid-loop
186
+ * transient rolls are accepted.
172
187
  */
173
188
  export type ResultProjection = "entry" | "last";
174
189
 
@@ -195,10 +210,40 @@ interface LoopCommon {
195
210
  result: ResultProjection;
196
211
  }
197
212
 
198
- /** Parallel-shaped push loop (units still run sequentially today). */
213
+ /** Parallel-shaped push loop — units run in bounded parallel (maxConcurrency). */
199
214
  export interface FanoutLoop extends LoopCommon {
200
215
  kind: "fanout";
201
216
  units: FanoutFn;
217
+ /** Per-fanout concurrency ceiling. Caps in-flight units to
218
+ * `min(concurrency, host maxConcurrency)`; `1` SERIALIZES the loop — the safe
219
+ * model for a stage that mutates SHARED state (e.g. `implement` applying a plan
220
+ * to one working tree, where parallel phases race on a shared file and a
221
+ * dependent phase can run before its prerequisite has landed). Absent ⇒ the host
222
+ * cap governs. Must be an integer ≥ 1 (validated at construction + load). */
223
+ concurrency?: number;
224
+ /** Opt out of collect-all: any unit failure halts the run. Default (absent) ⇒
225
+ * collect-all. Under parallel dispatch, the first failing unit halts the
226
+ * run terminally AND cancels in-flight siblings via the per-generation
227
+ * `genAbort` controller: the worker that records the terminal failure fires
228
+ * `genAbort.abort()`, which `session.abort()`s every still-running sibling and
229
+ * drains queued units from the semaphore. Cancelled siblings leave unfilled
230
+ * slots (no row written), so a terminally-failed run that is later resumed
231
+ * re-dispatches them. `genAbort` is also driven by run-level abort (Ctrl-C /
232
+ * `run.signal`), so the same machinery serves both. */
233
+ failFast?: boolean;
234
+ /**
235
+ * When set, the dispatcher injects each completed dependency's published
236
+ * artifact path into the dependent unit's prompt as `${depArtifactFlag} <path>`
237
+ * (one per direct `Unit.deps` entry whose slot is filled with a non-failed
238
+ * output). Pairs with `Unit.deps`: deps order the waves, this flag hands the
239
+ * dependent the upstream artifact to read (build `design` sets `"--upstream"`
240
+ * so a dependent slice reads its dependency's decided Key Interfaces). A
241
+ * failed/sentinel dep slot is skipped — the dependent designs blind for that
242
+ * dep, exactly as today. Engine-generic: the flag string is data; the engine
243
+ * knows nothing of the consuming skill. Validated non-empty at construction +
244
+ * load.
245
+ */
246
+ depArtifactFlag?: string;
202
247
  }
203
248
 
204
249
  /** Sequential accumulating pull loop. */
package/loop-kinds.ts CHANGED
@@ -1,17 +1,22 @@
1
1
  /**
2
2
  * loop-kinds.ts — the per-loop-kind vocabulary and strategy table.
3
3
  *
4
- * Everything that varies BY KIND across the loop machinery lives here, in
5
- * one `Record<LoopDef["kind"], LoopKindStrategy>`:
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:
6
9
  * - `pull` — the live driver's next-step rule (loop.ts `step`);
7
10
  * - `guardExpectation` — the resume fold's per-row determinism re-check
8
11
  * (runner/resume.ts `guardRow`);
9
12
  * - `hasPending` — the resume re-entry announce probe
10
13
  * (runner/resume-loop.ts).
11
- * A new loop kind (`panel` is hinted) extends the `LoopDef` union and this
12
- * table — the `Record` shape makes a missing strategy a compile error — and
13
- * touches nothing else: dispatch, persistence, cap policy, projection, and
14
- * completion are kind-agnostic in 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.
15
20
  *
16
21
  * Also home to the kind-agnostic cursor vocabulary the live driver and the
17
22
  * fold share: `LoopCursor`, `advanceCursor` (THE cursor state machine),
@@ -19,13 +24,18 @@
19
24
  */
20
25
 
21
26
  import type { AssessLoop, IterateLoop, LoopDef, StageDef, Unit, UnitRole } from "./api.js";
22
- import { resolveStagePrompt } from "./chain-state.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";
23
33
  import { type Artifact, handleToString } from "./handle.js";
24
34
  import { isPanel, type Judge, type PanelJudge, panelMembers, resolveJudgePrompt } from "./judge.js";
25
35
  import { MSG_LOOP_CURSOR_CORRUPT } from "./messages.js";
26
- import { finalizeOutput, type Output, type OutputMeta } from "./output.js";
27
- import { StagePreflightError } from "./runner/errors.js";
28
- import type { RunContext, RunState } from "./types.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";
29
39
 
30
40
  // ---------------------------------------------------------------------------
31
41
  // Cursor + entry vocabulary (kind-agnostic, shared live + fold)
@@ -59,6 +69,77 @@ export interface LoopEntry {
59
69
  units?: readonly Unit[];
60
70
  }
61
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
+
62
143
  /** Mutable generation cursor threaded through the continuation self-calls. */
63
144
  export interface LoopCursor {
64
145
  /** 0-based index of the NEXT unit (== the round for assess). */
@@ -82,6 +163,14 @@ export interface LoopCursor {
82
163
  panel?: { memberIndex: number; verdicts: Output[] };
83
164
  /** Units dispatched by THIS driver invocation — the resume silence rule. */
84
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;
85
174
  }
86
175
 
87
176
  /** Pristine cursor for a live (non-resume) loop entry. */
@@ -109,30 +198,40 @@ export const unitTagOf = (u: Unit): string => u.id ?? u.label;
109
198
  */
110
199
  export function advanceCursor(cursor: LoopCursor, role: UnitRole, output: Output, loop: LoopDef): void {
111
200
  if (role === "produce") {
112
- cursor.accumulated.push(output);
113
- cursor.lastProduce = { output, artifact: output.artifacts[0] };
114
- if (loop.kind === "assess") cursor.phase = "judge";
115
- else cursor.index++;
201
+ advanceProduce(cursor, output, loop);
116
202
  return;
117
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
+ }
118
222
 
119
- // judge / verify role — assess loops only (the only kind with a judge phase).
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 {
120
225
  const slot = (loop as AssessLoop).judge;
121
226
  if (isPanel(slot)) {
122
227
  const verdicts = cursor.panel?.verdicts ?? [];
123
228
  verdicts.push(output);
124
229
  const memberIndex = cursor.panel?.memberIndex ?? 0;
125
230
  if (memberIndex + 1 < slot.members.length) {
126
- // More members to grade — stay in the judge phase, advance the member,
127
- // keep the round (`index`) + `lastVerdict` untouched.
128
- cursor.panel = { memberIndex: memberIndex + 1, verdicts };
231
+ advancePanelMember(cursor, verdicts, memberIndex);
129
232
  return;
130
233
  }
131
- // Last member — fold the N verdicts to the panel's decision (pure) and
132
- // clear the sub-state. The folded verdict is what the produce phase's
133
- // `done` reads, exactly where a single judge's verdict would sit.
134
- cursor.lastVerdict = foldPanelVerdict(slot, verdicts, output.meta);
135
- cursor.panel = undefined;
234
+ foldPanelClose(cursor, slot, verdicts, output);
136
235
  } else {
137
236
  cursor.lastVerdict = output;
138
237
  }
@@ -140,6 +239,21 @@ export function advanceCursor(cursor: LoopCursor, role: UnitRole, output: Output
140
239
  cursor.index++;
141
240
  }
142
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
+
143
257
  /** Manufactured `Output.kind` for a panel's folded verdict — data-only, no artifact. */
144
258
  const PANEL_VERDICT_KIND = "panel-verdict";
145
259
 
@@ -149,8 +263,8 @@ const PANEL_VERDICT_KIND = "panel-verdict";
149
263
  * reusing the last member's `meta` keeps the manufactured verdict byte-identical
150
264
  * across live + resume (the member rows are the durable, replayed trail; a fresh
151
265
  * `nowIso()` would break the replay contract). The folded Output carries NO
152
- * artifact — it is routable decision DATA, not a file the loop projects (§5
153
- * boundary: the fold publishes data, member reasoning lives on member channels).
266
+ * artifact — it is routable decision DATA, not a file the loop projects (the
267
+ * fold publishes data, member reasoning lives on member channels).
154
268
  */
155
269
  function foldPanelVerdict(panel: PanelJudge, verdicts: readonly Output[], meta: OutputMeta): Output {
156
270
  return finalizeOutput({ kind: PANEL_VERDICT_KIND, artifacts: [], data: panel.fold(verdicts) }, meta);
@@ -169,7 +283,7 @@ function lastProduceOf(cursor: LoopCursor, stage: string): NonNullable<LoopCurso
169
283
  const lp = cursor.lastProduce;
170
284
  if (!lp) {
171
285
  const msg = MSG_LOOP_CURSOR_CORRUPT(stage, "no completed produce on the cursor");
172
- throw new StagePreflightError("invariant", stage, msg, msg, false);
286
+ throw invariantPreflight(stage, msg);
173
287
  }
174
288
  return lp;
175
289
  }
@@ -259,13 +373,39 @@ export interface ResumeProbe {
259
373
  units?: readonly Unit[];
260
374
  }
261
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
+ */
262
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;
263
403
  /**
264
404
  * The live driver's next-step rule. Cap-check positions preserve pinned
265
405
  * semantics: iterate checks POST-pull (the null terminator wins; the
266
- * generator gets one extra discarded call), assess checks pre-round,
267
- * fanout checks pre-index. For assess, a `done` verdict wins over the cap
268
- * (a done loop is a normal completion, never a cap event).
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).
269
409
  */
270
410
  pull(e: LoopEntry, cursor: LoopCursor, cap: number, run: RunContext): Promise<NextStep>;
271
411
  /**
@@ -284,34 +424,130 @@ export interface LoopKindStrategy {
284
424
  hasPending(loop: LoopDef, probe: ResumeProbe, run: RunContext): Promise<boolean>;
285
425
  }
286
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.
287
545
  const fanoutStrategy: LoopKindStrategy = {
288
- async pull(e, cursor, cap) {
289
- const units = e.units!; // runLoopStage computed it (empty list never reaches the driver)
290
- if (cursor.index >= units.length) return { kind: "complete" };
291
- if (cursor.index >= cap) return { kind: "cap", count: cursor.index };
292
- const u = units[cursor.index]!;
293
- const tag = unitTagOf(u);
294
- return {
295
- kind: "unit",
296
- role: "produce",
297
- tag,
298
- id: tag,
299
- label: u.label,
300
- skill: e.skill,
301
- prompt: `/skill:${e.skill} ${u.prompt}`,
302
- def: e.def,
303
- };
304
- },
305
- async guardExpectation(gen, row) {
306
- if (!gen.units || gen.cursor.index >= gen.units.length) return false;
307
- return unitTagOf(gen.units[gen.cursor.index]!) === row.unitId;
308
- },
309
- async hasPending(_loop, probe) {
310
- return probe.cursor.index < (probe.units?.length ?? 0);
311
- },
546
+ parallelizable: true,
312
547
  };
313
548
 
314
- const iterateStrategy: LoopKindStrategy = {
549
+ const iterateStrategy: SequentialStrategy = {
550
+ parallelizable: false,
315
551
  async pull(e, cursor, cap, run) {
316
552
  const loop = e.loop as IterateLoop;
317
553
  const u = await loop.next({
@@ -361,7 +597,8 @@ const iterateStrategy: LoopKindStrategy = {
361
597
  },
362
598
  };
363
599
 
364
- const assessStrategy: LoopKindStrategy = {
600
+ const assessStrategy: SequentialStrategy = {
601
+ parallelizable: false,
365
602
  // Including a synthesized verify loop. Verify-ness is derived from the
366
603
  // parent def (`e.def.verify`), never from the loop object: the synthesis
367
604
  // carries no marker, so live and resume can't disagree about flavoring.
@@ -385,7 +622,7 @@ const assessStrategy: LoopKindStrategy = {
385
622
  // a miss is the same corrupted-cursor class as a missing produce.
386
623
  if (!lp.artifact) {
387
624
  const msg = MSG_LOOP_CURSOR_CORRUPT(e.name, "judge skill dispatch found no produced artifact");
388
- throw new StagePreflightError("invariant", e.name, msg, msg, false);
625
+ throw invariantPreflight(e.name, msg);
389
626
  }
390
627
  prompt = `/skill:${judge.skill} ${handleToString(lp.artifact.handle)}`;
391
628
  } else {
@@ -456,10 +693,11 @@ const assessStrategy: LoopKindStrategy = {
456
693
  // member the rebuilt sub-state expects, so a missing/reordered member row
457
694
  // is drift, not a silently mis-folded verdict.
458
695
  async guardExpectation(gen, row) {
696
+ const loop = gen.loop as AssessLoop; // assessStrategy ⇒ gen.loop is the assess arm by construction
459
697
  if (row.role === "produce" && gen.cursor.lastVerdict !== undefined) {
460
- return !(gen.loop as AssessLoop).done(gen.cursor.lastVerdict);
698
+ return !loop.done(gen.cursor.lastVerdict);
461
699
  }
462
- const slot = (gen.loop as AssessLoop).judge;
700
+ const slot = loop.judge;
463
701
  if ((row.role === "judge" || row.role === "verify") && isPanel(slot)) {
464
702
  const memberIndex = gen.cursor.panel?.memberIndex ?? 0;
465
703
  gen.expected = {
@@ -481,13 +719,32 @@ const assessStrategy: LoopKindStrategy = {
481
719
 
482
720
  /**
483
721
  * One strategy per kind — the `Record` shape turns "added a `LoopDef` arm,
484
- * forgot the strategy" into a compile error. (`FanoutLoop` has no
485
- * strategy-specific fields beyond `units`, read off `LoopEntry`.)
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.
486
725
  */
487
- export const LOOP_STRATEGIES: Record<LoopDef["kind"], LoopKindStrategy> = {
726
+ export const LOOP_STRATEGIES = {
488
727
  fanout: fanoutStrategy,
489
728
  iterate: iterateStrategy,
490
729
  assess: assessStrategy,
491
- };
730
+ } satisfies Record<LoopDef["kind"], LoopKindStrategy>;
492
731
 
732
+ /** Base-contract accessor — all `parallelizable` reads (loop.ts route choice). */
493
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
+ }