@juicesharp/rpiv-workflow 2.2.0 → 2.3.1

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 (50) hide show
  1. package/audit-ctx.ts +7 -7
  2. package/audit.ts +29 -29
  3. package/chain-state.ts +14 -3
  4. package/death-scene.ts +9 -9
  5. package/docs/workflow-authoring.md +2 -2
  6. package/events.ts +1 -1
  7. package/failure-memos.ts +4 -4
  8. package/handle.ts +16 -1
  9. package/host.ts +1 -1
  10. package/loop-def.ts +1 -1
  11. package/loop-kinds.ts +134 -91
  12. package/loop-parallel.ts +15 -15
  13. package/loop-waves.ts +3 -3
  14. package/loop.ts +54 -35
  15. package/messages.ts +30 -17
  16. package/outcomes/collectors/workspace-diff.ts +3 -3
  17. package/outcomes/git-commit.ts +11 -4
  18. package/output-spec.ts +7 -7
  19. package/package.json +2 -2
  20. package/preview.ts +8 -1
  21. package/registration.ts +3 -3
  22. package/routing.ts +1 -1
  23. package/runner/chain-advance.ts +66 -26
  24. package/runner/errors.ts +1 -1
  25. package/runner/failure.ts +22 -23
  26. package/runner/preflight.ts +20 -20
  27. package/runner/resolve-stage.ts +3 -3
  28. package/runner/resume-entry.ts +5 -5
  29. package/runner/resume-loop.ts +5 -5
  30. package/runner/resume.ts +198 -133
  31. package/runner/run-stage.ts +111 -88
  32. package/runner/runner.ts +4 -4
  33. package/runner/script-stage.ts +17 -17
  34. package/sessions/bash-strikes.ts +9 -9
  35. package/sessions/extraction.ts +135 -77
  36. package/sessions/halt-routing.ts +14 -14
  37. package/sessions/index.ts +1 -1
  38. package/sessions/reattach.ts +10 -10
  39. package/sessions/sessions.ts +93 -53
  40. package/sessions/spawn.ts +5 -5
  41. package/sessions/success-persist.ts +3 -3
  42. package/stage-def.ts +2 -2
  43. package/stage-errors.ts +1 -1
  44. package/state/index.ts +1 -1
  45. package/state/names.ts +1 -1
  46. package/state/reads.ts +1 -1
  47. package/state/state.ts +4 -4
  48. package/state/writes.ts +2 -2
  49. package/types.ts +16 -16
  50. package/validate/stage-rules.ts +42 -17
