@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,165 @@
1
+ /**
2
+ * Run construction — the leaf that assembles a `RunContext` (and the pristine
3
+ * `RunState` it starts from) for both entry points. `runWorkflow` builds a
4
+ * fresh identity; `resumeWorkflow` threads the reconstructed one. Lives below
5
+ * the whole engine so resume, the chain walk, and the entries all share one
6
+ * construction site without importing each other.
7
+ */
8
+
9
+ import type { Workflow } from "../api.js";
10
+ import { LifecycleDispatcher, type LifecycleListeners } from "../events.js";
11
+ import type { ModelSelection, WorkflowHost } from "../host.js";
12
+ import { getSkillContracts } from "../skill-contracts/index.js";
13
+ import type { RunTrigger } from "../triggers.js";
14
+ import type { RunContext, RunState } from "../types.js";
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Policy constants
18
+ // ---------------------------------------------------------------------------
19
+
20
+ /**
21
+ * Per-DESTINATION cap on decision-edge retries. A "backward jump" is a
22
+ * *decision* resolving to an already-visited stage — i.e. the user's
23
+ * predicate chose to retry. Deterministic edges through a cycle (the loop
24
+ * body) are NOT counted, and each destination stage owns its own budget
25
+ * (`RunContext.revisits`), so the retry allowance is invariant to how many
26
+ * decision edges the cycle crosses per iteration and unrelated loops never
27
+ * share a pool. With 2: any given stage runs once unconditionally and may be
28
+ * re-entered up to 2 more times — at most 3 executions per stage.
29
+ */
30
+ export const MAX_BACKWARD_JUMPS = 2;
31
+
32
+ /**
33
+ * Run-wide safety cap on loop units — the backstop for any loop kind whose
34
+ * source never terminates (a pull generator that never returns `null`, an
35
+ * assess `done` that never trips). Clamps the effective cap of every loop
36
+ * (`min(loop.max, run.maxIterations)`). Mirrors rpiv-pi's `MAX_PHASES` (the
37
+ * convention cap a fanout author would self-impose); 32 is comfortably above
38
+ * any realistic per-stage unit count while still halting a runaway loop.
39
+ */
40
+ export const MAX_ITERATIONS = 32;
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // State + context construction
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * A pristine `RunState`. New runs start here (`runWorkflow`); the resume fold
48
+ * starts here too and replays the trail on top — ONE construction site, so a
49
+ * new `RunState` field can never silently diverge between live runs and
50
+ * resumes.
51
+ */
52
+ export function freshRunState(originalInput: string): RunState {
53
+ return {
54
+ originalInput,
55
+ primaryArtifact: undefined,
56
+ output: undefined,
57
+ named: {},
58
+ stagesCompleted: 0,
59
+ lastAllocatedStageNumber: 0,
60
+ telemetry: { backwardJumps: 0, droppedRoutingRows: [], droppedFailureRows: [] },
61
+ termination: { status: "running" },
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Assemble the `RunContext` shared by both entry points. `identity` carries the
67
+ * four fields that differ between a new run (fresh id/state/visited, caller
68
+ * trigger) and a resume (same run id, reconstructed state/visited, resume
69
+ * trigger); everything else derives identically from `options`.
70
+ *
71
+ * The skill-registry snapshot happens here, BEFORE any stage opens its first
72
+ * child session — `options.host` (Pi's registry-level handle) is enumerated once
73
+ * for `run.registeredSkills`; the runner reads that set thereafter and never
74
+ * touches the host again (every stage now runs in a detached child, so there is
75
+ * no stale-after-swap concern and no continue-policy host fallback).
76
+ */
77
+ export function buildRunContext(
78
+ cwd: string,
79
+ workflow: Workflow,
80
+ options: {
81
+ host?: WorkflowHost;
82
+ maxBackwardJumps?: number;
83
+ maxIterations?: number;
84
+ lifecycle?: LifecycleListeners;
85
+ signal?: AbortSignal;
86
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
87
+ },
88
+ identity: { runId: string; state: RunState; visited: Set<string>; trigger: RunTrigger },
89
+ ): RunContext {
90
+ return {
91
+ cwd,
92
+ runId: identity.runId,
93
+ workflow,
94
+ totalStages: countReachableStages(workflow),
95
+ state: identity.state,
96
+ visited: identity.visited,
97
+ // Fresh on every entry point: a resume grants each stage a fresh
98
+ // re-entry budget, exactly as the pre-ledger streak counter did.
99
+ revisits: new Map(),
100
+ registeredSkills: options.host ? snapshotRegisteredSkills(options.host) : undefined,
101
+ // Defensive COPY (not the live global Map) so a later registerSkillContracts
102
+ // call cannot mutate this run's snapshot mid-run — parity with the fresh-Set
103
+ // copy snapshotRegisteredSkills makes.
104
+ skillContracts: new Map(getSkillContracts()),
105
+ maxBackwardJumps: options.maxBackwardJumps ?? MAX_BACKWARD_JUMPS,
106
+ maxIterations: options.maxIterations ?? MAX_ITERATIONS,
107
+ trigger: identity.trigger,
108
+ lifecycle: new LifecycleDispatcher(options.lifecycle),
109
+ signal: options.signal,
110
+ resolveModel: options.resolveModel,
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Build the `registeredSkills` snapshot consumed by `ensureSkillRegistered`.
116
+ *
117
+ * Pi prefixes skill-source commands with `"skill:"` (agent-session.js); we
118
+ * strip the prefix so the set keys match `stage.skill` directly. Called
119
+ * exactly once per run, at run start, off the launcher's registry-level host.
120
+ *
121
+ * Non-skill commands (slash commands registered by extensions) are filtered
122
+ * out — the preflight only cares about skills.
123
+ */
124
+ export function snapshotRegisteredSkills(host: WorkflowHost): ReadonlySet<string> {
125
+ const skills = new Set<string>();
126
+ for (const cmd of host.getCommands()) {
127
+ if (cmd.source !== "skill") continue;
128
+ const name = cmd.name.startsWith("skill:") ? cmd.name.slice("skill:".length) : cmd.name;
129
+ skills.add(name);
130
+ }
131
+ return skills;
132
+ }
133
+
134
+ /**
135
+ * Upper bound for the status-line denominator — BFS reach from `workflow.start`.
136
+ *
137
+ * Relies on every `EdgeFn` carrying `.targets`. `validate-workflow.ts` enforces
138
+ * this at load time, so by the time the runner sees a workflow the contract
139
+ * holds. A `.targets`-less EdgeFn here means validation was bypassed (test
140
+ * fixture or programmatic embedder) — surface loudly instead of silently
141
+ * counting all declared stages.
142
+ */
143
+ function countReachableStages(workflow: Workflow): number {
144
+ const seen = new Set<string>();
145
+ const frontier: string[] = [workflow.start];
146
+ while (frontier.length > 0) {
147
+ const cur = frontier.shift()!;
148
+ if (seen.has(cur)) continue;
149
+ seen.add(cur);
150
+ const edge = workflow.edges[cur];
151
+ if (edge === undefined || edge === "stop") continue;
152
+ if (typeof edge === "string") {
153
+ if (workflow.stages[edge] && !seen.has(edge)) frontier.push(edge);
154
+ } else if (Array.isArray(edge.targets)) {
155
+ for (const t of edge.targets) {
156
+ if (t !== "stop" && workflow.stages[t] && !seen.has(t)) frontier.push(t);
157
+ }
158
+ } else {
159
+ throw new Error(
160
+ `countReachableStages: edge from "${cur}" is an EdgeFn without .targets — validateWorkflow should have rejected this workflow`,
161
+ );
162
+ }
163
+ }
164
+ return seen.size;
165
+ }
@@ -0,0 +1,490 @@
1
+ /**
2
+ * Per-stage execution pipeline + the chain walk's COMPOSITION SITE.
3
+ *
4
+ * `runStage` resolves the stage once (`resolveStage` — mode + dispatch
5
+ * derived in one place) and switches on `mode`:
6
+ * - `"loop"` — the unit-loop driver (loop.ts), one session per unit;
7
+ * - `"script"` — `def.run` called directly (script-stage.ts);
8
+ * - `"prompt"`/`"skill"` — preflights → prompt prep → input validation →
9
+ * snapshot → one Pi session.
10
+ *
11
+ * The chain walk is mutually recursive (runStage → session continuation →
12
+ * advanceChain → next runStage); the recursion is composed HERE via
13
+ * injection — `advanceChain` receives `ChainDeps.runNext`, the loop driver
14
+ * receives `LoopDeps`, the script stage receives `advance` — so every other
15
+ * engine module's imports point strictly downward (zero value-import
16
+ * cycles; the LoopDeps precedent applied to the whole walk).
17
+ *
18
+ * `runStageOrRecordFailure` is the walk's single catch site: a throw from
19
+ * anywhere in the pipeline (preflights, user fns, machinery) lands a uniform
20
+ * JSONL failure row via failure.ts.
21
+ */
22
+
23
+ import type { StageDef, Unit } from "../api.js";
24
+ import { failedArgs, notifyPartialArtifacts, runIdentityOf } from "../audit.js";
25
+ import { currentPrimaryArtifact, resolveStagePrompt, stageEntryArgs } from "../chain-state.js";
26
+ import { lifecycleCtxFor, skillStageRef } from "../events.js";
27
+ import { formatError } from "../internal-utils.js";
28
+ import { announceLoopStart, runLoop } from "../loop.js";
29
+ import { freezesEntryArgsOf } from "../loop-constructors.js";
30
+ import { buildLoopEntry, freshCursor, type LoopDeps, type LoopEntry } from "../loop-kinds.js";
31
+ import { validateUnitDeps } from "../loop-waves.js";
32
+ import {
33
+ FAIL_LOOP_CAP_HALT,
34
+ FAIL_VERIFY_FAILED,
35
+ MSG_CONTINUE_FALLBACK,
36
+ MSG_RESUME_SESSION_FALLBACK,
37
+ MSG_SNAPSHOT_FAILED,
38
+ } from "../messages.js";
39
+ import { continueStageSession, locateSessionFile, reattachStageSession, runStageSession } from "../sessions/index.js";
40
+ import { forkChildSession, reattachChildSession } from "../sessions/spawn.js";
41
+ import type { WorkflowStage } from "../state/index.js";
42
+ import type { RunContext, StageSession, WorkflowHostContext } from "../types.js";
43
+ import { advanceChain, type ChainDeps } from "./chain-advance.js";
44
+ import { type ChainOutcome, haltChain, recordAbortedAtSeam, recordEntryThrow, withStageEntryGuard } from "./failure.js";
45
+ import { ensureContractInputValid, ensureInputValid } from "./input-validation.js";
46
+ import { ensureLoopNotContinue, runLoopPreflights, runSingleStagePreflights } from "./preflight.js";
47
+ import { type ResolvedStage, resolveStage } from "./resolve-stage.js";
48
+ import { runScript } from "./script-stage.js";
49
+
50
+ // Re-exported for the package barrel + existing consumers; the class itself
51
+ // lives in the leaf errors.ts so preflight/input-validation can throw it
52
+ // without importing this module back.
53
+ export { StagePreflightError } from "./errors.js";
54
+ export type { ResolvedStage } from "./resolve-stage.js";
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Walk composition — the ONE place the mutual recursion is wired
58
+ // ---------------------------------------------------------------------------
59
+
60
+ const CHAIN_DEPS: ChainDeps = {
61
+ runNext: (curCtx, name, idx, run) => runStageOrRecordFailure(curCtx, name, idx, run),
62
+ };
63
+
64
+ /**
65
+ * Advance the chain after `completedName` finished at `completedIdx` — the
66
+ * composed `advanceChain` every continuation calls (session onSuccess, loop
67
+ * driver advance, script stage, resume route-onward).
68
+ */
69
+ export function advance(
70
+ curCtx: WorkflowHostContext,
71
+ completedName: string,
72
+ completedIdx: number,
73
+ run: RunContext,
74
+ ): Promise<ChainOutcome> {
75
+ return advanceChain(curCtx, completedName, completedIdx, run, CHAIN_DEPS);
76
+ }
77
+
78
+ /**
79
+ * Wraps `runStage` so a thrown stage records a JSONL failure row attributed
80
+ * to the stage that actually threw — not to the prior stage in the chain.
81
+ * Used by `runWorkflow` (start stage), `advanceChain` (next stage, via
82
+ * `ChainDeps`), and the resume entries — the walk's single catch site.
83
+ * Delegates the classify-then-record policy (cooperative-abort seam +
84
+ * mid-stage `WorkflowAbortError` vs terminal entry-throw) to
85
+ * `withStageEntryGuard` (failure.ts).
86
+ */
87
+ export async function runStageOrRecordFailure(
88
+ curCtx: WorkflowHostContext,
89
+ name: string,
90
+ idx: number,
91
+ run: RunContext,
92
+ ): Promise<ChainOutcome> {
93
+ return withStageEntryGuard(curCtx, name, run, () => runStage(curCtx, name, idx, run));
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // Per-stage pipeline
98
+ // ---------------------------------------------------------------------------
99
+
100
+ /**
101
+ * Builds the `/skill:<name> <args>` line sent into the session. The audit
102
+ * label is read off `stage.skill` by the caller — single source.
103
+ */
104
+ function buildPrompt(skill: string, inputForStage: string): string {
105
+ return `/skill:${skill} ${inputForStage}`;
106
+ }
107
+
108
+ /**
109
+ * The arg string the stage's `/skill:<name> <args>` prompt carries — a thin
110
+ * wrapper over the `stageEntryArgs` authority (chain-state.ts), which the
111
+ * resume fold also consumes at loop-generation open so live and resume can't
112
+ * drift. The preflights (`ensureUpstreamArtifact` / `ensureNamedReads`)
113
+ * guarantee every projection input on this path, so the authority's
114
+ * `undefined` arm is unreachable here; the `!` is safe.
115
+ */
116
+ export function inputForStage(stage: ResolvedStage, run: RunContext): string {
117
+ return stageEntryArgs(stage.def, stage.name, run.workflow.start, run.state)!;
118
+ }
119
+
120
+ /** One stage activation — dispatch on the mode derived once by `resolveStage`. */
121
+ export async function runStage(
122
+ curCtx: WorkflowHostContext,
123
+ currentName: string,
124
+ idx: number,
125
+ run: RunContext,
126
+ ): Promise<ChainOutcome> {
127
+ const stage = resolveStage(currentName, idx, run);
128
+ switch (stage.mode) {
129
+ case "loop":
130
+ return runLoopStage(curCtx, stage, idx, run);
131
+ case "script":
132
+ // Script stages skip the skill pipeline — no `/skill:` prompt, no
133
+ // registry check, no session, no collector snapshot. Input-schema
134
+ // validation still applies; the script runner owns its own status
135
+ // line + lifecycle fires.
136
+ await ensureInputValid(stage, run);
137
+ return runScript(curCtx, stage, idx, run, advance);
138
+ case "prompt":
139
+ case "skill":
140
+ return runSingleStage(curCtx, stage, idx, run);
141
+ }
142
+ }
143
+
144
+ /**
145
+ * The shared single-stage preparation steps — preflights → prompt prep →
146
+ * input validation → snapshot — extracted so the live path
147
+ * (`runSingleStage`) and session-backed resume (`resumeStageWithSession`)
148
+ * can't drift (the `buildLoopDeps` precedent applied to single stages).
149
+ * The branch offset is NOT prepared here: live derives it from the current
150
+ * branch (`computeBranchOffset`), resume takes it from the persisted row.
151
+ */
152
+ async function prepareSingleStage(
153
+ curCtx: WorkflowHostContext,
154
+ stage: ResolvedStage,
155
+ idx: number,
156
+ run: RunContext,
157
+ ): Promise<{ prompt: string; snapshot: unknown }> {
158
+ runSingleStagePreflights(stage, run);
159
+
160
+ const prompt =
161
+ stage.dispatch === "prompt"
162
+ ? await resolveStagePrompt(stage.def.prompt!, run.cwd, run.state)
163
+ : buildPrompt(stage.skill, inputForStage(stage, run));
164
+
165
+ await ensureInputValid(stage, run);
166
+ await ensureContractInputValid(stage, run);
167
+
168
+ const snapshot = await captureStageSnapshot(curCtx, stage.name, stage.def, idx, run);
169
+ return { prompt, snapshot };
170
+ }
171
+
172
+ /**
173
+ * The `StageSession` both single-stage entries build — live and resume use
174
+ * the SAME continuation pair (`onSuccess` → `advance`, `onFailure` →
175
+ * partial-artifact recap), so a promoted/reattached stage chains onward
176
+ * exactly like a live one.
177
+ */
178
+ function buildSingleStageSession(
179
+ stage: ResolvedStage,
180
+ idx: number,
181
+ run: RunContext,
182
+ prep: { prompt: string; snapshot: unknown },
183
+ branchOffset: number | undefined,
184
+ ): StageSession {
185
+ return {
186
+ cwd: run.cwd,
187
+ runId: run.runId,
188
+ state: run.state,
189
+ prompt: prep.prompt,
190
+ stageName: stage.name,
191
+ skill: stage.skill,
192
+ lifecycle: run.lifecycle,
193
+ runIdentity: runIdentityOf(run),
194
+ stage: stage.def,
195
+ skillContracts: run.skillContracts,
196
+ stageIndex: idx,
197
+ snapshot: prep.snapshot,
198
+ model: run.resolveModel?.({ stage: stage.name, skill: stage.skill }),
199
+ signal: run.signal,
200
+ branchOffset,
201
+ onFailure: (freshCtx) => notifyPartialArtifacts(freshCtx, run.cwd, run.runId),
202
+ onSuccess: (freshCtx) => advance(freshCtx, stage.name, idx, run),
203
+ };
204
+ }
205
+
206
+ /**
207
+ * The single-stage entry announcement — `onStageStart`. ONE helper for the
208
+ * live entry (`runSingleStage`) and the session-backed resume re-entry
209
+ * (`resumeWithSessionLadder`) — the fire stays aligned by sharing this one
210
+ * helper. Mirrors `announceLoopStart`
211
+ * (loop.ts) — the loop path's one-helper-for-live-and-resume exemplar.
212
+ */
213
+ function announceSingleStageStart(
214
+ curCtx: WorkflowHostContext,
215
+ run: RunContext,
216
+ stage: Pick<ResolvedStage, "name" | "stageNumber" | "skill">,
217
+ ): Promise<void> {
218
+ return run.lifecycle.fire(
219
+ curCtx,
220
+ "onStageStart",
221
+ skillStageRef(stage.name, stage.stageNumber, stage.skill),
222
+ lifecycleCtxFor(run),
223
+ );
224
+ }
225
+
226
+ /**
227
+ * The single-session path (prompt + skill dispatch): preflights → prompt
228
+ * prep → input validation → snapshot → session.
229
+ *
230
+ * Dispatch: a `prompt` stage sends author-owned raw text (resolved by the
231
+ * shared `resolveStagePrompt` authority — the loop driver's round-0 producer
232
+ * uses the same resolver); a skill stage sends `/skill:<name>
233
+ * <inputForStage>`. `stage.skill` already equals the record key for a
234
+ * prompt stage (it cannot set an explicit skill — load validation forbids
235
+ * it), so the status/session/audit labels are correct for both without a
236
+ * separate label. A PromptFn throw propagates to
237
+ * `runStageOrRecordFailure`, which records a terminal failure.
238
+ */
239
+ async function runSingleStage(
240
+ curCtx: WorkflowHostContext,
241
+ stage: ResolvedStage,
242
+ idx: number,
243
+ run: RunContext,
244
+ ): Promise<ChainOutcome> {
245
+ const prep = await prepareSingleStage(curCtx, stage, idx, run);
246
+
247
+ // onStageStart fires after preflight, before the Pi session opens.
248
+ await announceSingleStageStart(curCtx, run, stage);
249
+
250
+ // `continue` forks the predecessor's persisted session (`run.state.lastSession`)
251
+ // into a fresh child carrying its transcript; `continueStageSession` re-derives
252
+ // the branch offset from that forked branch (NOT the launcher's). No predecessor
253
+ // session — start stage, after a loop, or the file is gone — degrades to a fresh
254
+ // dispatch, matching the `prompt-continue-at-start` warning. Fresh stages always
255
+ // pass `branchOffset: undefined`.
256
+ if (stage.def.sessionPolicy === "continue") {
257
+ const file = continueForkFile(run);
258
+ if (file) {
259
+ const s = buildSingleStageSession(stage, idx, run, prep, undefined);
260
+ await forkChildSession(curCtx, s, file, (child) => continueStageSession(curCtx, child, s));
261
+ return "dispatched";
262
+ }
263
+ curCtx.ui.notify(MSG_CONTINUE_FALLBACK(stage.skill), "info");
264
+ }
265
+
266
+ await runStageSession(curCtx, buildSingleStageSession(stage, idx, run, prep, undefined));
267
+ return "dispatched";
268
+ }
269
+
270
+ /**
271
+ * The predecessor session a `continue` stage forks from, resolved to an on-disk
272
+ * file — or `null` to degrade to a fresh dispatch (no prior session recorded, or
273
+ * its file was cleaned up / moved beyond `locateSessionFile`'s reach).
274
+ */
275
+ function continueForkFile(run: RunContext): string | null {
276
+ const ref = run.state.lastSession;
277
+ return ref ? locateSessionFile(ref, run.runId, run.cwd) : null;
278
+ }
279
+
280
+ /**
281
+ * Session-backed resume of a failed/aborted single stage — adopt the
282
+ * interrupted session's branch (promotion) or continue it from its leaf
283
+ * (reattach), instead of re-running cold. Selected by `selectResumeEntry`
284
+ * when the failed trailer carries a `session` (the structured dispatch).
285
+ * Delegates the same classify-then-record policy as the live entry
286
+ * (`runStageOrRecordFailure`) to `withStageEntryGuard` (failure.ts); the
287
+ * fallback ladder itself lives in `resumeWithSessionLadder` below — the
288
+ * resume `inner` still wraps it, so a reattached `postStage`
289
+ * `WorkflowAbortError` or machinery throw is classified (abort vs terminal
290
+ * entry-throw) by the same authority as the live path.
291
+ */
292
+ export async function resumeStageWithSession(
293
+ curCtx: WorkflowHostContext,
294
+ last: WorkflowStage,
295
+ idx: number,
296
+ run: RunContext,
297
+ ): Promise<ChainOutcome> {
298
+ return withStageEntryGuard(curCtx, last.stage, run, () => resumeWithSessionLadder(curCtx, last, idx, run));
299
+ }
300
+
301
+ /**
302
+ * THE resume fallback ladder (called by `resumeStageWithSession` via
303
+ * `withStageEntryGuard`). Every precondition miss notifies
304
+ * (`MSG_RESUME_SESSION_FALLBACK`) and degrades to today's cold re-run via
305
+ * `runStageOrRecordFailure` — never a refusal, never a throw:
306
+ *
307
+ * 1. resolved mode must be `prompt`/`skill` (loop trailers never reach
308
+ * this arm — they carry `parent`; script stages are sessionless);
309
+ * 2. `locateSessionFile` must find the file on disk;
310
+ * 3. the same `prepareSingleStage` steps as live (a preflight throw lands
311
+ * in the same catch as the live entry);
312
+ * 4. `reattachChildSession` spawns a child BOUND to the persisted file (the
313
+ * host opens it, does NOT replay the prompt) and `reattachStageSession`
314
+ * (sessions/reattach.ts) runs promotion → reattach inside it, with the
315
+ * SAME `StageSession` the live path builds — `branchOffset` taken from
316
+ * the PERSISTED row (continue-policy stages), `undefined` for fresh.
317
+ *
318
+ * (The cooperative-abort pre-check — formerly step 1 here — now lives in
319
+ * `withStageEntryGuard`, which wraps this ladder; a mid-stage
320
+ * `WorkflowAbortError` thrown inside it is classified there too.)
321
+ *
322
+ * Lifecycle: `onStageStart` fires before the child (re)opens (same bracketing
323
+ * as live); promotion then fires `onStageEnd` via `recordStageSuccess` — a
324
+ * fast start→end pair is honest ("the stage's work was adopted"). There is no
325
+ * `{ cancelled }` arm — a detached reattach opens its own child, with no
326
+ * live-session swap for the user to dismiss.
327
+ */
328
+ async function resumeWithSessionLadder(
329
+ curCtx: WorkflowHostContext,
330
+ last: WorkflowStage,
331
+ idx: number,
332
+ run: RunContext,
333
+ ): Promise<ChainOutcome> {
334
+ const ref = last.session!; // dispatch arm guarantees non-null (resume-entry.ts)
335
+ const stage = resolveStage(last.stage, idx, run);
336
+
337
+ const fallBackCold = (why: string): Promise<ChainOutcome> => {
338
+ curCtx.ui.notify(MSG_RESUME_SESSION_FALLBACK(stage.skill, why), "info");
339
+ return runStageOrRecordFailure(curCtx, last.stage, idx, run);
340
+ };
341
+
342
+ // Defensive: a session-backed row for a stage whose def since became a
343
+ // loop/script stage — the session machinery below doesn't apply.
344
+ if (stage.mode !== "prompt" && stage.mode !== "skill") {
345
+ return runStageOrRecordFailure(curCtx, last.stage, idx, run);
346
+ }
347
+ const file = locateSessionFile(ref, run.runId, run.cwd);
348
+ if (!file) return fallBackCold("session file not found");
349
+
350
+ const prep = await prepareSingleStage(curCtx, stage, idx, run);
351
+ const s = buildSingleStageSession(stage, idx, run, prep, ref.branchOffset);
352
+
353
+ // Same bracketing as live: onStageStart before the (re)attached child opens.
354
+ await announceSingleStageStart(curCtx, run, stage);
355
+
356
+ // Detached reattach: spawn a child BOUND to the persisted session file (the
357
+ // host opens it and does NOT replay the prompt); reattachStageSession promotes
358
+ // from the loaded branch or nudges via resendIntoChild. Replaces the deleted
359
+ // live-session swap (`curCtx.switchSession`).
360
+ await reattachChildSession(curCtx, s, file, (child) => reattachStageSession(curCtx, child, s));
361
+ return "dispatched";
362
+ }
363
+
364
+ /**
365
+ * A stage with an effective loop (incl. the verify desugar) expands into one
366
+ * session per unit through the ONE driver. A push loop whose unit source
367
+ * returned an empty list falls through to the single-stage path — that path
368
+ * runs its own preflights, so e.g. a missing named read still halts with the
369
+ * targeted message (today's consumer contract).
370
+ *
371
+ * Push loops compute units FIRST (a throw — incl. a consumer haltPreflight —
372
+ * propagates with its own attribution; empty ⇒ single-stage fall-through);
373
+ * the remaining loop preflights run after (see preflight.ts).
374
+ *
375
+ * Capture semantics (pinned): `entryArtifact`, `entryArgs`, and `entryPair`
376
+ * are frozen HERE, before unit 1; per-unit snapshots are captured by the
377
+ * driver immediately before each unit's session.
378
+ *
379
+ * A `verify`-bearing stage enters here too (the desugar — `effectiveLoopOf`,
380
+ * folded into `resolveStage`); its onLoopStart reports `kind: "verify"` so
381
+ * listeners aren't told it's an assess loop.
382
+ *
383
+ * A prompt-dispatch assess/verify stage also enters here: the skill-registry
384
+ * and upstream-artifact preflights skip non-skill dispatch, and its
385
+ * `entryArgs` freezes to `""` (the `stageEntryArgs` prompt arm) — the round-0
386
+ * message is the stage's own `prompt`, resolved by the driver at dispatch.
387
+ */
388
+ async function runLoopStage(
389
+ curCtx: WorkflowHostContext,
390
+ stage: ResolvedStage,
391
+ idx: number,
392
+ run: RunContext,
393
+ ): Promise<ChainOutcome> {
394
+ const loop = stage.loop!;
395
+ ensureLoopNotContinue(stage);
396
+
397
+ // Push loops compute units FIRST (pinned ordering — a units() throw beats
398
+ // any other preflight's halt; empty ⇒ single-stage fall-through).
399
+ let units: readonly Unit[] | undefined;
400
+ if (loop.kind === "fanout") {
401
+ units = await loop.units({ cwd: run.cwd, artifact: currentPrimaryArtifact(run.state), state: run.state });
402
+ if (units.length === 0) return runSingleStage(curCtx, stage, idx, run);
403
+ // deps cycle / dangling-id → clean halt BEFORE any dispatch (the runtime unit
404
+ // list is invisible to the static load gate, so this is the only place it runs).
405
+ validateUnitDeps(units, stage.name);
406
+ }
407
+
408
+ runLoopPreflights(stage, run);
409
+
410
+ const entry = buildLoopEntry(
411
+ { stageIdx: idx, name: stage.name, skill: stage.skill, def: stage.def, loop },
412
+ {
413
+ entryArtifact: currentPrimaryArtifact(run.state),
414
+ entryArgs: freezesEntryArgsOf(loop) ? inputForStage(stage, run) : "",
415
+ entryPair: { output: run.state.output, primaryArtifact: run.state.primaryArtifact },
416
+ units,
417
+ },
418
+ );
419
+
420
+ await announceLoopStart(curCtx, run, entry);
421
+ await runLoop(curCtx, entry, freshCursor(), run, buildLoopDeps());
422
+ return "dispatched";
423
+ }
424
+
425
+ /**
426
+ * THE loop deps bundle — built identically by the live path and resume
427
+ * (`selectResumeEntry`), so the two can't drift.
428
+ */
429
+ export function buildLoopDeps(): LoopDeps {
430
+ return {
431
+ runStageSession,
432
+ advanceAfter: (freshCtx, name, completedIdx, ctx) => advance(freshCtx, name, completedIdx, ctx),
433
+ captureSnapshot: (ctx, name, def, i, r) => captureStageSnapshot(ctx, name, def, i, r),
434
+ haltLoop,
435
+ // Mid-flight run abort at the loop seam → FAIL_WORKFLOW_ABORTED.
436
+ recordAborted: (curCtx, name, run) => recordAbortedAtSeam(curCtx, name, run).then(() => undefined),
437
+ // Unexpected worker rejection → terminal-failure row, no re-throw. The
438
+ // unit's identity rides as a STRUCTURED field (`unit`) on the row — `stage`
439
+ // stays the parent graph identity, not a `name (unit N)` string.
440
+ recordWorkerThrow: (curCtx, unit, skill, run, err) =>
441
+ recordEntryThrow(curCtx, unit.parent, run, err, { ref: unit, skill }).then(() => undefined),
442
+ };
443
+ }
444
+
445
+ /**
446
+ * Terminal failure when a loop's `onCap: "halt"` trips. Verify stages get
447
+ * the verification-failed wording — the author declared a post-condition,
448
+ * not a loop, so "loop cap exceeded" would misattribute the failure.
449
+ */
450
+ export async function haltLoop(
451
+ curCtx: WorkflowHostContext,
452
+ run: RunContext,
453
+ e: Pick<LoopEntry, "name" | "def">,
454
+ count: number,
455
+ cap: number,
456
+ ): Promise<void> {
457
+ const args = e.def.verify ? failedArgs(FAIL_VERIFY_FAILED(e.name, cap)) : failedArgs(FAIL_LOOP_CAP_HALT(count, cap));
458
+ await haltChain(curCtx, run, e.name, e.name, args);
459
+ }
460
+
461
+ /** Runs whose snapshot-failure warning already fired — one notify per run, not per stage/unit. */
462
+ const snapshotWarnedRuns = new WeakSet<RunContext>();
463
+
464
+ export async function captureStageSnapshot(
465
+ curCtx: WorkflowHostContext,
466
+ stageName: string,
467
+ def: StageDef,
468
+ idx: number,
469
+ run: RunContext,
470
+ ): Promise<unknown> {
471
+ const snapshot = def.outcome?.collector.snapshot;
472
+ if (!snapshot) return undefined;
473
+ try {
474
+ return await snapshot({
475
+ cwd: run.cwd,
476
+ runId: run.runId,
477
+ stageIndex: idx,
478
+ state: run.state,
479
+ });
480
+ } catch (e) {
481
+ // Snapshot capture failure doesn't prevent stage execution — but a
482
+ // consistently-throwing custom snapshot must not silently disable
483
+ // diffing for the whole run, so the first failure warns.
484
+ if (!snapshotWarnedRuns.has(run)) {
485
+ snapshotWarnedRuns.add(run);
486
+ curCtx.ui.notify(MSG_SNAPSHOT_FAILED(stageName, formatError(e)), "warning");
487
+ }
488
+ return undefined;
489
+ }
490
+ }