@juicesharp/rpiv-workflow 2.1.0 → 2.2.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/loop-parallel.ts CHANGED
@@ -1,30 +1,37 @@
1
1
  /**
2
- * loop-parallel.ts — bounded-parallel, dependency-ordered fanout dispatch. Fanout
3
- * units fold into the cursor in DECLARED (index) order through `foldFanoutCompletion`
4
- * — never completion order — so `fanin` synthesis + resume stay deterministic at every
5
- * concurrency (Semaphore(1) just serializes). When units declare `Unit.deps`, the
6
- * scheduler dispatches in Kahn TOPOLOGICAL LEVELS (`computeWaveLevels`, loop-waves.ts):
7
- * one bounded-parallel wave per level, a dependent never opening before the units it
8
- * depends on have filled their slots. A deps-free fanout has ONE level — byte-identical
9
- * to the pre-wave flat dispatch.
2
+ * loop-parallel.ts — bounded-parallel, dependency-GATED fanout dispatch. Every active
3
+ * unit is dispatched into ONE generation-wide semaphore and awaits ITS OWN `Unit.deps`
4
+ * — not a topological level — so a dependent opens the instant its deps have filled
5
+ * their slots, even while unrelated siblings are still running. Kahn levels
6
+ * (`computeWaveLevels`, loop-waves.ts) remain the CYCLE GUARD and supply the dispatch
7
+ * ORDER (level asc, index asc); they are no longer a barrier. A deps-free fanout is a
8
+ * flat dispatch, and a cap-1 fanout (`implement`) dispatches in exactly declared order.
10
9
  *
11
- * CONCURRENCY MODEL — what is and isn't fold-confined. ONLY the `LoopCursor`
12
- * (`slots`/`filledCount`/`lastProduce`) is mutated exclusively by the serial
13
- * post-`allSettled` fold below. `run.state` is NOT: each worker's `postStage` mutates
14
- * `lastAllocatedStageNumber`, `stagesCompleted`, `output`, `primaryArtifact`
15
- * CONCURRENTLY across siblings. That is safe — every such mutator is a synchronous,
16
- * `await`-free read-modify-write (JS run-to-completion makes each atomic), and every
17
- * order-sensitive result is re-derived by the index-addressed fold or overwritten by
18
- * `projectResult` at close.
10
+ * Deps are awaited BEFORE the semaphore is acquired — a waiting dependent never holds a
11
+ * slot, so hold-and-wait (and with it deadlock) cannot arise; the DAG is acyclic by the
12
+ * guard above.
19
13
  *
20
- * `runFanoutWaves` is the ONE orchestrator both the live entry (`runFanoutParallel`)
14
+ * CONCURRENCY MODEL — why a per-unit fold is safe. Each unit folds itself through
15
+ * `foldFanoutCompletion` in its own continuation, so the cursor is now advanced from
16
+ * many continuations rather than one serial post-`allSettled` pass. That is safe for the
17
+ * same reason `run.state` already was: every mutator is a synchronous, `await`-free
18
+ * read-modify-write (JS run-to-completion makes each atomic), AND the fold is
19
+ * COMMUTATIVE by construction — `slots[i]` is index-addressed, `filledCount` is
20
+ * recomputed by `reduce` over the whole array (never incremented), and `lastProduce` is
21
+ * derived by `lastNonFailedSlot` scanning slots high→low. Declared order therefore
22
+ * survives completion order without a barrier. The one genuinely order-sensitive write,
23
+ * `state.primaryArtifact`, is last-writer-wins during dispatch either way (each worker's
24
+ * `postStage` already races it) and is overwritten by `projectResult` at close. The
25
+ * durable trail is likewise completion-ordered already, and resume places by
26
+ * `row.unitIndex`, never by trail order.
27
+ *
28
+ * `runFanoutGeneration` is the ONE orchestrator both the live entry (`runFanoutParallel`)
21
29
  * and the resume re-dispatch (`runFanoutResume`) — both thin wrappers in loop.ts —
22
30
  * degenerate to: each passes its `active` operand set (live: `0..dispatchCount-1`;
23
31
  * resume: the still-pending indices) and a `finalTail` for the path-specific completion
24
32
  * (live: hitCap-vs-finishLoop on the cap; resume: always finishLoop). It owns ONE
25
- * per-generation `genAbort` across every wave (so a fail-fast halt or run-abort in wave
26
- * k cancels in-flight siblings AND prevents wave k+1), computes the levels, intersects
27
- * each with `active`, and runs `dispatchWave` per non-empty level.
33
+ * per-generation `genAbort` (so a fail-fast halt or run-abort cancels in-flight siblings
34
+ * AND rejects every queued acquire), computes the order, and runs the generation.
28
35
  *
29
36
  * This module is a downward leaf: it consumes the shared loop foundation
30
37
  * (`loop-kinds.ts`, `loop-waves.ts`) and never imports loop.ts back (loop.ts → here only).
@@ -58,19 +65,19 @@ const fanoutUnitRef = (e: LoopEntry, i: number): UnitRef => {
58
65
  };
59
66
 
60
67
  /**
61
- * THE wave orchestrator — owns ONE per-generation `AbortController` across every
62
- * topological level. Computes Kahn levels over the full unit list, intersects each
63
- * with `active` (live: the first-cap indices; resume: the still-pending indices), and
64
- * dispatches the non-empty levels in order. The LAST active level runs `finalTail`
65
- * (live: hitCap-vs-finishLoop; resume: finishLoop); intermediate levels just settle.
68
+ * THE generation orchestrator — owns ONE per-generation `AbortController` and ONE
69
+ * semaphore across every active unit. Computes the Kahn levels over the full unit list
70
+ * (the cycle guard) and flattens them into the dispatch ORDER, intersected with `active`
71
+ * (live: the first-cap indices; resume: the still-pending indices). Runs `finalTail`
72
+ * (live: hitCap-vs-finishLoop; resume: finishLoop) once the generation settles.
66
73
  *
67
74
  * The `genAbort` fires on EITHER (a) run-level abort (Ctrl-C, `run.signal` — propagated
68
- * below) OR (b) the first fail-fast unit halt inside `dispatchWave`. The listener is
69
- * dropped BEFORE `finalTail` (which runs the downstream chain) so it never accumulates
75
+ * below) OR (b) the first fail-fast unit halt inside `dispatchGeneration`. The listener
76
+ * is dropped BEFORE `finalTail` (which runs the downstream chain) so it never accumulates
70
77
  * across stages. Levels are computed BEFORE the listener is wired, so a defensive
71
78
  * cycle-throw from `computeWaveLevels` can't leak it.
72
79
  */
