@juicesharp/rpiv-workflow 2.8.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/audit-ctx.ts +7 -0
- package/audit.ts +8 -0
- package/command-run.ts +84 -17
- package/command.ts +171 -22
- package/docs/embedding.md +4 -3
- package/docs/workflow-authoring.md +5 -4
- package/docs/workflow-basics.md +7 -4
- package/execution-host.ts +1 -1
- package/failure-memos.ts +11 -2
- package/index.ts +9 -1
- package/loop-def.ts +17 -0
- package/loop-kinds.ts +21 -2
- package/loop-parallel.ts +71 -24
- package/loops/constructors.ts +7 -0
- package/messages.ts +72 -5
- package/outcomes/collectors/directory-path.ts +4 -1
- package/outcomes/collectors/text-scan.ts +77 -13
- package/outcomes/collectors/transcript-path.ts +24 -1
- package/outcomes/collectors/url.ts +4 -1
- package/output-spec.ts +9 -0
- package/output.ts +22 -3
- package/package.json +2 -2
- package/registration.ts +2 -0
- package/runner/chain-advance.ts +140 -26
- package/runner/index.ts +7 -1
- package/runner/resume.ts +102 -9
- package/runner/run-context.ts +58 -4
- package/runner/run-stage.ts +1 -1
- package/runner/runner.ts +24 -4
- package/sessions/extraction.ts +1 -0
- package/sessions/halt-routing.ts +5 -1
- package/stage-def.ts +54 -4
- package/state/reads.ts +14 -1
- package/state/state.ts +47 -6
- package/transcript.ts +30 -11
- package/types.ts +55 -5
- package/validate/issue.ts +10 -0
- package/validate/stage-rules.ts +30 -0
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,
|
|
@@ -539,12 +554,16 @@ export function buildUnitSession(
|
|
|
539
554
|
snapshot,
|
|
540
555
|
branchOffset: undefined,
|
|
541
556
|
unit: { parent: e.name, role: u.role, index, id: u.id, label: u.label },
|
|
542
|
-
model: run.resolveModel?.({ stage: e.name, skill: u.skill }),
|
|
557
|
+
model: run.resolveModel?.({ workflow: run.workflow.name, stage: e.name, skill: u.skill }),
|
|
543
558
|
signal,
|
|
544
559
|
readSessionBranch: run.readSessionBranch,
|
|
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
|
|
225
|
-
*
|
|
226
|
-
* (
|
|
227
|
-
*
|
|
228
|
-
*
|
|
229
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
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
|
package/loops/constructors.ts
CHANGED
|
@@ -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
|
-
* `
|
|
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
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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
|
|
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
|
|
23
|
-
*
|
|
24
|
-
*
|
|
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
|
-
|
|
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 =
|
|
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({
|
|
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(
|
|
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.
|
|
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.
|
|
115
|
+
"@juicesharp/rpiv-config": "^2.10.0",
|
|
116
116
|
"jiti": "^2.7.0",
|
|
117
117
|
"typebox": "^1.1.24"
|
|
118
118
|
},
|