@juicesharp/rpiv-workflow 1.20.0 → 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/api.ts +1 -1
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +18 -0
- package/audit.ts +119 -164
- package/built-ins.ts +26 -6
- package/chain-state.ts +119 -68
- package/command-run.ts +35 -30
- package/command.ts +10 -4
- package/docs/workflow-authoring.md +34 -2
- package/events.ts +44 -4
- package/execution-host.ts +75 -0
- package/host.ts +137 -82
- package/internal-utils.ts +89 -3
- package/internal.ts +1 -0
- package/judge.ts +23 -11
- package/load/alias.ts +3 -3
- package/load/index.ts +15 -1
- package/load/issues.ts +2 -2
- package/load/legacy.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/skill-contract-phase.ts +1 -1
- package/loop-constructors.ts +19 -618
- package/loop-def.ts +60 -15
- package/loop-kinds.ts +319 -62
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +106 -80
- 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 +58 -33
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/transcript-path.ts +2 -15
- package/outcomes/collectors/union.ts +2 -1
- package/outcomes/collectors/url.ts +2 -14
- package/outcomes/collectors/workspace-diff.ts +1 -1
- package/outcomes/git-commit.ts +57 -6
- package/output-spec.ts +1 -1
- package/output.ts +59 -1
- package/package.json +16 -6
- package/preview.ts +18 -18
- package/registration.ts +11 -4
- package/routing-dsl.ts +53 -41
- package/routing.ts +46 -0
- package/runner/chain-advance.ts +30 -17
- package/runner/errors.ts +7 -30
- package/runner/failure.ts +67 -13
- package/runner/input-validation.ts +8 -5
- package/runner/preflight.ts +17 -21
- package/runner/resume-entry.ts +23 -3
- package/runner/resume-loop.ts +50 -29
- package/runner/resume.ts +96 -10
- package/runner/run-context.ts +20 -16
- package/runner/run-stage.ts +125 -91
- package/runner/runner.ts +163 -69
- package/runner/script-stage.ts +23 -29
- package/schema-compat.ts +1 -2
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +103 -60
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +2 -2
- package/sessions/locate.ts +60 -9
- package/sessions/reattach.ts +28 -20
- package/sessions/sessions.ts +103 -191
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contracts/composition.ts +8 -10
- package/skill-contracts/harvest.ts +3 -2
- package/skill-contracts/registry.ts +1 -1
- package/stage-def.ts +115 -47
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +1 -0
- package/state/paths.ts +11 -3
- package/state/raw.ts +2 -3
- package/state/resolve.ts +3 -3
- package/state/state.ts +26 -3
- package/state/writes.ts +1 -1
- package/types.ts +97 -43
- package/validate/contract-compat.ts +16 -11
- package/validate/graph.ts +10 -1
- package/validate/issue.ts +20 -6
- package/validate/stage-rules.ts +139 -60
- package/validate-output.ts +27 -20
- package/validate-workflow.ts +5 -3
- package/validation-bounds.ts +35 -0
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -77
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -112
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -113
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -120
- package/outcomes/git-commit.test.ts +0 -240
- 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/header-write-failure.test.ts +0 -64
- package/runner/resume-loop.test.ts +0 -1410
- package/runner/resume-session.test.ts +0 -400
- package/runner/resume.test.ts +0 -1805
- package/sessions/locate.test.ts +0 -77
package/loop-parallel.ts
ADDED
|
@@ -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
CHANGED
|
@@ -36,69 +36,35 @@
|
|
|
36
36
|
* no-op (pinned behavior).
|
|
37
37
|
*/
|
|
38
38
|
|
|
39
|
-
import type {
|
|
40
|
-
import { decorateStage, runIdentityOf } from "./audit.js";
|
|
39
|
+
import type { LoopDef } from "./api.js";
|
|
41
40
|
import { applyCompletedStage } from "./chain-state.js";
|
|
42
|
-
import { lifecycleCtxFor, skillStageRef
|
|
41
|
+
import { lifecycleCtxFor, skillStageRef } from "./events.js";
|
|
43
42
|
import { nowIso } from "./internal-utils.js";
|
|
44
43
|
import { isPanel } from "./judge.js";
|
|
45
44
|
import { panelVerdictChannel, panelVerdictDef } from "./loop-constructors.js";
|
|
46
45
|
import {
|
|
47
46
|
advanceCursor,
|
|
47
|
+
buildUnitSession,
|
|
48
|
+
foldFanoutCompletion,
|
|
48
49
|
type LoopCursor,
|
|
50
|
+
type LoopDeps,
|
|
49
51
|
type LoopEntry,
|
|
50
52
|
loopStrategyOf,
|
|
51
53
|
type NextStep,
|
|
52
54
|
presentedKindOf,
|
|
55
|
+
sequentialStrategyOf,
|
|
53
56
|
} from "./loop-kinds.js";
|
|
54
|
-
import {
|
|
55
|
-
|
|
56
|
-
MSG_LOOP_ZERO_UNITS,
|
|
57
|
-
MSG_STAGE_COMPLETE,
|
|
58
|
-
STATUS_KEY,
|
|
59
|
-
STATUS_LOOP_UNIT,
|
|
60
|
-
} from "./messages.js";
|
|
57
|
+
import { runFanoutWaves } from "./loop-parallel.js";
|
|
58
|
+
import { MSG_LOOP_CAP_ADVANCE, MSG_LOOP_ZERO_UNITS } from "./messages.js";
|
|
61
59
|
import { appendLoopCap } from "./state/index.js";
|
|
62
|
-
import type { RunContext,
|
|
63
|
-
|
|
64
|
-
export interface LoopDeps {
|
|
65
|
-
/** Dispatch one unit through the standard stage-session path. */
|
|
66
|
-
runStageSession: (ctx: WorkflowHostContext, s: StageSession) => Promise<void>;
|
|
67
|
-
/**
|
|
68
|
-
* Resume the chain after the loop finishes — receives the loop node's REAL
|
|
69
|
-
* name. `Promise<unknown>` so the walk's `ChainOutcome`-returning composed
|
|
70
|
-
* advance plugs in directly (the driver only awaits settlement).
|
|
71
|
-
*/
|
|
72
|
-
advanceAfter: (
|
|
73
|
-
curCtx: WorkflowHostContext,
|
|
74
|
-
completedName: string,
|
|
75
|
-
completedIdx: number,
|
|
76
|
-
run: RunContext,
|
|
77
|
-
) => Promise<unknown>;
|
|
78
|
-
/** Re-capture the outcome's pre-stage snapshot per unit (ctx + stage name for the fail-soft warning). */
|
|
79
|
-
captureSnapshot: (
|
|
80
|
-
curCtx: WorkflowHostContext,
|
|
81
|
-
stageName: string,
|
|
82
|
-
def: StageDef,
|
|
83
|
-
idx: number,
|
|
84
|
-
run: RunContext,
|
|
85
|
-
) => Promise<unknown>;
|
|
86
|
-
/** Record the terminal failure when `onCap: "halt"` trips — verify-worded for verify stages. */
|
|
87
|
-
haltLoop: (
|
|
88
|
-
curCtx: WorkflowHostContext,
|
|
89
|
-
run: RunContext,
|
|
90
|
-
e: Pick<LoopEntry, "name" | "def">,
|
|
91
|
-
count: number,
|
|
92
|
-
cap: number,
|
|
93
|
-
) => Promise<void>;
|
|
94
|
-
}
|
|
60
|
+
import type { RunContext, WorkflowHostContext } from "./types.js";
|
|
95
61
|
|
|
96
62
|
/**
|
|
97
63
|
* The loop-entry announcement — `onStageStart` then `onLoopStart` with the
|
|
98
64
|
* presented kind (+ the precomputed unit list when the loop has one). ONE
|
|
99
65
|
* helper for the live entry (`runLoopStage`) and the resume re-entry
|
|
100
|
-
* (`resumeLoopStage`)
|
|
101
|
-
*
|
|
66
|
+
* (`resumeLoopStage`) — the pair and the presented-kind expression stay
|
|
67
|
+
* aligned by sharing this one helper.
|
|
102
68
|
*/
|
|
103
69
|
export async function announceLoopStart(
|
|
104
70
|
curCtx: WorkflowHostContext,
|
|
@@ -116,6 +82,12 @@ export async function announceLoopStart(
|
|
|
116
82
|
);
|
|
117
83
|
}
|
|
118
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
|
+
|
|
119
91
|
/** Run (or resume) one loop generation. The caller fired onStageStart/onLoopStart. */
|
|
120
92
|
export async function runLoop(
|
|
121
93
|
curCtx: WorkflowHostContext,
|
|
@@ -125,9 +97,69 @@ export async function runLoop(
|
|
|
125
97
|
deps: LoopDeps,
|
|
126
98
|
): Promise<void> {
|
|
127
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
|
+
}
|
|
128
108
|
await step(curCtx, e, cursor, cap, run, deps);
|
|
129
109
|
}
|
|
130
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
|
+
|
|
131
163
|
// ---------------------------------------------------------------------------
|
|
132
164
|
// The step cycle
|
|
133
165
|
// ---------------------------------------------------------------------------
|
|
@@ -140,7 +172,7 @@ async function step(
|
|
|
140
172
|
run: RunContext,
|
|
141
173
|
deps: LoopDeps,
|
|
142
174
|
): Promise<void> {
|
|
143
|
-
const next = await
|
|
175
|
+
const next = await sequentialStrategyOf(e.loop.kind).pull(e, cursor, cap, run);
|
|
144
176
|
if (next.kind === "complete") return finishLoop(curCtx, e, cursor, run, deps);
|
|
145
177
|
if (next.kind === "cap") return hitCap(curCtx, e, cursor, next.count, cap, run, deps);
|
|
146
178
|
return dispatchUnit(curCtx, e, cursor, next, cap, run, deps);
|
|
@@ -156,43 +188,39 @@ async function dispatchUnit(
|
|
|
156
188
|
run: RunContext,
|
|
157
189
|
deps: LoopDeps,
|
|
158
190
|
): Promise<void> {
|
|
159
|
-
curCtx.ui.setStatus(STATUS_KEY, STATUS_LOOP_UNIT(e.stageIdx + 1, run.totalStages, u.skill, u.label));
|
|
160
|
-
|
|
161
|
-
const unitRef: UnitRef = { parent: e.name, role: u.role, index: cursor.index, id: u.id, label: u.label };
|
|
162
|
-
const event: UnitEvent = { role: u.role, index: cursor.index, unitId: u.id, label: u.label, skill: u.skill };
|
|
163
191
|
await run.lifecycle.fire(
|
|
164
192
|
curCtx,
|
|
165
193
|
"onUnitStart",
|
|
166
194
|
skillStageRef(e.name, e.stageIdx + 1, u.skill),
|
|
167
|
-
|
|
195
|
+
{ role: u.role, index: cursor.index, unitId: u.id, label: u.label, skill: u.skill },
|
|
168
196
|
lifecycleCtxFor(run),
|
|
169
197
|
);
|
|
170
198
|
|
|
171
199
|
const snapshot = await deps.captureSnapshot(curCtx, e.name, u.def, e.stageIdx, run);
|
|
172
200
|
|
|
173
|
-
await deps.runStageSession(
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
state: run.state,
|
|
177
|
-
prompt: u.prompt,
|
|
178
|
-
stageName: decorateStage(e.name, u.tag), // DISPLAY only — machine identity is `unit`
|
|
179
|
-
skill: u.skill,
|
|
180
|
-
lifecycle: run.lifecycle,
|
|
181
|
-
runIdentity: runIdentityOf(run),
|
|
182
|
-
stage: u.def,
|
|
183
|
-
skillContracts: run.skillContracts,
|
|
184
|
-
stageIndex: e.stageIdx,
|
|
185
|
-
snapshot,
|
|
186
|
-
branchOffset: undefined,
|
|
187
|
-
unit: unitRef,
|
|
188
|
-
onFailure: undefined,
|
|
189
|
-
onSuccess: (freshCtx, output) => {
|
|
201
|
+
await deps.runStageSession(
|
|
202
|
+
curCtx,
|
|
203
|
+
buildUnitSession(e, u, cursor.index, run, snapshot, run.signal, (freshCtx, output) => {
|
|
190
204
|
cursor.ranThisInvocation++;
|
|
191
|
-
|
|
192
|
-
|
|
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
|
+
}
|
|
193
221
|
return step(freshCtx, e, cursor, cap, run, deps);
|
|
194
|
-
},
|
|
195
|
-
|
|
222
|
+
}),
|
|
223
|
+
);
|
|
196
224
|
}
|
|
197
225
|
|
|
198
226
|
/**
|
|
@@ -217,8 +245,8 @@ export function publishPanelVerdict(
|
|
|
217
245
|
cursor: LoopCursor,
|
|
218
246
|
state: RunContext["state"],
|
|
219
247
|
): void {
|
|
220
|
-
if (loop.kind !== "assess") return;
|
|
221
|
-
const judge =
|
|
248
|
+
if (loop.kind !== "assess") return; // narrows `loop` to AssessLoop — no cast needed below
|
|
249
|
+
const judge = loop.judge;
|
|
222
250
|
if (!isPanel(judge) || cursor.panel !== undefined || cursor.phase !== "produce") return;
|
|
223
251
|
if (cursor.lastVerdict === undefined) return; // defensive — the fold always set it
|
|
224
252
|
applyCompletedStage(
|
|
@@ -260,9 +288,9 @@ export function projectResult(
|
|
|
260
288
|
}
|
|
261
289
|
|
|
262
290
|
/**
|
|
263
|
-
* Notification rules:
|
|
264
|
-
*
|
|
265
|
-
*
|
|
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.
|
|
266
294
|
*/
|
|
267
295
|
async function finishLoop(
|
|
268
296
|
curCtx: WorkflowHostContext,
|
|
@@ -272,9 +300,7 @@ async function finishLoop(
|
|
|
272
300
|
deps: LoopDeps,
|
|
273
301
|
): Promise<void> {
|
|
274
302
|
projectResult(e.loop, e.entryPair, cursor, run.state);
|
|
275
|
-
if (cursor.ranThisInvocation
|
|
276
|
-
curCtx.ui.notify(MSG_STAGE_COMPLETE(e.skill), "info");
|
|
277
|
-
} else if (cursor.accumulated.length === 0 && e.loop.kind === "iterate") {
|
|
303
|
+
if (cursor.ranThisInvocation === 0 && cursor.accumulated.length === 0 && e.loop.kind === "iterate") {
|
|
278
304
|
curCtx.ui.notify(MSG_LOOP_ZERO_UNITS(e.skill), "warning");
|
|
279
305
|
}
|
|
280
306
|
await deps.advanceAfter(curCtx, e.name, e.stageIdx, run);
|