@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
@@ -17,7 +17,7 @@ import { resolveSkill } from "../chain-state.js";
17
17
  import { lifecycleCtxFor, skillStageRef } from "../events.js";
18
18
  import { nowIso } from "../internal-utils.js";
19
19
  import { FAIL_BACKWARD_JUMP_EXHAUSTED, MSG_CHAIN_ADVANCE_FAILED, MSG_ROUTING_AUDIT_DROPPED } from "../messages.js";
20
- import { edgeIsDecision, nextStage } from "../routing.js";
20
+ import { bypassedRecoveryArms, edgeIsDecision, nextStage } from "../routing.js";
21
21
  import { appendRoutingDecision } from "../state/index.js";
22
22
  import type { RunContext, WorkflowHostContext } from "../types.js";
23
23
  import { type ChainOutcome, finalizeWorkflow } from "./failure.js";
@@ -58,8 +58,14 @@ export async function advanceChain(
58
58
 
59
59
  const fromRef = skillStageRef(currentName, idx + 1, resolveSkill(run.workflow.stages[currentName]!, currentName));
60
60
 
61
+ // Recovery arms this decision passed over for good — credited toward progress
62
+ // "coverage" by the bridge so a clean run's bar isn't frozen one-below until the
63
+ // end (build's slice-fix/plan-fix/code-fix). Empty for deterministic edges (no alternatives).
64
+ const chosen = result.kind === "stop" ? "stop" : result.stage;
65
+ const bypassed = wasDecision ? bypassedRecoveryArms(run.workflow, currentName, chosen, run.visited) : [];
66
+
61
67
  if (result.kind === "stop") {
62
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
68
+ await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run), bypassed);
63
69
  return finalizeWorkflow(curCtx, run);
64
70
  }
65
71
 
@@ -73,7 +79,7 @@ export async function advanceChain(
73
79
  // Fire onRoute after the routing decision has been audited (when applicable),
74
80
  // before the next stage runs. Deterministic auto-edges still fire so
75
81
  // listeners see every transition.
76
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run));
82
+ await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run), bypassed);
77
83
 
78
84
  // deps.runNext owns the catch for throws out of the *next* stage, so the
79
85
  // JSONL row records `nextName` (the stage that actually threw) rather than
@@ -121,8 +127,8 @@ function auditRoutingDecision(
121
127
  }
122
128
 
