@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
@@ -7,20 +7,25 @@
7
7
  * instead of catching. The injected runner owns the catch for
8
8
  * downstream-stage throws — the `ChainDeps` injection (the `LoopDeps`
9
9
  * pattern) keeps this module's imports strictly downward: the chain walk's
10
- * runStage ↔ advanceChain recursion is composed in run-stage.ts, not
10
+ * dispatchStage ↔ advanceChain recursion is composed in run-stage.ts, not
11
11
  * spelled as a module cycle.
12
12
  */
13
13
 
14
- import { takeRouteNote } from "../api.js";
15
- import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
14
+ import { type EdgeTarget, takeRouteNote } from "../api.js";
15
+ import { auditCtxFor, failedArgs, recordFatalFailure } from "../audit.js";
16
16
  import { resolveSkill } from "../chain-state.js";
17
17
  import { lifecycleCtxFor, skillStageRef } from "../events.js";
18
18
  import { nowIso } from "../internal-utils.js";
19
- import { FAIL_BACKWARD_JUMP_EXHAUSTED, MSG_CHAIN_ADVANCE_FAILED, MSG_ROUTING_AUDIT_DROPPED } from "../messages.js";
19
+ import {
20
+ FAIL_BACKWARD_JUMP_EXHAUSTED,
21
+ FAIL_GATE_STOP,
22
+ MSG_CHAIN_ADVANCE_FAILED,
23
+ MSG_ROUTING_AUDIT_DROPPED,
24
+ } from "../messages.js";
20
25
  import { edgeIsDecision, nextStage } from "../routing.js";
21
26
  import { appendRoutingDecision } from "../state/index.js";
22
27
  import type { RunContext, WorkflowHostContext } from "../types.js";
23
- import { type ChainOutcome, finalizeWorkflow } from "./failure.js";
28
+ import { type ChainOutcome, finalizeWorkflow, haltChain } from "./failure.js";
24
29
 
25
30
  /**
26
31
  * The walk continuation injected by the composition site
@@ -29,16 +34,16 @@ import { type ChainOutcome, finalizeWorkflow } from "./failure.js";
29
34
  * the mutual recursion of the chain walk lives in ONE composing module.
30
35
  */
31
36
  export interface ChainDeps {
32
- runNext: (curCtx: WorkflowHostContext, name: string, idx: number, run: RunContext) => Promise<ChainOutcome>;
37
+ runNext: (hostCtx: WorkflowHostContext, name: string, idx: number, run: RunContext) => Promise<ChainOutcome>;
33
38
  }
34
39
 
35
40
  /**
36
41
  * Decomposed into three helpers — `auditRoutingDecision`,
37
- * `checkBackwardJumpGuard`, `haltOnRoutingError` — each owning one
42
+ * `ensureBackwardJumpGuard`, `haltOnRoutingError` — each owning one
38
43
  * structural concern.
39
44
  */
40
45
  export async function advanceChain(
41
- curCtx: WorkflowHostContext,
46
+ hostCtx: WorkflowHostContext,
42
47
  currentName: string,
43
48
  idx: number,
44
49
  run: RunContext,
@@ -53,33 +58,39 @@ export async function advanceChain(
53
58
  const result = nextStage(run.workflow, currentName, { output: run.state.output, state: run.state });
54
59
 
55
60
  if (result.kind === "err") {
56
- return haltOnRoutingError(curCtx, run, currentName, result.reason);
61
+ return haltOnRoutingError(hostCtx, run, currentName, result.reason);
57
62
  }
58
63
 
59
- const fromRef = skillStageRef(currentName, idx + 1, resolveSkill(run.workflow.stages[currentName]!, currentName));
64
+ const skill = resolveSkill(run.workflow.stages[currentName]!, currentName);
65
+ const fromRef = skillStageRef(currentName, idx + 1, skill);
60
66
 
61
67
  if (result.kind === "stop") {
62
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
63
- return finalizeWorkflow(curCtx, run);
68
+ const note = stopRouteNote(wasDecision, run.workflow.edges[currentName]);
69
+ if (wasDecision) auditRoutingDecision(hostCtx, run, idx, currentName, "stop", note);
70
+ await run.lifecycle.fire(hostCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
71
+ if (isBlockedGateStop(note)) {
72
+ return haltChain(hostCtx, run, currentName, skill, failedArgs(FAIL_GATE_STOP(currentName, note)));
73
+ }
74
+ return finalizeWorkflow(hostCtx, run);
64
75
  }
65
76
 
66
77
  const nextName = result.stage;
67
78
  if (wasDecision) {
68
- auditRoutingDecision(curCtx, run, idx, currentName, nextName);
69
- const guard = await checkBackwardJumpGuard(curCtx, run, nextName);
79
+ auditRoutingDecision(hostCtx, run, idx, currentName, nextName);
80
+ const guard = await ensureBackwardJumpGuard(hostCtx, run, nextName);
70
81
  if (guard !== "continue") return guard;
71
82
  }
72
83
 
73
84
  // Fire onRoute after the routing decision has been audited (when applicable),
74
85
  // before the next stage runs. Deterministic auto-edges still fire so
75
86
  // listeners see every transition.
76
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run));
87
+ await run.lifecycle.fire(hostCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run));
77
88
 
