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