123
129
  /**
124
- * Per-loop cap on decision-edge retries. Returns `"continue"` when the run
125
- * may proceed, or the `"halted"` outcome when the cap tripped (and the
130
+ * Per-DESTINATION cap on decision-edge retries. Returns `"continue"` when the
131
+ * run may proceed, or the `"halted"` outcome when the cap tripped (and the
126
132
  * terminal failure has been recorded).
127
133
  *
128
134
  * A "backward jump" is a *decision-edge* resolving to an already-visited
@@ -133,10 +139,19 @@ function auditRoutingDecision(
133
139
  * mid-loop on any cycle longer than 2 stages, burning the entire budget
134
140
  * on a single retry iteration's deterministic hops.
135
141
  *
136
- * Reset-on-escape: a decision resolving to a NOT-visited stage escapes the
137
- * current cycle (we've moved to fresh territory), so the counter resets.
138
- * Each independent loop gets its own retry budget instead of a single
139
- * global pool that drains across unrelated loops.
142
+ * Each destination owns its budget (`run.revisits`): a stage may be
143
+ * re-entered via decision edges at most `maxBackwardJumps` times, regardless
144
+ * of how many OTHER decision edges the cycle crosses on the way. A shared
145
+ * streak counter would make the effective retry budget a function of the
146
+ * cycle's hop count — inserting a checking stage into a fix loop (a
147
+ * deterministic-floor edge, a confirm arm) silently taxed the fix budget.
148
+ * Per-destination counts are invariant to the cycle's shape, and unrelated
149
+ * loops are independent by construction (different destinations), which is
150
+ * what the old reset-on-escape rule existed to approximate.
151
+ *
152
+ * `state.telemetry.backwardJumps` stays the run-wide cumulative total of
153
+ * counted backward jumps (post-hoc telemetry only — never consulted for the
154
+ * halt decision, never reset).
140
155
  *
141
156
  * Trip attribution targets `nextName` (the stage the guard refused to
142
157
  * re-enter), not the just-completed stage.
@@ -146,17 +161,15 @@ async function checkBackwardJumpGuard(
146
161
  run: RunContext,
147
162
  nextName: string,
148
163
  ): Promise<"continue" | ChainOutcome> {
149
- const { state } = run;
150
- if (!run.visited.has(nextName)) {
151
- state.telemetry.backwardJumps = 0;
152
- return "continue";
153
- }
154
- state.telemetry.backwardJumps++;
155
- if (state.telemetry.backwardJumps <= run.maxBackwardJumps) return "continue";
164
+ if (!run.visited.has(nextName)) return "continue";
165
+ const revisits = (run.revisits.get(nextName) ?? 0) + 1;
166
+ run.revisits.set(nextName, revisits);
167
+ run.state.telemetry.backwardJumps++;
168
+ if (revisits <= run.maxBackwardJumps) return "continue";
156
169
  await recordTerminalFailure(
157
170
  curCtx,
158
171
  auditCtxFor(run, nextName, nextName),
159
- failedArgs(FAIL_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps)),
172
+ failedArgs(FAIL_BACKWARD_JUMP_EXHAUSTED(nextName, revisits, run.maxBackwardJumps)),
160
173
  );
161
174
  return "halted";
162
175
  }
package/runner/errors.ts CHANGED
@@ -1,33 +1,10 @@
1
1
  /**
2
- * The runner's typed-throw vocabulary — a leaf module so every layer of the
3
- * per-stage pipeline (preflights, input validation, the loop shortcut) can
4
- * throw it and the single catch site (`runStageOrRecordFailure`,
5
- * run-stage.ts) can catch it without any module importing back up.
2
+ * The runner's typed-throw vocabulary. The error type itself is a package-root
3
+ * shared kernel (`../stage-errors.ts`) so the engine's loop layer can throw it
4
+ * without importing into `runner/`; this module re-exports it so every layer of
5
+ * the per-stage pipeline (preflights, input validation, the loop shortcut) keeps
6
+ * its local `./errors.js` spelling and the single catch site
7
+ * (`runStageOrRecordFailure`, run-stage.ts) catches it as before.
6
8
  */
7
9
 
8
- /**
9
- * Thrown by a preflight check on failure; carries the recorded-row
10
- * attribution + notify/err messages so `runStageOrRecordFailure` can land
11
- * a uniform JSONL row regardless of which slot tripped.
12
- *
13
- * `kind` annotates the violation class for diagnostics only — control
14
- * flow at the catch site is uniform:
15
- * - `"halt"` — runtime-state failure (skill not registered, missing
16
- * upstream artifact, schema mismatch).
17
- * - `"invariant"` — authoring-time-knowable violation that
18
- * `validateWorkflow` should reject at load. A throw
19
- * here means validation was bypassed or the rule lives
20
- * only in the runner (continue-without-pi).
21
- */
22
- export class StagePreflightError extends Error {
23
- constructor(
24
- public readonly kind: "halt" | "invariant",
25
- public readonly skill: string,
26
- public readonly notifyMsg: string,
27
- public readonly errMsg: string,
28
- public readonly notifyPartial: boolean,
29
- ) {
30
- super(errMsg);
31
- this.name = "StagePreflightError";
32
- }
33
- }
10
+ export { haltPreflight, invariantPreflight, StagePreflightError } from "../stage-errors.js";
package/runner/failure.ts CHANGED
@@ -13,19 +13,18 @@ import {
13
13
  recordTerminalFailure,
14
14
  terminate,
15
15
  } from "../audit.js";
