@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.
package/loop-kinds.ts CHANGED
@@ -442,7 +442,21 @@ export interface SequentialStrategy extends LoopKindStrategy {
442
442
  * named channel. `cursor.filledCount` becomes the filled-slot count (completion);
443
443
  * `cursor.index` is left untouched — it stays the next-unit pointer. `lastProduce`
444
444
  * is the highest-index non-failed slot (deterministic — order-free, so live +
445
- * resume + re-dispatch agree). */
445
+ * resume + re-dispatch agree).
446
+ *
447
+ * THE INDEX-OVERWRITE HAZARD this fold owns: the sentinel a soft-halted unit
448
+ * places overwrites whatever its slot held from prior rounds, so the stale
449
+ * round-N fail the gate should have blocked on is ERASED from the channel the
450
+ * moment that dimension's unit dies — the gate then folds only the surviving
451
+ * dimensions, and absence is not failure. Only a DIMENSION-BEARING sentinel
452
+ * can represent the unresolved dimension (the gate-side twin comment sits on
453
+ * `allDimensionsPass`): it registers as the dimension's latest entry carrying
454
+ * no `pass`/`severity`, which reads blocking. The mirror hazard — an UNFILLED
455
+ * slot (infra death wrote no row) leaving the stale fail as the channel's
456
+ * entry for that dimension — blocks on a verdict the fix may already have
457
+ * addressed; that shape stays distinguishable because its slot is
458
+ * `undefined`, not a sentinel.
459
+ */
446
460
  export function foldFanoutCompletion(
447
461
  state: RunState,
448
462
  cursor: LoopCursor,
@@ -523,6 +537,7 @@ export function buildUnitSession(
523
537
  snapshot: unknown,
524
538
  signal: AbortSignal | undefined,
525
539
  onSuccess: StageSessionContext["onSuccess"],
540
+ attemptOrdinal?: number,
526
541
  ): StageSessionContext {
527
542
  return {
528
543
  cwd: run.cwd,
@@ -545,6 +560,10 @@ export function buildUnitSession(
545
560
  worktreeDigest: run.worktreeDigest,
546
561
  collectAll: shouldCollectAll(e.loop),
547
562
  laneUnitIndex: laneIndexFor(e.loop, index),
563
+ // The v3 trail contract's attempt ordinal (present on every fanout unit
564
+ // attempt; `auditFor` projects it onto the collected halt row). Omitted
565
+ // when undefined so the sequential callers keep byte-identical sessions.
566
+ ...(attemptOrdinal !== undefined ? { attemptOrdinal } : {}),
548
567
  onFailure: undefined,
549
568
  onSuccess,
550
569
  };
package/loop-parallel.ts CHANGED
@@ -221,12 +221,17 @@ function depArtifactSuffix(e: LoopEntry, cursor: LoopCursor, index: number, idTo
221
221
  return suffix;
222
222
  }
223
223
 
224
- /** Dispatch one fanout unit in its own child and RETURN its output. The cursor is NOT
225
- * touched here — the wave fold consumes the return value in index order. `promptSuffix`
226
- * (the resolved dep-artifact injection) is appended to the unit prompt by `fanoutUnitAt`.
227
- * A halted unit leaves `captured` unset; returns failedOutput. (Settle shapes unchanged
228
- * from the pre-wave dispatcher: collect-all unit failure → sentinel; fail-fast halt →
229
- * placement sentinel + graceful return; ABORT → throws WorkflowAbortError → unfilled slot.) */
224
+ /** Dispatch one fanout unit in its own child and RETURN its output — the
225
+ * unit's FINAL settled output when the loop opts into `retryHaltedUnits`
226
+ * (a soft-halted attempt re-dispatches up to that many more times; earlier
227
+ * attempts' sentinels never reach the fold). The cursor is NOT touched here —
228
+ * the wave fold consumes the return value in index order. `promptSuffix`
229
+ * (the resolved dep-artifact injection) is appended to the unit prompt by
230
+ * `fanoutUnitAt`. Settle shapes: collect-all unit failure → sentinel (retried
231
+ * when opted in); fail-fast halt → placement sentinel + graceful return;
232
+ * ABORT → throws WorkflowAbortError → unfilled slot. Both sentinel shapes
233
+ * carry the unit's label as their dimension so a dead unit is never
234
+ * anonymous to the gate folds. */
230
235
  async function dispatchUnitDetached(
231
236
  hostCtx: WorkflowHostContext,
232
237
  e: LoopEntry,
@@ -236,25 +241,67 @@ async function dispatchUnitDetached(
236
241
  signal: AbortSignal | undefined, // genAbort.signal — run-level abort OR fail-fast sibling cancel
237
242
  promptSuffix = "",
238
243
  ): Promise<Output> {
239
- if (signal?.aborted) throw new WorkflowAbortError(); // never open a child after abort; isAbortError → unfilled slot
244
+ // One attempt = the unit's whole dispatch: lifecycle start, pre-attempt
245
+ // snapshot, session build, execution. `attemptOrdinal` is the attempt's
246
+ // 1-based count — stamped onto the session so the collected halt row
247
+ // carries it (the resume fold's budget input). Returns the attempt's settled output
248
+ // when its continuation ran (a real output, or the soft-halt sentinel
249
+ // `softHaltUnit` handed `onSuccess`), `undefined` when the halt never
250
+ // reached `onSuccess` (a fail-fast / infra-death terminal halt — the run is
251
+ // over, there is nothing to retry).
252
+ const attempt = async (attemptOrdinal: number): Promise<Output | undefined> => {
253
+ if (signal?.aborted) throw new WorkflowAbortError(); // never open a child after abort; isAbortError → unfilled slot
254
+ const u = fanoutUnitAt(e, index, promptSuffix);
255
+ await run.lifecycle.fire(
256
+ hostCtx,
257
+ "onUnitStart",
258
+ skillStageRef(e.name, e.stageIdx + 1, u.skill),
259
+ { role: u.role, index, unitId: u.id, label: u.label, skill: u.skill },
260
+ lifecycleCtxFor(run),
261
+ );
262
+ // Re-captured PER ATTEMPT, before the stage body: a file is "new since
263
+ // snapshot" iff it is absent from THIS listing or its mtime moved — so a
264
+ // retry's disk-first collection sees only what the retry's own session
265
+ // wrote, never attempt-1's leftovers.
266
+ const snapshot = await deps.captureSnapshot(hostCtx, e.name, u.def, e.stageIdx, run);
267
+ let captured: Output | undefined;
268
+ await deps.executeStageSession(
269
+ hostCtx,
270
+ buildUnitSession(
271
+ e,
272
+ u,
273
+ index,
274
+ run,
275
+ snapshot,
276
+ signal,
277
+ (_child, output) => {
278
+ captured = output;
279
+ return Promise.resolve();
280
+ },
281
+ attemptOrdinal,
282
+ ),
283
+ );
284
+ return captured;
285
+ };
286
+
287
+ // Retry bound: a collect-all unit whose attempt settled as a failed
288
+ // sentinel (the unit soft-halted; the run survived) re-dispatches up to
289
+ // `retryHaltedUnits` more times — the ledger bound that a dead grade unit
290
+ // is re-dispatched once before any gate folds on its absence. Inert without
291
+ // the option, and under failFast by construction (a fail-fast halt leaves
292
+ // `captured` unset — the terminal path below, never a retry).
293
+ const retries = e.loop.kind === "fanout" && !isFailFast(e.loop) ? (e.loop.retryHaltedUnits ?? 0) : 0;
294
+ let settled = await attempt(1);
295
+ for (let used = 0; used < retries && settled !== undefined && isFailedOutput(settled); used++) {
296
+ settled = await attempt(used + 2);
297
+ }
298
+ if (settled !== undefined) return settled;
299
+ // Fail-fast placement sentinel (the run is terminating when this is used, so
300
+ // it is never read downstream; it only keeps the fold's Output type intact
301
+ // without a throw). The label rides as the dimension — symmetry with the
302
+ // soft-halt sentinel, so even this terminal shape names its unit.
240
303
  const u = fanoutUnitAt(e, index, promptSuffix);
241
- await run.lifecycle.fire(
242
- hostCtx,
243
- "onUnitStart",
244
- skillStageRef(e.name, e.stageIdx + 1, u.skill),
245
- { role: u.role, index, unitId: u.id, label: u.label, skill: u.skill },
246
- lifecycleCtxFor(run),
247
- );
248
- const snapshot = await deps.captureSnapshot(hostCtx, e.name, u.def, e.stageIdx, run);
249
- let captured: Output | undefined;
250
- await deps.executeStageSession(
251
- hostCtx,
252
- buildUnitSession(e, u, index, run, snapshot, signal, (_child, output) => {
253
- captured = output;
254
- return Promise.resolve();
255
- }),
256
- );
257
- return captured ?? failedOutput(unitOutputMeta(e, u, run), `${u.label}: unit halted`);
304
+ return failedOutput(unitOutputMeta(e, u, run), `${u.label}: unit halted`, u.label);
258
305
  }
259
306
 
260
307
  /** Minimal OutputMeta for a fail-fast placement sentinel. The run is terminating when
@@ -139,6 +139,10 @@ export interface FanoutOptions extends LoopOptionsBase {
139
139
  * stage instead of advancing into a fan-in over an empty channel. Over-cap
140
140
  * advancing generations never qualify; `failFast` wins when both are set. */
141
141
  haltWhenAllFailed?: boolean;
142
+ /** Re-dispatch a soft-halted collect-all unit up to N more times — the
143
+ * whole per-unit dispatch re-runs; only the final attempt's output folds.
144
+ * Integer >= 1 (throws at construction). */
145
+ retryHaltedUnits?: number;
142
146
  /** When set, the dispatcher appends `${depArtifactFlag} <path>` per direct
143
147
  * `Unit.deps` entry with a non-failed filled slot — handing the dependent unit
144
148
  * its dependencies' published artifacts (e.g. `"--upstream"`). Non-empty string;
@@ -182,6 +186,9 @@ export function fanout(opts: FanoutOptions): FanoutLoop {
182
186
  ...(opts.depArtifactFlag !== undefined ? { depArtifactFlag: checkedDepArtifactFlag(opts.depArtifactFlag) } : {}),
183
187
  ...(opts.failFast !== undefined ? { failFast: opts.failFast } : {}),
184
188
  ...(opts.haltWhenAllFailed !== undefined ? { haltWhenAllFailed: opts.haltWhenAllFailed } : {}),
189
+ ...(opts.retryHaltedUnits !== undefined
190
+ ? { retryHaltedUnits: checkedPositiveInt(opts.retryHaltedUnits, "fanout(): retryHaltedUnits") }
191
+ : {}),
185
192
  };
186
193
  }
187
194
 
package/messages.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  * `/wf` usage strings live in command.ts / preview.ts.
11
11
  */
12
12
 
13
+ import type { ProgressValue } from "./api.js";
13
14
  import { MAX_NAME_LENGTH } from "./state/index.js";
14
15
 
15
16
  /**
@@ -75,7 +76,7 @@ export const ERR_VALIDATE_RETRY_UNCHANGED = (skill: string) =>
75
76
  * a worktree unchanged since its last validation failure at the same progress
76
77
  * point (`stagesCompleted` unchanged). A `FailureText` consumed by `failedArgs`
77
78
  * (the sessionless `recordFatalFailure` descriptor, mirroring
78
- * `ensureBackwardJumpGuard` in `packages/rpiv-workflow/runner/chain-advance.ts`).
79
+ * `evaluateBackwardJumpGuard` in `packages/rpiv-workflow/runner/chain-advance.ts`).
79
80
  * The terminal skip carries the failure memo for free through the shared
80
81
  * `recordFatalFailure` writer hooks at `packages/rpiv-workflow/audit.ts:134`.
81
82
  */
@@ -118,10 +119,48 @@ export const FAIL_MISSING_NAMED_READ = (currentSkill: string, name: string, stag
118
119
  error: `Stage ${stageNumber} (${currentSkill}) reads "${name}" but state.named["${name}"] is empty; check that an upstream produces stage publishes this name`,
119
120
  });
120
121
 
121
- export const FAIL_BACKWARD_JUMP_EXHAUSTED = (stage: string, revisits: number, max: number): FailureText => ({
122
- toast: `rpiv: backward-jump limit exceeded — "${stage}" re-entered ${revisits} times (max ${max}) — stopping workflow to prevent infinite loop`,
123
- error: `Backward-jump limit exceeded: stage "${stage}" re-entered ${revisits} times (max ${max})`,
124
- });
122
+ /** Which re-entry limit tripped — the waive-aware cap or the absolute lap ceiling. */
123
+ export type BackwardJumpLimitKind = "cap" | "ceiling";
124
+
125
+ /**
126
+ * Everything the backward-jump halt text needs, one object — the guard
127
+ * defers rendering to the halt site, so a new limit arm extends the
128
+ * factory without another signature change.
129
+ */
130
+ export interface BackwardJumpHaltInfo {
131
+ stage: string;
132
+ limitKind: BackwardJumpLimitKind;
133
+ /** Tripping count (the cap's re-entry count, or the ceiling's lap count). */
134
+ count: number;
135
+ max: number;
136
+ /** The destination's most recent progress verdicts, oldest → newest; empty ⇒ clause omitted. */
137
+ progress: readonly ProgressValue[];
138
+ }
139
+
140
+ /**
141
+ * Shared head of both limit arms. The external replay tooling greps the
142
+ * failure row's errMsg for exactly this case-sensitive substring
143
+ * (`thoughts/shared/research/replay-scripts/cap-halts.py`).
144
+ */
145
+ export const BACKWARD_JUMP_LIMIT_HEAD = "Backward-jump limit exceeded";
146
+
147
+ /** `; last progress: …` — only when the ring has recorded at least one verdict. */
148
+ const backwardJumpProgressClause = (progress: readonly ProgressValue[]): string =>
149
+ progress.length > 0 ? `; last progress: ${progress.join(", ")}` : "";
150
+
151
+ export const FAIL_BACKWARD_JUMP_EXHAUSTED = (info: BackwardJumpHaltInfo): FailureText => {
152
+ const clause = backwardJumpProgressClause(info.progress);
153
+ if (info.limitKind === "ceiling") {
154
+ return {
155
+ toast: `rpiv: backward-jump limit exceeded — "${info.stage}" re-entered ${info.count} times, over the absolute lap ceiling (max ${info.max})${clause} — stopping workflow to prevent infinite loop`,
156
+ error: `${BACKWARD_JUMP_LIMIT_HEAD}: stage "${info.stage}" re-entered ${info.count} times, over the absolute lap ceiling (max ${info.max})${clause}`,
157
+ };
158
+ }
159
+ return {
160
+ toast: `rpiv: backward-jump limit exceeded — "${info.stage}" re-entered ${info.count} times (max ${info.max})${clause} — stopping workflow to prevent infinite loop`,
161
+ error: `${BACKWARD_JUMP_LIMIT_HEAD}: stage "${info.stage}" re-entered ${info.count} times (max ${info.max})${clause}`,
162
+ };
163
+ };
125
164
 
126
165
  /**
127
166
  * A decision edge terminated the chain because no branch matched — `match`
@@ -403,6 +442,34 @@ export const MSG_NAME_IGNORED_ON_RESUME =
403
442
  export const MSG_NAME_FLAG_MID_INPUT =
404
443
  "/wf: --name is only honored as the first or last token — a mid-input --name is treated as workflow input text";
405
444
 
445
+ /**
446
+ * A leading/trailing flag appeared more than once. The first-TYPED value
447
+ * wins in every slot (the parser ranks occurrences by their offset in the
448
+ * line, not by extraction order) and every other occurrence is stripped — never left in the
449
+ * input, where a leading `--max-jumps 9 research …` residual would bind the
450
+ * whole line as prompt text for the DEFAULT workflow.
451
+ */
452
+ export const MSG_FLAG_REPEATED = (flag: string) =>
453
+ `/wf: ${flag} given more than once — the first value wins, the rest are ignored`;
454
+
455
+ /**
456
+ * The waive-aware jump cap is at or above the absolute lap ceiling, so the
457
+ * ceiling (which counts every re-entry) always halts first and the cap can
458
+ * never trip — a `--max-jumps 20` alone still delivers at most `MAX_LAPS`
459
+ * re-entries. Surfaced at parse so the user raises `--max-laps` beside it.
460
+ */
461
+ export const MSG_JUMP_CAP_ABOVE_LAP_CEILING = (cap: number, ceiling: number) =>
462
+ `/wf: --max-jumps ${cap} is at or above the lap ceiling ${ceiling} — the ceiling halts first, so at most ${ceiling} re-entries per stage; raise --max-laps to widen the run`;
463
+
464
+ /**
465
+ * A programmatic budget option (`maxBackwardJumps` / `maxLaps` /
466
+ * `maxIterations`) that is not a non-negative integer. `??` passes `NaN`
467
+ * straight through, and `laps > NaN` is always false — the "always halts"
468
+ * ceiling would fail OPEN. Refused pre-flight, before any row is written.
469
+ */
470
+ export const MSG_BUDGET_INVALID = (option: string, value: number) =>
471
+ `${option} must be a non-negative integer, got ${String(value)}`;
472
+
406
473
  export const MSG_LOAD_ABORTED = (count: number) =>
407
474
  `/wf: ${count} ${count === 1 ? "config error" : "config errors"} — see warnings above (fix and re-run)`;
408
475
 
@@ -14,6 +14,7 @@
14
14
 
15
15
  import type { ArtifactCollector } from "../../output-spec.js";
16
16
  import { requireOpt } from "./require-opt.js";
17
+ import type { ToolCall } from "./tool-call.js";
17
18
  import { transcriptPathCollector } from "./transcript-path.js";
18
19
 
19
20
  export interface DirectoryPathCollectorOpts {
@@ -24,6 +25,8 @@ export interface DirectoryPathCollectorOpts {
24
25
  * etc.). Defaults to any common alphanumeric extension.
25
26
  */
26
27
  ext?: string;
28
+ /** Narrows the tool-argument fallback to matching tool calls (see `textScanCollector`). */
29
+ match?: (tc: ToolCall) => boolean;
27
30
  }
28
31
 
29
32
  export function directoryPathCollector(opts: DirectoryPathCollectorOpts): ArtifactCollector {
@@ -36,7 +39,7 @@ export function directoryPathCollector(opts: DirectoryPathCollectorOpts): Artifa
36
39
  const escapedDir = escapeRegex(opts.dir);
37
40
  const extPart = opts.ext ? escapeRegex(opts.ext) : "[a-zA-Z0-9]+";
38
41
  const pattern = new RegExp(`${escapedDir}/[\\w.-]+\\.${extPart}`, "g");
39
- return transcriptPathCollector({ pattern });
42
+ return transcriptPathCollector({ pattern, match: opts.match });
40
43
  }
41
44
 
42
45
  function escapeRegex(s: string): string {
@@ -1,44 +1,108 @@
1
1
  /**
2
2
  * The neutral text-scan primitive — scan assistant text (reverse) for `pattern`,
3
- * fatal-on-miss, single `role: "primary"` artifact via `toHandle`. The shared
4
- * body `transcriptPathCollector` and `urlCollector` share here (byte-identical
5
- * modulo the handle constructor + the "path"/"URL" noun). Build
3
+ * then, on a miss, tool-call arguments (the agent's recorded actions), fatal
4
+ * only when BOTH surfaces miss, single `role: "primary"` artifact via `toHandle`.
5
+ * The shared body `transcriptPathCollector` and `urlCollector` share here
6
+ * (byte-identical modulo the handle constructor + the "path"/"URL" noun). Build
6
7
  * domain-specific collectors by wrapping this + supplying a pattern + handle
7
8
  * constructor (`directoryPathCollector` already delegates this way to
8
9
  * `transcriptPathCollector`).
9
10
  *
10
- * Fatal when no match is found — produces stages that wire this
11
- * promise an output, and silently returning zero artifacts hides the
12
- * agent's failure mode behind a stale primary-artifact.
11
+ * Fatal when no match is found on either surface — produces stages that wire
12
+ * this promise an output, and silently returning zero artifacts hides the
13
+ * agent's failure mode behind a stale primary-artifact. The tool-argument
14
+ * fallback exists because the actionable string can ride a write tool-call's
15
+ * input (the recorded action) while the spoken announcement is mangled or
16
+ * typo'd — the two surfaces disagree in BOTH directions, so the union of both
17
+ * is the honest "what did the agent actually produce" scan. The tool-arg
18
+ * fallback can be narrowed per tool call via the optional `match` predicate —
19
+ * no default; the primitive stays host-agnostic (tool-name conventions live
20
+ * in wrapping layers, never here).
13
21
  */
14
22
 
15
23
  import type { ArtifactHandle } from "../../handle.js";
16
24
  import type { ArtifactCollector } from "../../output-spec.js";
17
25
  import { defineCollector } from "../../output-spec.js";
18
- import { lastMatchInBranch } from "../../transcript.js";
26
+ import { type BranchEntry, iterToolUses, lastMatchInBranch } from "../../transcript.js";
27
+ import { requireOpt } from "./require-opt.js";
28
+ import type { ToolCall } from "./tool-call.js";
19
29
 
20
30
  export interface TextScanCollectorOpts {
21
31
  /**
22
- * Pattern to match against assistant text. REQUIRED — the framework has no
23
- * default (layouts are project-specific). Use `g` to scan for all matches per
24
- * block (helper takes the last); without `g`, only the first per block.
32
+ * Pattern to match against assistant text (and, on a text miss, tool-call
33
+ * argument values). REQUIRED — the framework has no default (layouts are
34
+ * project-specific). Use `g` to scan for all matches per block (helper takes
35
+ * the last); without `g`, only the first per block.
25
36
  */
26
37
  pattern: RegExp;
27
38
  /** Constructs the artifact handle from the matched string (e.g. `fs`, `url`). */
28
39
  toHandle: (hit: string) => ArtifactHandle;
29
40
  /** Noun for the fatal-on-miss message ("path" / "URL"). */
30
41
  noun: string;
42
+ /**
43
+ * Narrows the tool-argument fallback to matching tool calls (the
44
+ * assistant-text scan is unaffected). No default — the primitive stays
45
+ * host-agnostic; a convention layer pins tool names via this predicate.
46
+ */
47
+ match?: (tc: ToolCall) => boolean;
48
+ /**
49
+ * Narrows the tool-argument fallback to these argument KEYS of a matching
50
+ * call (e.g. `["path"]` so a `write` call's `content` — which may quote a
51
+ * sibling artifact's path — can never outrank the path it actually wrote
52
+ * to). Absent ⇒ every string-valued argument is scanned, as before. Must be
53
+ * a non-empty array of strings when provided (construction-time guard).
54
+ */
55
+ argKeys?: readonly string[];
56
+ }
57
+
58
+ /** Last match of `pattern` against the branch's tool-use INPUT values — the
59
+ * fallback surface. Forward scan, last hit wins, mirroring the text scan's
60
+ * reverse-last-match semantics over the agent's recorded actions instead of
61
+ * its narration. `argKeys` restricts which argument values are consulted. */
62
+ function lastToolArgMatch(
63
+ branch: BranchEntry[],
64
+ pattern: RegExp,
65
+ offsetStart?: number,
66
+ match?: (tc: ToolCall) => boolean,
67
+ argKeys?: readonly string[],
68
+ ): string | undefined {
69
+ let last: string | undefined;
70
+ for (const use of iterToolUses(branch, offsetStart)) {
71
+ if (match !== undefined && !match(use)) continue;
72
+ for (const [key, value] of Object.entries(use.input)) {
73
+ if (argKeys !== undefined && !argKeys.includes(key)) continue;
74
+ if (typeof value !== "string") continue;
75
+ const matches = value.match(pattern);
76
+ if (matches !== null && matches.length > 0) last = matches[matches.length - 1];
77
+ }
78
+ }
79
+ return last;
31
80
  }
32
81
 
33
82
  export function textScanCollector(opts: TextScanCollectorOpts): ArtifactCollector {
34
- const { pattern, toHandle, noun } = opts;
83
+ requireOpt(
84
+ "textScanCollector",
85
+ "match",
86
+ "must be a function when provided",
87
+ opts.match === undefined || typeof opts.match === "function",
88
+ );
89
+ requireOpt(
90
+ "textScanCollector",
91
+ "argKeys",
92
+ "must be a non-empty array of strings when provided",
93
+ opts.argKeys === undefined ||
94
+ (Array.isArray(opts.argKeys) && opts.argKeys.length > 0 && opts.argKeys.every((k) => typeof k === "string")),
95
+ );
96
+ const { pattern, toHandle, noun, match, argKeys } = opts;
35
97
  return defineCollector({
36
98
  collect: (ctx) => {
37
- const hit = lastMatchInBranch(ctx.branch, pattern, ctx.branchOffset);
99
+ const hit =
100
+ lastMatchInBranch(ctx.branch, pattern, ctx.branchOffset) ??
101
+ lastToolArgMatch(ctx.branch, pattern, ctx.branchOffset, match, argKeys);
38
102
  if (!hit) {
39
103
  return {
40
104
  kind: "fatal",
41
- message: `${ctx.skill} finished without producing a ${noun} matching ${pattern.source}`,
105
+ message: `${ctx.skill} finished without producing a ${noun} matching ${pattern.source} (scanned assistant text and tool-call arguments)`,
42
106
  };
43
107
  }
44
108
  return { kind: "ok", artifacts: [{ handle: toHandle(hit), role: "primary" }] };
@@ -16,12 +16,17 @@
16
16
  * Fatal when no match is found — produces stages that wire this
17
17
  * promise an output, and silently returning zero artifacts hides the
18
18
  * agent's failure mode behind a stale primary-artifact.
19
+ *
20
+ * The optional `match` predicate is forwarded verbatim to the shared
21
+ * text-scan primitive — it narrows the tool-argument fallback surface
22
+ * (validated there, at construction, by delegation).
19
23
  */
20
24
 
21
25
  import { fs } from "../../handle.js";
22
26
  import type { ArtifactCollector } from "../../output-spec.js";
23
27
  import { requireOpt } from "./require-opt.js";
24
28
  import { textScanCollector } from "./text-scan.js";
29
+ import type { ToolCall } from "./tool-call.js";
25
30
 
26
31
  export interface TranscriptPathCollectorOpts {
27
32
  /**
@@ -31,9 +36,27 @@ export interface TranscriptPathCollectorOpts {
31
36
  * only the first match per block is considered.
32
37
  */
33
38
  pattern: RegExp;
39
+ /**
40
+ * Narrows the tool-argument fallback to matching tool calls — forwarded
41
+ * verbatim to `textScanCollector`, whose construction-time guard applies
42
+ * by delegation (this factory keeps only its own pattern guard).
43
+ */
44
+ match?: (tc: ToolCall) => boolean;
45
+ /**
46
+ * Narrows the tool-argument fallback to these argument keys of a matching
47
+ * call (e.g. `["path"]`) — forwarded verbatim to `textScanCollector`, whose
48
+ * construction-time guard applies by delegation.
49
+ */
50
+ argKeys?: readonly string[];
34
51
  }
35
52
 
36
53
  export function transcriptPathCollector(opts: TranscriptPathCollectorOpts): ArtifactCollector {
37
54
  requireOpt("transcriptPathCollector", "pattern", "is required and must be a RegExp", opts.pattern instanceof RegExp);
38
- return textScanCollector({ pattern: opts.pattern, toHandle: fs, noun: "path" });
55
+ return textScanCollector({
56
+ pattern: opts.pattern,
57
+ toHandle: fs,
58
+ noun: "path",
59
+ match: opts.match,
60
+ argKeys: opts.argKeys,
61
+ });
39
62
  }
@@ -14,6 +14,7 @@ import { url } from "../../handle.js";
14
14
  import type { ArtifactCollector } from "../../output-spec.js";
15
15
  import { requireOpt } from "./require-opt.js";
16
16
  import { textScanCollector } from "./text-scan.js";
17
+ import type { ToolCall } from "./tool-call.js";
17
18
 
18
19
  /**
19
20
  * Conservative URL matcher — `https?://` plus non-whitespace, stopping
@@ -26,6 +27,8 @@ const DEFAULT_URL_PATTERN = /\bhttps?:\/\/[^\s<>"'`]+[^\s<>"'`.,;:!?)\]}]/g;
26
27
  export interface UrlCollectorOpts {
27
28
  /** Override the default URL pattern (e.g. narrow to one host). */
28
29
  pattern?: RegExp;
30
+ /** Narrows the tool-argument fallback to matching tool calls (see `textScanCollector`). */
31
+ match?: (tc: ToolCall) => boolean;
29
32
  }
30
33
 
31
34
  export function urlCollector(opts: UrlCollectorOpts = {}): ArtifactCollector {
@@ -36,5 +39,5 @@ export function urlCollector(opts: UrlCollectorOpts = {}): ArtifactCollector {
36
39
  opts.pattern === undefined || opts.pattern instanceof RegExp,
37
40
  );
38
41
  const pattern = opts.pattern ?? DEFAULT_URL_PATTERN;
39
- return textScanCollector({ pattern, toHandle: url, noun: "URL" });
42
+ return textScanCollector({ pattern, toHandle: url, noun: "URL", match: opts.match });
40
43
  }
package/output-spec.ts CHANGED
@@ -51,6 +51,15 @@ export interface CollectContext<Snapshot = unknown> extends SnapshotContext {
51
51
  snapshot: Snapshot;
52
52
  /** Filled by the runner; collectors MUST NOT set this themselves. */
53
53
  skill: string;
54
+ /**
55
+ * Present iff this session IS one loop unit — the unit's display label.
56
+ * Grade panels label each dimension unit with the dimension it grades, so
57
+ * there it IS the verdict dimension; a collector may narrow collection to
58
+ * it (the disk-first verdict collector's determined-name tightness).
59
+ * Absent for single stages and unlabeled wirings — those collectors must
60
+ * degrade to their loose shapes, never fatal on what they accepted before.
61
+ */
62
+ unitLabel?: string;
54
63
  }
55
64
 
56
65
  /**
package/output.ts CHANGED
@@ -160,7 +160,7 @@ export function outputMeta(args: {
160
160
  /** The data shape of a failed-unit sentinel — collect-all fanout places one of
161
161
  * these in a unit's declared slot when the unit halts (the run survives). */
162
162
  export const FAILED_OUTPUT_KIND = "failed";
163
- export type FailedOutput = Output<"failed", { reason: string }>;
163
+ export type FailedOutput = Output<"failed", { reason: string; dimension?: string }>;
164
164
 
165
165
  /**
166
166
  * A failed unit's contribution to a collect-all fanout. A real `Output` with NO
@@ -168,9 +168,28 @@ export type FailedOutput = Output<"failed", { reason: string }>;
168
168
  * `fanin` reader contributes no args for it (the `.filter(Boolean)` convention
169
169
  * needs no widening); `advanceCursor` advances the index without making it the
170
170
  * "last" produce; and the resume fold replays it like any produce row.
171
+ *
172
+ * `dimension` — the failed unit's label (grade panels label each dimension unit
173
+ * with the dimension it grades). A DIMENSION-BEARING sentinel blocks its
174
+ * dimension at every gate fold: the fold registers a latest-map entry for any
175
+ * verdict whose `data.dimension` is a string, and a sentinel carries neither
176
+ * `pass` nor `severity`, so its entry reads blocking. A dimensionless sentinel
177
+ * (the pre-dimension shape, retained for unlabeled fanout wirings) is SKIPPED
178
+ * by the fold — absence is not failure — which is exactly how a dead grade
179
+ * unit once erased the stale round-1 fail its slot held and let the gate pass
180
+ * with four surviving dimensions. The key is OMITTED (not `undefined`-valued)
181
+ * when no dimension is given, so a dimensionless sentinel stays byte-identical
182
+ * to the prior on-disk shape.
171
183
  */
172
- export function failedOutput(meta: OutputMeta, reason: string): FailedOutput {
173
- return finalizeOutput({ kind: FAILED_OUTPUT_KIND, artifacts: [], data: { reason } }, meta);
184
+ export function failedOutput(meta: OutputMeta, reason: string, dimension?: string): FailedOutput {
185
+ return finalizeOutput(
186
+ {
187
+ kind: FAILED_OUTPUT_KIND,
188
+ artifacts: [],
189
+ data: { reason, ...(dimension !== undefined ? { dimension } : {}) },
190
+ },
191
+ meta,
192
+ );
174
193
  }
175
194
 
176
195
  export const isFailedOutput = (o: Output): o is FailedOutput => o.kind === FAILED_OUTPUT_KIND;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -112,7 +112,7 @@
112
112
  ]
113
113
  },
114
114
  "dependencies": {
115
- "@juicesharp/rpiv-config": "^2.9.0",
115
+ "@juicesharp/rpiv-config": "^2.10.0",
116
116
  "jiti": "^2.7.0",
117
117
  "typebox": "^1.1.24"
118
118
  },
package/registration.ts CHANGED
@@ -35,7 +35,9 @@ export {
35
35
  match,
36
36
  ON_INVALID_VALUES,
37
37
  type OnInvalid,
38
+ PROGRESS_VALUES,
38
39
  type ProducesScriptFn,
40
+ type ProgressValue,
39
41
  type PromptFn,
40
42
  type PromptStage,
41
43
  produces,