@juicesharp/rpiv-workflow 2.7.1 → 2.8.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.
package/chain-state.ts CHANGED
@@ -15,7 +15,7 @@ import type { PromptFn, StageDef } from "./api.js";
15
15
  import { type Artifact, handleToString } from "./handle.js";
16
16
  import { isFailedOutput, type Output } from "./output.js";
17
17
  import { readName, readsAll } from "./stage-def.js";
18
- import { resolvePublishName } from "./stage-identity.js";
18
+ import { actsPublishName, resolvePublishName } from "./stage-identity.js";
19
19
  import type { RunState } from "./types.js";
20
20
 
21
21
  // Stage-identity projections live in the dependency-free `stage-identity.ts`
@@ -195,6 +195,22 @@ export function applyCompletedStage(state: RunState, def: StageDef, stageName: s
195
195
  slot.push(output);
196
196
  return;
197
197
  }
198
+ // A side-effect stage with an EXPLICITLY NAMED outcome publishes onto that
199
+ // channel too (`actsPublishName` — explicit name only, never the record-key
200
+ // fallback), honoring the `Outcome.name` contract for acts stages. Without
201
+ // this, a gate folding an acts outcome's channel (validate-fix's
202
+ // `remediation` digest — the fix-round count AND the unchanged-tree stop)
203
+ // read a channel no code path ever wrote. The rolling primary stays
204
+ // governed by the acts rules below — a side-effect outcome never rolls it.
205
+ const actsKey = actsPublishName(def);
206
+ if (actsKey !== undefined) {
207
+ let slot = state.named[actsKey];
208
+ if (!slot) {
209
+ slot = [];
210
+ state.named[actsKey] = slot;
211
+ }
212
+ slot.push(output);
213
+ }
198
214
  clearPrimaryForActs(state, def);
199
215
  }
200
216
 
@@ -238,12 +238,13 @@ Every constructor accepts the shared introspectable facet and policy knobs:
238
238
  | `onCap` | fanout/iterate `"halt"` · assess `"advance"` | What happens at the effective cap (`min(max, run.maxIterations)`). `"halt"` — terminal failure (mirrors the backward-jump guard). `"advance"` — soft-stop: warn, land a `{type:"loop-cap"}` telemetry row, fire `onLoopCap`, keep the projected result, advance downstream. |
239
239
  | `result` | fanout `"entry"` · iterate/assess `"last"` | What the loop leaves in `{state.output, state.primaryArtifact}` (the pair is governed as one). `"entry"` restores the pair captured at loop entry (reproduces routing-sees-upstream); `"last"` uses the last completed produce unit's pair (zero produce units degrades to entry). |
240
240
 
241
- `fanout()` adds three knobs the sequential kinds have no use for:
241
+ `fanout()` adds four knobs the sequential kinds have no use for:
242
242
 
243
243
  | Knob (fanout only) | Default | Meaning |
244
244
  |---|---|---|
245
245
  | `concurrency` | host cap | Per-fanout in-flight ceiling, applied as `min(concurrency, host maxConcurrency)`. `1` **serializes** the loop — the safe model for units mutating shared state (e.g. applying a plan to one working tree). Integer ≥ 1, validated at construction and load. |
246
246
  | `failFast` | absent (collect-all) | Opt out of collect-all: the first failing unit halts the run terminally and cancels in-flight siblings. Cancelled siblings leave unfilled slots, so a later resume re-dispatches them. |
247
+ | `haltWhenAllFailed` | absent | Opt-in halt at generation close: when every declared slot of a closing generation is filled and every one is a failed sentinel (strict all-filled-all-failed), the run halts terminally at the loop stage (parent-attributed `FAIL_FANOUT_ALL_FAILED` row) instead of advancing into a fan-in over an empty channel. Collection is unchanged — per-unit collect-all soft-halt rows keep flowing, so resume still rebuilds sentinels rather than re-running dead units. An over-cap `"advance"` generation never qualifies (beyond-cap slots stay unfilled). `failFast` wins when both are set. |
247
248
  | `depArtifactFlag` | none | Injects each completed dependency's artifact path into the dependent unit's prompt as `<flag> <path>`, one per direct `deps` entry whose slot holds a non-failed output. Pairs with `Unit.deps` — `deps` orders the waves, this hands the dependent something to read. Failed dep slots are skipped. |
248
249
 
249
250
  #### The resume contract (all loop kinds)