16
- import { formatError } from "../internal-utils.js";
17
- import { FAIL_WORKFLOW_ABORTED, MSG_STAGE_THREW, MSG_WORKFLOW_COMPLETE, STATUS_KEY } from "../messages.js";
18
- import type { RunContext, WorkflowHostContext } from "../types.js";
16
+ import { formatError, isAbortError } from "../internal-utils.js";
17
+ import { FAIL_WORKFLOW_ABORTED, MSG_STAGE_THREW, MSG_WORKFLOW_COMPLETE } from "../messages.js";
18
+ import type { RunContext, UnitRef, WorkflowHostContext } from "../types.js";
19
19
  import { StagePreflightError } from "./errors.js";
20
20
 
21
21
  /**
22
22
  * Explicit result of one chain-walk step, threaded up through
23
23
  * `advanceChain` / `runStage` / `runStageOrRecordFailure`. The walk's halt
24
- * protocol used to be record-then-quietly-unwind by convention — every halt
25
- * site had to remember a bare `return` after `recordTerminalFailure`. With a
24
+ * protocol is record-then-halt, not record-then-quietly-unwind: with a
26
25
  * non-void return type, a branch that records a failure but forgets to stop
27
- * the walk no longer typechecks: every arm must RETURN an outcome, and halts
28
- * read `return haltChain(...)`.
26
+ * the walk no longer typechecks — every arm must RETURN an outcome, and
27
+ * halts read `return haltChain(...)`.
29
28
  *
30
29
  * - `"halted"` — a terminal failure/abort row was recorded; the walk
31
30
  * stops here and unwinds.
@@ -59,8 +58,14 @@ export async function haltChain(
59
58
  skill: string,
60
59
  args: Parameters<typeof recordTerminalFailure>[2],
61
60
  onFailure?: (ctx: WorkflowHostContext) => void,
61
+ unit?: UnitRef,
62
62
  ): Promise<ChainOutcome> {
63
- await recordTerminalFailure(curCtx, auditCtxFor(run, stageName, skill), args, onFailure);
63
+ await recordTerminalFailure(
64
+ curCtx,
65
+ auditCtxFor(run, stageName, skill, unit ? { unit } : undefined),
66
+ args,
67
+ onFailure,
68
+ );
64
69
  return "halted";
65
70
  }
66
71
 
@@ -72,12 +77,18 @@ export async function haltChain(
72
77
  * attribution + messages. Recorded with the carried payload exactly.
73
78
  * - Any other `Error` — unexpected machinery failure; recorded with the
74
79
  * generic `MSG_STAGE_THREW` shape attributed to the stage id.
80
+ *
81
+ * `unit` is present only for the fanout worker-throw sink (`recordWorkerThrow`):
82
+ * its `{ ref, skill }` lands the unit's structured identity on the row
83
+ * (`parent`/`role`/`unitId`/`unitIndex` via `unitRowFields`) and the fanned
84
+ * `skill`, so the unit's identity is NOT folded into the `stage` name string.
75
85
  */
