@juicesharp/rpiv-workflow 2.9.0 → 2.10.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.
@@ -11,7 +11,7 @@
11
11
  * spelled as a module cycle.
12
12
  */
13
13
 
14
- import { type EdgeTarget, takeRouteNote } from "../api.js";
14
+ import { type EdgeTarget, PROGRESS_VALUES, type ProgressValue, type StageDef, takeRouteNote } from "../api.js";
15
15
  import { auditCtxFor, failedArgs, recordFatalFailure } from "../audit.js";
16
16
  import { resolveSkill } from "../chain-state.js";
17
17
  import { lifecycleCtxFor, skillStageRef } from "../events.js";
@@ -19,12 +19,13 @@ import { nowIso } from "../internal-utils.js";
19
19
  import {
20
20
  FAIL_BACKWARD_JUMP_EXHAUSTED,
21
21
  FAIL_GATE_STOP,
22
+ type FailureText,
22
23
  MSG_CHAIN_ADVANCE_FAILED,
23
24
  MSG_ROUTING_AUDIT_DROPPED,
24
25
  } from "../messages.js";
25
26
  import { edgeIsDecision, nextStage } from "../routing.js";
26
27
  import { appendRoutingDecision } from "../state/index.js";
27
- import type { RunContext, WorkflowHostContext } from "../types.js";
28
+ import type { RunContext, RunState, WorkflowHostContext } from "../types.js";
28
29
  import { type ChainOutcome, finalizeWorkflow, haltChain } from "./failure.js";
29
30
 
30
31
  /**
@@ -39,8 +40,8 @@ export interface ChainDeps {
39
40
 
40
41
  /**
41
42
  * Decomposed into three helpers — `auditRoutingDecision`,
42
- * `ensureBackwardJumpGuard`, `haltOnRoutingError` — each owning one
43
- * structural concern.
43
+ * `evaluateBackwardJumpGuard` (+ `invokeProgressHook`), `haltOnRoutingError`
44
+ * — each owning one structural concern.
44
45
  */