73
- export async function runFanoutWaves(
80
+ export async function runFanoutGeneration(
74
81
  curCtx: WorkflowHostContext,
75
82
  e: LoopEntry,
76
83
  cursor: LoopCursor,
@@ -80,14 +87,19 @@ export async function runFanoutWaves(
80
87
  finalTail: () => Promise<void> | void,
81
88
  ): Promise<void> {
82
89
  const activeSet = new Set(active);
83
- const waves = computeWaveLevels(e.units!, e.name)
84
- .map((level) => level.filter((i) => activeSet.has(i)))
85
- .filter((level) => level.length > 0);
86
- // Resolve the dep→artifact identity map once (only when the flag is set).
87
- const idToIndex = e.loop.kind === "fanout" && e.loop.depArtifactFlag ? unitIdIndex(e.units!) : undefined;
90
+ // Levels earn their keep twice over, and neither use is a barrier: `computeWaveLevels`
91
+ // THROWS `invariantPreflight` on a dependency cycle (the defensive guard), and its
92
+ // flattening is the dispatch order — level asc, index asc, i.e. the order the wave
93
+ // scheduler used, so a cap-1 fanout stays byte-identical.
94
+ const order = computeWaveLevels(e.units!, e.name)
95
+ .flat()
96
+ .filter((i) => activeSet.has(i));
97
+ // The dep→index map is resolved unconditionally now: dep GATING needs it whether or
98
+ // not `depArtifactFlag` is set. `depArtifactSuffix` keeps its own flag guard.
99
+ const idToIndex = unitIdIndex(e.units!);
88
100
  // No active units (e.g. a resume with everything already filled) — still close the
89
101
  // loop via the tail (projection + advance), matching today's empty/all-done path.
90
- if (waves.length === 0) return finalTail();
102
+ if (order.length === 0) return finalTail();
91
103
 
92
104
  const genAbort = new AbortController();
93
105
  // Name the handler so it can be REMOVED once this generation settles — run.signal
@@ -99,35 +111,24 @@ export async function runFanoutWaves(
99
111
  }
100
112
  const detach = () => run.signal?.removeEventListener("abort", onRunAbort);
101
113
 
102
- for (let w = 0; w < waves.length; w++) {
103
- await dispatchWave(curCtx, e, cursor, run, deps, waves[w]!, genAbort, idToIndex);
104
- // Cross-wave gates — the same two checks the single-dispatch tail made, now
105
- // BETWEEN waves so a wave-k failure prevents wave-(k+1) dispatch. A fail-fast
106
- // halt already terminated state inside the worker; a run abort drained the
107
- // semaphore and rejects every later acquire.
108
- if (run.state.termination.status !== "running") {
109
- detach();
110
- return;
111
- }
112
- if (run.signal?.aborted) {
113
- detach();
114
- return deps.recordAborted(curCtx, e.name, run); // mid-flight abort → FAIL_WORKFLOW_ABORTED
115
- }
116
- }
117
- detach(); // all waves settled cleanly — drop the run-lifetime listener BEFORE the tail
114
+ await dispatchGeneration(curCtx, e, cursor, run, deps, order, genAbort, idToIndex);
115
+ detach(); // generation settled — drop the run-lifetime listener BEFORE the tail
116
+
117
+ // The same two gates the wave loop ran between levels, now once at the end: a
118
+ // fail-fast halt already terminated state inside the worker and aborted its
119
+ // siblings; a run abort drained the semaphore and rejected every later acquire.
120
+ if (run.state.termination.status !== "running") return;
121
+ if (run.signal?.aborted) return deps.recordAborted(curCtx, e.name, run); // mid-flight abort → FAIL_WORKFLOW_ABORTED
118
122
  return finalTail();
119
123
  }
120
124
 
121
125
  /**
122
- * Dispatch ONE topological level's operands through a shared semaphore + the
123
- * per-generation `genAbort`, folding each result at its DECLARED index. The body the
124
- * former single-shot `runFanoutDispatch` ran, MINUS the genAbort lifecycle (the
125
- * orchestrator owns it across waves) and the terminal disposition (the orchestrator
126
- * runs the tail once, after the last wave). NEVER throws — an unexpected worker
127
- * rejection lands a terminal-failure row via `recordWorkerThrow`; allSettled
128
- * guarantees every unit settled.
126
+ * Dispatch the whole generation through a shared semaphore + the per-generation
127
+ * `genAbort`, each unit gated on ITS OWN deps and folding itself at its DECLARED index.
128
+ * NEVER throws — an unexpected worker rejection lands a terminal-failure row via
129
+ * `recordWorkerThrow`; allSettled guarantees every unit settled.
129
130
  */
130
- async function dispatchWave(
131
+ async function dispatchGeneration(
131
132
  curCtx: WorkflowHostContext,
132
133
  e: LoopEntry,
133
134
  cursor: LoopCursor,
@@ -135,7 +136,7 @@ async function dispatchWave(
135
136
  deps: LoopDeps,
136
137
  ops: readonly number[],
137
138
  genAbort: AbortController,
138
- idToIndex: Map<string, number> | undefined,
139
+ idToIndex: Map<string, number>,
139
140
  ): Promise<void> {
140
141
  const failFast = isFailFast(e.loop);
141
142
  // A fanout may cap its own concurrency BELOW the host cap (`implement`'s
@@ -145,35 +146,55 @@ async function dispatchWave(
145
146
  Math.max(1, Math.min(loopCap ?? curCtx.maxConcurrency, curCtx.maxConcurrency)),
146
147
  genAbort.signal,
147
148
  ); // drains queued units on either abort
148
- const settled = await Promise.allSettled(
149
- ops.map((i) => {
150
- // Resolve `--upstream`-style dep-artifact injection from the slots prior waves
151
- // already filled. Empty when the loop sets no flag or the unit has no deps.
152
- const suffix = idToIndex ? depArtifactSuffix(e, cursor, i, idToIndex) : "";
153
- return sem
154
- .run(() => dispatchUnitDetached(curCtx, e, i, run, deps, genAbort.signal, suffix))
155
- .then((out) => {
156
- // a fail-fast unit's worker terminated state via recordTerminalFailure;
157
- // fire genAbort so in-flight siblings get session.abort()'d NOW.
158
- if (failFast && run.state.termination.status !== "running") genAbort.abort();
159
- return out;
160
- });
149
+
150
+ // One readiness latch per DISPATCHED unit, index-addressed. A dep with no latch is
151
+ // already settled: either it is outside `ops` (a resume whose prior invocation filled
152
+ // the slot) or it is dangling (`computeWaveLevels` treats those as satisfied too —
153
+ // `validateUnitDeps` owns the dangling report).
154
+ const latch = new Array<Promise<void> | undefined>(e.units!.length);
155
+ const open = new Array<(() => void) | undefined>(e.units!.length);
156
+ for (const i of ops)
157
+ latch[i] = new Promise<void>((resolve) => {
158
+ open[i] = resolve;
159
+ });
160
+ const depLatches = (i: number): Promise<void>[] =>
161
+ (e.units![i]!.deps ?? []).flatMap((d) => {
162
+ const di = idToIndex.get(d);
163
+ const l = di === undefined ? undefined : latch[di];
164
+ return l ? [l] : [];
165
+ });
166
+
167
+ await Promise.allSettled(
168
+ ops.map(async (i) => {
169
+ // Await THIS unit's deps — never a whole level — and do it BEFORE acquiring a
170
+ // slot, so a waiting dependent never holds one.
171
+ await Promise.all(depLatches(i));
172
+ try {
173
+ // Resolve `--upstream`-style dep-artifact injection from the slots this
174
+ // unit's deps just filled. Empty when the loop sets no flag or no deps.
175
+ const suffix = depArtifactSuffix(e, cursor, i, idToIndex);
176
+ const out = await sem.run(() => dispatchUnitDetached(curCtx, e, i, run, deps, genAbort.signal, suffix));
177
+ // ONE synchronous block, and its order is load-bearing. (1) A fail-fast
178
+ // unit's worker terminated state via recordTerminalFailure — fire genAbort
179
+ // so in-flight siblings get session.abort()'d NOW and no dependent released
180
+ // below can still slip into the semaphore. (2) Fold BEFORE the latch opens:
181
+ // a dependent's `depArtifactSuffix` reads `cursor.slots`, so an early
182
+ // release would make it design blind for this dep.
183
+ if (failFast && run.state.termination.status !== "running") genAbort.abort();
184
+ cursor.ranThisInvocation++;
185
+ // index-addressed placement (shared with the resume fold) so declared order
186
+ // survives parallel completion + dep gating + resume.
187
+ foldFanoutCompletion(run.state, cursor, e.def, e.name, i, e.units!.length, out);
188
+ } catch (reason) {
189
+ // aborted / never-started → unfilled slot (resume re-dispatches)
190
+ if (!isAbortError(reason)) await deps.recordWorkerThrow(curCtx, fanoutUnitRef(e, i), e.skill, run, reason);
191
+ } finally {
192
+ // Dependents proceed even when this unit failed — `depArtifactSuffix` skips
193
+ // a failed/unfilled slot, so they design blind for it rather than stalling.
194
+ open[i]?.();
195
+ }
161
196
  }),
162
197
  );
163
- // `ops[k]` maps the k-th settled result back to its DECLARED unit index.
164
- for (let k = 0; k < settled.length; k++) {
165
- const r = settled[k]!;
166
- const i = ops[k]!;
167
- if (r.status === "rejected") {
168
- if (isAbortError(r.reason)) continue; // aborted / never-started → unfilled slot (resume re-dispatches)
169
- await deps.recordWorkerThrow(curCtx, fanoutUnitRef(e, i), e.skill, run, r.reason);
170
- continue;
171
- }
172
- cursor.ranThisInvocation++;
173
- // index-addressed placement (shared with the resume fold) so declared order
174
- // survives parallel completion + waves + resume.
175
- foldFanoutCompletion(run.state, cursor, e.def, e.name, i, e.units!.length, r.value);
176
- }
177
198
  }
178
199
 
179
200
  /**
package/loop.ts CHANGED
@@ -54,7 +54,7 @@ import {
54
54
  presentedKindOf,
55
55
  sequentialStrategyOf,
56
56
  } from "./loop-kinds.js";
57
- import { runFanoutWaves } from "./loop-parallel.js";
57
+ import { runFanoutGeneration } from "./loop-parallel.js";
58
58
  import { MSG_LOOP_CAP_ADVANCE, MSG_LOOP_ZERO_UNITS } from "./messages.js";
59
59
  import { appendLoopCap } from "./state/index.js";
60
60
  import type { RunContext, WorkflowHostContext } from "./types.js";
@@ -109,11 +109,11 @@ export async function runLoop(
109
109
  }
110
110
 
111
111
  /**
112
- * Live bounded-parallel fanout entry — thin wrapper over `runFanoutWaves`
113
- * (loop-parallel.ts). Dispatches the first `cap` units (`0..dispatchCount-1`) in
114
- * dependency-ordered waves; on completion picks the cap policy: over-cap units trip
115
- * `hitCap` on the last wave, otherwise the loop finishes. iterate/assess never reach
116
- * here (not parallelizable).
112
+ * Live bounded-parallel fanout entry — thin wrapper over `runFanoutGeneration`
113
+ * (loop-parallel.ts). Dispatches the first `cap` units (`0..dispatchCount-1`), each
114
+ * gated on its own deps; on completion picks the cap policy: over-cap units trip
115
+ * `hitCap`, otherwise the loop finishes. iterate/assess never reach here (not
116
+ * parallelizable).
117
117
  */
118
118
  function runFanoutParallel(
119
119
  curCtx: WorkflowHostContext,
@@ -124,7 +124,7 @@ function runFanoutParallel(
124
124
  deps: LoopDeps,
125
125
  ): Promise<void> {
126
126
  const active = Array.from({ length: Math.min(e.units!.length, cap) }, (_u, i) => i);
127
- return runFanoutWaves(curCtx, e, cursor, run, deps, active, () =>
127
+ return runFanoutGeneration(curCtx, e, cursor, run, deps, active, () =>
128
128
  e.units!.length > cap ? hitCap(curCtx, e, cursor, cap, cap, run, deps) : finishLoop(curCtx, e, cursor, run, deps),
129
129
  );
130
130
  }
@@ -136,13 +136,14 @@ export function pendingFanoutIndices(cursor: LoopCursor, total: number): number[
136
136
  return out;
137
137
  }
138
138
 
139
- /** Resume re-dispatch — thin wrapper over `runFanoutWaves`. Runs the still-pending
140
- * fanout units in dependency-ordered waves (partitioning the pending set into
141
- * topological levels), folding each at its declared index (so completed slots keep
142
- * their position), and always finishes (the live run already settled the cap policy).
143
- * A ≥3-level DAG where wave 0 completed but waves 1-2 aborted re-waves correctly:
144
- * already-filled slots are skipped (not in `pending`); the remaining pending units
145
- * dispatch level-by-level, never a level-2 unit concurrent with its level-1 dep.
139
+ /** Resume re-dispatch — thin wrapper over `runFanoutGeneration`. Runs the still-pending
140
+ * fanout units, each gated on its own deps, folding each at its declared index (so
141
+ * completed slots keep their position), and always finishes (the live run already
142
+ * settled the cap policy). A ≥3-level DAG where the roots completed but their
143
+ * dependents aborted re-dispatches correctly: already-filled slots are skipped (not in
144
+ * `pending`) and so carry no readiness latch — a pending unit whose dep is outside
145
+ * `pending` treats it as satisfied and reads its filled slot, while a pending unit
146
+ * whose dep is ALSO pending still waits for it.
146
147
  * Pending fanout units COLD re-dispatch (a fresh child each) — fanout units are
147
148
  * idempotent (each writes its own distinct artifact at its declared index), so a
148
149
  * partial in-flight session is discarded rather than reattached; this matches
@@ -157,7 +158,7 @@ export function runFanoutResume(
157
158
  deps: LoopDeps,
158
159
  pending: readonly number[],
159
160
  ): Promise<void> {
160
- return runFanoutWaves(curCtx, e, cursor, run, deps, pending, () => finishLoop(curCtx, e, cursor, run, deps));
161
+ return runFanoutGeneration(curCtx, e, cursor, run, deps, pending, () => finishLoop(curCtx, e, cursor, run, deps));
161
162
  }
162
163
 
163
164
  // ---------------------------------------------------------------------------
package/messages.ts CHANGED
@@ -56,6 +56,32 @@ export const FAIL_VALIDATION_EXHAUSTED = (skill: string, failures: string): Fail
56
56
  error: `${skill} output validation failed after retries: ${failures}`,
57
57
  });
58
58
 
59
+ /**
60
+ * Validation-retry mechanism-1 — the agent was asked to fix the artifact but changed nothing
61
+ * observable in the worktree, so the `produce(attempt)` re-read + re-validate
62
+ * cycle would just re-run the same failing validation. Routed as the extraction
63
+ * retry loop's `Fatal.message` (the `{ kind: "aborted"; abort: { kind: "fatal" } }`
64
+ * arm of `onRetry` in `packages/rpiv-workflow/sessions/extraction.ts`), so the
65
+ * stage halts through the existing extraction-fatal path. Lands in
66
+ * `state.termination.error` + the JSONL row's `errMsg` via `haltStageOrSoftHalt`.
67
+ */
68
+ export const ERR_VALIDATE_RETRY_UNCHANGED = (skill: string) =>
69
+ `${skill}: validation retry halted — the working tree was unchanged after the fix prompt (no observable edit detected to tracked files or .rpiv/artifacts/); refusing to re-run the same failing validation`;
70
+
71
+ /**
72
+ * Validation-retry mechanism-2 — a schema-validated `produces` stage was re-dispatched against
73
+ * a worktree unchanged since its last validation failure at the same progress
74
+ * point (`stagesCompleted` unchanged). A `FailureText` consumed by `failedArgs`
75
+ * (the sessionless `recordTerminalFailure` descriptor, mirroring
76
+ * `checkBackwardJumpGuard` in `packages/rpiv-workflow/runner/chain-advance.ts`).
77
+ * The terminal skip carries the failure memo for free through the shared
78
+ * `recordTerminalFailure` writer hooks at `packages/rpiv-workflow/audit.ts:134`.
79
+ */
80
+ export const FAIL_VALIDATE_GATE_SKIPPED = (skill: string): FailureText => ({
81
+ toast: `✗ ${skill} re-dispatched with no observable change since its last validation failure — stopping workflow`,
82
+ error: `${skill} re-dispatched with an unchanged worktree since its last schema-validation failure (no observable fix detected); halting to avoid a no-op retry loop`,
83
+ });
84
+
59
85
  export const FAIL_INPUT_VALIDATION = (currentSkill: string, prevSkill: string, failures: string): FailureText => ({
60
86
  toast: `✗ ${currentSkill} input validation failed — upstream ${prevSkill} produced invalid data`,
61
87
  error: `Input validation failed for '${currentSkill}': upstream '${prevSkill}' produced invalid data: ${failures}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "2.1.0",
3
+ "version": "2.2.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",
@@ -46,7 +46,9 @@
46
46
  "chain-state.ts",
47
47
  "command.ts",
48
48
  "command-run.ts",
49
+ "death-scene.ts",
49
50
  "execution-host.ts",
51
+ "failure-memos.ts",
50
52
  "loop-constructors.ts",
51
53
  "loops/",
52
54
  "extension.ts",
@@ -86,6 +88,7 @@
86
88
  "validation-bounds.ts",
87
89
  "validate-workflow.ts",
88
90
  "validate/",
91
+ "worktree-digest.ts",
89
92
  "docs-protocol.ts",
90
93
  "docs/",
91
94
  "!docs/*.png",
@@ -108,7 +111,7 @@
108
111
  ]
109
112
  },
110
113
  "dependencies": {
111
- "@juicesharp/rpiv-config": "^2.1.0",
114
+ "@juicesharp/rpiv-config": "^2.2.0",
112
115
  "jiti": "^2.7.0",
113
116
  "typebox": "^1.1.24"
114
117
  },
package/registration.ts CHANGED
@@ -219,6 +219,11 @@ export {
219
219
  type WorkflowHeader,
220
220
  type WorkflowStage,
221
221
  } from "./state/index.js";
222
+ // The persisted-session branch shape the host-injected `readSessionBranch`
223
+ // reader returns (`WorkflowExecutionProvider.readSessionBranch` /
224
+ // `RunContext.readSessionBranch`). Re-exported so the rpiv-pi host can name the
225
+ // return type when it narrows `SessionManager.open(file).getBranch()`.
226
+ export type { BranchEntry } from "./transcript.js";
222
227
  export { DEFAULT_TRIGGER, type RunTrigger } from "./triggers.js";
223
228
  export { typeboxSchema } from "./typebox-adapter.js";
224
229
  // `RunState` is deliberately NOT here — it is runner-private; user contexts
package/routing.ts CHANGED
@@ -57,46 +57,6 @@ export function edgeIsDecision(workflow: Workflow, current: string): boolean {
57
57
  return typeof workflow.edges[current] === "function";
58
58
  }
59
59
 
60
- /**
61
- * The not-taken targets of a DECISION edge that are pure RECOVERY arms — a
62
- * stage whose own out-edge is a STRING edge pointing at an already-visited
63
- * stage, i.e. taking it would loop BACK into covered territory rather than make
64
- * forward progress.
65
- *
66
- * Used by the progress bridge (`rpiv-pi` lane-progress): when a gate takes its
67
- * pass arm, the failure arm (build's `slice-fix` / `plan-fix` / `code-fix`) is bypassed for good
68
- * on this path, so it counts toward "distinct nodes covered" — the bar reaches
69
- * full WHILE the terminal stage runs instead of freezing one-below until the
70
- * `onWorkflowEnd` snap. Surfaced as the `onRoute` lifecycle event's `bypassed`
71
- * argument.
72
- *
73
- * Deliberately narrow: a not-taken target is credited ONLY when its successor
74
- * is a string edge to an already-visited stage. A FORWARD arm (its successor
75
- * not yet visited) is merely deferred, not bypassed — crediting it would push
76
- * the numerator AHEAD of the stages actually reached. An arm with a gate/
77
- * terminal out-edge is left uncredited (conservative; never over-counts).
78
- *
79
- * Returns distinct names; `chosen`, `STOP`, and already-visited arms are
80
- * excluded, so the credited set never inflates the numerator past the reachable
81
- * total.
82
- */
83
- export function bypassedRecoveryArms(
84
- workflow: Workflow,
85
- from: string,
86
- chosen: string,
87
- visited: ReadonlySet<string>,
88
- ): string[] {
89
- const edge = workflow.edges[from];
90
- if (typeof edge !== "function" || !Array.isArray(edge.targets)) return [];
91
- const out: string[] = [];
92
- for (const t of edge.targets) {
93
- if (t === chosen || t === STOP || visited.has(t)) continue;
94
- const succ = workflow.edges[t]; // one-hop loop-back test
95
- if (typeof succ === "string" && visited.has(succ)) out.push(t);
96
- }
97
- return out;
98
- }
99
-
100
60
  // ---------------------------------------------------------------------------
101
61
  // Internals
102
62
  // ---------------------------------------------------------------------------
@@ -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 { bypassedRecoveryArms, edgeIsDecision, nextStage } from "../routing.js";
20
+ import { 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,14 +58,8 @@ 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
-
67
61
  if (result.kind === "stop") {
68
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run), bypassed);
62
+ await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
69
63
  return finalizeWorkflow(curCtx, run);
70
64
  }
71
65
 
@@ -79,7 +73,7 @@ export async function advanceChain(
79
73
  // Fire onRoute after the routing decision has been audited (when applicable),
80
74
  // before the next stage runs. Deterministic auto-edges still fire so
81
75
  // listeners see every transition.
82
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run), bypassed);
76
+ await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run));
83
77
 
84
78
  // deps.runNext owns the catch for throws out of the *next* stage, so the
85
79
  // JSONL row records `nextName` (the stage that actually threw) rather than
@@ -10,6 +10,7 @@ import type { Workflow } from "../api.js";
10
10
  import { LifecycleDispatcher, type LifecycleListeners } from "../events.js";
11
11
  import type { ModelSelection, WorkflowHost } from "../host.js";
12
12
  import { getSkillContracts } from "../skill-contracts/index.js";
13
+ import type { BranchEntry } from "../transcript.js";
13
14
  import type { RunTrigger } from "../triggers.js";
14
15
  import type { RunContext, RunState } from "../types.js";
15
16
 
@@ -24,10 +25,10 @@ import type { RunContext, RunState } from "../types.js";
24
25
  * body) are NOT counted, and each destination stage owns its own budget
25
26
  * (`RunContext.revisits`), so the retry allowance is invariant to how many
26
27
  * decision edges the cycle crosses per iteration and unrelated loops never
27
- * share a pool. With 2: any given stage runs once unconditionally and may be
28
- * re-entered up to 2 more times — at most 3 executions per stage.
28
+ * share a pool. With 3: any given stage runs once unconditionally and may be
29
+ * re-entered up to 3 more times — at most 4 executions per stage.
29
30
  */
30
- export const MAX_BACKWARD_JUMPS = 2;
31
+ export const MAX_BACKWARD_JUMPS = 3;
31
32
 
32
33
  /**
33
34
  * Run-wide safety cap on loop units — the backstop for any loop kind whose
@@ -58,6 +59,11 @@ export function freshRunState(originalInput: string): RunState {
58
59
  stagesCompleted: 0,
59
60
  lastAllocatedStageNumber: 0,
60
61
  telemetry: { backwardJumps: 0, droppedRoutingRows: [], droppedFailureRows: [] },
62
+ failureMemos: [],
63
+ // Validation-retry gate memory — fresh on every entry point (operator
64
+ // resume starts with NO prior baseline ⇒ first qualifying dispatch
65
+ // proceeds, mirroring the fresh-strike-budget policy).
66
+ lastGatedDispatch: undefined,
61
67
  termination: { status: "running" },
62
68
  };
63
69
  }
@@ -84,6 +90,8 @@ export function buildRunContext(
84
90
  lifecycle?: LifecycleListeners;
85
91
  signal?: AbortSignal;
86
92
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
93
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
94
+ worktreeDigest?: (cwd: string) => string | undefined;
87
95
  },
88
96
  identity: { runId: string; state: RunState; visited: Set<string>; trigger: RunTrigger },
89
97
  ): RunContext {
@@ -108,6 +116,8 @@ export function buildRunContext(
108
116
  lifecycle: new LifecycleDispatcher(options.lifecycle),
109
117
  signal: options.signal,
110
118
  resolveModel: options.resolveModel,
119
+ readSessionBranch: options.readSessionBranch,
120
+ worktreeDigest: options.worktreeDigest,
111
121
  };
112
122
  }
113
123