76
86
  export async function recordEntryThrow(
77
87
  curCtx: WorkflowHostContext,
78
88
  name: string,
79
89
  run: RunContext,
80
90
  e: unknown,
91
+ unit?: { ref: UnitRef; skill: string },
81
92
  ): Promise<ChainOutcome> {
82
93
  if (e instanceof StagePreflightError) {
83
94
  return haltChain(
@@ -90,19 +101,62 @@ export async function recordEntryThrow(
90
101
  );
91
102
  }
92
103
  const reason = formatError(e);
93
- return haltChain(curCtx, run, name, name, failedArgs(MSG_STAGE_THREW(name, reason), reason));
104
+ return haltChain(
105
+ curCtx,
106
+ run,
107
+ name,
108
+ unit?.skill ?? name,
109
+ failedArgs(MSG_STAGE_THREW(name, reason), reason),
110
+ undefined,
111
+ unit?.ref,
112
+ );
94
113
  }
95
114
 
96
115
  /**
97
- * Record the `"aborted"` terminal row for a cooperative-cancellation stop at
98
- * the between-stage seam (`run.signal` aborted before `name` ran).
116
+ * Record the `"aborted"` terminal row for a cooperative-cancellation stop — at
117
+ * the between-stage seam (`run.signal` aborted before `name` ran) OR when a
118
+ * mid-stage `postStage` throws `WorkflowAbortError`. Mirrors the error
119
+ * path's partial-artifacts recap (`recordEntryThrow` → `notifyPartialArtifacts`):
120
+ * artifacts produced by earlier stages are surfaced so the operator sees them
121
+ * instead of grepping the JSONL. No-op when no artifacts exist.
99
122
  */
100
123
  export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, run: RunContext): Promise<ChainOutcome> {
101
- return haltChain(curCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)));
124
+ return haltChain(curCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)), (ctx) =>
125
+ notifyPartialArtifacts(ctx, run.cwd, run.runId),
126
+ );
127
+ }
128
+
129
+ /**
130
+ * THE stage-entry guard — the ONE classify-then-record policy both single-stage
131
+ * entries share: pre-check the cooperative-abort signal, run `inner`, and on a
132
+ * throw classify it (mid-stage `WorkflowAbortError` → envelope-safe abort;
133
+ * anything else → terminal entry-throw row). Modeled after `advanceCursor`
134
+ * (loop.ts): one shared authority, callers hold their own preconditions.
135
+ *
136
+ * The two call sites (`runStageOrRecordFailure` live, `resumeStageWithSession`
137
+ * resume) cover DISJOINT scopes — the resume catch protects the reattach ladder
138
+ * (`resumeWithSessionLadder`) the live catch cannot reach — so both must exist.
139
+ * This wrapper merges the CLASSIFICATION POLICY (which throw is an abort vs a
140
+ * real entry-throw), not the scopes: each caller invokes it with its own `inner`
141
+ * + `name`, so a future widening of "what counts as abort" (a new cooperative-
142
+ * cancel signal beyond `WorkflowAbortError`) is one edit, here.
143
+ */
144
+ export async function withStageEntryGuard(
145
+ curCtx: WorkflowHostContext,
146
+ name: string,
147
+ run: RunContext,
148
+ inner: () => Promise<ChainOutcome>,
149
+ ): Promise<ChainOutcome> {
150
+ if (run.signal?.aborted) return recordAbortedAtSeam(curCtx, name, run);
151
+ try {
152
+ return await inner();
153
+ } catch (e) {
154
+ if (isAbortError(e)) return recordAbortedAtSeam(curCtx, name, run);
155
+ return recordEntryThrow(curCtx, name, run, e);
156
+ }
102
157
  }
103
158
 
104
159
  export function finalizeWorkflow(curCtx: WorkflowHostContext, run: RunContext): ChainOutcome {
105
- curCtx.ui.setStatus(STATUS_KEY, undefined);
106
160
  curCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
107
161
  terminate(run.state, { status: "completed" });
108
162
  return "completed";
@@ -29,7 +29,8 @@ import {
29
29
  type ValidationResult,
30
30
  validateOutputData,
31
31
  } from "../validate-output.js";
32
- import { StagePreflightError } from "./errors.js";
32
+ import { clampRange } from "../validation-bounds.js";
33
+ import { haltPreflight } from "./errors.js";
33
34
  import type { ResolvedStage } from "./resolve-stage.js";
34
35
 
35
36
  // ---------------------------------------------------------------------------
@@ -78,13 +79,13 @@ async function validateOrThrow(
78
79
  } catch (e) {
79
80
  if (errorPolicy === "degrade-on-non-timeout" && !(e instanceof SchemaTimeoutError)) return;
80
81
  const f = FAIL_INPUT_VALIDATION(stage.skill, prevSkill, formatError(e));
81
- throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
82
+ throw haltPreflight(stage.skill, f);
82
83
  }
83
84
 
84
85
  if (result.valid) return;
85
86
 
86
87
  const f = FAIL_INPUT_VALIDATION(stage.skill, prevSkill, result.failures.map(describeFailure).join("; "));
87
- throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
88
+ throw haltPreflight(stage.skill, f);
88
89
  }