78
89
  // deps.runNext owns the catch for throws out of the *next* stage, so the
79
90
  // JSONL row records `nextName` (the stage that actually threw) rather than
80
91
  // `currentName` (which would mis-attribute the failure to the prior stage
81
92
  // that already completed successfully).
82
- return deps.runNext(curCtx, nextName, idx + 1, run);
93
+ return deps.runNext(hostCtx, nextName, idx + 1, run);
83
94
  }
84
95
 
85
96
  /**
@@ -94,17 +105,21 @@ export async function advanceChain(
94
105
  * routing rows are pure telemetry).
95
106
  */
96
107
  function auditRoutingDecision(
97
- curCtx: WorkflowHostContext,
108
+ hostCtx: WorkflowHostContext,
98
109
  run: RunContext,
99
110
  idx: number,
100
111
  currentName: string,
101
112
  nextName: string,
113
+ noteOverride?: string,
102
114
  ): void {
103
115
  // Read-and-clear any note the edge attached to THIS pick (e.g. gate's
104
116
  // fallback-fired diagnostic). Same tick as the invocation — no other
105
117
  // decision can interleave. `undefined` is dropped by JSON.stringify.
118
+ // The stop branch reads the note BEFORE calling here (it decides
119
+ // halt-vs-finalize on it) and passes it as `noteOverride` — takeRouteNote
120
+ // is read-and-clear, so a second read would see nothing.
106
121
  const edge = run.workflow.edges[currentName];
107
- const note = typeof edge === "function" ? takeRouteNote(edge) : undefined;
122
+ const note = noteOverride ?? (typeof edge === "function" ? takeRouteNote(edge) : undefined);
108
123
  const fromStageIndex = idx + 1;
109
124
  const wrote = appendRoutingDecision(run.cwd, run.runId, {
110
125
  type: "routing",
@@ -116,7 +131,7 @@ function auditRoutingDecision(
116
131
  });
117
132
  if (!wrote) {
118
133
  run.state.telemetry.droppedRoutingRows.push({ fromStageIndex, fromStage: currentName, decision: nextName });
119
- curCtx.ui.notify(MSG_ROUTING_AUDIT_DROPPED(currentName, nextName), "warning");
134
+ hostCtx.ui.notify(MSG_ROUTING_AUDIT_DROPPED(currentName, nextName), "warning");
120
135
  }
121
136
  }
122
137
 
@@ -150,8 +165,8 @@ function auditRoutingDecision(
150
165
  * Trip attribution targets `nextName` (the stage the guard refused to
151
166
  * re-enter), not the just-completed stage.
152
167
  */
153
- async function checkBackwardJumpGuard(
154
- curCtx: WorkflowHostContext,
168
+ async function ensureBackwardJumpGuard(
169
+ hostCtx: WorkflowHostContext,
155
170
  run: RunContext,
156
171
  nextName: string,
157
172
  ): Promise<"continue" | ChainOutcome> {
@@ -160,8 +175,8 @@ async function checkBackwardJumpGuard(
160
175
  run.revisits.set(nextName, revisits);
161
176
  run.state.telemetry.backwardJumps++;
162
177
  if (revisits <= run.maxBackwardJumps) return "continue";
163
- await recordTerminalFailure(
164
- curCtx,
178
+ await recordFatalFailure(
179
+ hostCtx,
165
180
  auditCtxFor(run, nextName, nextName),
166
181
  failedArgs(FAIL_BACKWARD_JUMP_EXHAUSTED(nextName, revisits, run.maxBackwardJumps)),
167
182
  );
@@ -174,15 +189,40 @@ async function checkBackwardJumpGuard(
174
189
  * `currentName` (the edge belongs to the just-completed stage).
175
190
  */
176
191
  async function haltOnRoutingError(
177
- curCtx: WorkflowHostContext,
192
+ hostCtx: WorkflowHostContext,
178
193
  run: RunContext,
179
194
  currentName: string,
180
195
  reason: string,
181
196
  ): Promise<ChainOutcome> {
182
- await recordTerminalFailure(
183
- curCtx,
197
+ await recordFatalFailure(
198
+ hostCtx,
184
199
  auditCtxFor(run, currentName, currentName),
185
200
  failedArgs(MSG_CHAIN_ADVANCE_FAILED(currentName, reason), reason),
186
201
  );
187
202
  return "halted";
188
203
  }
204
+
205
+ /**
206
+ * Read the ROUTE_NOTE a decision EdgeFn attached to its most recent pick,
207
+ * or undefined when the stop did not come from a decision edge function.
208
+ *
209
+ * Returns the note VALUE, not a boolean — `takeRouteNote` reads the
210
+ * `ROUTE_NOTE` symbol once then clears it (read-and-clear), so a boolean
211
+ * variant called twice would see undefined on the second read. The single
212
+ * returned note is threaded to both the audit row and the halt-vs-finalize
213
+ * decision. Non-decision stops and declarative edges (string / STOP) carry
214
+ * no note.
215
+ */
216
+ const stopRouteNote = (wasDecision: boolean, edge: EdgeTarget): string | undefined =>
217
+ wasDecision && typeof edge === "function" ? takeRouteNote(edge) : undefined;
218
+
219
+ /**
220
+ * A decision stop carrying a ROUTE_NOTE is `match`'s no-fallback
221
+ * termination: the gate found no branch for the value it read (typically
222
+ * a failed verdict on a pass-only gate). That run is BLOCKED awaiting
223
+ * intervention, not complete — halt via `haltChain` so the trail and the
224
+ * lane show a stopped run instead of a silent ✓. A noteless decision stop
225
+ * (a custom edge deliberately returning STOP) and the ordinary
226
+ * end-of-chain stop remain completions.
227
+ */
228
+ const isBlockedGateStop = (note: string | undefined): note is string => note !== undefined;
package/runner/errors.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * without importing into `runner/`; this module re-exports it so every layer of
5
5
  * the per-stage pipeline (preflights, input validation, the loop shortcut) keeps
6
6
  * its local `./errors.js` spelling and the single catch site
7
- * (`runStageOrRecordFailure`, run-stage.ts) catches it as before.
7
+ * (`dispatchStageOrRecordFailure`, run-stage.ts) catches it as before.
8
8
  */
9
9
 
10
10
  export { haltPreflight, invariantPreflight, StagePreflightError } from "../stage-errors.js";
package/runner/failure.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  auditCtxFor,
11
11
  failedArgs,
12
12
  notifyPartialArtifacts,
13
- recordTerminalFailure,
13
+ recordFatalFailure,
14
14
  terminate,
15
15
  } from "../audit.js";
16
16
  import { formatError, isAbortError } from "../internal-utils.js";
@@ -20,7 +20,7 @@ import { StagePreflightError } from "./errors.js";
20
20
 
21
21
  /**
22
22
  * Explicit result of one chain-walk step, threaded up through
23
- * `advanceChain` / `runStage` / `runStageOrRecordFailure`. The walk's halt
23
+ * `advanceChain` / `dispatchStage` / `dispatchStageOrRecordFailure`. The walk's halt
24
24
  * protocol is record-then-halt, not record-then-quietly-unwind: with a
25
25
  * non-void return type, a branch that records a failure but forgets to stop
26
26
  * the walk no longer typechecks — every arm must RETURN an outcome, and
@@ -41,7 +41,7 @@ export type ChainOutcome = "halted" | "completed" | "dispatched";
41
41
  * path) so they never import the composition site back.
42
42
  */
43
43
  export type AdvanceFn = (
44
- curCtx: WorkflowHostContext,
44
+ hostCtx: WorkflowHostContext,
45
45
  completedName: string,
46
46
  completedIdx: number,
47
47
  run: RunContext,
@@ -52,20 +52,15 @@ export type AdvanceFn = (
52
52
  * halt idiom for walk arms: `return haltChain(...)`.
53
53
  */
54
54
  export async function haltChain(
55
- curCtx: WorkflowHostContext,
55
+ hostCtx: WorkflowHostContext,
56
56
  run: RunContext,
57
57
  stageName: string,
58
58
  skill: string,
59
- args: Parameters<typeof recordTerminalFailure>[2],
59
+ args: Parameters<typeof recordFatalFailure>[2],
60
60
  onFailure?: (ctx: WorkflowHostContext) => void,
61
61
  unit?: UnitRef,
62
62
  ): Promise<ChainOutcome> {
63
- await recordTerminalFailure(
64
- curCtx,
65
- auditCtxFor(run, stageName, skill, unit ? { unit } : undefined),
66
- args,
67
- onFailure,
68
- );
63
+ await recordFatalFailure(hostCtx, auditCtxFor(run, stageName, skill, unit ? { unit } : undefined), args, onFailure);
69
64
  return "halted";
70
65
  }
71
66
 
@@ -84,7 +79,7 @@ export async function haltChain(
84
79
  * `skill`, so the unit's identity is NOT folded into the `stage` name string.
85
80
  */
86
81
  export async function recordEntryThrow(
87
- curCtx: WorkflowHostContext,
82
+ hostCtx: WorkflowHostContext,
88
83
  name: string,
89
84
  run: RunContext,
90
85
  e: unknown,
@@ -92,7 +87,7 @@ export async function recordEntryThrow(
92
87
  ): Promise<ChainOutcome> {
93
88
  if (e instanceof StagePreflightError) {
94
89
  return haltChain(
95
- curCtx,
90
+ hostCtx,
96
91
  run,
97
92
  name,
98
93
  e.skill,
@@ -102,7 +97,7 @@ export async function recordEntryThrow(
102
97
  }
103
98
  const reason = formatError(e);
104
99
  return haltChain(
105
- curCtx,
100
+ hostCtx,
106
101
  run,
107
102
  name,
108
103
  unit?.skill ?? name,
@@ -120,8 +115,12 @@ export async function recordEntryThrow(
120
115
  * artifacts produced by earlier stages are surfaced so the operator sees them
121
116
  * instead of grepping the JSONL. No-op when no artifacts exist.
122
117
  */
123
- export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, run: RunContext): Promise<ChainOutcome> {
124
- return haltChain(curCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)), (ctx) =>
118
+ export function recordAbortedAtSeam(
119
+ hostCtx: WorkflowHostContext,
120
+ name: string,
121
+ run: RunContext,
122
+ ): Promise<ChainOutcome> {
123
+ return haltChain(hostCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)), (ctx) =>
125
124
  notifyPartialArtifacts(ctx, run.cwd, run.runId),
126
125
  );
127
126
  }
@@ -133,7 +132,7 @@ export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, r
133
132
  * anything else → terminal entry-throw row). Modeled after `advanceCursor`
134
133
  * (loop.ts): one shared authority, callers hold their own preconditions.
135
134
  *
136
- * The two call sites (`runStageOrRecordFailure` live, `resumeStageWithSession`
135
+ * The two call sites (`dispatchStageOrRecordFailure` live, `resumeStageWithSession`
137
136
  * resume) cover DISJOINT scopes — the resume catch protects the reattach ladder
138
137
  * (`resumeWithSessionLadder`) the live catch cannot reach — so both must exist.
139
138
  * This wrapper merges the CLASSIFICATION POLICY (which throw is an abort vs a
@@ -142,22 +141,22 @@ export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, r
142
141
  * cancel signal beyond `WorkflowAbortError`) is one edit, here.
143
142
  */
144
143
  export async function withStageEntryGuard(
145
- curCtx: WorkflowHostContext,
144
+ hostCtx: WorkflowHostContext,
146
145
  name: string,
147
146
  run: RunContext,
148
147
  inner: () => Promise<ChainOutcome>,
149
148
  ): Promise<ChainOutcome> {
150
- if (run.signal?.aborted) return recordAbortedAtSeam(curCtx, name, run);
149
+ if (run.signal?.aborted) return recordAbortedAtSeam(hostCtx, name, run);
151
150
  try {
152
151
  return await inner();
153
152
  } catch (e) {
154
- if (isAbortError(e)) return recordAbortedAtSeam(curCtx, name, run);
155
- return recordEntryThrow(curCtx, name, run, e);
153
+ if (isAbortError(e)) return recordAbortedAtSeam(hostCtx, name, run);
154
+ return recordEntryThrow(hostCtx, name, run, e);
156
155
  }
157
156
  }
158
157
 
159
- export function finalizeWorkflow(curCtx: WorkflowHostContext, run: RunContext): ChainOutcome {
160
- curCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
158
+ export function finalizeWorkflow(hostCtx: WorkflowHostContext, run: RunContext): ChainOutcome {
159
+ hostCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
161
160
  terminate(run.state, { status: "completed" });
162
161
  return "completed";
163
162
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Runtime preflights for the per-stage pipeline — every check that gates a
3
3
  * stage BEFORE its body dispatches. Each check throws `StagePreflightError`
4
- * on failure; `runStageOrRecordFailure` (run-stage.ts) catches and
4
+ * on failure; `dispatchStageOrRecordFailure` (run-stage.ts) catches and
5
5
  * records the JSONL row. Schema-backed input validation (the two POST-prompt
6
6
  * checks) lives beside this in `input-validation.ts`.
7
7
  *
@@ -26,10 +26,7 @@ import type { ResolvedStage } from "./resolve-stage.js";
26
26
  * The skill-path preflight sequence, in its load-bearing order:
27
27
  * 1. ensureUpstreamArtifact — halt: missing inherited artifact.
28
28
  * 2. ensureNamedReads — halt: a `reads:` name has no published entry.
29
- * 3. enforceSessionInvariants — invariant: authoring-time-knowable throws
30
- * (precede the registry check so the structural violation surfaces
31
- * regardless of the runtime registry).
32
- * 4. ensureSkillRegistered — halt: skill not registered in Pi.
29
+ * 3. ensureSkillRegistered — halt: skill not registered in Pi.
33
30
  * (Input-schema validation runs after prompt prep — see input-validation.ts.)
34
31
  */
35
32
  export function runSingleStagePreflights(stage: ResolvedStage, run: RunContext): void {
@@ -47,7 +44,7 @@ export function runSingleStagePreflights(stage: ResolvedStage, run: RunContext):
47
44
  export function ensureLoopNotContinue(stage: ResolvedStage): void {
48
45
  if (stage.def.sessionPolicy !== "continue") return;
49
46
  const reason =
50
- `runStage: stage "${stage.name}" cannot combine loop with sessionPolicy "continue" — ` +
47
+ `dispatchStage: stage "${stage.name}" cannot combine loop with sessionPolicy "continue" — ` +
51
48
  "each unit requires an isolated session";
52
49
  throw invariantPreflight(stage.name, MSG_STAGE_THREW(stage.name, reason), reason);
53
50
  }
@@ -125,22 +122,25 @@ function ensureSkillRegistered(stage: ResolvedStage, run: RunContext): void {
125
122
  * The start node consumes the user's brief; subsequent stages MUST inherit
126
123
  * an upstream artifactPath. Falling back to originalInput past the start
127
124
  * would silently hand a downstream skill the raw feature description.
128
- *
129
- * Three opt-outs skip the check:
130
- * - `inheritsArtifacts: false` (authored via `terminal()`) — stage consumes
131
- * `originalInput` by design.
132
- * - `reads: [...]` — stage builds its prompt from the named-publish
133
- * registry instead of the rolling primary slot; `ensureNamedReads`
134
- * enforces its own coverage rule.
135
- * - prompt dispatch — the stage builds its own text and never consumes the
136
- * rolling primary as an arg (a continue chat turn typically leans on
137
- * session context, not a handle).
138
125
  */
126
+
127
+ /** The start node consumes the user's brief; it has no upstream artifact to inherit. */
128
+ const isStartStage = (stage: ResolvedStage, run: RunContext): boolean => stage.name === run.workflow.start;
129
+
130
+ /** Authored via `terminal()`: the stage consumes `originalInput` by design. */
131
+ const optsOutOfArtifactInheritance = (stage: ResolvedStage): boolean => stage.def.inheritsArtifacts === false;
132
+
133
+ /** Builds its prompt from the named-publish registry, not the rolling primary slot. */
134
+ const readsNamedChannels = (stage: ResolvedStage): boolean => !!stage.def.reads?.length;
135
+
136
+ /** Prompt dispatch builds its own text and never takes the rolling primary as an arg. */
137
+ const isPromptDispatch = (stage: ResolvedStage): boolean => stage.dispatch === "prompt";
138
+
139
139
  function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
140
- if (stage.name === run.workflow.start) return;
141
- if (stage.def.inheritsArtifacts === false) return;
142
- if (stage.def.reads?.length) return;
143
- if (stage.dispatch === "prompt") return;
140
+ if (isStartStage(stage, run)) return;
141
+ if (optsOutOfArtifactInheritance(stage)) return;
142
+ if (readsNamedChannels(stage)) return;
143
+ if (isPromptDispatch(stage)) return;
144
144
  if (currentPrimaryArtifact(run.state)) return;
145
145
  const f = FAIL_MISSING_ARTIFACT(stage.skill, stage.stageNumber);
146
146
  throw haltPreflight(stage.skill, f);
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Stage resolution — derive a stage's dispatch identity ONCE, at the top of
3
- * `runStage`, so the rest of the pipeline switches on data instead of
3
+ * `dispatchStage`, so the rest of the pipeline switches on data instead of
4
4
  * re-probing the def's optional slots (`loop`/`verify`/`run`/`prompt`). The
5
5
  * old probe-the-optionals ladder needed a "slot ordering (load-bearing)"
6
6
  * comment; the ordering now lives in exactly one place (`stageModeOf`).
@@ -21,7 +21,7 @@ import type { RunContext } from "../types.js";
21
21
  */
22
22
  export type StageDispatch = "script" | "prompt" | "skill";
23
23
 
24
- /** The top-level dispatch slot `runStage` switches on. */
24
+ /** The top-level dispatch slot `dispatchStage` switches on. */
25
25
  export type StageMode = "loop" | StageDispatch;
26
26
 
27
27
  export interface ResolvedStage {
@@ -50,7 +50,7 @@ export function resolveStage(currentName: string, idx: number, run: RunContext):
50
50
  const def = run.workflow.stages[currentName];
51
51
  if (!def) {
52
52
  // validateWorkflow should catch this; defensive for tests bypassing validation.
53
- throw new Error(`runStage: stage "${currentName}" referenced by edges but missing from workflow.stages`);
53
+ throw new Error(`dispatchStage: stage "${currentName}" referenced by edges but missing from workflow.stages`);
54
54
  }
55
55
  const loop = effectiveLoopOf(def);
56
56
  const dispatch = dispatchOf(def);
@@ -16,7 +16,7 @@ import type { RunContext, WorkflowHostContext } from "../types.js";
16
16
  import { recordEntryThrow } from "./failure.js";
17
17
  import type { ReconstructResult } from "./resume.js";
18
18
  import { recordLoopDriftFailure, resumeLoopStage } from "./resume-loop.js";
19
- import { advance, buildLoopDeps, resumeStageWithSession, runStageOrRecordFailure } from "./run-stage.js";
19
+ import { advance, buildLoopDeps, dispatchStageOrRecordFailure, resumeStageWithSession } from "./run-stage.js";
20
20
 
21
21
  /**
22
22
  * Pick the chain re-entry thunk from the trail trailer. Dispatch keys on the
@@ -83,11 +83,11 @@ export function selectResumeEntry(
83
83
  // tests in resume.test.ts).
84
84
  return last.session !== null
85
85
  ? () => resumeStageWithSession(ctx, last, idx, run)
86
- : () => runStageOrRecordFailure(ctx, last.stage, idx, run);
86
+ : () => dispatchStageOrRecordFailure(ctx, last.stage, idx, run);
87
87
  }
88
88
 
89
89
  /**
90
- * Resume-entry counterpart of `runStageOrRecordFailure`'s catch. The live
90
+ * Resume-entry counterpart of `dispatchStageOrRecordFailure`'s catch. The live
91
91
  * chain reaches user fns (loop `next`/`done`/`feedForward`, judge prompts,
92
92
  * route predicates) only under that catch; the resume-loop and route-onward
93
93
  * entry thunks call the same fns directly, so a throw would otherwise escape
@@ -95,7 +95,7 @@ export function selectResumeEntry(
95
95
  * caller loses the result envelope.
96
96
  */
97
97
  async function guardResumeEntry(
98
- curCtx: WorkflowHostContext,
98
+ hostCtx: WorkflowHostContext,
99
99
  name: string,
100
100
  run: RunContext,
101
101
  entry: () => Promise<unknown>,
@@ -103,7 +103,7 @@ async function guardResumeEntry(
103
103
  try {
104
104
  await entry();
105
105
  } catch (e) {
106
- await recordEntryThrow(curCtx, name, run, e);
106
+ await recordEntryThrow(hostCtx, name, run, e);
107
107
  }
108
108
  }
109
109
 
@@ -17,12 +17,12 @@
17
17
  * probe pull is the documented harmless deterministic double-pull.
18
18
  */
19
19
 
20
- import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
20
+ import { auditCtxFor, failedArgs, recordFatalFailure } from "../audit.js";
21
21
  import { resolveSkill } from "../chain-state.js";
22
22
  import { announceLoopStart, pendingFanoutIndices, runFanoutResume, runLoop } from "../loop.js";
23
23
  import { effectiveLoopOf, freezesEntryArgsOf } from "../loop-constructors.js";
24
24
  import { buildLoopEntry, type LoopDeps, sequentialStrategyOf } from "../loop-kinds.js";
25
- import { validateUnitDeps } from "../loop-waves.js";
25
+ import { ensureUnitDeps } from "../loop-waves.js";
26
26
  import { FAIL_MISSING_ARTIFACT, type FailureText, MSG_RESUME_LOOP_MISMATCH } from "../messages.js";
27
27
  import type { RunContext, WorkflowHostContext } from "../types.js";
28
28
  import type { LoopResumePoint } from "./resume.js";
@@ -73,7 +73,7 @@ export async function resumeLoopStage(
73
73
  // Re-validate the recomputed DAG: the id-only drift guard PASSES when a user edits
74
74
  // only a slice's `deps` (ids/titles unchanged), so a newly-introduced cycle would
75
75
  // otherwise reach the dispatcher. guardResumeEntry catches this throw → clean failure.
76
- validateUnitDeps(point.units!, point.parent);
76
+ ensureUnitDeps(point.units!, point.parent);
77
77
  const pending = pendingFanoutIndices(point.cursor, point.units!.length); // slots === undefined
78
78
  if (pending.length > 0) await announceLoopStart(ctx, run, entry);
79
79
  await runFanoutResume(ctx, entry, point.cursor, run, deps, pending);
@@ -88,7 +88,7 @@ export async function resumeLoopStage(
88
88
  /**
89
89
  * One refusal recorder — the shared 3-step body for the two resume recorders
90
90
  * (`recordMissingArtifactFailure` / `recordLoopDriftFailure`): resolve the
91
- * terminal args + build the audit ctx + `recordTerminalFailure`. Each caller
91
+ * terminal args + build the audit ctx + `recordFatalFailure`. Each caller
92
92
  * supplies its own descriptor — a `FailureText` (missing-artifact) or a
93
93
  * `[notifyMsg, errMsg]` tuple (loop drift).
94
94
  */
@@ -100,7 +100,7 @@ function recordResumeRefusal(
100
100
  descriptor: FailureText | [notifyMsg: string, errMsg: string],
101
101
  ): Promise<void> {
102
102
  const args = Array.isArray(descriptor) ? failedArgs(descriptor[0], descriptor[1]) : failedArgs(descriptor);
103
- return recordTerminalFailure(ctx, auditCtxFor(run, parent, skill), args);
103
+ return recordFatalFailure(ctx, auditCtxFor(run, parent, skill), args);
104
104
  }
105
105
 
106
106
  /** Recorded refusal for a corrupted/truncated trail (reuses the forward preflight's messages). */