@juicesharp/rpiv-workflow 2.1.0 → 2.3.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 (57) hide show
  1. package/audit-ctx.ts +16 -8
  2. package/audit-rows.ts +10 -0
  3. package/audit.ts +48 -26
  4. package/chain-state.ts +26 -1
  5. package/death-scene.ts +232 -0
  6. package/docs/embedding.md +1 -1
  7. package/docs/workflow-authoring.md +2 -2
  8. package/events.ts +3 -27
  9. package/execution-host.ts +9 -0
  10. package/failure-memos.ts +74 -0
  11. package/handle.ts +16 -1
  12. package/host.ts +13 -1
  13. package/internal.ts +1 -0
  14. package/loop-def.ts +9 -5
  15. package/loop-kinds.ts +16 -13
  16. package/loop-parallel.ts +116 -95
  17. package/loop-waves.ts +3 -3
  18. package/loop.ts +46 -43
  19. package/messages.ts +53 -14
  20. package/outcomes/collectors/workspace-diff.ts +3 -3
  21. package/outcomes/git-commit.ts +11 -4
  22. package/output-spec.ts +7 -7
  23. package/package.json +5 -2
  24. package/preview.ts +8 -1
  25. package/registration.ts +8 -3
  26. package/routing.ts +1 -41
  27. package/runner/chain-advance.ts +50 -32
  28. package/runner/errors.ts +1 -1
  29. package/runner/failure.ts +22 -23
  30. package/runner/preflight.ts +3 -6
  31. package/runner/resolve-stage.ts +3 -3
  32. package/runner/resume-entry.ts +5 -5
  33. package/runner/resume-loop.ts +5 -5
  34. package/runner/resume.ts +1 -1
  35. package/runner/run-context.ts +13 -3
  36. package/runner/run-stage.ts +134 -60
  37. package/runner/runner.ts +19 -9
  38. package/runner/script-stage.ts +17 -17
  39. package/sessions/bash-strikes.ts +182 -0
  40. package/sessions/extraction.ts +51 -37
  41. package/sessions/halt-routing.ts +18 -13
  42. package/sessions/index.ts +1 -1
  43. package/sessions/reattach.ts +10 -10
  44. package/sessions/sessions.ts +63 -19
  45. package/sessions/spawn.ts +5 -5
  46. package/sessions/success-persist.ts +9 -3
  47. package/stage-def.ts +2 -2
  48. package/stage-errors.ts +1 -1
  49. package/stage-identity.ts +43 -4
  50. package/state/index.ts +1 -1
  51. package/state/names.ts +1 -1
  52. package/state/reads.ts +1 -1
  53. package/state/state.ts +14 -4
  54. package/state/writes.ts +2 -2
  55. package/transcript.ts +30 -0
  56. package/types.ts +105 -15
  57. package/worktree-digest.ts +148 -0
@@ -1,45 +1,54 @@
1
1
  /**
2
2
  * Per-stage execution pipeline + the chain walk's COMPOSITION SITE.
3
3
  *
4
- * `runStage` resolves the stage once (`resolveStage` — mode + dispatch
4
+ * `dispatchStage` resolves the stage once (`resolveStage` — mode + dispatch
5
5
  * derived in one place) and switches on `mode`:
6
6
  * - `"loop"` — the unit-loop driver (loop.ts), one session per unit;
7
7
  * - `"script"` — `def.run` called directly (script-stage.ts);
8
8
  * - `"prompt"`/`"skill"` — preflights → prompt prep → input validation →
9
9
  * snapshot → one Pi session.
10
10
  *
11
- * The chain walk is mutually recursive (runStage → session continuation →
12
- * advanceChain → next runStage); the recursion is composed HERE via
11
+ * The chain walk is mutually recursive (dispatchStage → session continuation →
12
+ * advanceChain → next dispatchStage); the recursion is composed HERE via
13
13
  * injection — `advanceChain` receives `ChainDeps.runNext`, the loop driver
14
14
  * receives `LoopDeps`, the script stage receives `advance` — so every other
15
15
  * engine module's imports point strictly downward (zero value-import
16
16
  * cycles; the LoopDeps precedent applied to the whole walk).
17
17
  *
18
- * `runStageOrRecordFailure` is the walk's single catch site: a throw from
18
+ * `dispatchStageOrRecordFailure` is the walk's single catch site: a throw from
19
19
  * anywhere in the pipeline (preflights, user fns, machinery) lands a uniform
20
20
  * JSONL failure row via failure.ts.
21
21
  */
