@juicesharp/rpiv-workflow 1.20.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/api.ts +1 -1
  2. package/audit-ctx.ts +103 -0
  3. package/audit-rows.ts +18 -0
  4. package/audit.ts +119 -164
  5. package/built-ins.ts +26 -6
  6. package/chain-state.ts +119 -68
  7. package/command-run.ts +35 -30
  8. package/command.ts +10 -4
  9. package/docs/workflow-authoring.md +34 -2
  10. package/events.ts +44 -4
  11. package/execution-host.ts +75 -0
  12. package/host.ts +137 -82
  13. package/internal-utils.ts +89 -3
  14. package/internal.ts +1 -0
  15. package/judge.ts +23 -11
  16. package/load/alias.ts +3 -3
  17. package/load/index.ts +15 -1
  18. package/load/issues.ts +2 -2
  19. package/load/legacy.ts +2 -2
  20. package/load/resolve-default.ts +3 -4
  21. package/load/skill-contract-phase.ts +1 -1
  22. package/loop-constructors.ts +19 -618
  23. package/loop-def.ts +60 -15
  24. package/loop-kinds.ts +319 -62
  25. package/loop-parallel.ts +250 -0
  26. package/loop-waves.ts +99 -0
  27. package/loop.ts +106 -80
  28. package/loops/constructors.ts +334 -0
  29. package/loops/derivations.ts +65 -0
  30. package/loops/introspection.ts +184 -0
  31. package/loops/panel.ts +196 -0
  32. package/loops/verify.ts +99 -0
  33. package/messages.ts +58 -33
  34. package/outcomes/collectors/index.ts +1 -0
  35. package/outcomes/collectors/text-scan.ts +47 -0
  36. package/outcomes/collectors/transcript-path.ts +2 -15
  37. package/outcomes/collectors/union.ts +2 -1
  38. package/outcomes/collectors/url.ts +2 -14
  39. package/outcomes/collectors/workspace-diff.ts +1 -1
  40. package/outcomes/git-commit.ts +57 -6
  41. package/output-spec.ts +1 -1
  42. package/output.ts +59 -1
  43. package/package.json +16 -6
  44. package/preview.ts +18 -18
  45. package/registration.ts +11 -4
  46. package/routing-dsl.ts +53 -41
  47. package/routing.ts +46 -0
  48. package/runner/chain-advance.ts +30 -17
  49. package/runner/errors.ts +7 -30
  50. package/runner/failure.ts +67 -13
  51. package/runner/input-validation.ts +8 -5
  52. package/runner/preflight.ts +17 -21
  53. package/runner/resume-entry.ts +23 -3
  54. package/runner/resume-loop.ts +50 -29
  55. package/runner/resume.ts +96 -10
  56. package/runner/run-context.ts +20 -16
  57. package/runner/run-stage.ts +125 -91
  58. package/runner/runner.ts +163 -69
  59. package/runner/script-stage.ts +23 -29
  60. package/schema-compat.ts +1 -2
  61. package/semaphore.ts +55 -0
  62. package/sessions/extraction.ts +103 -60
  63. package/sessions/halt-routing.ts +195 -0
  64. package/sessions/index.ts +2 -2
  65. package/sessions/locate.ts +60 -9
  66. package/sessions/reattach.ts +28 -20
  67. package/sessions/sessions.ts +103 -191
  68. package/sessions/spawn.ts +132 -119
  69. package/sessions/success-persist.ts +89 -0
  70. package/skill-contracts/composition.ts +8 -10
  71. package/skill-contracts/harvest.ts +3 -2
  72. package/skill-contracts/registry.ts +1 -1
  73. package/stage-def.ts +115 -47
  74. package/stage-errors.ts +84 -0
  75. package/stage-identity.ts +56 -0
  76. package/startup.ts +1 -0
  77. package/state/paths.ts +11 -3
  78. package/state/raw.ts +2 -3
  79. package/state/resolve.ts +3 -3
  80. package/state/state.ts +26 -3
  81. package/state/writes.ts +1 -1
  82. package/types.ts +97 -43
  83. package/validate/contract-compat.ts +16 -11
  84. package/validate/graph.ts +10 -1
  85. package/validate/issue.ts +20 -6
  86. package/validate/stage-rules.ts +139 -60
  87. package/validate-output.ts +27 -20
  88. package/validate-workflow.ts +5 -3
  89. package/validation-bounds.ts +35 -0
  90. package/load/cache.test.ts +0 -82
  91. package/load/shape-guards.test.ts +0 -77
  92. package/outcomes/collectors/directory-path.test.ts +0 -64
  93. package/outcomes/collectors/tool-call.test.ts +0 -112
  94. package/outcomes/collectors/transcript-path.test.ts +0 -70
  95. package/outcomes/collectors/union.test.ts +0 -113
  96. package/outcomes/collectors/url.test.ts +0 -67
  97. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  98. package/outcomes/git-commit.test.ts +0 -240
  99. package/outcomes/parsers/json-body.test.ts +0 -80
  100. package/runner/by-name.test.ts +0 -95
  101. package/runner/by-run-id.test.ts +0 -115
  102. package/runner/header-write-failure.test.ts +0 -64
  103. package/runner/resume-loop.test.ts +0 -1410
  104. package/runner/resume-session.test.ts +0 -400
  105. package/runner/resume.test.ts +0 -1805
  106. package/sessions/locate.test.ts +0 -77
