@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.
Files changed (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
@@ -0,0 +1,250 @@
1
+ /**
2
+ * loop-parallel.ts — bounded-parallel, dependency-ordered fanout dispatch. Fanout
3
+ * units fold into the cursor in DECLARED (index) order through `foldFanoutCompletion`
4
+ * — never completion order — so `fanin` synthesis + resume stay deterministic at every
5
+ * concurrency (Semaphore(1) just serializes). When units declare `Unit.deps`, the
6
+ * scheduler dispatches in Kahn TOPOLOGICAL LEVELS (`computeWaveLevels`, loop-waves.ts):
7
+ * one bounded-parallel wave per level, a dependent never opening before the units it
8
+ * depends on have filled their slots. A deps-free fanout has ONE level — byte-identical
9
+ * to the pre-wave flat dispatch.
10
+ *
11
+ * CONCURRENCY MODEL — what is and isn't fold-confined. ONLY the `LoopCursor`
12
+ * (`slots`/`filledCount`/`lastProduce`) is mutated exclusively by the serial
13
+ * post-`allSettled` fold below. `run.state` is NOT: each worker's `postStage` mutates
14
+ * `lastAllocatedStageNumber`, `stagesCompleted`, `output`, `primaryArtifact`
15
+ * CONCURRENTLY across siblings. That is safe — every such mutator is a synchronous,
16
+ * `await`-free read-modify-write (JS run-to-completion makes each atomic), and every
17
+ * order-sensitive result is re-derived by the index-addressed fold or overwritten by
18
+ * `projectResult` at close.
19
+ *
20
+ * `runFanoutWaves` is the ONE orchestrator both the live entry (`runFanoutParallel`)
21
+ * and the resume re-dispatch (`runFanoutResume`) — both thin wrappers in loop.ts —
22
+ * degenerate to: each passes its `active` operand set (live: `0..dispatchCount-1`;
23
+ * resume: the still-pending indices) and a `finalTail` for the path-specific completion
24
+ * (live: hitCap-vs-finishLoop on the cap; resume: always finishLoop). It owns ONE
25
+ * per-generation `genAbort` across every wave (so a fail-fast halt or run-abort in wave
26
+ * k cancels in-flight siblings AND prevents wave k+1), computes the levels, intersects
27
+ * each with `active`, and runs `dispatchWave` per non-empty level.
28
+ *
29
+ * This module is a downward leaf: it consumes the shared loop foundation
30
+ * (`loop-kinds.ts`, `loop-waves.ts`) and never imports loop.ts back (loop.ts → here only).
31
+ */
32
+
33
+ import { decorateStage } from "./audit.js";
34
+ import { lifecycleCtxFor, skillStageRef } from "./events.js";
35
+ import { handleToString } from "./handle.js";
36
+ import { isAbortError, nowIso, WorkflowAbortError } from "./internal-utils.js";
37
+ import {
38
+ buildUnitSession,
39
+ fanoutUnitAt,
40
+ foldFanoutCompletion,
41
+ isFailFast,
42
+ type LoopCursor,
43
+ type LoopDeps,
44
+ type LoopEntry,
45
+ type NextStep,
46
+ } from "./loop-kinds.js";
47
+ import { computeWaveLevels, unitIdIndex } from "./loop-waves.js";
48
+ import { failedOutput, isFailedOutput, type Output, type OutputMeta, outputMeta } from "./output.js";
49
+ import { Semaphore } from "./semaphore.js";
50
+ import type { RunContext, UnitRef, WorkflowHostContext } from "./types.js";
51
+
52
+ /** Structured identity for fanout unit `i` — carried on a worker-throw failure
53
+ * row (`recordWorkerThrow`) so the unit's identity lands in the row's structured
54
+ * `unit*` fields instead of being folded into the `stage` name string. */
55
+ const fanoutUnitRef = (e: LoopEntry, i: number): UnitRef => {
56
+ const u = fanoutUnitAt(e, i);
57
+ return { parent: e.name, role: u.role, index: i, id: u.id, label: u.label };
58
+ };
59
+
60
+ /**
61
+ * THE wave orchestrator — owns ONE per-generation `AbortController` across every
62
+ * topological level. Computes Kahn levels over the full unit list, intersects each
63
+ * with `active` (live: the first-cap indices; resume: the still-pending indices), and
64
+ * dispatches the non-empty levels in order. The LAST active level runs `finalTail`
65
+ * (live: hitCap-vs-finishLoop; resume: finishLoop); intermediate levels just settle.
66
+ *
67
+ * The `genAbort` fires on EITHER (a) run-level abort (Ctrl-C, `run.signal` — propagated
68
+ * below) OR (b) the first fail-fast unit halt inside `dispatchWave`. The listener is
69
+ * dropped BEFORE `finalTail` (which runs the downstream chain) so it never accumulates
70
+ * across stages. Levels are computed BEFORE the listener is wired, so a defensive
71
+ * cycle-throw from `computeWaveLevels` can't leak it.
72
+ */
73
+ export async function runFanoutWaves(
74
+ curCtx: WorkflowHostContext,
75
+ e: LoopEntry,
76
+ cursor: LoopCursor,
77
+ run: RunContext,
78
+ deps: LoopDeps,
79
+ active: readonly number[],
80
+ finalTail: () => Promise<void> | void,
81
+ ): Promise<void> {
82
+ const activeSet = new Set(active);
83
+ const waves = computeWaveLevels(e.units!, e.name)
84
+ .map((level) => level.filter((i) => activeSet.has(i)))
85
+ .filter((level) => level.length > 0);
86
+ // Resolve the dep→artifact identity map once (only when the flag is set).
87
+ const idToIndex = e.loop.kind === "fanout" && e.loop.depArtifactFlag ? unitIdIndex(e.units!) : undefined;
88
+ // No active units (e.g. a resume with everything already filled) — still close the
89
+ // loop via the tail (projection + advance), matching today's empty/all-done path.
90
+ if (waves.length === 0) return finalTail();
91
+
92
+ const genAbort = new AbortController();
93
+ // Name the handler so it can be REMOVED once this generation settles — run.signal
94
+ // lives for the WHOLE run, so an anonymous listener would accumulate across stages.
95
+ const onRunAbort = () => genAbort.abort();
96
+ if (run.signal) {
97
+ if (run.signal.aborted) genAbort.abort();
98
+ else run.signal.addEventListener("abort", onRunAbort, { once: true });
99
+ }
100
+ const detach = () => run.signal?.removeEventListener("abort", onRunAbort);
101
+
102
+ for (let w = 0; w < waves.length; w++) {
103
+ await dispatchWave(curCtx, e, cursor, run, deps, waves[w]!, genAbort, idToIndex);
104
+ // Cross-wave gates — the same two checks the single-dispatch tail made, now
105
+ // BETWEEN waves so a wave-k failure prevents wave-(k+1) dispatch. A fail-fast
106
+ // halt already terminated state inside the worker; a run abort drained the
107
+ // semaphore and rejects every later acquire.
108
+ if (run.state.termination.status !== "running") {
109
+ detach();
110
+ return;
111
+ }
112
+ if (run.signal?.aborted) {
113
+ detach();
114
+ return deps.recordAborted(curCtx, e.name, run); // mid-flight abort → FAIL_WORKFLOW_ABORTED
115
+ }
116
+ }
117
+ detach(); // all waves settled cleanly — drop the run-lifetime listener BEFORE the tail
118
+ return finalTail();
119
+ }
120
+
121
+ /**
122
+ * Dispatch ONE topological level's operands through a shared semaphore + the
123
+ * per-generation `genAbort`, folding each result at its DECLARED index. The body the
124
+ * former single-shot `runFanoutDispatch` ran, MINUS the genAbort lifecycle (the
125
+ * orchestrator owns it across waves) and the terminal disposition (the orchestrator
126
+ * runs the tail once, after the last wave). NEVER throws — an unexpected worker
127
+ * rejection lands a terminal-failure row via `recordWorkerThrow`; allSettled
128
+ * guarantees every unit settled.
129
+ */
130
+ async function dispatchWave(
131
+ curCtx: WorkflowHostContext,
132
+ e: LoopEntry,
133
+ cursor: LoopCursor,
134
+ run: RunContext,
135
+ deps: LoopDeps,
136
+ ops: readonly number[],
137
+ genAbort: AbortController,
138
+ idToIndex: Map<string, number> | undefined,
139
+ ): Promise<void> {
140
+ const failFast = isFailFast(e.loop);
141
+ // A fanout may cap its own concurrency BELOW the host cap (`implement`'s
142
+ // `concurrency: 1`); floored at 1, never raised above the host cap.
143
+ const loopCap = e.loop.kind === "fanout" ? e.loop.concurrency : undefined;
144
+ const sem = new Semaphore(
145
+ Math.max(1, Math.min(loopCap ?? curCtx.maxConcurrency, curCtx.maxConcurrency)),
146
+ genAbort.signal,
147
+ ); // drains queued units on either abort
148
+ const settled = await Promise.allSettled(
149
+ ops.map((i) => {
150
+ // Resolve `--upstream`-style dep-artifact injection from the slots prior waves
151
+ // already filled. Empty when the loop sets no flag or the unit has no deps.
152
+ const suffix = idToIndex ? depArtifactSuffix(e, cursor, i, idToIndex) : "";
153
+ return sem
154
+ .run(() => dispatchUnitDetached(curCtx, e, i, run, deps, genAbort.signal, suffix))
155
+ .then((out) => {
156
+ // a fail-fast unit's worker terminated state via recordTerminalFailure;
157
+ // fire genAbort so in-flight siblings get session.abort()'d NOW.
158
+ if (failFast && run.state.termination.status !== "running") genAbort.abort();
159
+ return out;
160
+ });
161
+ }),
162
+ );
163
+ // `ops[k]` maps the k-th settled result back to its DECLARED unit index.
164
+ for (let k = 0; k < settled.length; k++) {
165
+ const r = settled[k]!;
166
+ const i = ops[k]!;
167
+ if (r.status === "rejected") {
168
+ if (isAbortError(r.reason)) continue; // aborted / never-started → unfilled slot (resume re-dispatches)
169
+ await deps.recordWorkerThrow(curCtx, fanoutUnitRef(e, i), e.skill, run, r.reason);
170
+ continue;
171
+ }
172
+ cursor.ranThisInvocation++;
173
+ // index-addressed placement (shared with the resume fold) so declared order
174
+ // survives parallel completion + waves + resume.
175
+ foldFanoutCompletion(run.state, cursor, e.def, e.name, i, e.units!.length, r.value);
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Resolve the `depArtifactFlag` injection for unit `index`: ` <flag> <path>` per direct
181
+ * dep whose slot is filled with a NON-FAILED output. A failed/sentinel or still-unfilled
182
+ * dep slot is SKIPPED (the dependent designs blind for that dep) — so a failed upstream
183
+ * degrades gracefully instead of injecting a broken path; synthesize stays the backstop.
184
+ * Dangling ids never reach here (`validateUnitDeps` rejected them at the live entry); the
185
+ * `undefined` guard is defensive.
186
+ */
187
+ function depArtifactSuffix(e: LoopEntry, cursor: LoopCursor, index: number, idToIndex: Map<string, number>): string {
188
+ const flag = e.loop.kind === "fanout" ? e.loop.depArtifactFlag : undefined;
189
+ const deps = e.units![index]!.deps;
190
+ if (!flag || !deps?.length) return "";
191
+ let suffix = "";
192
+ for (const depId of deps) {
193
+ const di = idToIndex.get(depId);
194
+ if (di === undefined) continue; // dangling (defensive — validated away at the entry)
195
+ const out = cursor.slots?.[di];
196
+ if (!out || isFailedOutput(out)) continue; // unfilled or failed → skip (blind for this dep)
197
+ const handle = out.artifacts[0]?.handle;
198
+ if (handle) suffix += ` ${flag} ${handleToString(handle)}`;
199
+ }
200
+ return suffix;
201
+ }
202
+
203
+ /** Dispatch one fanout unit in its own child and RETURN its output. The cursor is NOT
204
+ * touched here — the wave fold consumes the return value in index order. `promptSuffix`
205
+ * (the resolved dep-artifact injection) is appended to the unit prompt by `fanoutUnitAt`.
206
+ * A halted unit leaves `captured` unset; returns failedOutput. (Settle shapes unchanged
207
+ * from the pre-wave dispatcher: collect-all unit failure → sentinel; fail-fast halt →
208
+ * placement sentinel + graceful return; ABORT → throws WorkflowAbortError → unfilled slot.) */
209
+ async function dispatchUnitDetached(
210
+ curCtx: WorkflowHostContext,
211
+ e: LoopEntry,
212
+ index: number,
213
+ run: RunContext,
214
+ deps: LoopDeps,
215
+ signal: AbortSignal | undefined, // genAbort.signal — run-level abort OR fail-fast sibling cancel
216
+ promptSuffix = "",
217
+ ): Promise<Output> {
218
+ if (signal?.aborted) throw new WorkflowAbortError(); // never open a child after abort; isAbortError → unfilled slot
219
+ const u = fanoutUnitAt(e, index, promptSuffix);
220
+ await run.lifecycle.fire(
221
+ curCtx,
222
+ "onUnitStart",
223
+ skillStageRef(e.name, e.stageIdx + 1, u.skill),
224
+ { role: u.role, index, unitId: u.id, label: u.label, skill: u.skill },
225
+ lifecycleCtxFor(run),
226
+ );
227
+ const snapshot = await deps.captureSnapshot(curCtx, e.name, u.def, e.stageIdx, run);
228
+ let captured: Output | undefined;
229
+ await deps.runStageSession(
230
+ curCtx,
231
+ buildUnitSession(e, u, index, run, snapshot, signal, (_child, output) => {
232
+ captured = output;
233
+ return Promise.resolve();
234
+ }),
235
+ );
236
+ return captured ?? failedOutput(unitOutputMeta(e, u, run), `${u.label}: unit halted`);
237
+ }
238
+
239
+ /** Minimal OutputMeta for a fail-fast placement sentinel. The run is terminating when
240
+ * this is used, so the sentinel is never read downstream; it only keeps the fold's
241
+ * Output type intact without a throw. */
242
+ function unitOutputMeta(e: LoopEntry, u: Extract<NextStep, { kind: "unit" }>, run: RunContext): OutputMeta {
243
+ return outputMeta({
244
+ stage: decorateStage(e.name, u.tag),
245
+ skill: u.skill,
246
+ stageNumber: run.state.lastAllocatedStageNumber,
247
+ ts: nowIso(),
248
+ runId: run.runId,
249
+ });
250
+ }
package/loop-waves.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * loop-waves.ts — topological wave scheduling for dependency-bearing fanout units.
3
+ *
4
+ * A fanout unit may declare `Unit.deps` (the `id ?? label` identities of units it
5
+ * depends on). `computeWaveLevels` assigns each unit a Kahn topological LEVEL over
6
+ * those DIRECTED edges — level 0 = roots (no deps), level k = max(dep levels)+1 —
7
+ * and groups unit INDICES by level. The wave dispatcher (loop-parallel.ts) runs one
8
+ * bounded-parallel dispatch per level, so a dependent never opens before the units it
9
+ * depends on have filled their slots. A deps-free fanout collapses to a single
10
+ * level — byte-identical to the pre-wave flat dispatch.
11
+ *
12
+ * Ordering vs grouping: this is NOT clusterSliceDag (built-in-workflows.ts), which
13
+ * is undirected union-find producing connected-component GROUPS for synth. Waves
14
+ * need DIRECTED levels — different algorithms over the same edge data.
15
+ *
16
+ * Leaf: the identity join key (`unitTagOf`) is the SAME one the resume drift guard
17
+ * and `fanoutUnitAt` read, so deps resolve against the exact ids the slots are keyed
18
+ * by. Validation throws the runner's typed preflight (deps are runtime-computed, so
19
+ * the static load gate can't see them — `stage-rules.ts` never inspects the unit list).
20
+ */
21
+
22
+ import type { Unit } from "./loop-def.js";
23
+ import { unitTagOf } from "./loop-kinds.js";
24
+ import { invariantPreflight } from "./stage-errors.js";
25
+
26
+ /** Built once; shared by level computation and the dispatcher's dep-artifact
27
+ * resolution so both resolve a dep id to the SAME index the cursor slots are
28
+ * keyed by. A duplicate identity keeps the FIRST index (dispatch + fold place
29
+ * by the first occurrence). */
30
+ export function unitIdIndex(units: readonly Unit[]): Map<string, number> {
31
+ const m = new Map<string, number>();
32
+ units.forEach((u, i) => {
33
+ const id = unitTagOf(u);
34
+ if (!m.has(id)) m.set(id, i);
35
+ });
36
+ return m;
37
+ }
38
+
39
+ /**
40
+ * Kahn topological levels over `Unit.deps`. `level[i]` is the longest-path-from-root
41
+ * depth — a pure DAG function independent of iteration order — so the fixpoint loop
42
+ * converges to the SAME level array every time, and indices stay ascending within a
43
+ * level: live dispatch and resume re-wave produce identical waves. A residual
44
+ * (unlevellable) node ⇒ a dependency cycle ⇒ `invariantPreflight`.
45
+ *
46
+ * Dangling deps (an id matching no unit) are SKIPPED here (treated as satisfied) so
47
+ * a single missing id can't masquerade as a cycle; `validateUnitDeps` is the one that
48
+ * reports dangling refs. At the live entry `validateUnitDeps` runs first, so a cycle
49
+ * reaching here is post-validation/defensive; the throw still lands a clean halt.
50
+ */
51
+ export function computeWaveLevels(units: readonly Unit[], stage: string): number[][] {
52
+ if (units.length === 0) return [];
53
+ const idToIndex = unitIdIndex(units);
54
+ const depIdx = units.map((u) =>
55
+ (u.deps ?? []).map((d) => idToIndex.get(d)).filter((x): x is number => x !== undefined),
56
+ );
57
+ const level = new Array<number>(units.length).fill(-1);
58
+ let remaining = units.length;
59
+ let progressed = true;
60
+ while (remaining > 0 && progressed) {
61
+ progressed = false;
62
+ for (let i = 0; i < units.length; i++) {
63
+ if (level[i] !== -1) continue;
64
+ const deps = depIdx[i]!;
65
+ if (deps.every((d) => level[d] !== -1)) {
66
+ level[i] = deps.length === 0 ? 0 : Math.max(...deps.map((d) => level[d]!)) + 1;
67
+ remaining--;
68
+ progressed = true;
69
+ }
70
+ }
71
+ }
72
+ if (remaining > 0) {
73
+ const stuck = level.flatMap((l, i) => (l === -1 ? [unitTagOf(units[i]!)] : []));
74
+ throw invariantPreflight(stage, `fanout deps form a cycle among units: ${stuck.join(", ")}`);
75
+ }
76
+ const levels: number[][] = Array.from({ length: Math.max(0, ...level) + 1 }, () => []);
77
+ level.forEach((l, i) => {
78
+ levels[l]!.push(i);
79
+ });
80
+ return levels;
81
+ }
82
+
83
+ /**
84
+ * Live-entry guard (run-stage.ts materialization + resume-loop.ts re-wave). Reports
85
+ * a DANGLING dep (an id matching no unit) and a dependency CYCLE, both as a clean
86
+ * `invariantPreflight` halt attributed to `stage`. Cheap; runs before dispatch so the
87
+ * dispatcher never has to throw. Cycle detection delegates to `computeWaveLevels`.
88
+ */
89
+ export function validateUnitDeps(units: readonly Unit[], stage: string): void {
90
+ const ids = new Set(units.map(unitTagOf));
91
+ for (const u of units) {
92
+ for (const d of u.deps ?? []) {
93
+ if (!ids.has(d)) {
94
+ throw invariantPreflight(stage, `fanout unit "${unitTagOf(u)}" declares unknown dep "${d}"`);
95
+ }
96
+ }
97
+ }
98
+ computeWaveLevels(units, stage); // throws on cycle
99
+ }
package/loop.ts ADDED
@@ -0,0 +1,330 @@
1
+ /**
2
+ * loop.ts — THE unit-loop driver. One continuation loop runs every loop
3
+ * stage: `fanout` (push: units precomputed), `iterate` (pull: one unit per
4
+ * generator call, accumulating), `assess` (producer→judge rounds until the
5
+ * judge's verdict satisfies `done`). The only per-kind code is the strategy
6
+ * table in loop-kinds.ts (`pull` / `guardExpectation` / `hasPending`) —
7
+ * dispatch, persistence, cap policy, result projection, and completion are
8
+ * shared and kind-agnostic here.
9
+ *
10
+ * A `verify`-bearing stage runs here too — `effectiveLoopOf` desugars it into
11
+ * a degenerate assess loop; verify-aware code is presentation only
12
+ * (role/label flavoring keyed on `e.def.verify` inside the assess strategy).
13
+ *
14
+ * Every unit runs `runStageSession` with a pre-decorated session: `stageName`
15
+ * carries the DISPLAY decoration (`decorateStage`), `unit` carries the
16
+ * machine identity that lands in the row's `parent`/`role`/`unitId`/`unitIndex`
17
+ * fields and the `onUnitStart`/`onUnitEnd` payloads.
18
+ *
19
+ * Continuation-style: each unit's `onSuccess` advances the cursor and
20
+ * re-enters `step`. Everything is awaited up the stack, so a throw from a
21
+ * user fn (`units`/`next`/`feedForward`/`done`/judge prompt) propagates to
22
+ * `runStageOrRecordFailure`'s single catch — a thrown `StagePreflightError`
23
+ * (the `haltPreflight` consumer contract) keeps its own attribution.
24
+ *
25
+ * Capture semantics (the post-refactor bug class — pinned):
26
+ * - `entryArtifact` + `entryPair` frozen by the CALLER before unit 1;
27
+ * - snapshot captured per unit, immediately before its session;
28
+ * - the skill registry was snapshotted once at run start (RunContext).
29
+ *
30
+ * `runner/run-stage.ts` injects primitives through `LoopDeps` so this
31
+ * module never imports the engine back (cycle-free).
32
+ *
33
+ * Resume re-enters `runLoop` with a fold-reconstructed cursor (see
34
+ * `runner/resume-loop.ts`); the silence rule — banner only when this
35
+ * invocation dispatched ≥1 unit — keeps a finished-loop resume a silent
36
+ * no-op (pinned behavior).
37
+ */
38
+
39
+ import type { LoopDef } from "./api.js";
40
+ import { applyCompletedStage } from "./chain-state.js";
41
+ import { lifecycleCtxFor, skillStageRef } from "./events.js";
42
+ import { nowIso } from "./internal-utils.js";
43
+ import { isPanel } from "./judge.js";
44
+ import { panelVerdictChannel, panelVerdictDef } from "./loop-constructors.js";
45
+ import {
46
+ advanceCursor,
47
+ buildUnitSession,
48
+ foldFanoutCompletion,
49
+ type LoopCursor,
50
+ type LoopDeps,
51
+ type LoopEntry,
52
+ loopStrategyOf,
53
+ type NextStep,
54
+ presentedKindOf,
55
+ sequentialStrategyOf,
56
+ } from "./loop-kinds.js";
57
+ import { runFanoutWaves } from "./loop-parallel.js";
58
+ import { MSG_LOOP_CAP_ADVANCE, MSG_LOOP_ZERO_UNITS } from "./messages.js";
59
+ import { appendLoopCap } from "./state/index.js";
60
+ import type { RunContext, WorkflowHostContext } from "./types.js";
61
+
62
+ /**
63
+ * The loop-entry announcement — `onStageStart` then `onLoopStart` with the
64
+ * presented kind (+ the precomputed unit list when the loop has one). ONE
65
+ * helper for the live entry (`runLoopStage`) and the resume re-entry
66
+ * (`resumeLoopStage`) — the pair and the presented-kind expression stay
67
+ * aligned by sharing this one helper.
68
+ */
69
+ export async function announceLoopStart(
70
+ curCtx: WorkflowHostContext,
71
+ run: RunContext,
72
+ e: Pick<LoopEntry, "stageIdx" | "name" | "skill" | "def" | "loop" | "units">,
73
+ ): Promise<void> {
74
+ const ref = skillStageRef(e.name, e.stageIdx + 1, e.skill);
75
+ await run.lifecycle.fire(curCtx, "onStageStart", ref, lifecycleCtxFor(run));
76
+ await run.lifecycle.fire(
77
+ curCtx,
78
+ "onLoopStart",
79
+ ref,
80
+ { kind: presentedKindOf(e.def, e.loop), ...(e.units ? { units: e.units } : {}) },
81
+ lifecycleCtxFor(run),
82
+ );
83
+ }
84
+
85
+ /** A pristine cursor ⇒ a live first entry. A resumed cursor (index advanced or
86
+ * any units folded) routes to the sequential path; resume instead
87
+ * re-dispatches only the still-pending children. */
88
+ const isPristine = (cursor: LoopCursor): boolean =>
89
+ cursor.index === 0 && cursor.accumulated.length === 0 && cursor.slots === undefined;
90
+
91
+ /** Run (or resume) one loop generation. The caller fired onStageStart/onLoopStart. */
92
+ export async function runLoop(
93
+ curCtx: WorkflowHostContext,
94
+ e: LoopEntry,
95
+ cursor: LoopCursor,
96
+ run: RunContext,
97
+ deps: LoopDeps,
98
+ ): Promise<void> {
99
+ const cap = Math.min(e.loop.max ?? Number.POSITIVE_INFINITY, run.maxIterations);
100
+ // ALL fanout goes through the index-addressed parallel path (Semaphore(1)
101
+ // just serializes when maxConcurrency === 1) — so the named-channel + cursor
102
+ // representation is identical at every concurrency AND matches the resume
103
+ // fold. iterate/assess keep the sequential step()/advanceCursor.
104
+ // (Live entry is always pristine; resume routes to runFanoutResume directly.)
105
+ if (e.loop.kind === "fanout" && loopStrategyOf(e.loop.kind).parallelizable && isPristine(cursor)) {
106
+ return runFanoutParallel(curCtx, e, cursor, cap, run, deps);
107
+ }
108
+ await step(curCtx, e, cursor, cap, run, deps);
109
+ }
110
+
111
+ /**
112
+ * Live bounded-parallel fanout entry — thin wrapper over `runFanoutWaves`
113
+ * (loop-parallel.ts). Dispatches the first `cap` units (`0..dispatchCount-1`) in
114
+ * dependency-ordered waves; on completion picks the cap policy: over-cap units trip
115
+ * `hitCap` on the last wave, otherwise the loop finishes. iterate/assess never reach
116
+ * here (not parallelizable).
117
+ */
118
+ function runFanoutParallel(
119
+ curCtx: WorkflowHostContext,
120
+ e: LoopEntry,
121
+ cursor: LoopCursor,
122
+ cap: number,
123
+ run: RunContext,
124
+ deps: LoopDeps,
125
+ ): Promise<void> {
126
+ const active = Array.from({ length: Math.min(e.units!.length, cap) }, (_u, i) => i);
127
+ return runFanoutWaves(curCtx, e, cursor, run, deps, active, () =>
128
+ e.units!.length > cap ? hitCap(curCtx, e, cursor, cap, cap, run, deps) : finishLoop(curCtx, e, cursor, run, deps),
129
+ );
130
+ }
131
+
132
+ /** Indices whose slot is still unfilled after the fold — the units to re-run. */
133
+ export function pendingFanoutIndices(cursor: LoopCursor, total: number): number[] {
134
+ const out: number[] = [];
135
+ for (let i = 0; i < total; i++) if (cursor.slots?.[i] === undefined) out.push(i);
136
+ return out;
137
+ }
138
+
139
+ /** Resume re-dispatch — thin wrapper over `runFanoutWaves`. Runs the still-pending
140
+ * fanout units in dependency-ordered waves (partitioning the pending set into
141
+ * topological levels), folding each at its declared index (so completed slots keep
142
+ * their position), and always finishes (the live run already settled the cap policy).
143
+ * A ≥3-level DAG where wave 0 completed but waves 1-2 aborted re-waves correctly:
144
+ * already-filled slots are skipped (not in `pending`); the remaining pending units
145
+ * dispatch level-by-level, never a level-2 unit concurrent with its level-1 dep.
146
+ * Pending fanout units COLD re-dispatch (a fresh child each) — fanout units are
147
+ * idempotent (each writes its own distinct artifact at its declared index), so a
148
+ * partial in-flight session is discarded rather than reattached; this matches
149
+ * what the live loop does. The run-scoped `childSessionsDir` + the id-first
150
+ * `locateSessionFile` serve the SINGLE-STAGE session-backed reattach path
151
+ * (run-stage.ts), not this fanout re-dispatch. */
152
+ export function runFanoutResume(
153
+ curCtx: WorkflowHostContext,
154
+ e: LoopEntry,
155
+ cursor: LoopCursor,
156
+ run: RunContext,
157
+ deps: LoopDeps,
158
+ pending: readonly number[],
159
+ ): Promise<void> {
160
+ return runFanoutWaves(curCtx, e, cursor, run, deps, pending, () => finishLoop(curCtx, e, cursor, run, deps));
161
+ }
162
+
163
+ // ---------------------------------------------------------------------------
164
+ // The step cycle
165
+ // ---------------------------------------------------------------------------
166
+
167
+ async function step(
168
+ curCtx: WorkflowHostContext,
169
+ e: LoopEntry,
170
+ cursor: LoopCursor,
171
+ cap: number,
172
+ run: RunContext,
173
+ deps: LoopDeps,
174
+ ): Promise<void> {
175
+ const next = await sequentialStrategyOf(e.loop.kind).pull(e, cursor, cap, run);
176
+ if (next.kind === "complete") return finishLoop(curCtx, e, cursor, run, deps);
177
+ if (next.kind === "cap") return hitCap(curCtx, e, cursor, next.count, cap, run, deps);
178
+ return dispatchUnit(curCtx, e, cursor, next, cap, run, deps);
179
+ }
180
+
181
+ /** Dispatch one unit session; the onSuccess continuation advances the cursor and re-enters step. */
182
+ async function dispatchUnit(
183
+ curCtx: WorkflowHostContext,
184
+ e: LoopEntry,
185
+ cursor: LoopCursor,
186
+ u: Extract<NextStep, { kind: "unit" }>,
187
+ cap: number,
188
+ run: RunContext,
189
+ deps: LoopDeps,
190
+ ): Promise<void> {
191
+ await run.lifecycle.fire(
192
+ curCtx,
193
+ "onUnitStart",
194
+ skillStageRef(e.name, e.stageIdx + 1, u.skill),
195
+ { role: u.role, index: cursor.index, unitId: u.id, label: u.label, skill: u.skill },
196
+ lifecycleCtxFor(run),
197
+ );
198
+
199
+ const snapshot = await deps.captureSnapshot(curCtx, e.name, u.def, e.stageIdx, run);
200
+
201
+ await deps.runStageSession(
202
+ curCtx,
203
+ buildUnitSession(e, u, cursor.index, run, snapshot, run.signal, (freshCtx, output) => {
204
+ cursor.ranThisInvocation++;
205
+ // Fanout owns its channel + cursor through the index-addressed
206
+ // `foldFanoutCompletion` (→ placeFanoutOutput) — `applyCompletedStage`
207
+ // early-returns for fanout, so this sequential single-dispatch fallback
208
+ // must fold here too, not lean on the removed `applyCompletedStage`
209
+ // channel push. `cursor.index` is the dispatched unit's index; the fold
210
+ // updates `filledCount` (not `index`), so advance the pointer explicitly.
211
+ // (Currently unreached for fanout: live → runFanoutParallel, resume →
212
+ // runFanoutResume; kept consistent so "index = pointer" holds everywhere.)
213
+ // iterate/assess keep the sequential cursor advance + panel publish.
214
+ if (e.loop.kind === "fanout") {
215
+ foldFanoutCompletion(run.state, cursor, e.def, e.name, cursor.index, e.units!.length, output);
216
+ cursor.index++;
217
+ } else {
218
+ advanceCursor(cursor, u.role, output, e.loop);
219
+ publishPanelVerdict(e.loop, e.name, cursor, run.state);
220
+ }
221
+ return step(freshCtx, e, cursor, cap, run, deps);
222
+ }),
223
+ );
224
+ }
225
+
226
+ /**
227
+ * Panel-close publish — lands a panel's FOLDED verdict on its named channel,
228
+ * run by BOTH the live driver (`dispatchUnit.onSuccess`) and the resume fold
229
+ * (`runner/resume.ts` `foldUnitRow`) immediately after the SAME `advanceCursor`,
230
+ * so the two paths publish byte-identically (THE REPLAY CONTRACT). Fires exactly
231
+ * once per round — only on the transition that closes a panel: the LAST member's
232
+ * judge advance is the one that clears `cursor.panel` AND flips back to `produce`
233
+ * with the folded verdict already on `lastVerdict`. A single judge (non-panel),
234
+ * a mid-panel member advance (`cursor.panel` still set), and every produce
235
+ * advance (`phase` left at `judge`) all fall through untouched. `advanceCursor`
236
+ * already manufactured the verdict (pure); this only appends it — the fold
237
+ * carries no artifact, so `applyCompletedStage` leaves the rolling primary alone
238
+ * and writes only the named channel. It lives BESIDE `advanceCursor`, not inside
239
+ * it: publishing mutates `RunState`, and `advanceCursor` must stay pure for the
240
+ * live + resume folds to agree.
241
+ */
242
+ export function publishPanelVerdict(
243
+ loop: LoopDef,
244
+ stageName: string,
245
+ cursor: LoopCursor,
246
+ state: RunContext["state"],
247
+ ): void {
248
+ if (loop.kind !== "assess") return; // narrows `loop` to AssessLoop — no cast needed below
249
+ const judge = loop.judge;
250
+ if (!isPanel(judge) || cursor.panel !== undefined || cursor.phase !== "produce") return;
251
+ if (cursor.lastVerdict === undefined) return; // defensive — the fold always set it
252
+ applyCompletedStage(
253
+ state,
254
+ panelVerdictDef(judge, stageName),
255
+ panelVerdictChannel(judge, stageName),
256
+ cursor.lastVerdict,
257
+ );
258
+ }
259
+
260
+ // ---------------------------------------------------------------------------
261
+ // Loop end — projection, notification, cap policy
262
+ // ---------------------------------------------------------------------------
263
+
264
+ /**
265
+ * The declared `result` projection — the ONE place the loop's outcome lands
266
+ * in `{state.output, state.primaryArtifact}` (the pair is governed as one;
267
+ * mid-loop transient rolls are accepted by design). The resume fold applies
268
+ * this same function at generation close.
269
+ */
270
+ export function projectResult(
271
+ loop: LoopDef,
272
+ entryPair: LoopEntry["entryPair"],
273
+ cursor: LoopCursor,
274
+ state: RunContext["state"],
275
+ ): void {
276
+ if (loop.result === "last" && cursor.lastProduce) {
277
+ state.output = cursor.lastProduce.output;
278
+ // `artifact` is undefined only for acts-stage units (produces units are
279
+ // guaranteed ≥1 artifact by enforceCompletionContract) — the entry
280
+ // primary carries through, mirroring how a single acts stage behaves.
281
+ state.primaryArtifact = cursor.lastProduce.artifact ?? entryPair.primaryArtifact;
282
+ return;
283
+ }
284
+ // "entry" — or "last" with zero produce units (degrades to entry: the
285
+ // zero-unit pull loop leaves the chain exactly as it found it).
286
+ state.output = entryPair.output;
287
+ state.primaryArtifact = entryPair.primaryArtifact;
288
+ }
289
+
290
+ /**
291
+ * Notification rules: the only toast is the zero-unit warning for a live empty
292
+ * pull loop. Loop completion itself is silent (the status line is the live
293
+ * progress channel); a resumed finished loop stays silent too.
294
+ */
295
+ async function finishLoop(
296
+ curCtx: WorkflowHostContext,
297
+ e: LoopEntry,
298
+ cursor: LoopCursor,
299
+ run: RunContext,
300
+ deps: LoopDeps,
301
+ ): Promise<void> {
302
+ projectResult(e.loop, e.entryPair, cursor, run.state);
303
+ if (cursor.ranThisInvocation === 0 && cursor.accumulated.length === 0 && e.loop.kind === "iterate") {
304
+ curCtx.ui.notify(MSG_LOOP_ZERO_UNITS(e.skill), "warning");
305
+ }
306
+ await deps.advanceAfter(curCtx, e.name, e.stageIdx, run);
307
+ }
308
+
309
+ /** Cap trip: "halt" → terminal failure; "advance" → durable telemetry + event + projected advance. */
310
+ async function hitCap(
311
+ curCtx: WorkflowHostContext,
312
+ e: LoopEntry,
313
+ cursor: LoopCursor,
314
+ count: number,
315
+ cap: number,
316
+ run: RunContext,
317
+ deps: LoopDeps,
318
+ ): Promise<void> {
319
+ if (e.loop.onCap === "halt") return deps.haltLoop(curCtx, run, e, count, cap);
320
+ appendLoopCap(run.cwd, run.runId, { type: "loop-cap", stage: e.name, count, max: cap, ts: nowIso() });
321
+ curCtx.ui.notify(MSG_LOOP_CAP_ADVANCE(e.skill, cap), "warning");
322
+ await run.lifecycle.fire(
323
+ curCtx,
324
+ "onLoopCap",
325
+ skillStageRef(e.name, e.stageIdx + 1, e.skill),
326
+ { kind: e.loop.kind, count, max: cap, policy: "advance" as const },
327
+ lifecycleCtxFor(run),
328
+ );
329
+ return finishLoop(curCtx, e, cursor, run, deps);
330
+ }