22
22
 
23
23
  import type { StageDef, Unit } from "../api.js";
24
- import { failedArgs, notifyPartialArtifacts, runIdentityOf } from "../audit.js";
24
+ import { auditCtxFor, failedArgs, notifyPartialArtifacts, recordFatalFailure, runIdentityOf } from "../audit.js";
25
25
  import { currentPrimaryArtifact, resolveStagePrompt, stageEntryArgs } from "../chain-state.js";
26
26
  import { lifecycleCtxFor, skillStageRef } from "../events.js";
27
+ import { failureMemoSuffix } from "../failure-memos.js";
27
28
  import { formatError } from "../internal-utils.js";
28
29
  import { announceLoopStart, runLoop } from "../loop.js";
29
30
  import { freezesEntryArgsOf } from "../loop-constructors.js";
30
31
  import { buildLoopEntry, freshCursor, type LoopDeps, type LoopEntry } from "../loop-kinds.js";
31
- import { validateUnitDeps } from "../loop-waves.js";
32
+ import { ensureUnitDeps } from "../loop-waves.js";
32
33
  import {
33
34
  FAIL_LOOP_CAP_HALT,
35
+ FAIL_VALIDATE_GATE_SKIPPED,
34
36
  FAIL_VERIFY_FAILED,
35
37
  MSG_CONTINUE_FALLBACK,
36
38
  MSG_RESUME_SESSION_FALLBACK,
37
39
  MSG_SNAPSHOT_FAILED,
38
40
  } from "../messages.js";
39
- import { continueStageSession, locateSessionFile, reattachStageSession, runStageSession } from "../sessions/index.js";
41
+ import {
42
+ continueStageSession,
43
+ executeStageSession,
44
+ locateSessionFile,
45
+ reattachStageSession,
46
+ } from "../sessions/index.js";
40
47
  import { forkChildSession, reattachChildSession } from "../sessions/spawn.js";
48
+ import { effectiveOutputSchemaOf } from "../stage-identity.js";
41
49
  import type { WorkflowStage } from "../state/index.js";
42
- import type { RunContext, StageSession, WorkflowHostContext } from "../types.js";
50
+ import type { RunContext, StageSessionContext, WorkflowHostContext } from "../types.js";
51
+ import { resolveDigest } from "../worktree-digest.js";
43
52
  import { advanceChain, type ChainDeps } from "./chain-advance.js";
44
53
  import { type ChainOutcome, haltChain, recordAbortedAtSeam, recordEntryThrow, withStageEntryGuard } from "./failure.js";
45
54
  import { ensureContractInputValid, ensureInputValid } from "./input-validation.js";
@@ -58,7 +67,7 @@ export type { ResolvedStage } from "./resolve-stage.js";
58
67
  // ---------------------------------------------------------------------------
59
68
 
60
69
  const CHAIN_DEPS: ChainDeps = {
61
- runNext: (curCtx, name, idx, run) => runStageOrRecordFailure(curCtx, name, idx, run),
70
+ runNext: (hostCtx, name, idx, run) => dispatchStageOrRecordFailure(hostCtx, name, idx, run),
62
71
  };
63
72
 
64
73
  /**
@@ -67,16 +76,16 @@ const CHAIN_DEPS: ChainDeps = {
67
76
  * driver advance, script stage, resume route-onward).
68
77
  */
69
78
  export function advance(
70
- curCtx: WorkflowHostContext,
79
+ hostCtx: WorkflowHostContext,
71
80
  completedName: string,
72
81
  completedIdx: number,
73
82
  run: RunContext,
74
83
  ): Promise<ChainOutcome> {
75
- return advanceChain(curCtx, completedName, completedIdx, run, CHAIN_DEPS);
84
+ return advanceChain(hostCtx, completedName, completedIdx, run, CHAIN_DEPS);
76
85
  }
77
86
 
78
87
  /**
79
- * Wraps `runStage` so a thrown stage records a JSONL failure row attributed
88
+ * Wraps `dispatchStage` so a thrown stage records a JSONL failure row attributed
80
89
  * to the stage that actually threw — not to the prior stage in the chain.
81
90
  * Used by `runWorkflow` (start stage), `advanceChain` (next stage, via
82
91
  * `ChainDeps`), and the resume entries — the walk's single catch site.
@@ -84,13 +93,13 @@ export function advance(
84
93
  * mid-stage `WorkflowAbortError` vs terminal entry-throw) to
85
94
  * `withStageEntryGuard` (failure.ts).
86
95
  */
