@juicesharp/rpiv-workflow 2.9.0 → 2.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/audit-ctx.ts CHANGED
@@ -50,6 +50,13 @@ export type AuditContext = Pick<
50
50
  session: SessionRef | null;
51
51
  isScript?: boolean;
52
52
  unit?: UnitRef;
53
+ /**
54
+ * The failed attempt's 1-based dispatch ordinal — present only for fanout
55
+ * unit sessions (threaded by `dispatchUnitDetached` through
56
+ * `buildUnitSession`); `auditFor` projects it onto the collected halt row
57
+ * (`recordUnitHalt`) for the resume fold's budget predicate.
58
+ */
59
+ attemptOrdinal?: number;
53
60
  };
54
61
 
55
62
  /**
package/audit.ts CHANGED
@@ -194,6 +194,14 @@ export function recordUnitHalt(ctx: WorkflowHostContext, audit: AuditContext, er
194
194
  errMsg,
195
195
  session: audit.session,
196
196
  ...unitRowFields(audit.unit),
197
+ // The failed unit's label — additive, collected rows only. The resume
198
+ // fold threads it into the rebuilt sentinel's dimension so the live and
199
+ // replayed sentinels stay byte-identical (rebuildCollectedSentinel).
200
+ ...(audit.unit ? { unitLabel: audit.unit.label } : {}),
201
+ // The failed attempt's 1-based ordinal — the resume fold's budget input:
202
+ // an under-budget collected row leaves its slot unfilled so resume
203
+ // re-dispatches the unit while `retryHaltedUnits` budget remains.
204
+ ...(audit.attemptOrdinal !== undefined ? { attemptOrdinal: audit.attemptOrdinal } : {}),
197
205
  });
198
206
  recordFailureForensics(ctx, audit, errMsg);
199
207
  }
package/command-run.ts CHANGED
@@ -11,7 +11,9 @@ import { formatError } from "./internal-utils.js";
11
11
  import { renderConfigLayer } from "./layers.js";
12
12
  import { findWorkflow, type Issue, loadWorkflows } from "./load/index.js";
13
13
  import {
14
+ MSG_FLAG_REPEATED,
14
15
  MSG_INTERACTIVE_ONLY,
16
+ MSG_JUMP_CAP_ABOVE_LAP_CEILING,
15
17
  MSG_LOAD_ABORTED,
16
18
  MSG_NAME_FLAG_MID_INPUT,
17
19
  MSG_NAME_IGNORED_ON_RESUME,
@@ -23,6 +25,11 @@ import {
23
25
  } from "./messages.js";
24
26
  import { formatWorkflowDetails, formatWorkflowList } from "./preview.js";
25
27
  import { resumeWorkflowByRunId, runWorkflow } from "./runner/index.js";
28
+ // The warning thresholds come from the constants module DIRECTLY, not the
29
+ // runner barrel: the handler suites mock the barrel wholesale (the float
30
+ // boundary), and a barrel import would let those suites pin a stale 3/8 pair
31
+ // while the real defaults drifted.
32
+ import { MAX_BACKWARD_JUMPS, MAX_LAPS } from "./runner/run-context.js";
26
33
  import { flushSkillContractProviders } from "./skill-contracts/index.js";
27
34
  import { isValidName } from "./state/index.js";
28
35
 
@@ -63,29 +70,52 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
63
70
  if (parsed.nameFlagIgnored) {
64
71
  ctx.ui.notify(MSG_NAME_FLAG_MID_INPUT, "warning");
65
72
  }
73
+ for (const flag of parsed.duplicateFlags ?? []) {
74
+ // A doubled --name on @resume: the winner is about to be dropped anyway
75
+ // (MSG_NAME_IGNORED_ON_RESUME below), so "the first value wins" would be
76
+ // a false promise stacked on the ignore toast — one warning, not two.
77
+ if (parsed.kind === "resume" && flag === "--name") continue;
78
+ ctx.ui.notify(MSG_FLAG_REPEATED(flag), "warning");
79
+ }
80
+ // The ceiling is arbitrated before the cap and counts every re-entry
81
+ // (`revisits ≤ laps`), so a cap at or above the ceiling can never trip —
82
+ // `--max-jumps 20` alone silently delivers MAX_LAPS re-entries. Warn on
83
+ // the EFFECTIVE pair (a flag absent ⇒ its default) before either arm runs;
84
+ // the run still proceeds, bounded by the ceiling.
85
+ const effectiveCap = parsed.maxBackwardJumps ?? MAX_BACKWARD_JUMPS;
86
+ const effectiveCeiling = parsed.maxLaps ?? MAX_LAPS;
87
+ if (effectiveCap >= effectiveCeiling) {
88
+ ctx.ui.notify(MSG_JUMP_CAP_ABOVE_LAP_CEILING(effectiveCap, effectiveCeiling), "warning");
89
+ }
66
90
 
67
91
  if (parsed.kind === "resume") {
68
92
  if (parsed.droppedName !== undefined) {
69
93
  ctx.ui.notify(MSG_NAME_IGNORED_ON_RESUME, "warning");
70
94
  }
71
- await handleResume(host, ctx, parsed.ref);
95
+ await handleResume(host, ctx, parsed.ref, parsed.maxBackwardJumps, parsed.maxLaps);
72
96
  return;
73
97
  }
74
98
 
75
- const { workflow: workflowName, input, name } = parsed;
76
-
77
- if (name !== undefined && !isValidName(name)) {
78
- ctx.ui.notify(MSG_NAME_INVALID(name), "error");
99
+ // Name validity is checked on run AND preview (a preview with a malformed
100
+ // --name still refuses, as it always did) — never on resume, where the
101
+ // name is dropped with its own warning above.
102
+ if (parsed.name !== undefined && !isValidName(parsed.name)) {
103
+ ctx.ui.notify(MSG_NAME_INVALID(parsed.name), "error");
79
104
  return;
80
105
  }
81
106
 
82
- if (!input) {
83
- const trimmed = args.trim();
84
- const previewing = trimmed.length > 0 && workflowNames.has(trimmed);
85
- ctx.ui.notify(previewing ? formatWorkflowDetails(loaded, trimmed) : formatWorkflowList(loaded), "info");
107
+ if (parsed.kind === "preview") {
108
+ // The parser decided list-vs-details on the flag-stripped residual;
109
+ // re-testing the raw line here would miss `/wf --max-jumps 6 review`.
110
+ ctx.ui.notify(
111
+ parsed.workflow !== undefined ? formatWorkflowDetails(loaded, parsed.workflow) : formatWorkflowList(loaded),
112
+ "info",
113
+ );
86
114
  return;
87
115
  }
88
116
 
117
+ const { workflow: workflowName, input, name } = parsed;
118
+
89
119
  // Block execution on load errors — running a partially-loaded workflow set
90
120
  // would silently mask the user's intent (e.g. their preferred workflow
91
121
  // failed to import).
@@ -115,22 +145,27 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
115
145
  // detached and appears as a lane. runWorkflow returns an envelope (never throws on
116
146
  // run failure), but a thrown predicate/invariant could still bubble — .catch keeps
117
147
  // Pi's dispatcher from printing a raw stack AND a floated promise from going
118
- // unhandled (NFR).
148
+ // unhandled (NFR). Both tails settle on the ctx captured HERE, possibly long
149
+ // after pi replaced the launcher session — notify via notifyOrDropIfStale so a
150
+ // stale ctx drops the toast instead of throwing out of the tail (which would
151
+ // be an unhandled rejection → uncaughtException → pi exits).
119
152
  void runWorkflow(ctx, {
120
153
  workflow,
121
154
  input,
122
155
  host,
123
156
  trigger: { kind: "command", name: "wf" },
124
157
  name,
158
+ maxBackwardJumps: parsed.maxBackwardJumps,
159
+ maxLaps: parsed.maxLaps,
125
160
  })
126
161
  .then((result) => {
127
162
  // Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
128
163
  if (!result.success && result.runId === undefined && result.error) {
129
- ctx.ui.notify(result.error, "error");
164
+ notifyOrDropIfStale(ctx, result.error, "error");
130
165
  }
131
166
  })
132
167
  .catch((e) => {
133
- ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
168
+ notifyOrDropIfStale(ctx, MSG_WORKFLOW_THREW(formatError(e)), "error");
134
169
  });
135
170
  }
136
171
 
@@ -138,13 +173,20 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
138
173
  // Resume handler
139
174
  // ---------------------------------------------------------------------------
140
175
 
141
- async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: string): Promise<void> {
176
+ async function handleResume(
177
+ host: WorkflowHost,
178
+ ctx: WorkflowHostContext,
179
+ ref: string,
180
+ maxBackwardJumps?: number,
181
+ maxLaps?: number,
182
+ ): Promise<void> {
142
183
  if (!ref) {
143
184
  ctx.ui.notify(MSG_RESUME_USAGE, "error");
144
185
  return;
145
186
  }
146
- // Float the resume off the prompt — identical shape to the run path.
147
- void resumeWorkflowByRunId(ctx, ref, { host })
187
+ // Float the resume off the prompt — identical shape to the run path,
188
+ // including the stale-safe settle tails.
189
+ void resumeWorkflowByRunId(ctx, ref, { host, maxBackwardJumps, maxLaps })
148
190
  .then((result) => {
149
191
  // A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
150
192
  // load error, workflow gone, or an unreconstructable trail) — nothing else
@@ -152,11 +194,11 @@ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: s
152
194
  // already notified by the stage machinery via its JSONL failure row;
153
195
  // re-notifying would double up.
154
196
  if (!result.success && result.runId === undefined && result.error) {
155
- ctx.ui.notify(result.error, "error");
197
+ notifyOrDropIfStale(ctx, result.error, "error");
156
198
  }
157
199
  })
158
200
  .catch((e) => {
159
- ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
201
+ notifyOrDropIfStale(ctx, MSG_WORKFLOW_THREW(formatError(e)), "error");
160
202
  });
161
203
  }
162
204
 
@@ -164,6 +206,31 @@ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: s
164
206
  // Private helpers
165
207
  // ---------------------------------------------------------------------------
166
208
 
209
+ /**
210
+ * Notify on the /wf command ctx captured at float time, swallowing ONLY the
211
+ * stale-ctx error pi-core throws once the launcher session has been replaced
212
+ * or disposed (/new, resume, fork, /reload, quit, auto-compaction — any of
213
+ * which can happen while a detached run is in flight). The toast is
214
+ * best-effort — the lane dock + JSONL trail already carry the outcome — but a
215
+ * throw from a settle tail escapes the .catch and kills pi as an
216
+ * uncaughtException. Any other error is a real bug and must propagate.
217
+ */
218
+ function notifyOrDropIfStale(ctx: WorkflowHostContext, message: string, level: "warning" | "error"): void {
219
+ try {
220
+ ctx.ui.notify(message, level);
221
+ } catch (e) {
222
+ if (!isStaleCtxError(e)) throw e;
223
+ }
224
+ }
225
+
226
+ // pi-core's ExtensionRunner throws this exact phrase from an invalidated ctx
227
+ // after session replacement/reload. Match the stable substring — the
228
+ // per-package twin of the rpiv-core/rpiv-btw/rpiv-todo copies (siblings never
229
+ // import each other at runtime).
230
+ function isStaleCtxError(e: unknown): boolean {
231
+ return /stale after session replacement/.test(String(e));
232
+ }
233
+
167
234
  /** Surface every load + validation issue as a notify, prefixed by severity. */