45
46
  export async function advanceChain(
46
47
  hostCtx: WorkflowHostContext,
@@ -76,9 +77,23 @@ export async function advanceChain(
76
77
 
77
78
  const nextName = result.stage;
78
79
  if (wasDecision) {
79
- auditRoutingDecision(hostCtx, run, idx, currentName, nextName);
80
- const guard = await ensureBackwardJumpGuard(hostCtx, run, nextName);
81
- if (guard !== "continue") return guard;
80
+ // Read-and-clear the edge's ROUTE_NOTE BEFORE the guard's await and the
81
+ // audit write: `takeRouteNote` reads once, and the guard's note (verdict
82
+ // + budget arithmetic) composes onto the SAME routing row this pick
83
+ // produces. First-visit rows carry the edge note alone (no guard note);
84
+ // re-entry rows carry `[edgeNote, guardNote].join("; ")`.
85
+ const edge = run.workflow.edges[currentName];
86
+ const edgeNote = typeof edge === "function" ? takeRouteNote(edge) : undefined;
87
+ const guard = await evaluateBackwardJumpGuard(run, nextName);
88
+ const note = guard.kind === "re-entry" ? [edgeNote, guard.note].filter(Boolean).join("; ") : edgeNote;
89
+ auditRoutingDecision(hostCtx, run, idx, currentName, nextName, note);
90
+ if (guard.kind === "re-entry" && guard.halt) {
91
+ // Trip order: routing row (with the composed note) FIRST, then
92
+ // exactly one failure row; `onRoute` fires after neither — the
93
+ // chain halts here.
94
+ await recordFatalFailure(hostCtx, auditCtxFor(run, nextName, nextName), failedArgs(guard.halt));
95
+ return "halted";
96
+ }
82
97
  }
83
98
 
84
99
  // Fire onRoute after the routing decision has been audited (when applicable),
@@ -136,9 +151,58 @@ function auditRoutingDecision(
136
151
  }
137
152
 
138
153
  /**
139
- * Per-DESTINATION cap on decision-edge retries. Returns `"continue"` when the
140
- * run may proceed, or the `"halted"` outcome when the cap tripped (and the
141
- * terminal failure has been recorded).
154
+ * Pure decision output of the backward-jump guard for one decision-edge
155
+ * pick. `first-visit` — the destination has not run yet; nothing else
156
+ * happens (no hook, no ledgers, no note). `re-entry` — the destination was
157
+ * visited: `note` (verdict + budget arithmetic) rides the routing row, and
158
+ * `halt` carries the deferred `FailureText` when the cap tripped —
159
+ * enforcement (the routing row, the failure row) stays in `advanceChain`,
160
+ * so an additional absolute bound can ride the same deferred-`halt` seam
161
+ * without touching the caller.
162
+ */
163
+ export type GuardEvaluation = { kind: "first-visit" } | { kind: "re-entry"; note: string; halt?: FailureText };
164
+
165
+ /**
166
+ * Ring depth for `RunContext.progressTrail` — the halt text carries at most
167
+ * this many most-recent verdicts per destination (oldest dropped beyond).
168
+ */
169
+ const PROGRESS_TRAIL_DEPTH = 3;
170
+
171
+ /**
172
+ * Invoke the re-entered stage's optional `progress` hook — the waiver vote.
173
+ * Fail-soft by design (the hook is an observation, never a halt surface):
174
+ * absent hook ⇒ `undefined` (no trail entry, no waiver — every re-entry
175
+ * counts); a throw ⇒ `"unknown"`; an off-union return (a jiti-loaded
176
+ * literal erased the `ProgressValue` union) ⇒ `"unknown"` via the one
177
+ * `PROGRESS_VALUES` membership check.
178
+ */
179
+ async function invokeProgressHook(stage: StageDef | undefined, state: RunState): Promise<ProgressValue | undefined> {
180
+ const hook = stage?.progress;
181
+ if (!hook) return undefined;
182
+ try {
183
+ const verdict = await hook(state);
184
+ return (PROGRESS_VALUES as readonly string[]).includes(verdict) ? verdict : "unknown";
185
+ } catch {
186
+ return "unknown";
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Per-DESTINATION re-entry arbitration for decision edges — the pure
192
+ * decision half (the audit + failure-row effects live in `advanceChain`'s
193
+ * decision arm). Returns `{ kind: "first-visit" }` or
194
+ * `{ kind: "re-entry", note, halt? }`: `note` is the guard note composed
195
+ * into the routing row (verdict + both budgets' arithmetic); `halt` carries
196
+ * the deferred `FailureText` when a limit tripped. Two ledgers, two
197
+ * taxonomies: `run.laps` is the ABSOLUTE per-destination count (every
198
+ * re-entry counts, whatever the `progress` verdict — the `maxLaps + 1`-th
199
+ * re-entry halts on the ceiling, verdict-proof); `run.revisits` is the
200
+ * WAIVE-AWARE count (an "improved" verdict waives the re-entry — no
201
+ * increment, only non-waived re-entries spend the `maxBackwardJumps`
202
+ * cap). So `revisits ≤ laps` always, and both limits trip on the same
203
+ * re-entry only when `maxBackwardJumps ≥ maxLaps`. Arbitration is
204
+ * CEILING-FIRST: the lap compare runs before the improved-waive, so the
205
+ * absolute bound can never be outlived by a verdict.
142
206
  *
143
207
  * A "backward jump" is a *decision-edge* resolving to an already-visited
144
208
  * stage — i.e. a deliberate retry choice. Deterministic forward edges that
@@ -159,28 +223,78 @@ function auditRoutingDecision(
159
223
  * what the old reset-on-escape rule existed to approximate.
160
224
  *
161
225
  * `state.telemetry.backwardJumps` stays the run-wide cumulative total of
162
- * counted backward jumps (post-hoc telemetry only — never consulted for the
163
- * halt decision, never reset).
226
+ * decision-edge re-entries — waived or counted (post-hoc telemetry only —
227
+ * never consulted for the halt decision, never reset). The per-destination
228
+ * verdict ring (`run.progressTrail`) records every hook invocation (absent
229
+ * hook ⇒ no entry) and rides the halt text.
164
230
  *
165
231
  * Trip attribution targets `nextName` (the stage the guard refused to
166
232
  * re-enter), not the just-completed stage.
167
233
  */
168
- async function ensureBackwardJumpGuard(
169
- hostCtx: WorkflowHostContext,
170
- run: RunContext,
171
- nextName: string,
172
- ): Promise<"continue" | ChainOutcome> {
173
- if (!run.visited.has(nextName)) return "continue";
234
+ export async function evaluateBackwardJumpGuard(run: RunContext, nextName: string): Promise<GuardEvaluation> {
235
+ if (!run.visited.has(nextName)) return { kind: "first-visit" };
236
+
237
+ const verdict = await invokeProgressHook(run.workflow.stages[nextName], run.state);
238
+ run.state.telemetry.backwardJumps++;
239
+ // Absolute lap ledger — every re-entry counts here, whatever the verdict.
240
+ const laps = (run.laps.get(nextName) ?? 0) + 1;
241
+ run.laps.set(nextName, laps);
242
+ if (verdict !== undefined) {
243
+ const ring = run.progressTrail.get(nextName) ?? [];
244
+ ring.push(verdict);
245
+ if (ring.length > PROGRESS_TRAIL_DEPTH) ring.splice(0, ring.length - PROGRESS_TRAIL_DEPTH);
246
+ run.progressTrail.set(nextName, ring);
247
+ }
248
+ // Guard-note vocabulary: `jump: counted (<verdict>) n/m, lap l/L` /
249
+ // `jump: waived (improved), n/m, lap l/L` — the verdict parenthetical is
250
+ // omitted when no hook is declared, and the waived form renders the
251
+ // verdict itself, never its panel-side derivation (the guard knows the
252
+ // four-value verdict, nothing more).
253
+ const verdictSegment = verdict === undefined ? "" : ` (${verdict})`;
254
+
255
+ // Ceiling-first arbitration: the lap ceiling is verdict-proof (waived
256
+ // re-entries count), so it is compared BEFORE the improved-waive — an
257
+ // all-"improved" trail still halts on the maxLaps+1-th re-entry.
258
+ if (laps > run.maxLaps) {
259
+ return {
260
+ kind: "re-entry",
261
+ note: `jump: counted${verdictSegment} lap ${laps}/${run.maxLaps}, over the absolute lap ceiling`,
262
+ halt: FAIL_BACKWARD_JUMP_EXHAUSTED({
263
+ stage: nextName,
264
+ limitKind: "ceiling",
265
+ count: laps,
266
+ max: run.maxLaps,
267
+ progress: run.progressTrail.get(nextName) ?? [],
268
+ }),
269
+ };
270
+ }
271
+
272
+ if (verdict === "improved") {
273
+ // Waived: the cap budget is untouched; every other aspect of the
274
+ // re-entry (routing row, onRoute, re-dispatch) is byte-identical to a
275
+ // counted re-entry under budget. The lap ledger above still counted it.
276
+ const count = run.revisits.get(nextName) ?? 0;
277
+ return {
278
+ kind: "re-entry",
279
+ note: `jump: waived (improved), ${count}/${run.maxBackwardJumps}, lap ${laps}/${run.maxLaps}`,
280
+ };
281
+ }
282
+
174
283
  const revisits = (run.revisits.get(nextName) ?? 0) + 1;
175
284
  run.revisits.set(nextName, revisits);
176
- run.state.telemetry.backwardJumps++;
177
- if (revisits <= run.maxBackwardJumps) return "continue";
178
- await recordFatalFailure(
179
- hostCtx,
180
- auditCtxFor(run, nextName, nextName),
181
- failedArgs(FAIL_BACKWARD_JUMP_EXHAUSTED(nextName, revisits, run.maxBackwardJumps)),
182
- );
183
- return "halted";
285
+ const note = `jump: counted${verdictSegment} ${revisits}/${run.maxBackwardJumps}, lap ${laps}/${run.maxLaps}`;
286
+ if (revisits <= run.maxBackwardJumps) return { kind: "re-entry", note };
287
+ return {
288
+ kind: "re-entry",
289
+ note,
290
+ halt: FAIL_BACKWARD_JUMP_EXHAUSTED({
291
+ stage: nextName,
292
+ limitKind: "cap",
293
+ count: revisits,
294
+ max: run.maxBackwardJumps,
295
+ progress: run.progressTrail.get(nextName) ?? [],
296
+ }),
297
+ };
184
298
  }
185
299
 
186
300
  /**
package/runner/index.ts CHANGED
@@ -8,5 +8,11 @@ export type { RunWorkflowOptions, RunWorkflowResult } from "../types.js";
8
8
  export { type RunWorkflowByNameOptions, runWorkflowByName } from "./by-name.js";
9
9
  export { type ResumeWorkflowByRunIdOptions, resumeWorkflowByRunId } from "./by-run-id.js";
10
10
  export { StagePreflightError } from "./errors.js";
11
- export { MAX_BACKWARD_JUMPS } from "./run-context.js";
11
+ export {
12
+ MAX_BACKWARD_JUMPS,
13
+ MAX_ITERATIONS,
14
+ MAX_LAPS,
15
+ type RunBudgetOptions,
16
+ validateRunBudgets,
17
+ } from "./run-context.js";
12
18
  export { type ResumeWorkflowOptions, resumeWorkflow, runWorkflow } from "./runner.js";
package/runner/resume.ts CHANGED
@@ -27,6 +27,7 @@
27
27
  import type { LoopDef, StageDef, Unit, Workflow } from "../api.js";
28
28
  import { applyStageSuccess, rollLastSession } from "../audit-rows.js";
29
29
  import { stageEntryArgs } from "../chain-state.js";
30
+ import { pushFailureMemo } from "../failure-memos.js";
30
31
  import type { Artifact } from "../handle.js";
31
32
  import { formatError } from "../internal-utils.js";
32
33
  import { panelMembers } from "../judge.js";
@@ -133,9 +134,12 @@ export async function reconstructState(
133
134
  prevNode: undefined,
134
135
  gen: undefined,
135
136
  drift: undefined,
137
+ rowIndex: -1,
138
+ recordedGens: scanClosedFanoutGenerations(rows),
136
139
  };
137
140
 
138
141
  for (const [i, row] of rows.entries()) {
142
+ acc.rowIndex = i;
139
143
  // A routed-stop separator closes (and projects) the open generation
140
144
  // BEFORE this row folds — the live driver had already projected the loop
141
145
  // when its route fired, so the replayed state at a post-stop re-dispatch
@@ -228,6 +232,17 @@ interface FoldAcc {
228
232
  prevNode: { stage: string; reentrant: boolean } | undefined;
229
233
  gen: OpenGeneration | undefined;
230
234
  drift: { parent: string; errMsg: string } | undefined;
235
+ /** Index of the row being folded — `openGeneration` keys `recordedGens` by it. */
236
+ rowIndex: number;
237
+ /**
238
+ * Fanout generations the trail already CLOSED with every unit done, keyed by
239
+ * the index of their first unit row: the recorded unit tags in `unitIndex`
240
+ * order. A closed, fully-done generation dispatches nothing on resume, so its
241
+ * recorded rows are the authority over a unit source that reads state the
242
+ * run has since moved past (a basename-keyed snapshot overwritten by a later
243
+ * round). Only the trailing open generation still needs the live recompute.
244
+ */
245
+ recordedGens: Map<number, readonly string[]>;
231
246
  }
232
247
 
233
248
  // --- Fold predicates — single canonical spellings of the row-kind tests ---
@@ -277,6 +292,7 @@ function rebuildCollectedSentinel(row: WorkflowStage, runId: string): Output {
277
292
  runId,
278
293
  }),
279
294
  row.errMsg!, // defined: the single caller gates on isCollectedSoftHalt(row)
295
+ row.unitLabel, // the live sentinel's dimension — recordUnitHalt persisted it
280
296
  );
281
297
  }
282
298
 
@@ -323,6 +339,52 @@ function closeGeneration(acc: FoldAcc): void {
323
339
  * re-derived post-fold, where the generation's own appends have moved the
324
340
  * `.at(-1)` cursors.
325
341
  */
342
+ /**
343
+ * Pre-scan: every maximal run of consecutive unit rows sharing a `parent` that
344
+ * is followed by a non-unit row (closed) and whose rows are all completed or
345
+ * collected soft-halts (done). Keyed by the first row's index; value = unit
346
+ * tags in `unitIndex` order. A generation still at the trail's tail, or one
347
+ * with a pending / hard-failed slot, or one followed by its parent's own
348
+ * halt/abort marker, is NOT listed — resume must re-dispatch into it, so the
349
+ * live unit source stays authoritative there.
350
+ */
351
+ function scanClosedFanoutGenerations(rows: readonly WorkflowStage[]): Map<number, readonly string[]> {
352
+ const out = new Map<number, readonly string[]>();
353
+ let start = -1;
354
+ let parent: string | undefined;
355
+ let tags: (string | undefined)[] = [];
356
+ let allDone = true;
357
+ const flush = (closed: boolean): void => {
358
+ if (start >= 0 && closed && allDone && tags.length > 0 && tags.every((t) => t !== undefined)) {
359
+ out.set(start, tags as string[]);
360
+ }
361
+ start = -1;
362
+ parent = undefined;
363
+ tags = [];
364
+ allDone = true;
365
+ };
366
+ for (const [i, row] of rows.entries()) {
367
+ const unit = isUnitRow(row);
368
+ if (unit && row.parent === parent) {
369
+ if (row.unitIndex !== undefined) tags[row.unitIndex] = row.unitId;
370
+ allDone &&= isCompletedRow(row) || isCollectedSoftHalt(row);
371
+ continue;
372
+ }
373
+ // A non-unit row closes the generation UNLESS it is the parent's own
374
+ // halt/abort marker (same stage, not completed): that row means the
375
+ // generation stopped mid-flight and its unfilled slots must re-dispatch.
376
+ flush(!(row.stage === parent && !isCompletedRow(row)));
377
+ if (unit) {
378
+ start = i;
379
+ parent = row.parent;
380
+ if (row.unitIndex !== undefined) tags[row.unitIndex] = row.unitId;
381
+ allDone = isCompletedRow(row) || isCollectedSoftHalt(row);
382
+ }
383
+ }
384
+ flush(false); // a generation at the trail's tail is never closed
385
+ return out;
386
+ }
387
+
326
388
  async function openGeneration(
327
389
  acc: FoldAcc,
328
390
  workflow: Workflow,
@@ -350,13 +412,21 @@ async function openGeneration(
350
412
  units: undefined,
351
413
  };
352
414
  if (loop.kind === "fanout") {
353
- acc.gen.units = await guarded(acc, acc.gen.parent, () =>
354
- (loop as Extract<LoopDef, { kind: "fanout" }>).units({
355
- cwd: acc.cwd,
356
- artifact: acc.state.primaryArtifact,
357
- state: acc.state,
358
- }),
359
- );
415
+ const recorded = acc.recordedGens.get(acc.rowIndex);
416
+ if (recorded) {
417
+ // Closed and fully done on the trail: nothing to dispatch, so the
418
+ // recorded tags ARE the generation. Skips the live recompute, whose
419
+ // inputs may no longer match this round's.
420
+ acc.gen.units = recorded.map((tag) => ({ prompt: "", label: tag, id: tag }));
421
+ } else {
422
+ acc.gen.units = await guarded(acc, acc.gen.parent, () =>
423
+ (loop as Extract<LoopDef, { kind: "fanout" }>).units({
424
+ cwd: acc.cwd,
425
+ artifact: acc.state.primaryArtifact,
426
+ state: acc.state,
427
+ }),
428
+ );
429
+ }
360
430
  }
361
431
  return undefined;
362
432
  }
@@ -378,6 +448,16 @@ async function openGeneration(
378
448
  * an aborted in-flight unit, which wrote NO row at all — leaves the slot
379
449
  * unfilled so resume re-dispatches that unit. Resets `gen.expected` (consumed)
380
450
  * on every fanout row.
451
+ *
452
+ * RETRY TRAILS: a unit dispatched under `retryHaltedUnits` writes ONE
453
+ * collected row per FAILED attempt (plus its completed row when the final
454
+ * attempt succeeds) — all at the same `unitIndex`, each stamped with its
455
+ * 1-based `attemptOrdinal` (the v3 trail contract). Under-budget rows are
456
+ * SKIPPED, not overwritten: the budget predicate below leaves their slot
457
+ * unfilled, so the unit re-dispatches while budget remains. Only the FINAL
458
+ * attempt's collected row (ordinal beyond budget, or absent — pre-ordinal
459
+ * trails / non-retrying loops) folds its sentinel, converging with the live
460
+ * path, which folds only the unit's final captured output.
381
461
  */
382
462
  function foldFanoutRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): void {
383
463
  const units = gen.units!; // dispatcher gates this arm on gen.loop.kind === "fanout" && gen.units
@@ -385,8 +465,21 @@ function foldFanoutRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): v
385
465
  applyStageSuccess(acc.state, gen.def, row.stage, row.output);
386
466
  foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, units.length, row.output);
387
467
  } else if (isCollectedSoftHalt(row)) {
388
- const sentinel = rebuildCollectedSentinel(row, acc.runId);
389
- foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, units.length, sentinel);
468
+ // Budget-aware fold (the v3 trail contract): a collected row written by
469
+ // an attempt whose ordinal still has `retryHaltedUnits` budget remaining
470
+ // leaves its slot UNFILLED — `pendingFanoutIndices` re-dispatches it
471
+ // exactly like a pending unit. No isFailFast mirror needed: under
472
+ // failFast the live driver never writes a collected row (collect-all is
473
+ // fanout-non-failFast only — `shouldCollectAll`), so this arm cannot see
474
+ // a fail-fast trail.
475
+ // Every collected halt re-enters the memo ledger (live: recordUnitHalt), so
476
+ // later prompts — the re-dispatch's included — carry it as the live run's do.
477
+ pushFailureMemo(acc.state, { stage: gen.parent, unitId: row.unitId }, row.errMsg ?? "");
478
+ const budget = gen.loop.kind === "fanout" ? (gen.loop.retryHaltedUnits ?? 0) : 0;
479
+ if (!(row.attemptOrdinal !== undefined && row.attemptOrdinal <= budget)) {
480
+ const sentinel = rebuildCollectedSentinel(row, acc.runId);
481
+ foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, units.length, sentinel);
482
+ }
390
483
  }