87
- export async function runStageOrRecordFailure(
88
- curCtx: WorkflowHostContext,
96
+ export async function dispatchStageOrRecordFailure(
97
+ hostCtx: WorkflowHostContext,
89
98
  name: string,
90
99
  idx: number,
91
100
  run: RunContext,
92
101
  ): Promise<ChainOutcome> {
93
- return withStageEntryGuard(curCtx, name, run, () => runStage(curCtx, name, idx, run));
102
+ return withStageEntryGuard(hostCtx, name, run, () => dispatchStage(hostCtx, name, idx, run));
94
103
  }
95
104
 
96
105
  // ---------------------------------------------------------------------------
@@ -118,8 +127,8 @@ export function inputForStage(stage: ResolvedStage, run: RunContext): string {
118
127
  }
119
128
 
120
129
  /** One stage activation — dispatch on the mode derived once by `resolveStage`. */
121
- export async function runStage(
122
- curCtx: WorkflowHostContext,
130
+ export async function dispatchStage(
131
+ hostCtx: WorkflowHostContext,
123
132
  currentName: string,
124
133
  idx: number,
125
134
  run: RunContext,
@@ -127,17 +136,17 @@ export async function runStage(
127
136
  const stage = resolveStage(currentName, idx, run);
128
137
  switch (stage.mode) {
129
138
  case "loop":
130
- return runLoopStage(curCtx, stage, idx, run);
139
+ return runLoopStage(hostCtx, stage, idx, run);
131
140
  case "script":
132
141
  // Script stages skip the skill pipeline — no `/skill:` prompt, no
133
142
  // registry check, no session, no collector snapshot. Input-schema
134
143
  // validation still applies; the script runner owns its own status
135
144
  // line + lifecycle fires.
136
145
  await ensureInputValid(stage, run);
137
- return runScript(curCtx, stage, idx, run, advance);
146
+ return runScript(hostCtx, stage, idx, run, advance);
138
147
  case "prompt":
139
148
  case "skill":
140
- return runSingleStage(curCtx, stage, idx, run);
149
+ return runSingleStage(hostCtx, stage, idx, run);
141
150
  }
142
151
  }
143
152
 
@@ -150,7 +159,7 @@ export async function runStage(
150
159
  * branch (`computeBranchOffset`), resume takes it from the persisted row.
151
160
  */
152
161
  async function prepareSingleStage(
153
- curCtx: WorkflowHostContext,
162
+ hostCtx: WorkflowHostContext,
154
163
  stage: ResolvedStage,
155
164
  idx: number,
156
165
  run: RunContext,
@@ -165,12 +174,12 @@ async function prepareSingleStage(
165
174
  await ensureInputValid(stage, run);
166
175
  await ensureContractInputValid(stage, run);
167
176
 
168
- const snapshot = await captureStageSnapshot(curCtx, stage.name, stage.def, idx, run);
177
+ const snapshot = await captureStageSnapshot(hostCtx, stage.name, stage.def, idx, run);
169
178
  return { prompt, snapshot };
170
179
  }
171
180
 
172
181
  /**
173
- * The `StageSession` both single-stage entries build — live and resume use
182
+ * The `StageSessionContext` both single-stage entries build — live and resume use
174
183
  * the SAME continuation pair (`onSuccess` → `advance`, `onFailure` →
175
184
  * partial-artifact recap), so a promoted/reattached stage chains onward
176
185
  * exactly like a live one.
@@ -181,12 +190,12 @@ function buildSingleStageSession(
181
190
  run: RunContext,
182
191
  prep: { prompt: string; snapshot: unknown },
183
192
  branchOffset: number | undefined,
184
- ): StageSession {
193
+ ): StageSessionContext {
185
194
  return {
186
195
  cwd: run.cwd,
187
196
  runId: run.runId,
188
197
  state: run.state,
189
- prompt: prep.prompt,
198
+ prompt: prep.prompt + failureMemoSuffix(run.state),
190
199
  stageName: stage.name,
191
200
  skill: stage.skill,
192
201
  lifecycle: run.lifecycle,
@@ -197,6 +206,8 @@ function buildSingleStageSession(
197
206
  snapshot: prep.snapshot,
198
207
  model: run.resolveModel?.({ stage: stage.name, skill: stage.skill }),
199
208
  signal: run.signal,
209
+ readSessionBranch: run.readSessionBranch,
210
+ worktreeDigest: run.worktreeDigest,
200
211
  branchOffset,
201
212
  onFailure: (freshCtx) => notifyPartialArtifacts(freshCtx, run.cwd, run.runId),
202
213
  onSuccess: (freshCtx) => advance(freshCtx, stage.name, idx, run),
@@ -211,18 +222,75 @@ function buildSingleStageSession(
211
222
  * (loop.ts) — the loop path's one-helper-for-live-and-resume exemplar.
212
223
  */
213
224
  function announceSingleStageStart(
214
- curCtx: WorkflowHostContext,
225
+ hostCtx: WorkflowHostContext,
215
226
  run: RunContext,
216
227
  stage: Pick<ResolvedStage, "name" | "stageNumber" | "skill">,
217
228
  ): Promise<void> {
218
229
  return run.lifecycle.fire(
219
- curCtx,
230
+ hostCtx,
220
231
  "onStageStart",
221
232
  skillStageRef(stage.name, stage.stageNumber, stage.skill),
222
233
  lifecycleCtxFor(run),
223
234
  );
224
235
  }
225
236
 
237
+ /**
238
+ * Validation-retry mechanism-2: fail-fast a re-dispatch of a schema-validated
239
+ * produces stage against an UNCHANGED worktree (no observable fix since the last
240
+ * validation failure at the same progress point) — WITHOUT dispatching the
241
+ * session or running preflights. Returns `true` when the stage is halted (the
242
+ * caller short-circuits with `return "halted"`); `false` to proceed.
243
+ *
244
+ * Operator resume is excluded: session-backed resume never reaches
245
+ * `runSingleStage`, and a cold re-run under `trigger.meta.resumedFrom` is
246
+ * bypassed by `isOperatorResume`. The terminal skip carries the failure memo
247
+ * for free through the shared `recordFatalFailure` writer
248
+ * (`packages/rpiv-workflow/audit.ts:122`). An `undefined` digest (non-repo / git
249
+ * missing) ALWAYS proceeds — degrade on a missing signal, never skip.
250
+ *
251
+ * The qualifying predicate — "a produces stage with an effective output schema"
252
+ * — is the shared `effectiveOutputSchemaOf`
253
+ * (`packages/rpiv-workflow/stage-identity.ts`): the single RUNTIME spelling also
254
+ * consumed by the extraction retry loop (`sessions/extraction.ts`), so the gate
255
+ * and the retry loop agree on what "schema-validated" means and can no longer
256
+ * drift on the precedence order or the contract key.
257
+ */
258
+ export async function gateValidationRedispatch(
259
+ hostCtx: WorkflowHostContext,
260
+ stage: ResolvedStage,
261
+ run: RunContext,
262
+ ): Promise<boolean> {
263
+ const isOperatorResume = run.trigger.meta?.resumedFrom !== undefined;
264
+ const qualifies =
265
+ stage.def.kind === "produces" && !!effectiveOutputSchemaOf(stage.def, stage.name, run.skillContracts);
266
+ if (!isOperatorResume && qualifies) {
267
+ const digest = resolveDigest(run.worktreeDigest, run.cwd);
268
+ const baseline = run.state.lastGatedDispatch;
269
+ if (
270
+ baseline &&
271
+ baseline.stage === stage.name &&
272
+ digest !== undefined &&
273
+ digest === baseline.digest &&
274
+ run.state.stagesCompleted === baseline.stagesCompleted
275
+ ) {
276
+ await recordFatalFailure(
277
+ hostCtx,
278
+ auditCtxFor(run, stage.name, stage.skill),
279
+ failedArgs(FAIL_VALIDATE_GATE_SKIPPED(stage.skill)),
280
+ );
281
+ return true;
282
+ }
283
+ // Overwrite the baseline on every qualifying dispatch with a defined
284
+ // digest, so the NEXT dispatch of this stage compares against the most
285
+ // recent state (the "tree changed" / "fix ran" proceed arms both land
286
+ // here after the non-matching halt check above).
287
+ if (digest !== undefined) {
288
+ run.state.lastGatedDispatch = { stage: stage.name, digest, stagesCompleted: run.state.stagesCompleted };
289
+ }
290
+ }
291
+ return false;
292
+ }
293
+
226
294
  /**
227
295
  * The single-session path (prompt + skill dispatch): preflights → prompt
228
296
  * prep → input validation → snapshot → session.
@@ -234,18 +302,24 @@ function announceSingleStageStart(
234
302
  * prompt stage (it cannot set an explicit skill — load validation forbids
235
303
  * it), so the status/session/audit labels are correct for both without a
236
304
  * separate label. A PromptFn throw propagates to
237
- * `runStageOrRecordFailure`, which records a terminal failure.
305
+ * `dispatchStageOrRecordFailure`, which records a terminal failure.
238
306
  */
239
307
  async function runSingleStage(
240
- curCtx: WorkflowHostContext,
308
+ hostCtx: WorkflowHostContext,
241
309
  stage: ResolvedStage,
242
310
  idx: number,
243
311
  run: RunContext,
244
312
  ): Promise<ChainOutcome> {
245
- const prep = await prepareSingleStage(curCtx, stage, idx, run);
313
+ // Validation-retry mechanism-2 lives in `gateValidationRedispatch` (above) —
314
+ // fail-fast an unchanged-tree re-dispatch of a schema-validated produces
315
+ // stage BEFORE preflights or the session open. `true` ⇒ already recorded a
316
+ // terminal failure row; halt here.
317
+ if (await gateValidationRedispatch(hostCtx, stage, run)) return "halted";
318
+
319
+ const prep = await prepareSingleStage(hostCtx, stage, idx, run);
246
320
 
247
321
  // onStageStart fires after preflight, before the Pi session opens.
248
- await announceSingleStageStart(curCtx, run, stage);
322
+ await announceSingleStageStart(hostCtx, run, stage);
249
323
 
250
324
  // `continue` forks the predecessor's persisted session (`run.state.lastSession`)
251
325
  // into a fresh child carrying its transcript; `continueStageSession` re-derives
@@ -257,13 +331,13 @@ async function runSingleStage(
257
331
  const file = continueForkFile(run);
258
332
  if (file) {
259
333
  const s = buildSingleStageSession(stage, idx, run, prep, undefined);
260
- await forkChildSession(curCtx, s, file, (child) => continueStageSession(curCtx, child, s));
334
+ await forkChildSession(hostCtx, s, file, (child) => continueStageSession(hostCtx, child, s));
261
335
  return "dispatched";
262
336
  }
263
- curCtx.ui.notify(MSG_CONTINUE_FALLBACK(stage.skill), "info");
337
+ hostCtx.ui.notify(MSG_CONTINUE_FALLBACK(stage.skill), "info");
264
338
  }
265
339
 
266
- await runStageSession(curCtx, buildSingleStageSession(stage, idx, run, prep, undefined));
340
+ await executeStageSession(hostCtx, buildSingleStageSession(stage, idx, run, prep, undefined));
267
341
  return "dispatched";
268
342
  }
269
343
 
@@ -283,26 +357,26 @@ function continueForkFile(run: RunContext): string | null {
283
357
  * (reattach), instead of re-running cold. Selected by `selectResumeEntry`
284
358
  * when the failed trailer carries a `session` (the structured dispatch).
285
359
  * Delegates the same classify-then-record policy as the live entry
286
- * (`runStageOrRecordFailure`) to `withStageEntryGuard` (failure.ts); the
360
+ * (`dispatchStageOrRecordFailure`) to `withStageEntryGuard` (failure.ts); the
287
361
  * fallback ladder itself lives in `resumeWithSessionLadder` below — the
288
362
  * resume `inner` still wraps it, so a reattached `postStage`
289
363
  * `WorkflowAbortError` or machinery throw is classified (abort vs terminal
290
364
  * entry-throw) by the same authority as the live path.
291
365
  */
292
366
  export async function resumeStageWithSession(
293
- curCtx: WorkflowHostContext,
367
+ hostCtx: WorkflowHostContext,
294
368
  last: WorkflowStage,
295
369
  idx: number,
296
370
  run: RunContext,
297
371
  ): Promise<ChainOutcome> {
298
- return withStageEntryGuard(curCtx, last.stage, run, () => resumeWithSessionLadder(curCtx, last, idx, run));
372
+ return withStageEntryGuard(hostCtx, last.stage, run, () => resumeWithSessionLadder(hostCtx, last, idx, run));
299
373
  }
300
374
 
301
375
  /**
302
376
  * THE resume fallback ladder (called by `resumeStageWithSession` via
303
377
  * `withStageEntryGuard`). Every precondition miss notifies
304
378
  * (`MSG_RESUME_SESSION_FALLBACK`) and degrades to today's cold re-run via
305
- * `runStageOrRecordFailure` — never a refusal, never a throw:
379
+ * `dispatchStageOrRecordFailure` — never a refusal, never a throw:
306
380
  *
307
381
  * 1. resolved mode must be `prompt`/`skill` (loop trailers never reach
308
382
  * this arm — they carry `parent`; script stages are sessionless);
@@ -312,7 +386,7 @@ export async function resumeStageWithSession(
312
386
  * 4. `reattachChildSession` spawns a child BOUND to the persisted file (the
313
387
  * host opens it, does NOT replay the prompt) and `reattachStageSession`
314
388
  * (sessions/reattach.ts) runs promotion → reattach inside it, with the
315
- * SAME `StageSession` the live path builds — `branchOffset` taken from
389
+ * SAME `StageSessionContext` the live path builds — `branchOffset` taken from
316
390
  * the PERSISTED row (continue-policy stages), `undefined` for fresh.
317
391
  *
318
392
  * (The cooperative-abort pre-check — formerly step 1 here — now lives in
@@ -326,7 +400,7 @@ export async function resumeStageWithSession(
326
400
  * live-session swap for the user to dismiss.
327
401
  */
328
402
  async function resumeWithSessionLadder(
329
- curCtx: WorkflowHostContext,
403
+ hostCtx: WorkflowHostContext,
330
404
  last: WorkflowStage,
331
405
  idx: number,
332
406
  run: RunContext,
@@ -335,29 +409,29 @@ async function resumeWithSessionLadder(
335
409
  const stage = resolveStage(last.stage, idx, run);
336
410
 
337
411
  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);
412
+ hostCtx.ui.notify(MSG_RESUME_SESSION_FALLBACK(stage.skill, why), "info");
413
+ return dispatchStageOrRecordFailure(hostCtx, last.stage, idx, run);
340
414
  };
341
415
 
342
416
  // Defensive: a session-backed row for a stage whose def since became a
343
417
  // loop/script stage — the session machinery below doesn't apply.
344
418
  if (stage.mode !== "prompt" && stage.mode !== "skill") {
345
- return runStageOrRecordFailure(curCtx, last.stage, idx, run);
419
+ return dispatchStageOrRecordFailure(hostCtx, last.stage, idx, run);
346
420
  }
347
421
  const file = locateSessionFile(ref, run.runId, run.cwd);
348
422
  if (!file) return fallBackCold("session file not found");
349
423
 
350
- const prep = await prepareSingleStage(curCtx, stage, idx, run);
424
+ const prep = await prepareSingleStage(hostCtx, stage, idx, run);
351
425
  const s = buildSingleStageSession(stage, idx, run, prep, ref.branchOffset);
352
426
 
353
427
  // Same bracketing as live: onStageStart before the (re)attached child opens.
354
- await announceSingleStageStart(curCtx, run, stage);
428
+ await announceSingleStageStart(hostCtx, run, stage);
355
429
 
356
430
  // Detached reattach: spawn a child BOUND to the persisted session file (the
357
431
  // host opens it and does NOT replay the prompt); reattachStageSession promotes
358
432
  // 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));
433
+ // live-session swap (`hostCtx.switchSession`).
434
+ await reattachChildSession(hostCtx, s, file, (child) => reattachStageSession(hostCtx, child, s));
361
435
  return "dispatched";
362
436
  }
363
437
 
@@ -386,7 +460,7 @@ async function resumeWithSessionLadder(
386
460
  * message is the stage's own `prompt`, resolved by the driver at dispatch.
387
461
  */
388
462
  async function runLoopStage(
389
- curCtx: WorkflowHostContext,
463
+ hostCtx: WorkflowHostContext,
390
464
  stage: ResolvedStage,
391
465
  idx: number,
392
466
  run: RunContext,
@@ -399,10 +473,10 @@ async function runLoopStage(
399
473
  let units: readonly Unit[] | undefined;
400
474
  if (loop.kind === "fanout") {
401
475
  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);
476
+ if (units.length === 0) return runSingleStage(hostCtx, stage, idx, run);
403
477
  // deps cycle / dangling-id → clean halt BEFORE any dispatch (the runtime unit
404
478
  // list is invisible to the static load gate, so this is the only place it runs).
405
- validateUnitDeps(units, stage.name);
479
+ ensureUnitDeps(units, stage.name);
406
480
  }
407
481
 
408
482
  runLoopPreflights(stage, run);
@@ -417,8 +491,8 @@ async function runLoopStage(
417
491
  },
418
492
  );
419
493
 
420
- await announceLoopStart(curCtx, run, entry);
421
- await runLoop(curCtx, entry, freshCursor(), run, buildLoopDeps());
494
+ await announceLoopStart(hostCtx, run, entry);
495
+ await runLoop(hostCtx, entry, freshCursor(), run, buildLoopDeps());
422
496
  return "dispatched";
423
497
  }
424
498
 
@@ -428,17 +502,17 @@ async function runLoopStage(
428
502
  */
429
503
  export function buildLoopDeps(): LoopDeps {
430
504
  return {
431
- runStageSession,
505
+ executeStageSession,
432
506
  advanceAfter: (freshCtx, name, completedIdx, ctx) => advance(freshCtx, name, completedIdx, ctx),
433
507
  captureSnapshot: (ctx, name, def, i, r) => captureStageSnapshot(ctx, name, def, i, r),
434
508
  haltLoop,
435
509
  // Mid-flight run abort at the loop seam → FAIL_WORKFLOW_ABORTED.
436
- recordAborted: (curCtx, name, run) => recordAbortedAtSeam(curCtx, name, run).then(() => undefined),
510
+ recordAborted: (hostCtx, name, run) => recordAbortedAtSeam(hostCtx, name, run).then(() => undefined),
437
511
  // Unexpected worker rejection → terminal-failure row, no re-throw. The
438
512
  // unit's identity rides as a STRUCTURED field (`unit`) on the row — `stage`
439
513
  // 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),
514
+ recordWorkerThrow: (hostCtx, unit, skill, run, err) =>
515
+ recordEntryThrow(hostCtx, unit.parent, run, err, { ref: unit, skill }).then(() => undefined),
442
516
  };
443
517
  }
444
518
 
@@ -448,21 +522,21 @@ export function buildLoopDeps(): LoopDeps {
448
522
  * not a loop, so "loop cap exceeded" would misattribute the failure.
449
523
  */
450
524
  export async function haltLoop(
451
- curCtx: WorkflowHostContext,
525
+ hostCtx: WorkflowHostContext,
452
526
  run: RunContext,
453
527
  e: Pick<LoopEntry, "name" | "def">,
454
528
  count: number,
455
529
  cap: number,
456
530
  ): Promise<void> {
457
531
  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);
532
+ await haltChain(hostCtx, run, e.name, e.name, args);
459
533
  }
460
534
 
461
535
  /** Runs whose snapshot-failure warning already fired — one notify per run, not per stage/unit. */
462
536
  const snapshotWarnedRuns = new WeakSet<RunContext>();
463
537
 
464
538
  export async function captureStageSnapshot(
465
- curCtx: WorkflowHostContext,
539
+ hostCtx: WorkflowHostContext,
466
540
  stageName: string,
467
541
  def: StageDef,
468
542
  idx: number,
@@ -483,7 +557,7 @@ export async function captureStageSnapshot(
483
557
  // diffing for the whole run, so the first failure warns.
484
558
  if (!snapshotWarnedRuns.has(run)) {
485
559
  snapshotWarnedRuns.add(run);
486
- curCtx.ui.notify(MSG_SNAPSHOT_FAILED(stageName, formatError(e)), "warning");
560
+ hostCtx.ui.notify(MSG_SNAPSHOT_FAILED(stageName, formatError(e)), "warning");
487
561
  }
488
562
  return undefined;
489
563
  }
package/runner/runner.ts CHANGED
@@ -33,6 +33,7 @@ import {
33
33
  } from "../messages.js";
34
34
  import { pruneOrphanedChildSessions } from "../sessions/index.js";
35
35
  import {
36
+ appendHeader,
36
37
  type ClaimResult,
37
38
  claimName,
38
39
  generateRunId,
@@ -40,15 +41,15 @@ import {
40
41
  releaseName,
41
42
  STATE_SCHEMA_VERSION,
42
43
  type WorkflowHeader,
43
- writeHeader,
44
44
  } from "../state/index.js";
45
45
  import { childSessionsDir } from "../state/paths.js";
46
+ import type { BranchEntry } from "../transcript.js";
46
47
  import { DEFAULT_TRIGGER } from "../triggers.js";
47
48
  import type { RunContext, RunWorkflowOptions, RunWorkflowResult } from "../types.js";
48
49
  import { reconstructState } from "./resume.js";
49
50
  import { resumeRefusalError, selectResumeEntry } from "./resume-entry.js";
50
51
  import { buildRunContext, freshRunState } from "./run-context.js";
51
- import { runStageOrRecordFailure } from "./run-stage.js";
52
+ import { dispatchStageOrRecordFailure } from "./run-stage.js";
52
53
 
53
54
  // ---------------------------------------------------------------------------
54
55
  // Shared tail — executeRun
@@ -120,6 +121,7 @@ function referencedSessionIds(run: RunContext): Set<string> {
120
121
  interface DetachedExecutor {
121
122
  execCtx: WorkflowHostContext;
122
123
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
124
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
123
125
  signal?: AbortSignal;
124
126
  dispose?: () => void;
125
127
  }
@@ -148,6 +150,7 @@ async function detachExecutor(
148
150
  runId: string,
149
151
  options: {
150
152
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
153
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
151
154
  signal?: AbortSignal;
152
155
  name?: string; // lane display name (run --name ?? workflow name)
153
156
  /** Workflow name (the dock's dim `workflow:` tag); threaded from workflow.name / header.workflow. */
@@ -157,7 +160,13 @@ async function detachExecutor(
157
160
  },
158
161
  ): Promise<DetachedExecutor> {
159
162
  const provider = getWorkflowExecutionProvider();
160
- if (!provider) return { execCtx: ctx, resolveModel: options.resolveModel, signal: options.signal };
163
+ if (!provider)
164
+ return {
165
+ execCtx: ctx,
166
+ resolveModel: options.resolveModel,
167
+ readSessionBranch: options.readSessionBranch,
168
+ signal: options.signal,
169
+ };
161
170
  // Resolve the run-scoped session dir here (internal layout helper) and hand the
162
171
  // provider a concrete string; rpiv-pi never imports childSessionsDir.
163
172
  const exec = await provider.createHost(ctx, {
@@ -171,6 +180,7 @@ async function detachExecutor(
171
180
  execCtx: exec.host,
172
181
  dispose: exec.dispose,
173
182
  resolveModel: options.resolveModel ?? provider.resolveModel,
183
+ readSessionBranch: options.readSessionBranch ?? provider.readSessionBranch,
174
184
  signal: options.signal ?? exec.signal, // provider-owned abort handle
175
185
  };
176
186
  }
@@ -222,7 +232,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
222
232
  // makes the run unlistable and unresumable while its stage rows land, so a
223
233
  // failed append rejects the start and rolls back the name claim (the index
224
234
  // must not point at a run that never existed).
225
- const headerWritten = writeHeader(cwd, {
235
+ const headerWritten = appendHeader(cwd, {
226
236
  runId,
227
237
  workflow: workflow.name,
228
238
  input: options.input,
@@ -237,7 +247,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
237
247
  }
238
248
 
239
249
  // Detach to the executor host (the executor relays UI back to the live session).
240
- const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, runId, {
250
+ const { execCtx, resolveModel, readSessionBranch, signal, dispose } = await detachExecutor(ctx, cwd, runId, {
241
251
  ...options,
242
252
  name: options.name ?? workflow.name,
243
253
  workflow: workflow.name,
@@ -251,7 +261,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
251
261
  const run = buildRunContext(
252
262
  cwd,
253
263
  workflow,
254
- { ...options, resolveModel, signal },
264
+ { ...options, resolveModel, readSessionBranch, signal },
255
265
  {
256
266
  runId,
257
267
  state: freshRunState(options.input),
@@ -259,7 +269,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
259
269
  trigger,
260
270
  },
261
271
  );
262
- return await executeRun(execCtx, run, () => runStageOrRecordFailure(execCtx, workflow.start, 0, run));
272
+ return await executeRun(execCtx, run, () => dispatchStageOrRecordFailure(execCtx, workflow.start, 0, run));
263
273
  } finally {
264
274
  dispose?.(); // unsubscribe the onTerminalInput tap — leaks accumulate on the TUI otherwise
265
275
  }
@@ -324,7 +334,7 @@ export async function resumeWorkflow(
324
334
  // pending-fanout re-dispatch, or a cold-routed continue fork) runs against the
325
335
  // real executor, not the bare launcher ctx. Same run id ⇒ same childSessionsDir,
326
336
  // so reattach/fork resolve the original run's persisted child sessions.
327
- const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, header.runId, {
337
+ const { execCtx, resolveModel, readSessionBranch, signal, dispose } = await detachExecutor(ctx, cwd, header.runId, {
328
338
  ...options,
329
339
  name: header.name ?? header.workflow,
330
340
  workflow: header.workflow,
@@ -337,7 +347,7 @@ export async function resumeWorkflow(
337
347
  const run = buildRunContext(
338
348
  cwd,
339
349
  workflow,
340
- { ...options, resolveModel, signal },
350
+ { ...options, resolveModel, readSessionBranch, signal },
341
351
  {
342
352
  runId: header.runId, // SAME run — new rows append to the same file
343
353
  state: recon.state,