168
235
  function surfaceIssues(ctx: WorkflowHostContext, issues: readonly Issue[]): void {
169
236
  for (const issue of issues) {
package/command.ts CHANGED
@@ -114,24 +114,113 @@ export function registerWorkflowCommand(host: WorkflowHost): void {
114
114
  // ---------------------------------------------------------------------------
115
115
 
116
116
  const LEADING_NAME_FLAG = /^--name\s+(\S+)\s*/;
117
+ /** `--max-jumps <n>` — per-run override of the backward-jump cap; leading or trailing only, like `--name`. */
118
+ const LEADING_JUMPS_FLAG = /^--max-jumps\s+(\d+)\s*/;
119
+ const TRAILING_JUMPS_FLAG = /\s+--max-jumps\s+(\d+)$/;
120
+ /** `--max-laps <n>` — per-run override of the absolute lap ceiling; leading or trailing only, like `--name`. */
121
+ const LEADING_LAPS_FLAG = /^--max-laps\s+(\d+)\s*/;
122
+ const TRAILING_LAPS_FLAG = /\s+--max-laps\s+(\d+)$/;
117
123
  const TRAILING_NAME_FLAG = /\s+--name\s+(\S+)$/;
118
124
  /** Any surviving `--name` token after the leading/trailing extraction — input text, flagged. */
119
125
  const MID_NAME_FLAG = /(?:^|\s)--name(?:\s|$)/;
120
126
 
127
+ /**
128
+ * The extractable leading/trailing flags with their reader. One row per
129
+ * flag; the fixpoint in `parseArgs` walks this table so a new flag is a
130
+ * one-row addition, not another copy of the extraction sequence.
131
+ *
132
+ * Anchor invariant (the first-typed ranking depends on it): every `leading`
133
+ * form is `^`-anchored so its match sits at the residual's head, and every
134
+ * `trailing` form is `\s+`-prefixed and `$`-anchored so `match.index` is the
135
+ * offset of the whitespace before the token. `parseArgs` turns those into
136
+ * typed offsets; a row anchored any other way would rank wrong. Pinned by
137
+ * `command.test.ts`, which also derives its permutation grammar from this
138
+ * table. Exported for tests only.
139
+ */
140
+ export const FLAG_EXTRACTORS = [
141
+ { key: "name", token: "--name", leading: LEADING_NAME_FLAG, trailing: TRAILING_NAME_FLAG },
142
+ { key: "maxBackwardJumps", token: "--max-jumps", leading: LEADING_JUMPS_FLAG, trailing: TRAILING_JUMPS_FLAG },
143
+ { key: "maxLaps", token: "--max-laps", leading: LEADING_LAPS_FLAG, trailing: TRAILING_LAPS_FLAG },
144
+ ] as const;
145
+
146
+ type FlagKey = (typeof FLAG_EXTRACTORS)[number]["key"];
147
+
148
+ /** Record one extracted flag's raw token under its key. */
149
+ function assignFlag(
150
+ flags: { name?: string; maxBackwardJumps?: number; maxLaps?: number },
151
+ key: FlagKey,
152
+ raw: string,
153
+ ): void {
154
+ if (key === "name") flags.name = raw;
155
+ else if (key === "maxBackwardJumps") flags.maxBackwardJumps = Number(raw);
156
+ else flags.maxLaps = Number(raw);
157
+ }
158
+
159
+ /** Flag tokens that appeared more than once (first-typed wins, the rest were stripped) — in `--name`, `--max-jumps`, `--max-laps` order. */
160
+ type DuplicateFlags = { duplicateFlags?: readonly string[] };
161
+
121
162
  export type ParsedCommand =
122
- | { kind: "run"; workflow: string; input: string; name?: string; nameFlagIgnored?: boolean }
123
- | { kind: "resume"; ref: string; droppedName?: string; nameFlagIgnored?: boolean };
163
+ | ({
164
+ /**
165
+ * Nothing to run: the residual after flag extraction was empty (list
166
+ * every workflow) or exactly one registered workflow name (`workflow`
167
+ * — show its details). Decided HERE, on the flag-stripped residual,
168
+ * so `/wf --max-jumps 6 review` previews `review` — the command layer
169
+ * never re-reads the raw line.
170
+ */
171
+ kind: "preview";
172
+ workflow?: string;
173
+ name?: string;
174
+ nameFlagIgnored?: boolean;
175
+ maxBackwardJumps?: number;
176
+ maxLaps?: number;
177
+ } & DuplicateFlags)
178
+ | ({
179
+ kind: "run";
180
+ workflow: string;
181
+ input: string;
182
+ name?: string;
183
+ nameFlagIgnored?: boolean;
184
+ maxBackwardJumps?: number;
185
+ maxLaps?: number;
186
+ } & DuplicateFlags)
187
+ | ({
188
+ kind: "resume";
189
+ ref: string;
190
+ droppedName?: string;
191
+ nameFlagIgnored?: boolean;
192
+ maxBackwardJumps?: number;
193
+ maxLaps?: number;
194
+ } & DuplicateFlags);
124
195
 
125
196
  /**
126
197
  * First token is a workflow name iff recognised; otherwise the whole arg is
127
198
  * input bound to the resolved default. When no default is registered (the
128
199
  * empty-registry case), the returned `workflow` is `""` and the orchestrator
129
- * surfaces `MSG_NO_WORKFLOWS_REGISTERED`.
200
+ * surfaces `MSG_NO_WORKFLOWS_REGISTERED`. An empty residual, or a residual
201
+ * that is exactly a workflow name, is a `preview` (list / details) — a `run`
202
+ * always carries non-empty input.
130
203
  *
131
204
  * `--name <slug>` is honored ONLY in leading or trailing position (leading
132
- * wins when both are present). A `--name` anywhere else is the user's own
133
- * prompt text (`/wf fix the --name handling bug`) — it stays in the input
134
- * untouched and `nameFlagIgnored` is set so the command layer can warn.
205
+ * wins when both are present). A `--name` that is neither — one that still
206
+ * sits mid-input once every leading/trailing flag has been peeled — is the
207
+ * user's own prompt text (`/wf fix the --name handling bug`): it stays in
208
+ * the input untouched and `nameFlagIgnored` is set so the command layer can
209
+ * warn. (A tail run like `go --name a --name b` is NOT mid-input: both peel
210
+ * as trailing, the second as a duplicate.)
211
+ * The two caps flags — `--max-jumps <n>` and `--max-laps <n>` — follow the
212
+ * same rule (leading or trailing only, any relative order among the three);
213
+ * a mid-position caps token stays in the input untouched and, unlike
214
+ * `--name`, sets no flag.
215
+ *
216
+ * A flag repeated in a leading/trailing slot (`--max-jumps 6 --max-jumps 9
217
+ * research …`) is consumed, not stranded: the FIRST-TYPED value wins in
218
+ * every slot (each occurrence is ranked by its offset in the line, not by
219
+ * extraction order), every other occurrence is stripped, and the token
220
+ * lands in `duplicateFlags` so the command layer can warn.
221
+ * Leaving the repeat in the residual would make `--max-jumps` the first
222
+ * token — not a workflow name — and bind the whole line (the user's
223
+ * intended workflow included) as prompt text for the DEFAULT workflow.
135
224
  *
136
225
  * `@<ref>` on the first token is the resume sigil — the first whitespace-
137
226
  * delimited token after `@` is the run reference. Leading space after the
@@ -142,31 +231,88 @@ export function parseArgs(
142
231
  loaded: { workflowNames: ReadonlySet<string>; default: string | undefined },
143
232
  ): ParsedCommand {
144
233
  let trimmed = args.trim();
145
- let name: string | undefined;
146
-
147
- // Extract --name <slug> from the leading or trailing token position only.
148
- const leading = LEADING_NAME_FLAG.exec(trimmed);
149
- if (leading) {
150
- name = leading[1];
151
- trimmed = trimmed.slice(leading[0].length);
152
- } else {
153
- const trailing = TRAILING_NAME_FLAG.exec(trimmed);
154
- if (trailing) {
155
- name = trailing[1];
156
- trimmed = trimmed.slice(0, trailing.index);
234
+ const flags: { name?: string; maxBackwardJumps?: number; maxLaps?: number } = {};
235
+
236
+ // Fixpoint flag extraction: each pass walks every flag and tries its
237
+ // LEADING form first, then its TRAILING form, against the current
238
+ // residual; a pass that extracts nothing ends the loop (every extraction
239
+ // shortens the residual, so it terminates). A fixed extraction SEQUENCE
240
+ // (jumps, then name) silently swallows a flag in same-slot permutations —
241
+ // `--max-laps 8 --max-jumps 6 --name x` would strand `--max-jumps 6` as
242
+ // input text; the fixpoint peels the leading/trailing positions in any
243
+ // relative order. A flag that matches AGAIN after it was already
244
+ // extracted is stripped and recorded as a duplicate — skipping it would
245
+ // leave the repeat as the residual's first token and hijack workflow
246
+ // resolution. The FIRST-TYPED value wins: extraction order is NOT typed
247
+ // order (a trailing run peels from the end; a head flag can mask a
248
+ // leading match for a whole pass), so every occurrence carries its offset
249
+ // in the trimmed line and the smallest offset wins — no slot heuristic.
250
+ // A mid-position token matches neither form and stays as input text
251
+ // (silent for both caps flags; `--name` additionally warns via
252
+ // MID_NAME_FLAG below).
253
+ const extracted = new Map<FlagKey, number>(); // key → typed offset of the kept occurrence
254
+ const repeated = new Set<FlagKey>();
255
+ let consumedHead = 0; // chars sliced off the front of `trimmed` so far — restores typed offsets
256
+ for (;;) {
257
+ let extractedThisPass = false;
258
+ for (const flag of FLAG_EXTRACTORS) {
259
+ let raw: string;
260
+ let offset: number;
261
+ const lead = flag.leading.exec(trimmed);
262
+ if (lead !== null) {
263
+ raw = lead[1]!;
264
+ offset = consumedHead;
265
+ trimmed = trimmed.slice(lead[0].length);
266
+ consumedHead += lead[0].length;
267
+ } else {
268
+ const trail = flag.trailing.exec(trimmed);
269
+ if (trail === null) continue;
270
+ raw = trail[1]!;
271
+ offset = consumedHead + trail.index;
272
+ trimmed = trimmed.slice(0, trail.index);
273
+ }
274
+ const prior = extracted.get(flag.key);
275
+ if (prior === undefined || offset < prior) {
276
+ assignFlag(flags, flag.key, raw);
277
+ extracted.set(flag.key, offset);
278
+ }
279
+ if (prior !== undefined) repeated.add(flag.key);
280
+ extractedThisPass = true;
157
281
  }
282
+ if (!extractedThisPass) break;
158
283
  }
284
+ // Reported in FLAG_EXTRACTORS order (not extraction order, which varies
285
+ // with the line's shape) so the command layer's warnings are stable.
286
+ const duplicates = FLAG_EXTRACTORS.filter((f) => repeated.has(f.key)).map((f) => f.token);
287
+ const name = flags.name;
288
+ // Conditional spread — an absent flag must stay an ABSENT key, not a
289
+ // present-undefined one: ONE key-presence convention for every optional
290
+ // field, pinned with `toStrictEqual` (a lenient `toEqual` equates the two
291
+ // shapes and would mask a regression either way).
292
+ const caps = {
293
+ ...(flags.maxBackwardJumps !== undefined ? { maxBackwardJumps: flags.maxBackwardJumps } : {}),
294
+ ...(flags.maxLaps !== undefined ? { maxLaps: flags.maxLaps } : {}),
295
+ ...(duplicates.length > 0 ? { duplicateFlags: duplicates } : {}),
296
+ };
297
+ const named = name !== undefined ? { name } : {};
298
+
159
299
  const nameFlagIgnored = MID_NAME_FLAG.test(trimmed);
160
300
  const ignored = nameFlagIgnored ? { nameFlagIgnored: true as const } : {};
161
301
 
162
302
  if (trimmed.startsWith("@")) {
163
303
  // @resume — name has no meaning here; carry it as `droppedName` so the
164
304
  // command layer can warn instead of silently dropping it.
165
- return { kind: "resume", ref: trimmed.slice(1).trim().split(/\s+/)[0] ?? "", droppedName: name, ...ignored };
305
+ return {
306
+ kind: "resume",
307
+ ref: trimmed.slice(1).trim().split(/\s+/)[0] ?? "",
308
+ ...(name !== undefined ? { droppedName: name } : {}),
309
+ ...ignored,
310
+ ...caps,
311
+ };
166
312
  }
167
313
 
168
314
  if (!trimmed) {
169
- return { kind: "run", workflow: loaded.default ?? "", input: "", name, ...ignored };
315
+ return { kind: "preview", ...named, ...ignored, ...caps };
170
316
  }
171
317
 
172
318
  const firstSpace = trimmed.indexOf(" ");
@@ -174,8 +320,11 @@ export function parseArgs(
174
320
 
175
321
  if (loaded.workflowNames.has(firstToken)) {
176
322
  const remaining = firstSpace === -1 ? "" : trimmed.slice(firstSpace + 1).trim();
177
- return { kind: "run", workflow: firstToken, input: remaining, name, ...ignored };
323
+ if (!remaining) {
324
+ return { kind: "preview", workflow: firstToken, ...named, ...ignored, ...caps };
325
+ }
326
+ return { kind: "run", workflow: firstToken, input: remaining, ...named, ...ignored, ...caps };
178
327
  }
179
328
 
180
- return { kind: "run", workflow: loaded.default ?? "", input: trimmed, name, ...ignored };
329
+ return { kind: "run", workflow: loaded.default ?? "", input: trimmed, ...named, ...ignored, ...caps };
181
330
  }
package/docs/embedding.md CHANGED
@@ -23,10 +23,10 @@ package boundary.
23
23
 
24
24
  | Entry | Contents | When to import it |
25
25
  | --- | --- | --- |
26
- | `@juicesharp/rpiv-workflow` | Everything in `/registration` plus the runner (`runWorkflow`, `runWorkflowByName`, `resumeWorkflow`, `resumeWorkflowByRunId`) | Embedders that execute runs |
26
+ | `@juicesharp/rpiv-workflow` | Everything in `/registration` plus the runner (`runWorkflow`, `runWorkflowByName`, `resumeWorkflow`, `resumeWorkflowByRunId`), the budget defaults (`MAX_BACKWARD_JUMPS`, `MAX_LAPS`, `MAX_ITERATIONS`), `validateRunBudgets` and its `RunBudgetOptions` type | Embedders that execute runs |
27
27
  | `@juicesharp/rpiv-workflow/registration` | The runner-free surface: DSL, loader, outcomes, handles, validators, host port types. The single canonical enumeration of the public API | Authoring, loading, validating — skips the ~530 ms engine graph |
28
28
  | `@juicesharp/rpiv-workflow/startup` | Only the registrars a sibling wires at extension load (~9 ms) | Extension `default` exports |
29
- | `@juicesharp/rpiv-workflow/runner` | The runner surface on its own, plus `StagePreflightError` and `MAX_BACKWARD_JUMPS` | Callers that already hold the DSL elsewhere |
29
+ | `@juicesharp/rpiv-workflow/runner` | The runner surface on its own, plus `StagePreflightError`, the budget defaults (`MAX_BACKWARD_JUMPS`, `MAX_LAPS`, `MAX_ITERATIONS`), `validateRunBudgets` and its `RunBudgetOptions` type | Callers that already hold the DSL elsewhere |
30
30
  | `@juicesharp/rpiv-workflow/internal` | Test-only seams (`recordStage`, registry resets) | Tests |
31
31
 
32
32
  The Pi extension `default` entry is `./extension.ts`, not the barrel — loading
@@ -151,6 +151,7 @@ const result = await runWorkflow(ctx, { // ctx: WorkflowHostContext
151
151
  | `host` | `WorkflowHost` | none; used for the skill-registration preflight snapshot |
152
152
  | `maxIterations` | `number` | `32` — run-wide cap on loop units of every kind |
153
153
  | `maxBackwardJumps` | `number` | `3` per destination stage |
154
+ | `maxLaps` | `number` | `8` per destination stage — absolute ceiling on decision-edge re-entries; improved-waived laps count toward it. Fresh per invocation (a resume starts both re-entry ledgers empty) |
154
155
  | `trigger` | `RunTrigger` | `{ kind: "programmatic" }` |
155
156
  | `lifecycle` | `LifecycleListeners` | none |
156
157
  | `signal` | `AbortSignal` | none |
@@ -215,7 +216,7 @@ Like `runWorkflowByName`, neither throws: an unresolvable run-id, error-severity
215
216
  load issues, a workflow that is no longer registered, or an unreconstructable trail
216
217
  each come back as a failure envelope.
217
218
 
218
- Run trails carry a schema version (`STATE_SCHEMA_VERSION = 2`). Resuming a run
219
+ Run trails carry a schema version (`STATE_SCHEMA_VERSION = 3`). Resuming a run
219
220
  recorded under a different version is **refused** with a version mismatch — there
220
221
  is no in-place migration.
221
222
 
@@ -238,13 +238,14 @@ 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 four knobs the sequential kinds have no use for:
241
+ `fanout()` adds five 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
+ | `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 (a unit interrupted inside its `retryHaltedUnits` window is the exception — its slot re-dispatches while retry budget remains). An over-cap `"advance"` generation never qualifies (beyond-cap slots stay unfilled). `failFast` wins when both are set. With `retryHaltedUnits` set, the close waits for every unit's retries — see that row. |
248
+ | `retryHaltedUnits` | absent (exactly one dispatch) | Re-dispatch a soft-halted collect-all unit (a failed sentinel in its slot) up to `retryHaltedUnits` MORE times. One attempt = the unit's whole dispatch with a fresh pre-attempt snapshot — a retry's disk-first collection sees only its own session's writes, and the attempt-1 failure memo rides the re-dispatch prompt as the additive suffix (same unit prompt otherwise). Only the FINAL attempt's output folds. With `haltWhenAllFailed` set, the close waits for every unit's retries — it fires only when every FINAL attempt is a failed sentinel; a unit that recovers on retry keeps the generation alive. Integer ≥ 1, validated at construction and load. Inert under `failFast` (a fail-fast halt terminates the run; there is nothing left to re-dispatch into). |
248
249
  | `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. |
249
250
 
250
251
  #### The resume contract (all loop kinds)
@@ -691,7 +692,7 @@ Grouped by discovery model:
691
692
 
692
693
  | Collector | Signature | What it does |
693
694
  |-----------|-----------|--------------|
694
- | `transcriptPathCollector` | `({ pattern: RegExp })` | Scans assistant text for the last regex match; emits one `fs` artifact. |
695
+ | `transcriptPathCollector` | `({ pattern: RegExp, match?, argKeys? })` | Scans assistant text for the last regex match; on a miss, the string arguments of the agent's tool calls (`match` narrows by call, `argKeys` by argument key — e.g. `match: (tc) => tc.name === "write", argKeys: ["path"]`). Emits one `fs` artifact. |
695
696
  | `directoryPathCollector` | `({ dir, ext? })` | Wrapper over `transcriptPathCollector` for `<dir>/<file>.<ext>`. |
696
697
  | `urlCollector` | `({ pattern? })` | Scans for `https?://…`; emits a `url` handle. |
697
698
 
@@ -699,7 +700,7 @@ Grouped by discovery model:
699
700
 
700
701
  | Collector | Signature | What it does |
701
702
  |-----------|-----------|--------------|
702
- | `toolCallCollector` | `({ match, toArtifact })` | Walks every `tool_use` part; emits N artifacts via author's mappers. |
703
+ | `toolCallCollector` | `({ match, toArtifact })` | Walks every tool-invocation part (Pi's `toolCall`/`arguments`, normalised to `{ name, input }`); emits N artifacts via author's mappers. |
703
704
 
704
705
  **Diff the filesystem:**
705
706
 
@@ -59,7 +59,7 @@ Resume folds the JSONL trail back into run state and re-enters at the pending st
59
59
  | Non-interactive session | `/wf requires interactive mode` |
60
60
  | No workflows registered | A message telling you to install a sibling that bundles workflows or author one in `.rpiv/workflows/config.ts`. This is the standalone-install default state — the package ships zero workflows |
61
61
  | Any load issue with `severity: "error"` | `/wf: N config errors — see warnings above (fix and re-run)`; execution is blocked until the config loads clean |
62
- | A run recorded under an older state schema | Resume is refused with a version mismatch. `STATE_SCHEMA_VERSION` is `2`; there is no in-place migration |
62
+ | A run recorded under an older state schema | Resume is refused with a version mismatch. `STATE_SCHEMA_VERSION` is `3`; there is no in-place migration |
63
63
  | First `/wf` before the runtime pre-warms | One toast: `rpiv: loading workflow runtime (first /wf after load)…`. The runtime pre-warms 2000 ms after extension load |
64
64
 
65
65
  ## File structure
@@ -184,18 +184,21 @@ Alongside the trail:
184
184
  - `runs/names.json` — the `--name` slug → run-id index.
185
185
  - `runs/<run-id>/sessions/` — the child session files backing that run's stages.
186
186
 
187
- Trails carry `STATE_SCHEMA_VERSION`, currently `2`. A run recorded under a different version cannot be resumed.
187
+ Trails carry `STATE_SCHEMA_VERSION`, currently `3`. A run recorded under a different version cannot be resumed.
188
188
 
189
189
  The package sets no explicit file modes; writes use the process umask. If a write fails, the error tells you to check filesystem permissions for `.rpiv/workflows/runs/`.
190
190
 
191
191
  ## Run caps
192
192
 
193
- Two backstops bound every run regardless of what a workflow declares:
193
+ Three backstops bound every run regardless of what a workflow declares:
194
194
 
195
195
  | Cap | Default | Effect |
196
196
  | --- | --- | --- |
197
197
  | `maxIterations` | `32` | Run-wide ceiling on loop units of every kind. The effective loop cap is `min(loop.max, run.maxIterations)` |
198
- | Backward-jump budget | `3` per destination stage | At most 4 executions of any one stage across decision-edge loop-backs |
198
+ | Backward-jump budget | `3` per destination stage | At most 4 executions of any one stage across decision-edge loop-backs. A stage declaring a `progress` hook that reports `"improved"` waives a re-entry past this budget |
199
+ | Lap ceiling | `8` per destination stage | Absolute ceiling on decision-edge re-entries — counted or waived. Even an all-`"improved"` loop halts on the `maxLaps + 1`-th re-entry of one stage |
200
+
201
+ Both re-entry budgets are per invocation: a resume (`/wf @<run-id>`) starts them fresh. Raise them per run with `--max-jumps <n>` and `--max-laps <n>` — each honored in the leading or trailing position like `--name`, in any relative order, at most once; a mid-position token stays as workflow input text.
199
202
 
200
203
  ## Trusting overlay files
201
204
 
package/failure-memos.ts CHANGED
@@ -41,9 +41,18 @@ export const MAX_FAILURE_MEMO_ERR_LEN = 500;
41
41
  * only for a loop-unit failure (the unit's stable audit id).
42
42
  */
43
43
  export function appendFailureMemo(state: RunState, audit: AuditContext, errMsg: string): void {
44
+ pushFailureMemo(state, { stage: audit.unit?.parent ?? audit.stageName, unitId: audit.unit?.id }, errMsg);
45
+ }
46
+
47
+ /**
48
+ * Push a memo by machine identity — the resume fold's entry: a skipped
49
+ * under-budget collected row's `errMsg` re-enters the ledger here so the
50
+ * re-dispatched unit's prompt carries it exactly as the live retry's does.
51
+ */
52
+ export function pushFailureMemo(state: RunState, id: { stage: string; unitId?: string }, errMsg: string): void {
44
53
  const memo: FailureMemo = {
45
- stage: audit.unit?.parent ?? audit.stageName,
46
- ...(audit.unit?.id ? { unitId: audit.unit.id } : {}),
54
+ stage: id.stage,
55
+ ...(id.unitId ? { unitId: id.unitId } : {}),
47
56
  errMsg: truncateErr(errMsg),
48
57
  ts: nowIso(),
49
58
  };
package/index.ts CHANGED
@@ -75,10 +75,17 @@
75
75
  // engine. This entry layers the runner on top for embedders.
76
76
  export * from "./registration.js";
77
77
 
78
- // The execution engine — the only re-export unique to this entry.
78
+ // The execution engine — the only re-export unique to this entry. The budget
79
+ // defaults and `validateRunBudgets` ride along: the runner refuses a malformed
80
+ // `maxBackwardJumps`/`maxLaps`/`maxIterations` pre-flight, so an embedder
81
+ // must be able to pre-validate and read the defaults the refusal math uses.
79
82
  export {
83
+ MAX_BACKWARD_JUMPS,
84
+ MAX_ITERATIONS,
85
+ MAX_LAPS,
80
86
  type ResumeWorkflowByRunIdOptions,
81
87
  type ResumeWorkflowOptions,
88
+ type RunBudgetOptions,
82
89
  type RunWorkflowByNameOptions,
83
90
  type RunWorkflowOptions,
84
91
  type RunWorkflowResult,
@@ -86,6 +93,7 @@ export {
86
93
  resumeWorkflowByRunId,
87
94
  runWorkflow,
88
95
  runWorkflowByName,
96
+ validateRunBudgets,
89
97
  } from "./runner/index.js";
90
98
 
91
99
  // NOTE: the Pi extension `default` entry is `./extension.ts`, not this barrel,
package/loop-def.ts CHANGED
@@ -248,6 +248,23 @@ export interface FanoutLoop extends LoopCommon {
248
248
  * outputs; the chain advances).
249
249
  */
250
250
  haltWhenAllFailed?: boolean;
251
+ /**
252
+ * Re-dispatch a soft-halted collect-all unit (a failed sentinel in its
253
+ * slot) up to `retryHaltedUnits` MORE times. One attempt = the unit's
254
+ * whole dispatch: unit start, pre-attempt snapshot, session build,
255
+ * execution — so a retry's disk-first collection sees only what the
256
+ * retry's own session wrote, and the attempt-1 failure memo rides the
257
+ * re-dispatch prompt as the additive suffix (same unit prompt otherwise).
258
+ * The fold sees only the FINAL attempt's output. Integer >= 1 when
259
+ * present; absent ⇒ exactly one dispatch (the prior contract).
260
+ * Collect-all units only — inert under `failFast` (a fail-fast halt
261
+ * terminates the run; there is nothing left to re-dispatch into).
262
+ * Retries complete inside the per-unit worker before the generation
263
+ * folds, so a set `haltWhenAllFailed` close sees only final attempts —
264
+ * the halt fires only when every unit's FINAL attempt is a failed
265
+ * sentinel; a unit that recovers on retry keeps the generation alive.
266
+ */
267
+ retryHaltedUnits?: number;
251
268
  /**
252
269
  * When set, the dispatcher injects each completed dependency's published
253
270
  * artifact path into the dependent unit's prompt as `${depArtifactFlag} <path>`