391
484
  gen.expected = undefined; // consumed
392
485
  }
@@ -9,6 +9,7 @@
9
9
  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
+ import { MSG_BUDGET_INVALID } from "../messages.js";
12
13
  import { getSkillContracts } from "../skill-contracts/index.js";
13
14
  import type { BranchEntry } from "../transcript.js";
14
15
  import type { RunTrigger } from "../triggers.js";
@@ -30,6 +31,17 @@ import type { RunContext, RunState } from "../types.js";
30
31
  */
31
32
  export const MAX_BACKWARD_JUMPS = 3;
32
33
 
34
+ /**
35
+ * Per-DESTINATION absolute ceiling on decision-edge re-entries — the
36
+ * verdict-proof backstop ABOVE the waive-aware `MAX_BACKWARD_JUMPS` cap.
37
+ * Every re-entry counts toward it, whatever the stage `progress` hook
38
+ * votes: a destination whose laps keep reporting "improved" waives the
39
+ * cap but never this ceiling, so the `maxLaps + 1`-th re-entry of one
40
+ * stage always halts. Fresh per invocation like the cap — a resume
41
+ * re-opens a closed loop with both budgets restored.
42
+ */
43
+ export const MAX_LAPS = 8;
44
+
33
45
  /**
34
46
  * Run-wide safety cap on loop units — the backstop for any loop kind whose
35
47
  * source never terminates (a pull generator that never returns `null`, an
@@ -40,6 +52,38 @@ export const MAX_BACKWARD_JUMPS = 3;
40
52
  */