package/runner/resume.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  * fold-replayed `RunState` at the unit boundary + this generation's
9
9
  * accumulated outputs. Because the fold replays rows in trail order, at row
10
10
  * *i* the state is byte-identical to what the live driver saw — so the fold
11
- * verifies EVERY unit row against the recomputed expectation (strictly
12
- * stronger than the old per-primitive half-guards). Drift (or a generator
11
+ * verifies EVERY unit row against the recomputed expectation. Drift (or a
12
+ * generator
13
13
  * throw) does not refuse outright: the fold finishes applying so state is
14
14
  * complete, and returns `drift` — `resumeWorkflow`'s entry thunk records the
15
15
  * terminal failure with full lifecycle bracketing and zero dispatch.
@@ -25,16 +25,24 @@
25
25
  */
26
26
 
27
27
  import type { LoopDef, StageDef, Unit, Workflow } from "../api.js";
28
- import { applyStageSuccess } from "../audit-rows.js";
28
+ import { applyStageSuccess, rollLastSession } from "../audit-rows.js";
29
29
  import { stageEntryArgs } from "../chain-state.js";
30
30
  import type { Artifact } from "../handle.js";
31
31
  import { formatError } from "../internal-utils.js";
32
32
  import { panelMembers } from "../judge.js";
33
33
  import { projectResult, publishPanelVerdict } from "../loop.js";
34
- import { effectiveLoopOf } from "../loop-constructors.js";
35
- import { advanceCursor, freshCursor, judgeStageDef, type LoopCursor, loopStrategyOf } from "../loop-kinds.js";
34
+ import { effectiveLoopOf, freezesEntryArgsOf } from "../loop-constructors.js";
35
+ import {
36
+ advanceCursor,
37
+ foldFanoutCompletion,
38
+ freshCursor,
39
+ judgeStageDef,
40
+ type LoopCursor,
41
+ sequentialStrategyOf,
42
+ unitTagOf,
43
+ } from "../loop-kinds.js";
36
44
  import { ERR_RESUME_LOOP_MISMATCH } from "../messages.js";
37
- import type { Output } from "../output.js";
45
+ import { failedOutput, type Output, outputMeta } from "../output.js";
38
46
  import {
39
47
  readAllStagesForResume,
40
48
  STATE_SCHEMA_VERSION,
@@ -107,6 +115,7 @@ export async function reconstructState(
107
115
 
108
116
  const acc: FoldAcc = {
109
117
  cwd,
118
+ runId: header.runId,
110
119
  state: freshRunState(header.input),
111
120
  visited: new Set<string>(),
112
121
  lastStageNumber: 0,
@@ -122,9 +131,26 @@ export async function reconstructState(
122
131
  if (refusal) return refusal;
123
132
  continue;
124
133
  }
134
+ // A non-completed, parent-unset row for the SAME stage as the open FANOUT
135
+ // generation is that generation's own halt marker: a mid-flight abort
136
+ // writes a stage-level `aborted` row (recordAbortedAtSeam) AFTER the
137
+ // completed unit rows. Closing the generation on it would discard the
138
+ // reconstructed cursor whose completed-unit slots are already filled,
139
+ // forcing resume to cold-re-enter the loop and re-dispatch EVERY unit
140
+ // (finding 7: the aborted-mid-flight fanout re-ran completed units,
141
+ // duplicating the channel and collapsing the downstream fan-in). Keep the
142
+ // generation open — `trailing` then carries the filled slots and
143
+ // `pendingFanoutIndices` dispatches only the genuinely-pending units. A
144
+ // COMPLETED parent row still closes+advances; a stage with no completed
145
+ // units never opened a generation, so it falls through and re-runs whole.
146
+ if (acc.gen?.parent === row.stage && acc.gen.loop.kind === "fanout" && row.status !== "completed") {
147
+ acc.visited.add(row.stage);
148
+ acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
149
+ continue;
150
+ }
125
151
  closeGeneration(acc);
126
152
  const def = workflow.stages[row.stage];
127
- // Unknown key refuses — including LEGACY decorated rows (pre-redesign
153
+ // Unknown key refuses — including LEGACY decorated rows (older
128
154
  // runs carry no `parent`, so their unit rows land here): stage-gone.
129
155
  if (!def) return { ok: false, reason: "stage-gone", detail: row.stage };
130
156
  noteChainNode(acc, row.stage, row.status !== "completed");
@@ -170,6 +196,9 @@ interface OpenGeneration {
170
196
 
171
197
  interface FoldAcc {
172
198
  cwd: string;
199
+ /** Header runId — the rebuilt `failedOutput` sentinel's meta.runId,
200
+ * byte-identical to the live `outputMetaFor`'s `s.runId`. RunState carries no id. */
201
+ runId: string;
173
202
  state: RunState;
174
203
  visited: Set<string>;
175
204
  lastStageNumber: number;
@@ -202,6 +231,12 @@ function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): void {
202
231
  acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
203
232
  if (row.status !== "completed") return;
204
233
  applyStageSuccess(acc.state, def, row.stage, row.output);
234
+ // Roll the predecessor session forward through the SAME authority the live
235
+ // `recordStageSuccess` single-stage branch uses (`rollLastSession`) — so a
236
+ // post-resume cold dispatch of a `continue` stage forks the same predecessor
237
+ // the live run would have, and the null-handling can't drift. Single-stage
238
+ // rows only (unit rows fold via `foldUnitRow`, which never touches this slot).
239
+ rollLastSession(acc.state, row.session);
205
240
  }
206
241
 
207
242
  /** Close the open generation: project the declared result — the live loop-advance, replayed. */
@@ -238,7 +273,7 @@ async function foldUnitRow(
238
273
  // only safe place to derive the round-0 arg. `reads` projections in
239
274
  // particular must NOT be re-derived post-fold, where the generation's
240
275
  // own appends have moved the `.at(-1)` cursors.
241
- entryArgs: loop.kind === "assess" ? stageEntryArgs(def, row.parent!, workflow.start, acc.state) : "",
276
+ entryArgs: freezesEntryArgsOf(loop) ? stageEntryArgs(def, row.parent!, workflow.start, acc.state) : "",
242
277
  cursor: freshCursor(),
243
278
  units: undefined,
244
279
  };
@@ -259,6 +294,43 @@ async function foldUnitRow(
259
294
 
260
295
  if (!acc.drift) await guardRow(acc, gen, row);
261
296
 
297
+ // Fanout: place-by-`unitIndex` (NOT trail order) so declared order survives a
298
+ // completion-ordered / out-of-order trail. A slot is FILLED — and so NOT
299
+ // re-dispatched on resume — only when the row is a COMPLETED unit or a
300
+ // COLLECTED soft-halt:
301
+ // • completed → `applyStageSuccess` (bookkeeping + state.output, mirroring the
302
+ // live `recordStageSuccess`) THEN the channel-owning `foldFanoutCompletion`;
303
+ // • collected (`status:"failed"` + `collected:true`) → rebuild the `failedOutput`
304
+ // sentinel from `errMsg` and place it via `foldFanoutCompletion` ONLY (the live
305
+ // `softHaltUnit` runs no `applyStageSuccess` — the fold owns the single channel
306
+ // write). The rebuilt meta is byte-identical to the live sentinel's (see
307
+ // `outputMetaFor`): decorated `row.stage`, `row.skill`, `row.stageNumber`.
308
+ // A hard `status:"failed"` row (no `collected`) or a genuinely pending row — and
309
+ // an aborted in-flight unit, which wrote NO row at all — leaves the slot
310
+ // unfilled so resume re-dispatches that unit. `gen.units` is absent only when the
311
+ // units generator threw at open (already drift); fall through to the produce arm's
312
+ // `advanceCursor` so the refused fold still applies bookkeeping.
313
+ if (gen.loop.kind === "fanout" && gen.units) {
314
+ if (row.status === "completed" && row.output) {
315
+ applyStageSuccess(acc.state, gen.def, row.stage, row.output);
316
+ foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, gen.units.length, row.output);
317
+ } else if (row.collected && row.errMsg !== undefined) {
318
+ const sentinel = failedOutput(
319
+ outputMeta({
320
+ stage: row.stage,
321
+ skill: row.skill,
322
+ stageNumber: row.stageNumber,
323
+ ts: row.ts,
324
+ runId: acc.runId,
325
+ }),
326
+ row.errMsg,
327
+ );
328
+ foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, gen.units.length, sentinel);
329
+ }
330
+ gen.expected = undefined; // consumed
331
+ return undefined; // pending / hard-failed slots stay unfilled — resume re-dispatches them
332
+ }
333
+
262
334
  if (row.status !== "completed") return undefined; // pending unit — cursor stays (resume re-runs it)
263
335
 
264
336
  if (row.role === "judge" || row.role === "verify") {
@@ -299,7 +371,10 @@ async function foldUnitRow(
299
371
  return undefined;
300
372
  }
301
373
 
302
- // produce row — fanout/iterate units and assess producers alike
374
+ // produce row — iterate units and assess producers (fanout is placed by index
375
+ // above; a fanout row only reaches here when `gen.units` is absent because the
376
+ // units generator threw at open — already drift — so `advanceCursor` keeps the
377
+ // refused fold applying bookkeeping without a `length`-of-undefined).
303
378
  applyStageSuccess(acc.state, gen.def, row.stage, row.output);
304
379
  if (!row.output) return undefined; // defensive — completed unit rows always carry output
305
380
  advanceCursor(gen.cursor, "produce", row.output, gen.loop);
@@ -316,12 +391,23 @@ async function foldUnitRow(
316
391
  * be recorded against complete state.
317
392
  */
318
393
  async function guardRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): Promise<void> {
394
+ // Fanout no longer asserts trail order: parallel completion + resume re-dispatch
395
+ // produce out-of-order trails, and the fanout cursor tracks `filledCount` (a
396
+ // count, not a trail position), so a sequential `unitIndex === cursor.index`
397
+ // check would falsely drift. The `unitId` is a PLACEMENT key — verify it
398
+ // identifies the unit declared at `row.unitIndex`.
399
+ if (gen.loop.kind === "fanout") {
400
+ const i = row.unitIndex ?? -1;
401
+ const ok = i >= 0 && i < (gen.units?.length ?? 0) && unitTagOf(gen.units![i]!) === row.unitId;
402
+ if (!ok) setDrift(acc, gen.parent);
403
+ return;
404
+ }
319
405
  const judgeRole = gen.def.verify ? "verify" : "judge";
320
406
  const expectRole = gen.loop.kind === "assess" ? (gen.cursor.phase === "judge" ? judgeRole : "produce") : "produce";
321
407
  if (row.role !== expectRole || row.unitIndex !== gen.cursor.index) return setDrift(acc, gen.parent);
322
408
 
323
409
  const matches = await guarded(acc, gen.parent, () =>
324
- loopStrategyOf(gen.loop.kind).guardExpectation(gen, row, acc.cwd, acc.state),
410
+ sequentialStrategyOf(gen.loop.kind).guardExpectation(gen, row, acc.cwd, acc.state),
325
411
  );
326
412
  if (acc.drift) return;
327
413
  if (!matches) setDrift(acc, gen.parent);
@@ -8,7 +8,7 @@
8
8
 
9
9
  import type { Workflow } from "../api.js";
10
10
  import { LifecycleDispatcher, type LifecycleListeners } from "../events.js";
11
- import type { WorkflowHost } from "../host.js";
11
+ import type { ModelSelection, WorkflowHost } from "../host.js";
12
12
  import { getSkillContracts } from "../skill-contracts/index.js";
13
13
  import type { RunTrigger } from "../triggers.js";
14
14
  import type { RunContext, RunState } from "../types.js";
@@ -18,13 +18,14 @@ import type { RunContext, RunState } from "../types.js";
18
18
  // ---------------------------------------------------------------------------
19
19
 
20
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.
21
+ * Per-DESTINATION cap on decision-edge retries. A "backward jump" is a
22
+ * *decision* resolving to an already-visited stage — i.e. the user's
23
+ * predicate chose to retry. Deterministic edges through a cycle (the loop
24
+ * body) are NOT counted, and each destination stage owns its own budget
25
+ * (`RunContext.revisits`), so the retry allowance is invariant to how many
26
+ * decision edges the cycle crosses per iteration and unrelated loops never
27
+ * share a pool. With 2: any given stage runs once unconditionally and may be
28
+ * re-entered up to 2 more times — at most 3 executions per stage.
28
29
  */
29
30
  export const MAX_BACKWARD_JUMPS = 2;
30
31
 
@@ -67,11 +68,11 @@ export function freshRunState(originalInput: string): RunState {
67
68
  * trigger) and a resume (same run id, reconstructed state/visited, resume
68
69
  * trigger); everything else derives identically from `options`.
69
70
  *
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.
71
+ * The skill-registry snapshot happens here, BEFORE any stage opens its first
72
+ * child session — `options.host` (Pi's registry-level handle) is enumerated once
73
+ * for `run.registeredSkills`; the runner reads that set thereafter and never
74
+ * touches the host again (every stage now runs in a detached child, so there is
75
+ * no stale-after-swap concern and no continue-policy host fallback).
75
76
  */
76
77
  export function buildRunContext(
77
78
  cwd: string,
@@ -82,6 +83,7 @@ export function buildRunContext(
82
83
  maxIterations?: number;
83
84
  lifecycle?: LifecycleListeners;
84
85
  signal?: AbortSignal;
86
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
85
87
  },
86
88
  identity: { runId: string; state: RunState; visited: Set<string>; trigger: RunTrigger },
87
89
  ): RunContext {
@@ -92,17 +94,20 @@ export function buildRunContext(
92
94
  totalStages: countReachableStages(workflow),
93
95
  state: identity.state,
94
96
  visited: identity.visited,
97
+ // Fresh on every entry point: a resume grants each stage a fresh
98
+ // re-entry budget, exactly as the pre-ledger streak counter did.
99
+ revisits: new Map(),
95
100
  registeredSkills: options.host ? snapshotRegisteredSkills(options.host) : undefined,
96
101
  // Defensive COPY (not the live global Map) so a later registerSkillContracts
97
102
  // call cannot mutate this run's snapshot mid-run — parity with the fresh-Set
98
103
  // copy snapshotRegisteredSkills makes.
99
104
  skillContracts: new Map(getSkillContracts()),
100
- continueHost: options.host,
101
105
  maxBackwardJumps: options.maxBackwardJumps ?? MAX_BACKWARD_JUMPS,
102
106
  maxIterations: options.maxIterations ?? MAX_ITERATIONS,
103
107
  trigger: identity.trigger,
104
108
  lifecycle: new LifecycleDispatcher(options.lifecycle),
105
109
  signal: options.signal,
110
+ resolveModel: options.resolveModel,
106
111
  };
107
112
  }
108
113
 
@@ -111,8 +116,7 @@ export function buildRunContext(
111
116
  *
112
117
  * Pi prefixes skill-source commands with `"skill:"` (agent-session.js); we
113
118
  * 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).
119
+ * exactly once per run, at run start, off the launcher's registry-level host.
116
120
  *
117
121
  * Non-skill commands (slash commands registered by extensions) are filtered
118
122
  * out — the preflight only cares about skills.
@@ -21,26 +21,27 @@
21
21
  */
22
22
 
23
23
  import type { StageDef, Unit } from "../api.js";
24
- import { auditCtxFor, failedArgs, notifyPartialArtifacts, recordCancellation, runIdentityOf } from "../audit.js";
24
+ import { failedArgs, notifyPartialArtifacts, 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 { formatError } from "../internal-utils.js";
28
- import { announceLoopStart, type LoopDeps, runLoop } from "../loop.js";
29
- import { freshCursor, type LoopEntry } from "../loop-kinds.js";
28
+ import { announceLoopStart, runLoop } from "../loop.js";
29
+ import { freezesEntryArgsOf } from "../loop-constructors.js";
30
+ import { buildLoopEntry, freshCursor, type LoopDeps, type LoopEntry } from "../loop-kinds.js";
31
+ import { validateUnitDeps } from "../loop-waves.js";
30
32
  import {
31
33
  FAIL_LOOP_CAP_HALT,
32
34
  FAIL_VERIFY_FAILED,
35
+ MSG_CONTINUE_FALLBACK,
33
36
  MSG_RESUME_SESSION_FALLBACK,
34
37
  MSG_SNAPSHOT_FAILED,
35
- STATUS_KEY,
36
- STATUS_STAGE,
37
38
  } from "../messages.js";
38
- import { locateSessionFile, reattachStageSession, runStageSession } from "../sessions/index.js";
39
+ import { continueStageSession, locateSessionFile, reattachStageSession, runStageSession } from "../sessions/index.js";
40
+ import { forkChildSession, reattachChildSession } from "../sessions/spawn.js";
39
41
  import type { WorkflowStage } from "../state/index.js";
40
- import { readBranch } from "../transcript.js";
41
42
  import type { RunContext, StageSession, WorkflowHostContext } from "../types.js";
42
43
  import { advanceChain, type ChainDeps } from "./chain-advance.js";
43
- import { type ChainOutcome, haltChain, recordAbortedAtSeam, recordEntryThrow } from "./failure.js";
44
+ import { type ChainOutcome, haltChain, recordAbortedAtSeam, recordEntryThrow, withStageEntryGuard } from "./failure.js";
44
45
  import { ensureContractInputValid, ensureInputValid } from "./input-validation.js";
45
46
  import { ensureLoopNotContinue, runLoopPreflights, runSingleStagePreflights } from "./preflight.js";
46
47
  import { type ResolvedStage, resolveStage } from "./resolve-stage.js";
@@ -78,13 +79,10 @@ export function advance(
78
79
  * Wraps `runStage` so a thrown stage records a JSONL failure row attributed
79
80
  * to the stage that actually threw — not to the prior stage in the chain.
80
81
  * 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).
82
+ * `ChainDeps`), and the resume entries — the walk's single catch site.
83
+ * Delegates the classify-then-record policy (cooperative-abort seam +
84
+ * mid-stage `WorkflowAbortError` vs terminal entry-throw) to
85
+ * `withStageEntryGuard` (failure.ts).
88
86
  */
89
87
  export async function runStageOrRecordFailure(
90
88
  curCtx: WorkflowHostContext,
@@ -92,12 +90,7 @@ export async function runStageOrRecordFailure(
92
90
  idx: number,
93
91
  run: RunContext,
94
92
  ): 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
- }
93
+ return withStageEntryGuard(curCtx, name, run, () => runStage(curCtx, name, idx, run));
101
94
  }
102
95
 
103
96
  // ---------------------------------------------------------------------------
@@ -106,8 +99,7 @@ export async function runStageOrRecordFailure(
106
99
 
107
100
  /**
108
101
  * 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.
102
+ * label is read off `stage.skill` by the caller — single source.
111
103
  */
112
104
  function buildPrompt(skill: string, inputForStage: string): string {
113
105
  return `/skill:${skill} ${inputForStage}`;
@@ -169,7 +161,6 @@ async function prepareSingleStage(
169
161
  stage.dispatch === "prompt"
170
162
  ? await resolveStagePrompt(stage.def.prompt!, run.cwd, run.state)
171
163
  : buildPrompt(stage.skill, inputForStage(stage, run));
172
- curCtx.ui.setStatus(STATUS_KEY, STATUS_STAGE(stage.stageNumber, run.totalStages, stage.skill));
173
164
 
174
165
  await ensureInputValid(stage, run);
175
166
  await ensureContractInputValid(stage, run);
@@ -204,13 +195,34 @@ function buildSingleStageSession(
204
195
  skillContracts: run.skillContracts,
205
196
  stageIndex: idx,
206
197
  snapshot: prep.snapshot,
207
- continueHost: run.continueHost,
198
+ model: run.resolveModel?.({ stage: stage.name, skill: stage.skill }),
199
+ signal: run.signal,
208
200
  branchOffset,
209
201
  onFailure: (freshCtx) => notifyPartialArtifacts(freshCtx, run.cwd, run.runId),
210
202
  onSuccess: (freshCtx) => advance(freshCtx, stage.name, idx, run),
211
203
  };
212
204
  }
213
205
 
206
+ /**
207
+ * The single-stage entry announcement — `onStageStart`. ONE helper for the
208
+ * live entry (`runSingleStage`) and the session-backed resume re-entry
209
+ * (`resumeWithSessionLadder`) — the fire stays aligned by sharing this one
210
+ * helper. Mirrors `announceLoopStart`
211
+ * (loop.ts) — the loop path's one-helper-for-live-and-resume exemplar.
212
+ */
213
+ function announceSingleStageStart(
214
+ curCtx: WorkflowHostContext,
215
+ run: RunContext,
216
+ stage: Pick<ResolvedStage, "name" | "stageNumber" | "skill">,
217
+ ): Promise<void> {
218
+ return run.lifecycle.fire(
219
+ curCtx,
220
+ "onStageStart",
221
+ skillStageRef(stage.name, stage.stageNumber, stage.skill),
222
+ lifecycleCtxFor(run),
223
+ );
224
+ }
225
+
214
226
  /**
215
227
  * The single-session path (prompt + skill dispatch): preflights → prompt
216
228
  * prep → input validation → snapshot → session.
@@ -231,60 +243,88 @@ async function runSingleStage(
231
243
  run: RunContext,
232
244
  ): Promise<ChainOutcome> {
233
245
  const prep = await prepareSingleStage(curCtx, stage, idx, run);
234
- const branchOffset = computeBranchOffset(curCtx, stage.def);
235
246
 
236
247
  // 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
- );
248
+ await announceSingleStageStart(curCtx, run, stage);
249
+
250
+ // `continue` forks the predecessor's persisted session (`run.state.lastSession`)
251
+ // into a fresh child carrying its transcript; `continueStageSession` re-derives
252
+ // the branch offset from that forked branch (NOT the launcher's). No predecessor
253
+ // session — start stage, after a loop, or the file is gone — degrades to a fresh
254
+ // dispatch, matching the `prompt-continue-at-start` warning. Fresh stages always
255
+ // pass `branchOffset: undefined`.
256
+ if (stage.def.sessionPolicy === "continue") {
257
+ const file = continueForkFile(run);
258
+ if (file) {
259
+ const s = buildSingleStageSession(stage, idx, run, prep, undefined);
260
+ await forkChildSession(curCtx, s, file, (child) => continueStageSession(curCtx, child, s));
261
+ return "dispatched";
262
+ }
263
+ curCtx.ui.notify(MSG_CONTINUE_FALLBACK(stage.skill), "info");
264
+ }
243
265
 
244
- await runStageSession(curCtx, buildSingleStageSession(stage, idx, run, prep, branchOffset));
266
+ await runStageSession(curCtx, buildSingleStageSession(stage, idx, run, prep, undefined));
245
267
  return "dispatched";
246
268
  }
247
269
 
270
+ /**
271
+ * The predecessor session a `continue` stage forks from, resolved to an on-disk
272
+ * file — or `null` to degrade to a fresh dispatch (no prior session recorded, or
273
+ * its file was cleaned up / moved beyond `locateSessionFile`'s reach).
274
+ */
275
+ function continueForkFile(run: RunContext): string | null {
276
+ const ref = run.state.lastSession;
277
+ return ref ? locateSessionFile(ref, run.runId, run.cwd) : null;
278
+ }
279
+
248
280
  /**
249
281
  * Session-backed resume of a failed/aborted single stage — adopt the
250
282
  * interrupted session's branch (promotion) or continue it from its leaf
251
283
  * (reattach), instead of re-running cold. Selected by `selectResumeEntry`
252
284
  * when the failed trailer carries a `session` (the structured dispatch).
253
- *
254
- * Owns the FALLBACK LADDER: every precondition miss notifies
285
+ * Delegates the same classify-then-record policy as the live entry
286
+ * (`runStageOrRecordFailure`) to `withStageEntryGuard` (failure.ts); the
287
+ * fallback ladder itself lives in `resumeWithSessionLadder` below — the
288
+ * resume `inner` still wraps it, so a reattached `postStage`
289
+ * `WorkflowAbortError` or machinery throw is classified (abort vs terminal
290
+ * entry-throw) by the same authority as the live path.
291
+ */
292
+ export async function resumeStageWithSession(
293
+ curCtx: WorkflowHostContext,
294
+ last: WorkflowStage,
295
+ idx: number,
296
+ run: RunContext,
297
+ ): Promise<ChainOutcome> {
298
+ return withStageEntryGuard(curCtx, last.stage, run, () => resumeWithSessionLadder(curCtx, last, idx, run));
299
+ }
300
+
301
+ /**
302
+ * THE resume fallback ladder (called by `resumeStageWithSession` via
303
+ * `withStageEntryGuard`). Every precondition miss notifies
255
304
  * (`MSG_RESUME_SESSION_FALLBACK`) and degrades to today's cold re-run via
256
305
  * `runStageOrRecordFailure` — never a refusal, never a throw:
257
306
  *
258
- * 1. cooperative-abort check (same seam as `runStageOrRecordFailure`);
259
- * 2. resolved mode must be `prompt`/`skill` (loop trailers never reach
307
+ * 1. resolved mode must be `prompt`/`skill` (loop trailers never reach
260
308
  * 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
309
+ * 2. `locateSessionFile` must find the file on disk;
310
+ * 3. the same `prepareSingleStage` steps as live (a preflight throw lands
264
311
  * in the same catch as the live entry);
265
- * 6. `switchSession` adopts the session and `reattachStageSession`
312
+ * 4. `reattachChildSession` spawns a child BOUND to the persisted file (the
313
+ * host opens it, does NOT replay the prompt) and `reattachStageSession`
266
314
  * (sessions/reattach.ts) runs promotion → reattach inside it, with the
267
315
  * SAME `StageSession` the live path builds — `branchOffset` taken from
268
316
  * the PERSISTED row (continue-policy stages), `undefined` for fresh.
269
317
  *
270
- * Lifecycle: `onStageStart` fires before `switchSession` (same bracketing
318
+ * (The cooperative-abort pre-check — formerly step 1 here — now lives in
319
+ * `withStageEntryGuard`, which wraps this ladder; a mid-stage
320
+ * `WorkflowAbortError` thrown inside it is classified there too.)
321
+ *
322
+ * Lifecycle: `onStageStart` fires before the child (re)opens (same bracketing
271
323
  * as live); promotion then fires `onStageEnd` via `recordStageSuccess` — a
272
- * fast start→end pair is honest ("the stage's work was adopted").
324
+ * fast start→end pair is honest ("the stage's work was adopted"). There is no
325
+ * `{ cancelled }` arm — a detached reattach opens its own child, with no
326
+ * live-session swap for the user to dismiss.
273
327
  */
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
328
  async function resumeWithSessionLadder(
289
329
  curCtx: WorkflowHostContext,
290
330
  last: WorkflowStage,
@@ -304,27 +344,20 @@ async function resumeWithSessionLadder(
304
344
  if (stage.mode !== "prompt" && stage.mode !== "skill") {
305
345
  return runStageOrRecordFailure(curCtx, last.stage, idx, run);
306
346
  }
307
- if (!curCtx.switchSession) return fallBackCold("host cannot switch sessions");
308
- const file = locateSessionFile(ref);
347
+ const file = locateSessionFile(ref, run.runId, run.cwd);
309
348
  if (!file) return fallBackCold("session file not found");
310
349
 
311
350
  const prep = await prepareSingleStage(curCtx, stage, idx, run);
312
351
  const s = buildSingleStageSession(stage, idx, run, prep, ref.branchOffset);
313
352
 
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
- );
353
+ // Same bracketing as live: onStageStart before the (re)attached child opens.
354
+ await announceSingleStageStart(curCtx, run, stage);
321
355
 
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));
356
+ // Detached reattach: spawn a child BOUND to the persisted session file (the
357
+ // host opens it and does NOT replay the prompt); reattachStageSession promotes
358
+ // from the loaded branch or nudges via resendIntoChild. Replaces the deleted
359
+ // live-session swap (`curCtx.switchSession`).
360
+ await reattachChildSession(curCtx, s, file, (child) => reattachStageSession(curCtx, child, s));
328
361
  return "dispatched";
329
362
  }
330
363
 
@@ -367,21 +400,22 @@ async function runLoopStage(
367
400
  if (loop.kind === "fanout") {
368
401
  units = await loop.units({ cwd: run.cwd, artifact: currentPrimaryArtifact(run.state), state: run.state });
369
402
  if (units.length === 0) return runSingleStage(curCtx, stage, idx, run);
403
+ // deps cycle / dangling-id → clean halt BEFORE any dispatch (the runtime unit
404
+ // list is invisible to the static load gate, so this is the only place it runs).
405
+ validateUnitDeps(units, stage.name);
370
406
  }
371
407
 
372
408
  runLoopPreflights(stage, run);
373
409
 
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
- };
410
+ const entry = buildLoopEntry(
411
+ { stageIdx: idx, name: stage.name, skill: stage.skill, def: stage.def, loop },
412
+ {
413
+ entryArtifact: currentPrimaryArtifact(run.state),
414
+ entryArgs: freezesEntryArgsOf(loop) ? inputForStage(stage, run) : "",
415
+ entryPair: { output: run.state.output, primaryArtifact: run.state.primaryArtifact },
416
+ units,
417
+ },
418
+ );
385
419
 
386
420
  await announceLoopStart(curCtx, run, entry);
387
421
  await runLoop(curCtx, entry, freshCursor(), run, buildLoopDeps());
@@ -390,8 +424,7 @@ async function runLoopStage(
390
424
 
391
425
  /**
392
426
  * 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).
427
+ * (`selectResumeEntry`), so the two can't drift.
395
428
  */
396
429
  export function buildLoopDeps(): LoopDeps {
397
430
  return {
@@ -399,6 +432,13 @@ export function buildLoopDeps(): LoopDeps {
399
432
  advanceAfter: (freshCtx, name, completedIdx, ctx) => advance(freshCtx, name, completedIdx, ctx),
400
433
  captureSnapshot: (ctx, name, def, i, r) => captureStageSnapshot(ctx, name, def, i, r),
401
434
  haltLoop,
435
+ // Mid-flight run abort at the loop seam → FAIL_WORKFLOW_ABORTED.
436
+ recordAborted: (curCtx, name, run) => recordAbortedAtSeam(curCtx, name, run).then(() => undefined),
437
+ // Unexpected worker rejection → terminal-failure row, no re-throw. The
438
+ // unit's identity rides as a STRUCTURED field (`unit`) on the row — `stage`
439
+ // stays the parent graph identity, not a `name (unit N)` string.
440
+ recordWorkerThrow: (curCtx, unit, skill, run, err) =>
441
+ recordEntryThrow(curCtx, unit.parent, run, err, { ref: unit, skill }).then(() => undefined),
402
442
  };
403
443
  }
404
444
 
@@ -418,12 +458,6 @@ export async function haltLoop(
418
458
  await haltChain(curCtx, run, e.name, e.name, args);
419
459
  }
420
460
 
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
461
  /** Runs whose snapshot-failure warning already fired — one notify per run, not per stage/unit. */
428
462
  const snapshotWarnedRuns = new WeakSet<RunContext>();
429
463