89
90
 
90
91
  // ---------------------------------------------------------------------------
@@ -100,9 +101,11 @@ async function validateOrThrow(
100
101
  * firing a 100 ms timeout before a real I/O probe gets a chance to settle.
101
102
  */
102
103
  function clampValidateTimeoutMs(raw: number | undefined): number {
103
- return Math.max(
104
+ return clampRange(
105
+ raw,
104
106
  MIN_VALIDATION_RETRY_TIMEOUT_MS,
105
- Math.min(raw ?? DEFAULT_VALIDATION_RETRY_TIMEOUT_MS, MAX_VALIDATION_RETRY_TIMEOUT_MS),
107
+ DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
108
+ MAX_VALIDATION_RETRY_TIMEOUT_MS,
106
109
  );
107
110
  }
108
111
 
@@ -17,8 +17,9 @@ import {
17
17
  FAIL_SKILL_NOT_REGISTERED,
18
18
  MSG_STAGE_THREW,
19
19
  } from "../messages.js";
20
+ import { readName } from "../stage-def.js";
20
21
  import type { RunContext } from "../types.js";
21
- import { StagePreflightError } from "./errors.js";
22
+ import { haltPreflight, invariantPreflight } from "./errors.js";
22
23
  import type { ResolvedStage } from "./resolve-stage.js";
23
24
 
24
25
  /**
@@ -34,7 +35,6 @@ import type { ResolvedStage } from "./resolve-stage.js";
34
35
  export function runSingleStagePreflights(stage: ResolvedStage, run: RunContext): void {
35
36
  ensureUpstreamArtifact(stage, run);
36
37
  ensureNamedReads(stage, run);
37
- enforceSessionInvariants(stage, run);
38
38
  ensureSkillRegistered(stage, run);
39
39
  }
40
40
 
@@ -49,13 +49,12 @@ export function ensureLoopNotContinue(stage: ResolvedStage): void {
49
49
  const reason =
50
50
  `runStage: stage "${stage.name}" cannot combine loop with sessionPolicy "continue" — ` +
51
51
  "each unit requires an isolated session";
52
- throw new StagePreflightError("invariant", stage.name, MSG_STAGE_THREW(stage.name, reason), reason, false);
52
+ throw invariantPreflight(stage.name, MSG_STAGE_THREW(stage.name, reason), reason);
53
53
  }
54
54
 
55
55
  /**
56
- * Loop-stage preflights, run UNIFORMLY for every loop kind (the old
57
- * shortcuts bypassed them: a ≥1-unit fanout ran none; iterate ran none;
58
- * assess re-ran two inline):
56
+ * Loop-stage preflights, run UNIFORMLY for every loop kind — no kind takes a
57
+ * shortcut:
59
58
  * - ensureNamedReads + ensureSkillRegistered for ALL loops (every loop's
60
59
  * units dispatch `/skill:<skill>`, and generators read declared channels);
61
60
  * - ensureUpstreamArtifact for ASSESS ONLY — the round-0 producer arg is
@@ -88,7 +87,7 @@ export function ensureJudgeSkillRegistered(judge: AnyJudge, stage: ResolvedStage
88
87
  if (member.skill === undefined) continue;
89
88
  if (run.registeredSkills.has(member.skill)) continue;
90
89
  const f = FAIL_SKILL_NOT_REGISTERED(member.skill, stage.stageNumber);
91
- throw new StagePreflightError("halt", member.skill, f.toast, f.error, true);
90
+ throw haltPreflight(member.skill, f);
92
91
  }
93
92
  }
94
93
 
@@ -105,9 +104,8 @@ export function ensureJudgeSkillRegistered(judge: AnyJudge, stage: ResolvedStage
105
104
  * into a properly-attributed stage halt.
106
105
  *
107
106
  * Reads the snapshot in `run.registeredSkills` rather than calling
108
- * `host.getCommands()` mid-run, because Pi marks the `WorkflowHost` handle
109
- * stale on the first `ctx.newSession()` — the snapshot is built once in
110
- * `buildRunContext` before any session replaces the outer ctx.
107
+ * `host.getCommands()` mid-run — the snapshot is built once in
108
+ * `buildRunContext` at run start, off the launcher's registry-level host.
111
109
  *
112
110
  * Skipped for non-skill dispatch (a prompt stage sends raw text — there is
113
111
  * no skill to verify) and when `registeredSkills` is undefined (hostless
@@ -120,7 +118,7 @@ function ensureSkillRegistered(stage: ResolvedStage, run: RunContext): void {
120
118
  if (run.registeredSkills.has(stage.skill)) return;
121
119
 
122
120
  const f = FAIL_SKILL_NOT_REGISTERED(stage.skill, stage.stageNumber);
123
- throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
121
+ throw haltPreflight(stage.skill, f);
124
122
  }
125
123
 
126
124
  /**
@@ -145,7 +143,7 @@ function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
145
143
  if (stage.dispatch === "prompt") return;
146
144
  if (currentPrimaryArtifact(run.state)) return;
147
145
  const f = FAIL_MISSING_ARTIFACT(stage.skill, stage.stageNumber);
148
- throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
146
+ throw haltPreflight(stage.skill, f);
149
147
  }
150
148
 
151
149
  /**
@@ -158,16 +156,14 @@ function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
158
156
  function ensureNamedReads(stage: ResolvedStage, run: RunContext): void {
159
157
  const reads = stage.def.reads;
160
158
  if (!reads?.length) return;
161
- for (const name of reads) {
159
+ for (const read of reads) {
160
+ const name = readName(read);
161
+ // Reads `.length` of a possibly PRE-SIZED produces-fanout channel as
162
+ // "satisfied". Safe by ordering: this runs at the READING stage's entry,
163
+ // AFTER the upstream fanout stage's fold completed its channel, so it never
164
+ // observes a half-filled produces-fanout channel.
162
165
  if (run.state.named[name]?.length) continue;
163
166
  const f = FAIL_MISSING_NAMED_READ(stage.skill, name, stage.stageNumber);
164
- throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
165
- }
166
- }
167
-
168
- function enforceSessionInvariants(stage: ResolvedStage, run: RunContext): void {
169
- if (stage.def.sessionPolicy === "continue" && !run.continueHost) {
170
- const reason = `runStage: stage "${stage.name}" uses sessionPolicy "continue" but no workflow host was provided to runWorkflow`;
171
- throw new StagePreflightError("invariant", stage.name, MSG_STAGE_THREW(stage.name, reason), reason, false);
167
+ throw haltPreflight(stage.skill, f);
172
168
  }
173
169
  }
@@ -55,12 +55,32 @@ export function selectResumeEntry(
55
55
  resumeLoopStage(ctx, recon.trailing!, idx, run, buildLoopDeps()),
56
56
  );
57
57
  }
58
+ if (recon.trailing && recon.trailing.parent === last.stage) {
59
+ // Open FANOUT generation whose trailer is its OWN parent-unset abort/halt
60
+ // stage row (a mid-flight abort). The fold keeps the generation open for
61
+ // exactly this case (see resume.ts), so `recon.trailing` carries the
62
+ // completed-unit slots — re-enter the loop to replay them and dispatch
63
+ // only the pending units (finding 7). Without this arm the aborted trailer
64
+ // falls through to the cold stage re-run below and re-dispatches EVERY
65
+ // unit, duplicating the channel and collapsing the downstream fan-in.
66
+ return () =>
67
+ guardResumeEntry(ctx, last.stage, run, () => resumeLoopStage(ctx, recon.trailing!, idx, run, buildLoopDeps()));
68
+ }
58
69
  if (last.status === "completed") {
59
- // route onward; finished run ⇒ hits stop ⇒ no-op
70
+ // c2 no-op path: a fully-completed run routes onward from its last stage,
71
+ // which hits `stop` ⇒ `finalizeWorkflow` ⇒ success. The walk runs the
72
+ // normal lifecycle bracket (onWorkflowStart/onWorkflowEnd) but dispatches
73
+ // no stage session — no stage re-run, no child spawned, zero new JSONL
74
+ // stage rows. This is the safe no-op behind resuming a finished run via
75
+ // @<runId>.
60
76
  return () => guardResumeEntry(ctx, last.stage, run, () => advance(ctx, last.stage, idx, run));
61
77
  }
62
- // failed/aborted trailer — session-backed rows try promotion/reattach,
63
- // sessionless rows re-run cold (today's behavior).
78
+ // failed/aborted trailer — the c2 boundary. Re-attempting this stage is
79
+ // intentional and the core resume retry use case: session-backed rows try
80
+ // promotion/reattach (`resumeStageWithSession`), sessionless rows re-run cold
81
+ // (today's behavior). Deliberately OUTSIDE c2's no-op guarantee — a new stage
82
+ // row IS appended and the stage re-runs (see the completed-vs-failed boundary
83
+ // tests in resume.test.ts).
64
84
  return last.session !== null
65
85
  ? () => resumeStageWithSession(ctx, last, idx, run)
66
86
  : () => runStageOrRecordFailure(ctx, last.stage, idx, run);
@@ -19,10 +19,11 @@
19
19
 
20
20
  import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
21
21
  import { resolveSkill } from "../chain-state.js";
22
- import { announceLoopStart, type LoopDeps, runLoop } from "../loop.js";
23
- import { effectiveLoopOf } from "../loop-constructors.js";
24
- import { type LoopEntry, loopStrategyOf } from "../loop-kinds.js";
25
- import { FAIL_MISSING_ARTIFACT, MSG_RESUME_LOOP_MISMATCH } from "../messages.js";
22
+ import { announceLoopStart, pendingFanoutIndices, runFanoutResume, runLoop } from "../loop.js";
23
+ import { effectiveLoopOf, freezesEntryArgsOf } from "../loop-constructors.js";
24
+ import { buildLoopEntry, type LoopDeps, sequentialStrategyOf } from "../loop-kinds.js";
25
+ import { validateUnitDeps } from "../loop-waves.js";
26
+ import { FAIL_MISSING_ARTIFACT, type FailureText, MSG_RESUME_LOOP_MISMATCH } from "../messages.js";
26
27
  import type { RunContext, WorkflowHostContext } from "../types.js";
27
28
  import type { LoopResumePoint } from "./resume.js";
28
29
 
@@ -47,7 +48,7 @@ export async function resumeLoopStage(
47
48
  // skill args exist) and the driver re-resolves the stage's own `prompt` at
48
49
  // round-0 dispatch.
49
50
  let entryArgs = "";
50
- if (loop.kind === "assess") {
51
+ if (freezesEntryArgsOf(loop)) {
51
52
  if (point.entryArgs === undefined) {
52
53
  await recordMissingArtifactFailure(ctx, run, point.parent, skill, idx);
53
54
  return;
@@ -55,25 +56,53 @@ export async function resumeLoopStage(
55
56
  entryArgs = point.entryArgs;
56
57
  }
57
58
 
58
- const entry: LoopEntry = {
59
- stageIdx: idx,
60
- name: point.parent,
61
- skill,
62
- def,
63
- loop,
64
- entryArtifact: point.entryArtifact,
65
- entryArgs,
66
- entryPair: point.entryPair,
67
- units: point.units, // fanout: the fold's recomputed-and-verified list — no second compute
68
- };
59
+ const entry = buildLoopEntry(
60
+ { stageIdx: idx, name: point.parent, skill, def, loop },
61
+ {
62
+ entryArtifact: point.entryArtifact,
63
+ entryArgs,
64
+ entryPair: point.entryPair,
65
+ units: point.units, // fanout: the fold's recomputed-and-verified list — no second compute
66
+ },
67
+ );
68
+
69
+ // Fanout resume re-dispatches ONLY the still-unfilled indices in bounded
70
+ // parallel (folding each at its declared slot) — never a cold whole-loop
71
+ // re-entry, so already-completed/collected units keep their place.
72
+ if (loop.kind === "fanout") {
73
+ // Re-validate the recomputed DAG: the id-only drift guard PASSES when a user edits
74
+ // only a slice's `deps` (ids/titles unchanged), so a newly-introduced cycle would
75
+ // otherwise reach the dispatcher. guardResumeEntry catches this throw → clean failure.
76
+ validateUnitDeps(point.units!, point.parent);
77
+ const pending = pendingFanoutIndices(point.cursor, point.units!.length); // slots === undefined
78
+ if (pending.length > 0) await announceLoopStart(ctx, run, entry);
79
+ await runFanoutResume(ctx, entry, point.cursor, run, deps, pending);
80
+ return;
81
+ }
69
82
 
70
- // Pending-work probe (strategy table) gates the announce only — a
71
- // finished-loop resume stays a pinned SILENT no-op.
72
- if (await loopStrategyOf(loop.kind).hasPending(loop, point, run)) await announceLoopStart(ctx, run, entry);
83
+ if (await sequentialStrategyOf(loop.kind).hasPending(loop, point, run)) await announceLoopStart(ctx, run, entry);
73
84
 
74
85
  await runLoop(ctx, entry, point.cursor, run, deps);
75
86
  }
76
87
 
88
+ /**
89
+ * One refusal recorder — the shared 3-step body for the two resume recorders
90
+ * (`recordMissingArtifactFailure` / `recordLoopDriftFailure`): resolve the
91
+ * terminal args + build the audit ctx + `recordTerminalFailure`. Each caller
92
+ * supplies its own descriptor — a `FailureText` (missing-artifact) or a
93
+ * `[notifyMsg, errMsg]` tuple (loop drift).
94
+ */
95
+ function recordResumeRefusal(
96
+ ctx: WorkflowHostContext,
97
+ run: RunContext,
98
+ parent: string,
99
+ skill: string,
100
+ descriptor: FailureText | [notifyMsg: string, errMsg: string],
101
+ ): Promise<void> {
102
+ const args = Array.isArray(descriptor) ? failedArgs(descriptor[0], descriptor[1]) : failedArgs(descriptor);
103
+ return recordTerminalFailure(ctx, auditCtxFor(run, parent, skill), args);
104
+ }
105
+
77
106
  /** Recorded refusal for a corrupted/truncated trail (reuses the forward preflight's messages). */
78
107
  function recordMissingArtifactFailure(
79
108
  ctx: WorkflowHostContext,
@@ -82,11 +111,7 @@ function recordMissingArtifactFailure(
82
111
  skill: string,
83
112
  idx: number,
84
113
  ): Promise<void> {
85
- return recordTerminalFailure(
86
- ctx,
87
- auditCtxFor(run, parent, skill),
88
- failedArgs(FAIL_MISSING_ARTIFACT(skill, idx + 1)),
89
- );
114
+ return recordResumeRefusal(ctx, run, parent, skill, FAIL_MISSING_ARTIFACT(skill, idx + 1));
90
115
  }
91
116
 
92
117
  /**
@@ -102,9 +127,5 @@ export function recordLoopDriftFailure(
102
127
  errMsg: string,
103
128
  ): Promise<void> {
104
129
  const skill = resolveSkill(run.workflow.stages[parent]!, parent);
105
- return recordTerminalFailure(
106
- ctx,
107
- auditCtxFor(run, parent, skill),
108
- failedArgs(MSG_RESUME_LOOP_MISMATCH(parent), errMsg),
109
- );
130
+ return recordResumeRefusal(ctx, run, parent, skill, [MSG_RESUME_LOOP_MISMATCH(parent), errMsg]);
110
131
  }