41
53
  export const MAX_ITERATIONS = 32;
42
54
 
55
+ /**
56
+ * The run budgets an embedder may override — the single key list behind
57
+ * `RunBudgetOptions`, the validator, and `buildRunContext`'s options type, so
58
+ * a fourth budget is a one-row addition here plus its default below.
59
+ */
60
+ const BUDGET_KEYS = ["maxBackwardJumps", "maxLaps", "maxIterations"] as const;
61
+
62
+ /** The run budgets an embedder may override — each a non-negative integer or absent. */
63
+ export type RunBudgetOptions = { [K in (typeof BUDGET_KEYS)[number]]?: number };
64
+
65
+ /**
66
+ * Validate the budget options an embedder may thread in. `??` passes `NaN`
67
+ * straight through to the ledgers, where `laps > NaN` is always false — the
68
+ * ceiling documented as "always halts" would fail OPEN (an always-"improved"
69
+ * hook never spends the cap either, so nothing terminates the loop) while
70
+ * `revisits <= NaN` fails CLOSED on the first counted re-entry. Non-integers
71
+ * and negatives are refused for the same reason: the compares are integer
72
+ * arithmetic. The CLI regexes gate `\d+`, so only the programmatic options
73
+ * path can reach this. Returns the first offending option's message, or
74
+ * `undefined` when every supplied budget is well-formed; `runWorkflow` and
75
+ * `resumeWorkflow` refuse pre-flight on it (before any row is written) and
76
+ * `buildRunContext` throws on it as the backstop.
77
+ */
78
+ export function validateRunBudgets(options: RunBudgetOptions): string | undefined {
79
+ for (const key of BUDGET_KEYS) {
80
+ const value = options[key];
81
+ if (value === undefined) continue;
82
+ if (!Number.isInteger(value) || value < 0) return MSG_BUDGET_INVALID(key, value);
83
+ }
84
+ return undefined;
85
+ }
86
+
43
87
  // ---------------------------------------------------------------------------