@@ -1,27 +1,27 @@
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 { auditCtxFor, failedArgs, notifyPartialArtifacts, recordTerminalFailure, 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
27
  import { failureMemoSuffix } from "../failure-memos.js";
@@ -29,7 +29,7 @@ import { formatError } from "../internal-utils.js";
29
29
  import { announceLoopStart, runLoop } from "../loop.js";
30
30
  import { freezesEntryArgsOf } from "../loop-constructors.js";
31
31
  import { buildLoopEntry, freshCursor, type LoopDeps, type LoopEntry } from "../loop-kinds.js";
32
- import { validateUnitDeps } from "../loop-waves.js";
32
+ import { ensureUnitDeps } from "../loop-waves.js";
33
33
  import {
34
34
  FAIL_LOOP_CAP_HALT,
35
35
  FAIL_VALIDATE_GATE_SKIPPED,
@@ -38,11 +38,17 @@ import {
38
38
  MSG_RESUME_SESSION_FALLBACK,
39
39
  MSG_SNAPSHOT_FAILED,
40
40
  } from "../messages.js";
41
- import { continueStageSession, locateSessionFile, reattachStageSession, runStageSession } from "../sessions/index.js";
41
+ import {
42
+ continueStageSession,
43
+ executeStageSession,
44
+ locateSessionFile,
45
+ reattachStageSession,
46
+ } from "../sessions/index.js";
42
47
  import { forkChildSession, reattachChildSession } from "../sessions/spawn.js";
48
+ import type { SkillContractMap } from "../skill-contract.js";
43
49
  import { effectiveOutputSchemaOf } from "../stage-identity.js";
44
50
  import type { WorkflowStage } from "../state/index.js";
45
- import type { RunContext, StageSession, WorkflowHostContext } from "../types.js";
51
+ import type { RunContext, RunState, StageSessionContext, WorkflowHostContext } from "../types.js";
46
52
  import { resolveDigest } from "../worktree-digest.js";
47
53
  import { advanceChain, type ChainDeps } from "./chain-advance.js";
48
54
  import { type ChainOutcome, haltChain, recordAbortedAtSeam, recordEntryThrow, withStageEntryGuard } from "./failure.js";
@@ -62,7 +68,7 @@ export type { ResolvedStage } from "./resolve-stage.js";
62
68
  // ---------------------------------------------------------------------------
63
69
 
64
70
  const CHAIN_DEPS: ChainDeps = {
65
- runNext: (curCtx, name, idx, run) => runStageOrRecordFailure(curCtx, name, idx, run),
71
+ runNext: (hostCtx, name, idx, run) => dispatchStageOrRecordFailure(hostCtx, name, idx, run),
66
72
  };
67
73
 
68
74
  /**
@@ -71,16 +77,16 @@ const CHAIN_DEPS: ChainDeps = {
71
77
  * driver advance, script stage, resume route-onward).
72
78
  */
73
79
  export function advance(
74
- curCtx: WorkflowHostContext,
80
+ hostCtx: WorkflowHostContext,
75
81
  completedName: string,
76
82
  completedIdx: number,
77
83
  run: RunContext,
78
84
  ): Promise<ChainOutcome> {
79
- return advanceChain(curCtx, completedName, completedIdx, run, CHAIN_DEPS);
85
+ return advanceChain(hostCtx, completedName, completedIdx, run, CHAIN_DEPS);
80
86
  }
81
87
 
82
88
  /**
83
- * Wraps `runStage` so a thrown stage records a JSONL failure row attributed
89
+ * Wraps `dispatchStage` so a thrown stage records a JSONL failure row attributed
84
90
  * to the stage that actually threw — not to the prior stage in the chain.
85
91
  * Used by `runWorkflow` (start stage), `advanceChain` (next stage, via
86
92
  * `ChainDeps`), and the resume entries — the walk's single catch site.
@@ -88,13 +94,13 @@ export function advance(
88
94
  * mid-stage `WorkflowAbortError` vs terminal entry-throw) to
89
95
  * `withStageEntryGuard` (failure.ts).
90
96
  */
91
- export async function runStageOrRecordFailure(
92
- curCtx: WorkflowHostContext,
97
+ export async function dispatchStageOrRecordFailure(
98
+ hostCtx: WorkflowHostContext,
93
99
  name: string,
94
100
  idx: number,
95
101
  run: RunContext,
96
102
  ): Promise<ChainOutcome> {
97
- return withStageEntryGuard(curCtx, name, run, () => runStage(curCtx, name, idx, run));
103
+ return withStageEntryGuard(hostCtx, name, run, () => dispatchStage(hostCtx, name, idx, run));
98
104
  }
99
105
 
100
106
  // ---------------------------------------------------------------------------
@@ -122,8 +128,8 @@ export function inputForStage(stage: ResolvedStage, run: RunContext): string {
122
128
  }
123
129
 
124
130
  /** One stage activation — dispatch on the mode derived once by `resolveStage`. */
125
- export async function runStage(
126
- curCtx: WorkflowHostContext,
131
+ export async function dispatchStage(
132
+ hostCtx: WorkflowHostContext,
127
133
  currentName: string,
128
134
  idx: number,
129
135
  run: RunContext,
@@ -131,17 +137,17 @@ export async function runStage(
131
137
  const stage = resolveStage(currentName, idx, run);
132
138
  switch (stage.mode) {
133
139
  case "loop":
134
- return runLoopStage(curCtx, stage, idx, run);
140
+ return runLoopStage(hostCtx, stage, idx, run);
135
141
  case "script":
136
142
  // Script stages skip the skill pipeline — no `/skill:` prompt, no
137
143
  // registry check, no session, no collector snapshot. Input-schema
138
144
  // validation still applies; the script runner owns its own status
139
145
  // line + lifecycle fires.
140
146
  await ensureInputValid(stage, run);
141
- return runScript(curCtx, stage, idx, run, advance);
147
+ return runScript(hostCtx, stage, idx, run, advance);
142
148
  case "prompt":
143
149
  case "skill":
144
- return runSingleStage(curCtx, stage, idx, run);
150
+ return runSingleStage(hostCtx, stage, idx, run);
145
151
  }
146
152
  }
147
153
 
@@ -154,7 +160,7 @@ export async function runStage(
154
160
  * branch (`computeBranchOffset`), resume takes it from the persisted row.
155
161
  */
156
162
  async function prepareSingleStage(
157
- curCtx: WorkflowHostContext,
163
+ hostCtx: WorkflowHostContext,
158
164
  stage: ResolvedStage,
159
165
  idx: number,
160
166
  run: RunContext,
@@ -169,12 +175,12 @@ async function prepareSingleStage(
169
175
  await ensureInputValid(stage, run);
170
176
  await ensureContractInputValid(stage, run);
171
177
 
172
- const snapshot = await captureStageSnapshot(curCtx, stage.name, stage.def, idx, run);
178
+ const snapshot = await captureStageSnapshot(hostCtx, stage.name, stage.def, idx, run);
173
179
  return { prompt, snapshot };
174
180
  }
175
181
 
176
182
  /**
177
- * The `StageSession` both single-stage entries build — live and resume use
183
+ * The `StageSessionContext` both single-stage entries build — live and resume use
178
184
  * the SAME continuation pair (`onSuccess` → `advance`, `onFailure` →
179
185
  * partial-artifact recap), so a promoted/reattached stage chains onward
180
186
  * exactly like a live one.
@@ -185,7 +191,7 @@ function buildSingleStageSession(
185
191
  run: RunContext,
186
192
  prep: { prompt: string; snapshot: unknown },
187
193
  branchOffset: number | undefined,
188
- ): StageSession {
194
+ ): StageSessionContext {
189
195
  return {
190
196
  cwd: run.cwd,
191
197
  runId: run.runId,
@@ -217,18 +223,45 @@ function buildSingleStageSession(
217
223
  * (loop.ts) — the loop path's one-helper-for-live-and-resume exemplar.
218
224
  */
219
225
  function announceSingleStageStart(
220
- curCtx: WorkflowHostContext,
226
+ hostCtx: WorkflowHostContext,
221
227
  run: RunContext,
222
228
  stage: Pick<ResolvedStage, "name" | "stageNumber" | "skill">,
223
229
  ): Promise<void> {
224
230
  return run.lifecycle.fire(
225
- curCtx,
231
+ hostCtx,
226
232
  "onStageStart",
227
233
  skillStageRef(stage.name, stage.stageNumber, stage.skill),
228
234
  lifecycleCtxFor(run),
229
235
  );
230
236
  }
231
237
 
238
+ /** A `produces` stage carrying an effective output schema — the gate's
239
+ * qualifying predicate. Spelled through the shared `effectiveOutputSchemaOf`
240
+ * so the gate and the extraction retry loop agree on "schema-validated". */
241
+ const isSchemaValidatedProducesStage = (stage: ResolvedStage, skillContracts: SkillContractMap | undefined): boolean =>
242
+ stage.def.kind === "produces" && !!effectiveOutputSchemaOf(stage.def, stage.name, skillContracts);
243
+
244
+ /** The worktree digest and progress point match the last gated baseline for
245
+ * THIS stage — no observable fix ran between the two dispatches. The
246
+ * `digest !== undefined` term narrows the digest compare inside the body. */
247
+ const isUnchangedTreeRedispatch = (
248
+ baseline: { stage: string; digest: string; stagesCompleted: number } | undefined,
249
+ stage: ResolvedStage,
250
+ digest: string | undefined,
251
+ stagesCompleted: number,
252
+ ): boolean =>
253
+ baseline !== undefined &&
254
+ baseline.stage === stage.name &&
255
+ digest !== undefined &&
256
+ digest === baseline.digest &&
257
+ stagesCompleted === baseline.stagesCompleted;
258
+
259
+ /** Records this dispatch's worktree digest + progress point as the gate
260
+ * baseline, so the NEXT dispatch of this stage compares against it. */
261
+ const recordGatedDispatchBaseline = (state: RunState, stage: ResolvedStage, digest: string): void => {
262
+ state.lastGatedDispatch = { stage: stage.name, digest, stagesCompleted: state.stagesCompleted };
263
+ };
264
+
232
265
  /**
233
266
  * Validation-retry mechanism-2: fail-fast a re-dispatch of a schema-validated
234
267
  * produces stage against an UNCHANGED worktree (no observable fix since the last
@@ -239,7 +272,7 @@ function announceSingleStageStart(
239
272
  * Operator resume is excluded: session-backed resume never reaches
240
273
  * `runSingleStage`, and a cold re-run under `trigger.meta.resumedFrom` is
241
274
  * bypassed by `isOperatorResume`. The terminal skip carries the failure memo
242
- * for free through the shared `recordTerminalFailure` writer
275
+ * for free through the shared `recordFatalFailure` writer
243
276
  * (`packages/rpiv-workflow/audit.ts:122`). An `undefined` digest (non-repo / git
244
277
  * missing) ALWAYS proceeds — degrade on a missing signal, never skip.
245
278
  *
@@ -251,38 +284,28 @@ function announceSingleStageStart(
251
284
  * drift on the precedence order or the contract key.
252
285
  */
253
286
  export async function gateValidationRedispatch(
254
- curCtx: WorkflowHostContext,
287
+ hostCtx: WorkflowHostContext,
255
288
  stage: ResolvedStage,
256
289
  run: RunContext,
257
290
  ): Promise<boolean> {
258
291
  const isOperatorResume = run.trigger.meta?.resumedFrom !== undefined;
259
- const qualifies =
260
- stage.def.kind === "produces" && !!effectiveOutputSchemaOf(stage.def, stage.name, run.skillContracts);
261
- if (!isOperatorResume && qualifies) {
262
- const digest = resolveDigest(run.worktreeDigest, run.cwd);
263
- const baseline = run.state.lastGatedDispatch;
264
- if (
265
- baseline &&
266
- baseline.stage === stage.name &&
267
- digest !== undefined &&
268
- digest === baseline.digest &&
269
- run.state.stagesCompleted === baseline.stagesCompleted
270
- ) {
271
- await recordTerminalFailure(
272
- curCtx,
273
- auditCtxFor(run, stage.name, stage.skill),
274
- failedArgs(FAIL_VALIDATE_GATE_SKIPPED(stage.skill)),
275
- );
276
- return true;
277
- }
278
- // Overwrite the baseline on every qualifying dispatch with a defined
279
- // digest, so the NEXT dispatch of this stage compares against the most
280
- // recent state (the "tree changed" / "fix ran" proceed arms both land
281
- // here after the non-matching halt check above).
282
- if (digest !== undefined) {
283
- run.state.lastGatedDispatch = { stage: stage.name, digest, stagesCompleted: run.state.stagesCompleted };
284
- }
292
+ // Qualify → read guard → write. An operator-resume run and a stage with no
293
+ // effective output schema both fall through, leaving `lastGatedDispatch` alone.
294
+ if (isOperatorResume || !isSchemaValidatedProducesStage(stage, run.skillContracts)) return false;
295
+ const digest = resolveDigest(run.worktreeDigest, run.cwd);
296
+ if (isUnchangedTreeRedispatch(run.state.lastGatedDispatch, stage, digest, run.state.stagesCompleted)) {
297
+ await recordFatalFailure(
298
+ hostCtx,
299
+ auditCtxFor(run, stage.name, stage.skill),
300
+ failedArgs(FAIL_VALIDATE_GATE_SKIPPED(stage.skill)),
301
+ );
302
+ return true;
285
303
  }
304
+ // Overwrite the baseline on every qualifying dispatch with a defined
305
+ // digest, so the NEXT dispatch of this stage compares against the most
306
+ // recent state (the "tree changed" / "fix ran" proceed arms both land
307
+ // here after the non-matching halt check above).
308
+ if (digest !== undefined) recordGatedDispatchBaseline(run.state, stage, digest);
286
309
  return false;
287
310
  }
288
311
 
@@ -297,10 +320,10 @@ export async function gateValidationRedispatch(
297
320
  * prompt stage (it cannot set an explicit skill — load validation forbids
298
321
  * it), so the status/session/audit labels are correct for both without a
299
322
  * separate label. A PromptFn throw propagates to
300
- * `runStageOrRecordFailure`, which records a terminal failure.
323
+ * `dispatchStageOrRecordFailure`, which records a terminal failure.
301
324
  */
302
325
  async function runSingleStage(
303
- curCtx: WorkflowHostContext,
326
+ hostCtx: WorkflowHostContext,
304
327
  stage: ResolvedStage,
305
328
  idx: number,
306
329
  run: RunContext,
@@ -309,12 +332,12 @@ async function runSingleStage(
309
332
  // fail-fast an unchanged-tree re-dispatch of a schema-validated produces
310
333
  // stage BEFORE preflights or the session open. `true` ⇒ already recorded a
311
334
  // terminal failure row; halt here.
312
- if (await gateValidationRedispatch(curCtx, stage, run)) return "halted";
335
+ if (await gateValidationRedispatch(hostCtx, stage, run)) return "halted";
313
336
 
314
- const prep = await prepareSingleStage(curCtx, stage, idx, run);
337
+ const prep = await prepareSingleStage(hostCtx, stage, idx, run);
315
338
 
316
339
  // onStageStart fires after preflight, before the Pi session opens.
317
- await announceSingleStageStart(curCtx, run, stage);
340
+ await announceSingleStageStart(hostCtx, run, stage);
318
341
 
319
342
  // `continue` forks the predecessor's persisted session (`run.state.lastSession`)
320
343
  // into a fresh child carrying its transcript; `continueStageSession` re-derives
@@ -326,13 +349,13 @@ async function runSingleStage(
326
349
  const file = continueForkFile(run);
327
350
  if (file) {
328
351
  const s = buildSingleStageSession(stage, idx, run, prep, undefined);
329
- await forkChildSession(curCtx, s, file, (child) => continueStageSession(curCtx, child, s));
352
+ await forkChildSession(hostCtx, s, file, (child) => continueStageSession(hostCtx, child, s));
330
353
  return "dispatched";
331
354
  }
332
- curCtx.ui.notify(MSG_CONTINUE_FALLBACK(stage.skill), "info");
355
+ hostCtx.ui.notify(MSG_CONTINUE_FALLBACK(stage.skill), "info");
333
356
  }
334
357
 
335
- await runStageSession(curCtx, buildSingleStageSession(stage, idx, run, prep, undefined));
358
+ await executeStageSession(hostCtx, buildSingleStageSession(stage, idx, run, prep, undefined));
336
359
  return "dispatched";
337
360
  }
338
361
 
@@ -352,26 +375,26 @@ function continueForkFile(run: RunContext): string | null {
352
375
  * (reattach), instead of re-running cold. Selected by `selectResumeEntry`
353
376
  * when the failed trailer carries a `session` (the structured dispatch).
354
377
  * Delegates the same classify-then-record policy as the live entry
355
- * (`runStageOrRecordFailure`) to `withStageEntryGuard` (failure.ts); the
378
+ * (`dispatchStageOrRecordFailure`) to `withStageEntryGuard` (failure.ts); the
356
379
  * fallback ladder itself lives in `resumeWithSessionLadder` below — the
357
380
  * resume `inner` still wraps it, so a reattached `postStage`
358
381
  * `WorkflowAbortError` or machinery throw is classified (abort vs terminal
359
382
  * entry-throw) by the same authority as the live path.
360
383
  */
361
384
  export async function resumeStageWithSession(
362
- curCtx: WorkflowHostContext,
385
+ hostCtx: WorkflowHostContext,
363
386
  last: WorkflowStage,
364
387
  idx: number,
365
388
  run: RunContext,
366
389
  ): Promise<ChainOutcome> {
367
- return withStageEntryGuard(curCtx, last.stage, run, () => resumeWithSessionLadder(curCtx, last, idx, run));
390
+ return withStageEntryGuard(hostCtx, last.stage, run, () => resumeWithSessionLadder(hostCtx, last, idx, run));
368
391
  }
369
392
 
370
393
  /**
371
394
  * THE resume fallback ladder (called by `resumeStageWithSession` via
372
395
  * `withStageEntryGuard`). Every precondition miss notifies
373
396
  * (`MSG_RESUME_SESSION_FALLBACK`) and degrades to today's cold re-run via
374
- * `runStageOrRecordFailure` — never a refusal, never a throw:
397
+ * `dispatchStageOrRecordFailure` — never a refusal, never a throw:
375
398
  *
376
399
  * 1. resolved mode must be `prompt`/`skill` (loop trailers never reach
377
400
  * this arm — they carry `parent`; script stages are sessionless);
@@ -381,7 +404,7 @@ export async function resumeStageWithSession(
381
404
  * 4. `reattachChildSession` spawns a child BOUND to the persisted file (the
382
405
  * host opens it, does NOT replay the prompt) and `reattachStageSession`
383
406
  * (sessions/reattach.ts) runs promotion → reattach inside it, with the
384
- * SAME `StageSession` the live path builds — `branchOffset` taken from
407
+ * SAME `StageSessionContext` the live path builds — `branchOffset` taken from
385
408
  * the PERSISTED row (continue-policy stages), `undefined` for fresh.
386
409
  *
387
410
  * (The cooperative-abort pre-check — formerly step 1 here — now lives in
@@ -395,7 +418,7 @@ export async function resumeStageWithSession(
395
418
  * live-session swap for the user to dismiss.
396
419
  */
397
420
  async function resumeWithSessionLadder(
398
- curCtx: WorkflowHostContext,
421
+ hostCtx: WorkflowHostContext,
399
422
  last: WorkflowStage,
400
423
  idx: number,
401
424
  run: RunContext,
@@ -404,29 +427,29 @@ async function resumeWithSessionLadder(
404
427
  const stage = resolveStage(last.stage, idx, run);
405
428
 
406
429
  const fallBackCold = (why: string): Promise<ChainOutcome> => {
407
- curCtx.ui.notify(MSG_RESUME_SESSION_FALLBACK(stage.skill, why), "info");
408
- return runStageOrRecordFailure(curCtx, last.stage, idx, run);
430
+ hostCtx.ui.notify(MSG_RESUME_SESSION_FALLBACK(stage.skill, why), "info");
431
+ return dispatchStageOrRecordFailure(hostCtx, last.stage, idx, run);
409
432
  };
410
433
 
411
434
  // Defensive: a session-backed row for a stage whose def since became a
412
435
  // loop/script stage — the session machinery below doesn't apply.
413
436
  if (stage.mode !== "prompt" && stage.mode !== "skill") {
414
- return runStageOrRecordFailure(curCtx, last.stage, idx, run);
437
+ return dispatchStageOrRecordFailure(hostCtx, last.stage, idx, run);
415
438
  }
416
439
  const file = locateSessionFile(ref, run.runId, run.cwd);
417
440
  if (!file) return fallBackCold("session file not found");
418
441
 
419
- const prep = await prepareSingleStage(curCtx, stage, idx, run);
442
+ const prep = await prepareSingleStage(hostCtx, stage, idx, run);
420
443
  const s = buildSingleStageSession(stage, idx, run, prep, ref.branchOffset);
421
444
 
422
445
  // Same bracketing as live: onStageStart before the (re)attached child opens.
423
- await announceSingleStageStart(curCtx, run, stage);
446
+ await announceSingleStageStart(hostCtx, run, stage);
424
447
 
425
448
  // Detached reattach: spawn a child BOUND to the persisted session file (the
426
449
  // host opens it and does NOT replay the prompt); reattachStageSession promotes
427
450
  // from the loaded branch or nudges via resendIntoChild. Replaces the deleted
428
- // live-session swap (`curCtx.switchSession`).
429
- await reattachChildSession(curCtx, s, file, (child) => reattachStageSession(curCtx, child, s));
451
+ // live-session swap (`hostCtx.switchSession`).
452
+ await reattachChildSession(hostCtx, s, file, (child) => reattachStageSession(hostCtx, child, s));
430
453
  return "dispatched";
431
454
  }
432
455
 
@@ -455,7 +478,7 @@ async function resumeWithSessionLadder(
455
478
  * message is the stage's own `prompt`, resolved by the driver at dispatch.
456
479
  */
457
480
  async function runLoopStage(
458
- curCtx: WorkflowHostContext,
481
+ hostCtx: WorkflowHostContext,
459
482
  stage: ResolvedStage,
460
483
  idx: number,
461
484
  run: RunContext,
@@ -468,10 +491,10 @@ async function runLoopStage(
468
491
  let units: readonly Unit[] | undefined;
469
492
  if (loop.kind === "fanout") {
470
493
  units = await loop.units({ cwd: run.cwd, artifact: currentPrimaryArtifact(run.state), state: run.state });
471
- if (units.length === 0) return runSingleStage(curCtx, stage, idx, run);
494
+ if (units.length === 0) return runSingleStage(hostCtx, stage, idx, run);
472
495
  // deps cycle / dangling-id → clean halt BEFORE any dispatch (the runtime unit
473
496
  // list is invisible to the static load gate, so this is the only place it runs).
474
- validateUnitDeps(units, stage.name);
497
+ ensureUnitDeps(units, stage.name);
475
498
  }
476
499
 
477
500
  runLoopPreflights(stage, run);
@@ -486,8 +509,8 @@ async function runLoopStage(
486
509
  },
487
510
  );
488
511
 
489
- await announceLoopStart(curCtx, run, entry);
490
- await runLoop(curCtx, entry, freshCursor(), run, buildLoopDeps());
512
+ await announceLoopStart(hostCtx, run, entry);
513
+ await runLoop(hostCtx, entry, freshCursor(), run, buildLoopDeps());
491
514
  return "dispatched";
492
515
  }
493
516
 
@@ -497,17 +520,17 @@ async function runLoopStage(
497
520
  */
498
521
  export function buildLoopDeps(): LoopDeps {
499
522
  return {
500
- runStageSession,
523
+ executeStageSession,
501
524
  advanceAfter: (freshCtx, name, completedIdx, ctx) => advance(freshCtx, name, completedIdx, ctx),
502
525
  captureSnapshot: (ctx, name, def, i, r) => captureStageSnapshot(ctx, name, def, i, r),
503
526
  haltLoop,
504
527
  // Mid-flight run abort at the loop seam → FAIL_WORKFLOW_ABORTED.
505
- recordAborted: (curCtx, name, run) => recordAbortedAtSeam(curCtx, name, run).then(() => undefined),
528
+ recordAborted: (hostCtx, name, run) => recordAbortedAtSeam(hostCtx, name, run).then(() => undefined),
506
529
  // Unexpected worker rejection → terminal-failure row, no re-throw. The
507
530
  // unit's identity rides as a STRUCTURED field (`unit`) on the row — `stage`
508
531
  // stays the parent graph identity, not a `name (unit N)` string.
509
- recordWorkerThrow: (curCtx, unit, skill, run, err) =>
510
- recordEntryThrow(curCtx, unit.parent, run, err, { ref: unit, skill }).then(() => undefined),
532
+ recordWorkerThrow: (hostCtx, unit, skill, run, err) =>
533
+ recordEntryThrow(hostCtx, unit.parent, run, err, { ref: unit, skill }).then(() => undefined),
511
534
  };
512
535
  }
513
536
 
@@ -517,21 +540,21 @@ export function buildLoopDeps(): LoopDeps {
517
540
  * not a loop, so "loop cap exceeded" would misattribute the failure.
518
541
  */
519
542
  export async function haltLoop(
520
- curCtx: WorkflowHostContext,
543
+ hostCtx: WorkflowHostContext,
521
544
  run: RunContext,
522
545
  e: Pick<LoopEntry, "name" | "def">,
523
546
  count: number,
524
547
  cap: number,
525
548
  ): Promise<void> {
526
549
  const args = e.def.verify ? failedArgs(FAIL_VERIFY_FAILED(e.name, cap)) : failedArgs(FAIL_LOOP_CAP_HALT(count, cap));
527
- await haltChain(curCtx, run, e.name, e.name, args);
550
+ await haltChain(hostCtx, run, e.name, e.name, args);
528
551
  }
529
552
 
530
553
  /** Runs whose snapshot-failure warning already fired — one notify per run, not per stage/unit. */
531
554
  const snapshotWarnedRuns = new WeakSet<RunContext>();
532
555
 
533
556
  export async function captureStageSnapshot(
534
- curCtx: WorkflowHostContext,
557
+ hostCtx: WorkflowHostContext,
535
558
  stageName: string,
536
559
  def: StageDef,
537
560
  idx: number,
@@ -552,7 +575,7 @@ export async function captureStageSnapshot(
552
575
  // diffing for the whole run, so the first failure warns.
553
576
  if (!snapshotWarnedRuns.has(run)) {
554
577
  snapshotWarnedRuns.add(run);
555
- curCtx.ui.notify(MSG_SNAPSHOT_FAILED(stageName, formatError(e)), "warning");
578
+ hostCtx.ui.notify(MSG_SNAPSHOT_FAILED(stageName, formatError(e)), "warning");
556
579
  }
557
580
  return undefined;
558
581
  }
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,7 +41,6 @@ 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
46
  import type { BranchEntry } from "../transcript.js";
@@ -49,7 +49,7 @@ import type { RunContext, RunWorkflowOptions, RunWorkflowResult } from "../types
49
49
  import { reconstructState } from "./resume.js";
50
50
  import { resumeRefusalError, selectResumeEntry } from "./resume-entry.js";
51
51
  import { buildRunContext, freshRunState } from "./run-context.js";
52
- import { runStageOrRecordFailure } from "./run-stage.js";
52
+ import { dispatchStageOrRecordFailure } from "./run-stage.js";
53
53
 
54
54
  // ---------------------------------------------------------------------------
55
55
  // Shared tail — executeRun
@@ -232,7 +232,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
232
232
  // makes the run unlistable and unresumable while its stage rows land, so a
233
233
  // failed append rejects the start and rolls back the name claim (the index
234
234
  // must not point at a run that never existed).
235
- const headerWritten = writeHeader(cwd, {
235
+ const headerWritten = appendHeader(cwd, {
236
236
  runId,
237
237
  workflow: workflow.name,
238
238
  input: options.input,
@@ -269,7 +269,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
269
269
  trigger,
270
270
  },
271
271
  );
272
- return await executeRun(execCtx, run, () => runStageOrRecordFailure(execCtx, workflow.start, 0, run));
272
+ return await executeRun(execCtx, run, () => dispatchStageOrRecordFailure(execCtx, workflow.start, 0, run));
273
273
  } finally {
274
274
  dispose?.(); // unsubscribe the onTerminalInput tap — leaks accumulate on the TUI otherwise
275
275
  }
@@ -29,7 +29,7 @@
29
29
  */
30
30
 
31
31
  import type { ScriptContext } from "../api.js";
32
- import { auditCtxFor, failAuditWrite, failedArgs, recordTerminalFailure } from "../audit.js";
32
+ import { auditCtxFor, failAuditWrite, failedArgs, recordFatalFailure } from "../audit.js";
33
33
  import { allocateStageNumber, persistStageSuccess } from "../audit-rows.js";
34
34
  import { lifecycleCtxFor, scriptStageRef } from "../events.js";
35
35
  import type { Artifact } from "../handle.js";
@@ -49,22 +49,22 @@ import type { ResolvedStage } from "./resolve-stage.js";
49
49
  /**
50
50
  * Drive a script stage: lifecycle-fire `onStageStart`, retry-loop the
51
51
  * `run` body against `outputSchema`, then either persist + advance or
52
- * record a terminal failure. Sole entry point — `runStage` branches
52
+ * record a terminal failure. Sole entry point — `dispatchStage` branches
53
53
  * here on `mode === "script"`, passing the composed `advance`.
54
54
  *
55
- * Caller pre-conditions (held by `runStage`):
55
+ * Caller pre-conditions (held by `dispatchStage`):
56
56
  * - `ensureInputValid` already passed.
57
57
  * - `mode === "script"` (a script stage cannot carry a `loop`).
58
58
  */
59
59
  export async function runScript(
60
- curCtx: WorkflowHostContext,
60
+ hostCtx: WorkflowHostContext,
61
61
  stage: ResolvedStage,
62
62
  idx: number,
63
63
  run: RunContext,
64
64
  advance: AdvanceFn,
65
65
  ): Promise<ChainOutcome> {
66
66
  const ref = scriptStageRef(stage.name, stage.stageNumber);
67
- await run.lifecycle.fire(curCtx, "onStageStart", ref, lifecycleCtxFor(run));
67
+ await run.lifecycle.fire(hostCtx, "onStageStart", ref, lifecycleCtxFor(run));
68
68
 
69
69
  const scriptCtx: ScriptContext = {
70
70
  cwd: run.cwd,
@@ -85,7 +85,7 @@ export async function runScript(
85
85
  },
86
86
  {
87
87
  produce: async () => {
88
- const invocation = await invokeRun(curCtx, stage, scriptCtx, run, stageNumber);
88
+ const invocation = await invokeRun(hostCtx, stage, scriptCtx, run, stageNumber);
89
89
  if (!invocation.ok) return { kind: "aborted", abort: "recorded" };
90
90
  const output = finalizeOutput(
91
91
  invocation.raw,
@@ -110,7 +110,7 @@ export async function runScript(
110
110
  };
111
111
  },
112
112
  onRetry: async (attempt) => {
113
- await run.lifecycle.fire(curCtx, "onStageRetry", ref, attempt, lifecycleCtxFor(run));
113
+ await run.lifecycle.fire(hostCtx, "onStageRetry", ref, attempt, lifecycleCtxFor(run));
114
114
  return { kind: "ok" };
115
115
  },
116
116
  },
@@ -119,8 +119,8 @@ export async function runScript(
119
119
  if (result.kind === "aborted") return "halted";
120
120
  if (result.kind === "exhausted") {
121
121
  const failureSummary = result.failures.map(describeFailure).join("; ");
122
- await recordTerminalFailure(
123
- curCtx,
122
+ await recordFatalFailure(
123
+ hostCtx,
124
124
  scriptAuditCtx(run, stage, stageNumber),
125
125
  failedArgs(FAIL_VALIDATION_EXHAUSTED(stage.name, failureSummary)),
126
126
  );
@@ -137,12 +137,12 @@ export async function runScript(
137
137
  stage.def,
138
138
  );
139
139
  if (!persisted) {
140
- failAuditWrite(curCtx, run.state, stage.name);
140
+ failAuditWrite(hostCtx, run.state, stage.name);
141
141
  return "halted";
142
142
  }
143
143
 
144
- await run.lifecycle.fire(curCtx, "onStageEnd", ref, output, lifecycleCtxFor(run));
145
- return advance(curCtx, stage.name, idx, run);
144
+ await run.lifecycle.fire(hostCtx, "onStageEnd", ref, output, lifecycleCtxFor(run));
145
+ return advance(hostCtx, stage.name, idx, run);
146
146
  }
147
147
 
148
148
  type ScriptInvocationResult =
@@ -157,7 +157,7 @@ type ScriptInvocationResult =
157
157
  * failure attributed via `MSG_SCRIPT_THREW` + `ERR_SCRIPT_THREW`.
158
158
  */
159
159
  async function invokeRun(
160
- curCtx: WorkflowHostContext,
160
+ hostCtx: WorkflowHostContext,
161
161
  stage: ResolvedStage,
162
162
  scriptCtx: ScriptContext,
163
163
  run: RunContext,
@@ -172,10 +172,10 @@ async function invokeRun(
172
172
  return { ok: true, raw };
173
173
  } catch (e) {
174
174
  const reason = formatError(e);
175
- // `recordTerminalFailure` fires `onStageError` itself — the caller must
175
+ // `recordFatalFailure` fires `onStageError` itself — the caller must
176
176
  // not fire a second time on the `ok: false` return.
177
- await recordTerminalFailure(
178
- curCtx,
177
+ await recordFatalFailure(
178
+ hostCtx,
179
179
  scriptAuditCtx(run, stage, stageNumber),
180
180
  failedArgs(FAIL_SCRIPT_THREW(stage.name, reason)),
181
181
  );
@@ -184,7 +184,7 @@ async function invokeRun(
184
184
  }
185
185
 
186
186
  /**
187
- * Build the `AuditCtx`-shaped object `recordTerminalFailure` needs for
187
+ * Build the `AuditContext`-shaped object `recordFatalFailure` needs for
188
188
  * a script-stage halt. The `skill` field doubles as the lifecycle
189
189
  * `onStageError` ref payload — using `stage.name` keeps the failure
190
190
  * attribution aligned with the success row's `stage` identity.