package/loop-def.ts CHANGED
@@ -235,6 +235,19 @@ export interface FanoutLoop extends LoopCommon {
235
235
  * re-dispatches them. `genAbort` is also driven by run-level abort (Ctrl-C /
236
236
  * `run.signal`), so the same machinery serves both. */
237
237
  failFast?: boolean;
238
+ /**
239
+ * Opt-in halt at generation CLOSE: when a closing generation's every declared
240
+ * slot is filled and every one is a failed sentinel (the strict
241
+ * all-filled-all-failed condition), the run halts terminally at the loop
242
+ * stage with a parent-attributed `FAIL_FANOUT_ALL_FAILED` row instead of
243
+ * advancing into a fan-in over an empty channel. An over-cap generation
244
+ * under `onCap: "advance"` NEVER qualifies (beyond-cap slots stay
245
+ * unfilled, so `filledCount < slots.length`). `failFast` wins when both
246
+ * are set — it halts at the FIRST unit failure, before any close. Absent ⇒
247
+ * the collect-all contract is unchanged (failed slots become sentinel
248
+ * outputs; the chain advances).
249
+ */
250
+ haltWhenAllFailed?: boolean;
238
251
  /**
239
252
  * When set, the dispatcher injects each completed dependency's published
240
253
  * artifact path into the dependent unit's prompt as `${depArtifactFlag} <path>`
package/loop-kinds.ts CHANGED
@@ -124,6 +124,19 @@ export interface LoopDeps {
124
124
  count: number,
125
125
  cap: number,
126
126
  ) => Promise<void>;
127
+ /** Record the terminal all-failed generation-close halt
128
+ * (FAIL_FANOUT_ALL_FAILED) — parent-attributed, sessionless, unit-field-free
129
+ * (the `haltLoop` recording shape), so the resume fold's halt-marker
130
+ * predicate keeps the generation open and a later resume re-derives the
131
+ * halt with zero new resume code. Fired from `finishLoop`'s single halt
132
+ * spelling across all four closing paths. */
133
+ haltLoopWhenAllFailed: (
134
+ hostCtx: WorkflowHostContext,
135
+ run: RunContext,
136
+ e: Pick<LoopEntry, "name" | "skill">,
137
+ failed: number,
138
+ total: number,
139
+ ) => Promise<void>;
127
140
  /** Record a mid-flight run abort at the loop seam (FAIL_WORKFLOW_ABORTED).
128
141
  * Keeps the drivers free of engine imports; wired to `recordAbortedAtSeam`. */
129
142
  recordAborted: (hostCtx: WorkflowHostContext, name: string, run: RunContext) => Promise<void>;
@@ -455,12 +468,33 @@ function lastNonFailedSlot(slots: readonly (Output | undefined)[]): LoopCursor["
455
468
  return undefined;
456
469
  }
457
470
 
471
+ /** THE strict all-failed generation-close predicate — `true` when every declared
472
+ * slot is filled and every one is a failed sentinel (the fan-in would read an
473
+ * empty channel). Reuses `lastNonFailedSlot`: `undefined` is exactly the
474
+ * "no non-failed slot" verdict, so the conjunction is filled + all-failed. An
475
+ * over-cap-advancing generation NEVER satisfies it (beyond-cap slots stay
476
+ * `undefined`, so `filledCount < slots.length`). Consumed by `finishLoop`'s
477
+ * single halt spelling (loop.ts) across all four closing paths. */
478
+ export const allFanoutSlotsFailed = (cursor: LoopCursor): boolean =>
479
+ cursor.slots !== undefined &&
480
+ cursor.filledCount === cursor.slots.length &&
481
+ lastNonFailedSlot(cursor.slots) === undefined;
482
+
458
483
  /** THE fanout fail-fast narrow — `true` when a fanout loop opted out of the
459
484
  * default collect-all via `fanout({ failFast: true })`. The ONE spelling of the
460
485
  * kind+field guard the dispatcher (sibling-cancel) and `buildUnitSession`
461
486
  * (`collectAll`) both read, so the narrow can't drift across its read sites. */
462
487
  export const isFailFast = (loop: LoopDef): boolean => loop.kind === "fanout" && loop.failFast === true;
463
488
 
489
+ /** THE haltWhenAllFailed narrow — `true` when a fanout loop opted into the
490
+ * all-failed generation-close halt via `fanout({ haltWhenAllFailed: true })`.
491
+ * The ONE spelling of the kind+field guard `finishLoop` reads (loop.ts),
492
+ * mirroring `isFailFast` above so the two fanout flags can't drift across
493
+ * their read sites. The `=== true` keeps the flag boolean-safe for
494
+ * jiti-loaded literals. */
495
+ export const isHaltWhenAllFailed = (loop: LoopDef): boolean =>
496
+ loop.kind === "fanout" && loop.haltWhenAllFailed === true;
497
+
464
498
  /** fanout units collect-all by default (opt out via fanout({ failFast: true }));
465
499
  * the `kind === "fanout"` guard is LOAD-BEARING: iterate/assess units MUST NOT
466
500
  * collect-all — they advance the cursor (advanceCursor), so a soft-halt sentinel
package/loop.ts CHANGED
@@ -44,8 +44,10 @@ import { type AnyJudge, isPanel, type PanelJudge } from "./judge.js";
44
44
  import { panelVerdictChannel, panelVerdictDef } from "./loop-constructors.js";
45
45
  import {
46
46
  advanceCursor,
47
+ allFanoutSlotsFailed,
47
48
  buildUnitSession,
48
49
  foldFanoutCompletion,
50
+ isHaltWhenAllFailed,
49
51
  type LoopCursor,
50
52
  type LoopDeps,
51
53
  type LoopEntry,
@@ -319,6 +321,18 @@ async function finishLoop(
319
321
  run: RunContext,
320
322
  deps: LoopDeps,
321
323
  ): Promise<void> {
324
+ // haltWhenAllFailed — the SINGLE spelling of the all-failed generation-close
325
+ // halt. It lives here (never a loop-parallel gate twin) because finishLoop is
326
+ // the one funnel every closing path reaches: the live under-cap finalTail, the
327
+ // live over-cap `onCap: "advance"` tail (hitCap → finishLoop), the resume
328
+ // re-dispatch tail (runFanoutResume), and the resume all-filled early tail
329
+ // (runFanoutGeneration's order.length === 0 shortcut bypasses the
330
+ // post-dispatch gates). Strict predicate: an over-cap-advancing generation
331
+ // never qualifies (beyond-cap slots stay unfilled).
332
+ if (isHaltWhenAllFailed(e.loop) && allFanoutSlotsFailed(cursor)) {
333
+ await deps.haltLoopWhenAllFailed(hostCtx, run, e, cursor.filledCount ?? 0, cursor.slots?.length ?? 0);
334
+ return;
335
+ }
322
336
  projectResult(e.loop, e.entryPair, cursor, run.state);
323
337
  if (isZeroUnitPullLoop(cursor, e.loop)) {
324
338
  hostCtx.ui.notify(MSG_LOOP_ZERO_UNITS(e.skill), "warning");
@@ -134,6 +134,11 @@ export interface FanoutOptions extends LoopOptionsBase {
134
134
  concurrency?: number;
135
135
  /** Opt out of collect-all: any unit failure halts the run (default ⇒ collect-all). */
136
136
  failFast?: boolean;
137
+ /** Opt-in terminal halt when a generation CLOSES with every declared slot a
138
+ * failed sentinel (strict all-filled-all-failed) — the run stops at the loop
139
+ * stage instead of advancing into a fan-in over an empty channel. Over-cap
140
+ * advancing generations never qualify; `failFast` wins when both are set. */
141
+ haltWhenAllFailed?: boolean;
137
142
  /** When set, the dispatcher appends `${depArtifactFlag} <path>` per direct
138
143
  * `Unit.deps` entry with a non-failed filled slot — handing the dependent unit
139
144
  * its dependencies' published artifacts (e.g. `"--upstream"`). Non-empty string;
@@ -176,6 +181,7 @@ export function fanout(opts: FanoutOptions): FanoutLoop {
176
181
  : {}),
177
182
  ...(opts.depArtifactFlag !== undefined ? { depArtifactFlag: checkedDepArtifactFlag(opts.depArtifactFlag) } : {}),
178
183
  ...(opts.failFast !== undefined ? { failFast: opts.failFast } : {}),
184
+ ...(opts.haltWhenAllFailed !== undefined ? { haltWhenAllFailed: opts.haltWhenAllFailed } : {}),
179
185
  };
180
186
  }
181
187
 
package/messages.ts CHANGED
@@ -130,9 +130,14 @@ export const FAIL_BACKWARD_JUMP_EXHAUSTED = (stage: string, revisits: number, ma
130
130
  * intervention, not complete; `note` is the edge's own no-match diagnostic
131
131
  * (the ROUTE_NOTE `match` attaches), so the toast names the value that failed
132
132
  * to route. The stage's own output (its verdict) holds the findings.
133
+ *
134
+ * The toast names `/wf @<runId>` — resume re-runs the halted gate against
135
+ * the repaired tree and continues on a pass, reusing every upstream
136
+ * artifact; a bare "re-run" reads as "start over" and re-pays the whole
137
+ * front-load (observed: full re-runs of research+plan for a one-line fix).
133
138
  */
134
- export const FAIL_GATE_STOP = (stage: string, note: string): FailureText => ({
135
- toast: `✗ workflow stopped at "${stage}" — its routing gate matched no branch (${note}); see the stage's verdict for findings, then fix and re-run`,
139
+ export const FAIL_GATE_STOP = (stage: string, note: string, runId: string): FailureText => ({
140
+ toast: `✗ workflow stopped at "${stage}" — its routing gate matched no branch (${note}); see the stage's verdict for findings, then fix and resume with /wf @${runId}`,
136
141
  error: `Routing gate after "${stage}" matched no branch: ${note}`,
137
142
  });
138
143
 
@@ -154,6 +159,20 @@ export const FAIL_LOOP_CAP_HALT = (count: number, max: number): FailureText => (
154
159
  error: `Loop cap exceeded: ${count} units (max ${max})`,
155
160
  });
156
161
 
162
+ /**
163
+ * A `haltWhenAllFailed` fanout generation closed with EVERY declared slot a
164
+ * failed sentinel (strict all-filled-all-failed) — the run halts terminally at
165
+ * the loop stage instead of advancing into a fan-in over an empty channel.
166
+ * `failed`/`total` are the closing generation's failed and total slot counts;
167
+ * the `error` string's fanout-stage attribution becomes the recap
168
+ * `failureReason`. Tests pin substrings (`Fanout all-failed`), not full
169
+ * sentences.
170
+ */
171
+ export const FAIL_FANOUT_ALL_FAILED = (skill: string, failed: number, total: number): FailureText => ({
172
+ toast: `rpiv: ${skill} fanout failed in full (${failed}/${total} units) — stopping workflow`,
173
+ error: `Fanout all-failed at stage "${skill}" (${failed}/${total} units failed)`,
174
+ });
175
+
157
176
  /**
158
177
  * A loop hit its effective cap under `onCap: "advance"` — soft-stop: warn,
159
178
  * land the {type:"loop-cap"} telemetry row, keep the projected result,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "2.7.1",
3
+ "version": "2.8.0",
4
4
  "description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -112,7 +112,7 @@
112
112
  ]
113
113
  },
114
114
  "dependencies": {
115
- "@juicesharp/rpiv-config": "^2.7.1",
115
+ "@juicesharp/rpiv-config": "^2.8.0",
116
116
  "jiti": "^2.7.0",
117
117
  "typebox": "^1.1.24"
118
118
  },
@@ -69,7 +69,7 @@ export async function advanceChain(
69
69
  if (wasDecision) auditRoutingDecision(hostCtx, run, idx, currentName, "stop", note);
70
70
  await run.lifecycle.fire(hostCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
71
71
  if (isBlockedGateStop(note)) {
72
- return haltChain(hostCtx, run, currentName, skill, failedArgs(FAIL_GATE_STOP(currentName, note)));
72
+ return haltChain(hostCtx, run, currentName, skill, failedArgs(FAIL_GATE_STOP(currentName, note, run.runId)));
73
73
  }
74
74
  return finalizeWorkflow(hostCtx, run);
75
75
  }
@@ -5,12 +5,14 @@
5
5
  * `resume-loop.ts` (which owns the loop-trailer arm's dispatch).
6
6
  */
7
7
 
8
+ import type { Workflow } from "../api.js";
8
9
  import {
9
10
  ERR_RESUME_MALFORMED_ROW,
10
11
  ERR_RESUME_NO_ROWS,
11
12
  ERR_RESUME_STAGE_GONE,
12
13
  ERR_RESUME_VERSION_MISMATCH,
13
14
  } from "../messages.js";
15
+ import { STOP } from "../routing-dsl.js";
14
16
  import { STATE_SCHEMA_VERSION } from "../state/index.js";
15
17
  import type { RunContext, WorkflowHostContext } from "../types.js";
16
18
  import { recordEntryThrow } from "./failure.js";
@@ -25,10 +27,15 @@ import { advance, buildLoopDeps, dispatchStageOrRecordFailure, resumeStageWithSe
25
27
  * (zero dispatch; lifecycle bracketing identical to every other entry);
26
28
  * - trailing unit row → re-enter the loop with the fold's cursor;
27
29
  * - completed normal trailer → route onward (finished run hits stop ⇒ no-op);
30
+ * - gate-stop halt on a side-effect stage → dispatch the gate's sole
31
+ * non-stop target, or re-route (idempotent re-stop) when the target is
32
+ * ambiguous — NEVER replay the arm (see the arm's comment);
28
33
  * - failed/aborted trailer → session-backed rows try promotion/reattach
29
34
  * (`resumeStageWithSession`); sessionless rows re-run cold (today's
30
35
  * behavior). Dispatch keys on the STRUCTURED `session` field, mirroring
31
- * the `parent !== undefined` arm.
36
+ * the `parent !== undefined` arm. A gate-stop halt on a produces stage
37
+ * lands here deliberately: its halt row is sessionless by construction
38
+ * (`auditCtxFor`), so the gate stage re-runs cold — the re-measure.
32
39
  */
33
40
  export function selectResumeEntry(
34
41
  ctx: WorkflowHostContext,
@@ -75,6 +82,25 @@ export function selectResumeEntry(
75
82
  // @<runId>.
76
83
  return () => guardResumeEntry(ctx, last.stage, run, () => advance(ctx, last.stage, idx, run));
77
84
  }
85
+ // Gate-stop halt off a SIDE-EFFECT stage: re-running the arm would replay
86
+ // its side effects against a tree the user has since hand-repaired — the
87
+ // observed livelock is a remediation arm that re-runs, changes nothing (the
88
+ // hand-fix already landed), and re-trips the very unchanged-tree gate that
89
+ // halted it. The re-measure path is the gate's own onward target: dispatch
90
+ // its sole non-stop target so the fix loop's verification body re-judges
91
+ // the repaired tree. A gate with several onward targets (none exist today)
92
+ // must NOT fall through to the cold re-dispatch below — that is exactly the
93
+ // replay this arm exists to prevent — so it re-routes instead: `advance`
94
+ // re-fires the edge over the replayed channels, which either picks a live
95
+ // onward branch or re-stops with the same note (an idempotent halt, zero
96
+ // side effects). Only a PRODUCES gate stage takes the re-dispatch below,
97
+ // where re-running IS the re-measure (fresh judgment, route re-folds).
98
+ if (recon.gateStop && run.workflow.stages[last.stage]?.kind === "side-effect") {
99
+ const onward = soleOnwardTarget(run.workflow, last.stage);
100
+ return onward !== undefined
101
+ ? () => guardResumeEntry(ctx, onward, run, () => dispatchStageOrRecordFailure(ctx, onward, idx + 1, run))
102
+ : () => guardResumeEntry(ctx, last.stage, run, () => advance(ctx, last.stage, idx, run));
103
+ }
78
104
  // failed/aborted trailer — the c2 boundary. Re-attempting this stage is
79
105
  // intentional and the core resume retry use case: session-backed rows try
80
106
  // promotion/reattach (`resumeStageWithSession`), sessionless rows re-run cold
@@ -86,6 +112,19 @@ export function selectResumeEntry(
86
112
  : () => dispatchStageOrRecordFailure(ctx, last.stage, idx, run);
87
113
  }
88
114
 
115
+ /**
116
+ * The single non-stop target a decision edge can route onward to, or
117
+ * `undefined` when the edge declares none, several, or a target no longer in
118
+ * the workflow. Reads the `.targets` metadata every decision edge carries
119
+ * (`validate-workflow.ts` enforces it at load time), so no predicate is probed.
120
+ */
121
+ function soleOnwardTarget(workflow: Workflow, stage: string): string | undefined {
122
+ const edge = workflow.edges[stage];
123
+ if (typeof edge !== "function" || !edge.targets) return undefined;
124
+ const onward = edge.targets.filter((t) => t !== STOP);
125
+ return onward.length === 1 && workflow.stages[onward[0]!] ? onward[0] : undefined;
126
+ }
127
+
89
128
  /**
90
129
  * Resume-entry counterpart of `dispatchStageOrRecordFailure`'s catch. The live
91
130
  * chain reaches user fns (loop `next`/`done`/`feedForward`, judge prompts,
package/runner/resume.ts CHANGED
@@ -44,6 +44,7 @@ import {
44
44
  import { ERR_RESUME_LOOP_MISMATCH } from "../messages.js";
45
45
  import { failedOutput, type Output, outputMeta } from "../output.js";
46
46
  import {
47
+ type RoutingDecision,
47
48
  readAllStagesForResume,
48
49
  STATE_SCHEMA_VERSION,
49
50
  type WorkflowHeader,
@@ -89,6 +90,15 @@ export type ReconstructResult =
89
90
  trailing?: LoopResumePoint;
90
91
  /** Guard tripped mid-fold — the resume entry records this as a terminal failure. */
91
92
  drift?: { parent: string; errMsg: string };
93
+ /**
94
+ * The trail's terminal failed row is a GATE-STOP HALT: it sits
95
+ * immediately behind a routed-stop `RoutingDecision` from the same
96
+ * stage (the [stop row, `FAIL_GATE_STOP` row] pair chain-advance
97
+ * writes for a noted decision stop). The entry selector uses it to
98
+ * pick the re-measure path for a side-effect gate stage — an ordinary
99
+ * stage failure (no stop row behind it) never sets this.
100
+ */
101
+ gateStop?: RoutingDecision;
92
102
  }
93
103
  | { ok: false; reason: "no-rows" | "stage-gone" | "malformed-row" | "version-mismatch"; detail: string };
94
104
 
@@ -125,7 +135,15 @@ export async function reconstructState(
125
135
  drift: undefined,
126
136
  };
127
137
 
128
- for (const row of rows) {
138
+ for (const [i, row] of rows.entries()) {
139
+ // A routed-stop separator closes (and projects) the open generation
140
+ // BEFORE this row folds — the live driver had already projected the loop
141
+ // when its route fired, so the replayed state at a post-stop re-dispatch
142
+ // stays byte-identical to what the live resume saw (THE REPLAY
143
+ // CONTRACT). This also stops a gate-stop halt row from masquerading as a
144
+ // mid-flight abort marker below, and splits the halted generation from
145
+ // the fresh one a stop-resume re-dispatch appends for the same parent.
146
+ if (read.stopBefore.has(i)) closeGeneration(acc);
129
147
  if (isUnitRow(row)) {
130
148
  const refusal = await foldUnitRow(acc, workflow, row);
131
149
  if (refusal) return refusal;
@@ -147,6 +165,14 @@ export async function reconstructState(
147
165
 
148
166
  acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically
149
167
 
168
+ // Gate-stop halt trailer: the last row is the failed `FAIL_GATE_STOP` row
169
+ // chain-advance appended right behind its routed-stop routing row (same
170
+ // stage by construction — both are written from `currentName`; the equality
171
+ // check is the shape guard against a foreign interleaving).
172
+ const last = rows[rows.length - 1]!;
173
+ const stopAtLast = read.stopBefore.get(rows.length - 1);
174
+ const gateStop = last.status === "failed" && stopAtLast?.fromStage === last.stage ? stopAtLast : undefined;
175
+
150
176
  return {
151
177
  ok: true,
152
178
  state: acc.state,
@@ -156,6 +182,7 @@ export async function reconstructState(
156
182
  rows,
157
183
  trailing: acc.gen ? toPoint(acc.gen) : undefined,
158
184
  drift: acc.drift,
185
+ gateStop,
159
186
  };
160
187
  }
161
188
 
@@ -31,6 +31,7 @@ import { freezesEntryArgsOf } from "../loop-constructors.js";
31
31
  import { buildLoopEntry, freshCursor, type LoopDeps, type LoopEntry } from "../loop-kinds.js";
32
32
  import { ensureUnitDeps } from "../loop-waves.js";
33
33
  import {
34
+ FAIL_FANOUT_ALL_FAILED,
34
35
  FAIL_LOOP_CAP_HALT,
35
36
  FAIL_VALIDATE_GATE_SKIPPED,
36
37
  FAIL_VERIFY_FAILED,
@@ -524,6 +525,7 @@ export function buildLoopDeps(): LoopDeps {
524
525
  advanceAfter: (freshCtx, name, completedIdx, ctx) => advance(freshCtx, name, completedIdx, ctx),
525
526
  captureSnapshot: (ctx, name, def, i, r) => captureStageSnapshot(ctx, name, def, i, r),
526
527
  haltLoop,
528
+ haltLoopWhenAllFailed,
527
529
  // Mid-flight run abort at the loop seam → FAIL_WORKFLOW_ABORTED.
528
530
  recordAborted: (hostCtx, name, run) => recordAbortedAtSeam(hostCtx, name, run).then(() => undefined),
529
531
  // Unexpected worker rejection → terminal-failure row, no re-throw. The
@@ -550,6 +552,27 @@ export async function haltLoop(
550
552
  await haltChain(hostCtx, run, e.name, e.name, args);
551
553
  }
552
554
 
555
+ /**
556
+ * Terminal failure when a `haltWhenAllFailed` fanout generation closes with
557
+ * every declared slot a failed sentinel (strict all-filled-all-failed). Fired
558
+ * ONCE at the generation close — `finishLoop`'s single spelling (loop.ts),
559
+ * never per-unit. Parent-attributed, sessionless, unit-field-free — the exact
560
+ * `haltLoop` recording shape, so the resume fold's halt-marker predicate
561
+ * (`isOpenFanoutHaltMarker`) keeps the generation open and a later resume
562
+ * re-derives the halt deterministically with zero new resume code.
563
+ * `recordFatalFailure`'s first-failure-wins guard makes it safe beside
564
+ * concurrent sibling collect-all soft-halt rows.
565
+ */
566
+ export async function haltLoopWhenAllFailed(
567
+ hostCtx: WorkflowHostContext,
568
+ run: RunContext,
569
+ e: Pick<LoopEntry, "name" | "skill">,
570
+ failed: number,
571
+ total: number,
572
+ ): Promise<void> {
573
+ await haltChain(hostCtx, run, e.name, e.name, failedArgs(FAIL_FANOUT_ALL_FAILED(e.skill, failed, total)));
574
+ }
575
+
553
576
  /** Runs whose snapshot-failure warning already fired — one notify per run, not per stage/unit. */
554
577
  const snapshotWarnedRuns = new WeakSet<RunContext>();
555
578
 
package/stage-identity.ts CHANGED
@@ -33,6 +33,23 @@ export function resolvePublishName(def: StageDef, stageName: string): string {
33
33
  return def.outcome?.name ?? stageName;
34
34
  }
35
35
 
36
+ /**
37
+ * The `state.named` key a SIDE-EFFECT stage publishes its `Output` onto, or
38
+ * `undefined` for the silent majority. Acts stages publish ONLY under an
39
+ * EXPLICIT outcome name — never the record-key fallback produces stages get:
40
+ * defaulting would make every `implement`/`commit`-shaped stage suddenly
41
+ * publish a channel, widening `reads:` semantics for existing graphs. The
42
+ * `Outcome.name` doc has always promised the named slot for "any stage wired
43
+ * with this outcome"; the runtime write honoring it only for `produces` left
44
+ * an acts outcome's channel silently unwritten (a gate folding
45
+ * `state.named.remediation` read a channel that never existed). Twin of
46
+ * `resolvePublishName` — the runtime write (`applyCompletedStage`) and the
47
+ * load-time publish scan (`publishedNamesOf`) both key off this projection.
48
+ */
49
+ export function actsPublishName(def: StageDef): string | undefined {
50
+ return def.kind !== "produces" ? def.outcome?.name : undefined;
51
+ }
52
+
36
53
  /**
37
54
  * Resolve a stage's effective skill — the contract-registry key. Twin of
38
55
  * `resolvePublishName`. Single source of truth so the runtime resolution
package/state/reads.ts CHANGED
@@ -121,6 +121,14 @@ const hasValidSessionRef = (row: object): boolean => {
121
121
  const isRoutingDecision = (row: unknown): row is RoutingDecision =>
122
122
  !!row && (row as { type?: unknown }).type === "routing";
123
123
 
124
+ /**
125
+ * The routed-stop decision literal — mirrors routing-dsl's `STOP`, not
126
+ * imported so state/ stays a leaf. ONE local spelling for both consumers
127
+ * (the resume reader's separator scan and `trailingRoutingStop`), so the
128
+ * mirror can't drift within this module.
129
+ */
130
+ const ROUTED_STOP = "stop";
131
+
124
132
  /** Shape guard for loop-cap telemetry rows. */
125
133
  const isLoopCapRow = (r: unknown): r is LoopCapRow => (r as { type?: unknown } | undefined)?.type === "loop-cap";
126
134
 
@@ -151,14 +159,29 @@ export function readAllStages(cwd: string, runId: string): WorkflowStage[] {
151
159
  * replays the trail as its system of record, and silently dropping a row
152
160
  * would replay a hole ("this stage never ran") — e.g. route onward past a
153
161
  * stage whose failure row lost its `status`.
162
+ *
163
+ * `stopBefore` maps a stage-row index to the routed-stop `RoutingDecision`
164
+ * that immediately precedes it in the trail — the fold's GENERATION
165
+ * SEPARATOR. A gate-stop halt writes [routing stop, failed stage row], and a
166
+ * later resume appends fresh rows behind that pair; when the halted gate is a
167
+ * fanout parent, its old and new unit rows would otherwise sit contiguous in
168
+ * this stage-only projection and mis-fold as ONE generation. Only stops
169
+ * FOLLOWED by a stage row are recorded: a trailing stop (the noteless-stop
170
+ * completion) stays invisible here, preserving the finished-run no-op resume.
154
171
  */
155
172
  export function readAllStagesForResume(
156
173
  cwd: string,
157
174
  runId: string,
158
- ): { ok: true; rows: WorkflowStage[] } | { ok: false; detail: string } {
175
+ ): { ok: true; rows: WorkflowStage[]; stopBefore: Map<number, RoutingDecision> } | { ok: false; detail: string } {
159
176
  const rows: WorkflowStage[] = [];
177
+ const stopBefore = new Map<number, RoutingDecision>();
178
+ let pendingStop: RoutingDecision | undefined;
160
179
  for (const parsed of readParsedRows(cwd, runId)) {
161
180
  if (isWorkflowStage(parsed) && hasValidSessionRef(parsed)) {
181
+ if (pendingStop) {
182
+ stopBefore.set(rows.length, pendingStop);
183
+ pendingStop = undefined;
184
+ }
162
185
  rows.push(parsed);
163
186
  continue;
164
187
  }
@@ -166,8 +189,11 @@ export function readAllStagesForResume(
166
189
  const label = typeof parsed.stage === "string" ? ` ("${parsed.stage}")` : "";
167
190
  return { ok: false, detail: `stage row ${parsed.stageNumber}${label} failed the shape guard` };
168
191
  }
192
+ // Non-stop routing rows are pure telemetry and stay invisible to the
193
+ // fold, exactly as before.
194
+ if (isRoutingDecision(parsed) && parsed.decision === ROUTED_STOP) pendingStop = parsed;
169
195
  }
170
- return { ok: true, rows };
196
+ return { ok: true, rows, stopBefore };
171
197
  }
172
198
 
173
199
  export function readRoutingDecisions(cwd: string, runId: string): RoutingDecision[] {
@@ -243,7 +269,7 @@ function recapOutcomeOf(last: WorkflowStage): RunRecap["outcome"] {
243
269
  function trailingRoutingStop(cwd: string, runId: string): RoutingDecision | undefined {
244
270
  const rows = readParsedRows(cwd, runId);
245
271
  const last = rows[rows.length - 1];
246
- return isRoutingDecision(last) && last.decision === "stop" ? last : undefined;
272
+ return isRoutingDecision(last) && last.decision === ROUTED_STOP ? last : undefined;
247
273
  }
248
274
 
249
275
  /**
@@ -30,7 +30,7 @@ import {
30
30
  verifyShapeIssues,
31
31
  } from "../loop-constructors.js";
32
32
  import { readName } from "../stage-def.js";
33
- import { resolvePublishName } from "../stage-identity.js";
33
+ import { actsPublishName, resolvePublishName } from "../stage-identity.js";
34
34
  import {
35
35
  MAX_VALIDATION_RETRIES,
36
36
  MAX_VALIDATION_RETRY_TIMEOUT_MS,
@@ -427,6 +427,11 @@ export function publishedNamesOf(w: Workflow): Set<string> {
427
427
  const published = new Set<string>();
428
428
  for (const [name, stage] of Object.entries(w.stages)) {
429
429
  if (stage.kind === "produces") published.add(resolvePublishName(stage, name));
430
+ // Acts stages with an EXPLICITLY NAMED outcome publish too (the runtime
431
+ // write rule in `applyCompletedStage`) — the scan must match it so a
432
+ // downstream `reads: ["<acts-outcome>"]` doesn't falsely error at load.
433
+ const actsKey = actsPublishName(stage);
434
+ if (actsKey !== undefined) published.add(actsKey);
430
435
  // Every judge channel (single judge, panel members, AND the folded verdict)
431
436
  // counts for reachability — shared walk with the contract-compat index.
432
437
  forEachJudgeChannel(stage, name, (channel) => published.add(channel));