44
88
  // State + context construction
45
89
  // ---------------------------------------------------------------------------
@@ -83,10 +127,8 @@ export function freshRunState(originalInput: string): RunState {
83
127
  export function buildRunContext(
84
128
  cwd: string,
85
129
  workflow: Workflow,
86
- options: {
130
+ options: RunBudgetOptions & {
87
131
  host?: WorkflowHost;
88
- maxBackwardJumps?: number;
89
- maxIterations?: number;
90
132
  lifecycle?: LifecycleListeners;
91
133
  signal?: AbortSignal;
92
134
  resolveModel?: (id: { workflow: string; stage: string; skill: string }) => ModelSelection | undefined;
@@ -95,6 +137,10 @@ export function buildRunContext(
95
137
  },
96
138
  identity: { runId: string; state: RunState; visited: Set<string>; trigger: RunTrigger },
97
139
  ): RunContext {
140
+ // Backstop for any constructor path that skipped the pre-flight check —
141
+ // a malformed budget must never reach the ledgers.
142
+ const budgetError = validateRunBudgets(options);
143
+ if (budgetError !== undefined) throw new Error(budgetError);
98
144
  return {
99
145
  cwd,
100
146
  runId: identity.runId,
@@ -105,12 +151,20 @@ export function buildRunContext(
105
151
  // Fresh on every entry point: a resume grants each stage a fresh
106
152
  // re-entry budget, exactly as the pre-ledger streak counter did.
107
153
  revisits: new Map(),
154
+ // Fresh beside `revisits`: the progress-verdict ring is engine memory
155
+ // (never persisted), so both entry points — run and resume — start it
156
+ // empty.
157
+ progressTrail: new Map(),
158
+ // Absolute lap ledger — the ceiling's counter, same fresh-per-
159
+ // invocation rule as `revisits` (a resume re-opens the loop).
160
+ laps: new Map(),
108
161
  registeredSkills: options.host ? snapshotRegisteredSkills(options.host) : undefined,
109
162
  // Defensive COPY (not the live global Map) so a later registerSkillContracts
110
163
  // call cannot mutate this run's snapshot mid-run — parity with the fresh-Set
111
164
  // copy snapshotRegisteredSkills makes.
112
165
  skillContracts: new Map(getSkillContracts()),
113
166
  maxBackwardJumps: options.maxBackwardJumps ?? MAX_BACKWARD_JUMPS,
167
+ maxLaps: options.maxLaps ?? MAX_LAPS,
114
168
  maxIterations: options.maxIterations ?? MAX_ITERATIONS,
115
169
  trigger: identity.trigger,
116
170
  lifecycle: new LifecycleDispatcher(options.lifecycle),
package/runner/runner.ts CHANGED
@@ -48,7 +48,7 @@ import { DEFAULT_TRIGGER } from "../triggers.js";
48
48
  import type { RunContext, RunWorkflowOptions, RunWorkflowResult } from "../types.js";
49
49
  import { reconstructState } from "./resume.js";
50
50
  import { resumeRefusalError, selectResumeEntry } from "./resume-entry.js";
51
- import { buildRunContext, freshRunState } from "./run-context.js";
51
+ import { buildRunContext, freshRunState, validateRunBudgets } from "./run-context.js";
52
52
  import { dispatchStageOrRecordFailure } from "./run-stage.js";
53
53
 
54
54
  // ---------------------------------------------------------------------------
@@ -216,6 +216,12 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
216
216
  };
217
217
  }
218
218
 
219
+ // A malformed budget (`NaN`, a negative, a fraction) would make a ledger
220
+ // compare fail open — refused here, before the name claim and the header,
221
+ // so nothing is written for a run that could never halt.
222
+ const budgetError = validateRunBudgets(options);
223
+ if (budgetError !== undefined) return { stagesCompleted: 0, success: false, error: budgetError };
224
+
219
225
  const cwd = ctx.cwd;
220
226
  const runId = generateRunId();
221
227
  const trigger = options.trigger ?? DEFAULT_TRIGGER;
@@ -284,6 +290,14 @@ export interface ResumeWorkflowOptions {
284
290
  host?: WorkflowHost;
285
291
  /** Per-destination decision-edge re-entry cap. Defaults to MAX_BACKWARD_JUMPS. */
286
292
  maxBackwardJumps?: number;
293
+ /**
294
+ * Per-destination ABSOLUTE ceiling on decision-edge re-entries — counts
295
+ * every re-entry (improved-waived laps included), unlike the waive-aware
296
+ * `maxBackwardJumps` cap. The `maxLaps + 1`-th re-entry of one stage
297
+ * halts. Defaults to MAX_LAPS; fresh per invocation (a resume starts
298
+ * both re-entry ledgers empty).
299
+ */
300
+ maxLaps?: number;
287
301
  /** Run-wide safety cap on loop units (all kinds). Defaults to MAX_ITERATIONS. */
288
302
  maxIterations?: number;
289
303
  /** The user's `@<ref>` — surfaced in trigger.meta + refusal messages. */
@@ -318,6 +332,12 @@ export async function resumeWorkflow(
318
332
  const { workflow, header } = options;
319
333
  const cwd = ctx.cwd;
320
334
 
335
+ // Same pre-flight refusal as `runWorkflow` — a resume threads the same
336
+ // budget options and appends to the same trail, so a malformed budget is
337
+ // refused before any row lands.
338
+ const budgetError = validateRunBudgets(options);
339
+ if (budgetError !== undefined) return { stagesCompleted: 0, success: false, error: budgetError };
340
+
321
341
  const recon = await reconstructState(cwd, workflow, header);
322
342
  if (!recon.ok) {
323
343
  // Pure envelope — no self-notify, mirroring `runWorkflow`'s pre-flight
@@ -138,6 +138,7 @@ function buildCollectCtx(
138
138
  branchOffset,
139
139
  snapshot: s.snapshot,
140
140
  skill: s.skill,
141
+ ...(s.unit?.label !== undefined ? { unitLabel: s.unit.label } : {}),
141
142
  };
142
143
  }
143
144
 
@@ -184,7 +184,7 @@ async function softHaltUnit(
184
184
  reason,
185
185
  lifecycleCtxFromSession(s),
186
186
  );
187
- await s.onSuccess(ctx, failedOutput(outputMetaFor(s), reason));
187
+ await s.onSuccess(ctx, failedOutput(outputMetaFor(s), reason, s.unit?.label));
188
188
  }
189
189
 
190
190
  /** OutputMeta for a sentinel — same stage number the failed row carries, so the
@@ -236,4 +236,8 @@ const auditFor = (s: StageSessionContext, session: SessionRef | null): AuditCont
236
236
  // Loop units thread their identity onto failure/cancellation rows so failed
237
237
  // trailers carry the structured fields the resume drift guard consumes.
238
238
  ...(s.unit ? { unit: s.unit } : {}),
239
+ // The failed attempt's 1-based ordinal (fanout units only) — projected onto
240
+ // the collected halt row for the resume fold's budget predicate. Omitted
241
+ // when absent (sequential units, single stages).
242
+ ...(s.attemptOrdinal !== undefined ? { attemptOrdinal: s.attemptOrdinal } : {}),
239
243
  });