@juicesharp/rpiv-workflow 1.20.0 → 2.0.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.
Files changed (106) hide show
  1. package/api.ts +1 -1
  2. package/audit-ctx.ts +103 -0
  3. package/audit-rows.ts +18 -0
  4. package/audit.ts +119 -164
  5. package/built-ins.ts +26 -6
  6. package/chain-state.ts +119 -68
  7. package/command-run.ts +35 -30
  8. package/command.ts +10 -4
  9. package/docs/workflow-authoring.md +34 -2
  10. package/events.ts +44 -4
  11. package/execution-host.ts +75 -0
  12. package/host.ts +137 -82
  13. package/internal-utils.ts +89 -3
  14. package/internal.ts +1 -0
  15. package/judge.ts +23 -11
  16. package/load/alias.ts +3 -3
  17. package/load/index.ts +15 -1
  18. package/load/issues.ts +2 -2
  19. package/load/legacy.ts +2 -2
  20. package/load/resolve-default.ts +3 -4
  21. package/load/skill-contract-phase.ts +1 -1
  22. package/loop-constructors.ts +19 -618
  23. package/loop-def.ts +60 -15
  24. package/loop-kinds.ts +319 -62
  25. package/loop-parallel.ts +250 -0
  26. package/loop-waves.ts +99 -0
  27. package/loop.ts +106 -80
  28. package/loops/constructors.ts +334 -0
  29. package/loops/derivations.ts +65 -0
  30. package/loops/introspection.ts +184 -0
  31. package/loops/panel.ts +196 -0
  32. package/loops/verify.ts +99 -0
  33. package/messages.ts +58 -33
  34. package/outcomes/collectors/index.ts +1 -0
  35. package/outcomes/collectors/text-scan.ts +47 -0
  36. package/outcomes/collectors/transcript-path.ts +2 -15
  37. package/outcomes/collectors/union.ts +2 -1
  38. package/outcomes/collectors/url.ts +2 -14
  39. package/outcomes/collectors/workspace-diff.ts +1 -1
  40. package/outcomes/git-commit.ts +57 -6
  41. package/output-spec.ts +1 -1
  42. package/output.ts +59 -1
  43. package/package.json +16 -6
  44. package/preview.ts +18 -18
  45. package/registration.ts +11 -4
  46. package/routing-dsl.ts +53 -41
  47. package/routing.ts +46 -0
  48. package/runner/chain-advance.ts +30 -17
  49. package/runner/errors.ts +7 -30
  50. package/runner/failure.ts +67 -13
  51. package/runner/input-validation.ts +8 -5
  52. package/runner/preflight.ts +17 -21
  53. package/runner/resume-entry.ts +23 -3
  54. package/runner/resume-loop.ts +50 -29
  55. package/runner/resume.ts +96 -10
  56. package/runner/run-context.ts +20 -16
  57. package/runner/run-stage.ts +125 -91
  58. package/runner/runner.ts +163 -69
  59. package/runner/script-stage.ts +23 -29
  60. package/schema-compat.ts +1 -2
  61. package/semaphore.ts +55 -0
  62. package/sessions/extraction.ts +103 -60
  63. package/sessions/halt-routing.ts +195 -0
  64. package/sessions/index.ts +2 -2
  65. package/sessions/locate.ts +60 -9
  66. package/sessions/reattach.ts +28 -20
  67. package/sessions/sessions.ts +103 -191
  68. package/sessions/spawn.ts +132 -119
  69. package/sessions/success-persist.ts +89 -0
  70. package/skill-contracts/composition.ts +8 -10
  71. package/skill-contracts/harvest.ts +3 -2
  72. package/skill-contracts/registry.ts +1 -1
  73. package/stage-def.ts +115 -47
  74. package/stage-errors.ts +84 -0
  75. package/stage-identity.ts +56 -0
  76. package/startup.ts +1 -0
  77. package/state/paths.ts +11 -3
  78. package/state/raw.ts +2 -3
  79. package/state/resolve.ts +3 -3
  80. package/state/state.ts +26 -3
  81. package/state/writes.ts +1 -1
  82. package/types.ts +97 -43
  83. package/validate/contract-compat.ts +16 -11
  84. package/validate/graph.ts +10 -1
  85. package/validate/issue.ts +20 -6
  86. package/validate/stage-rules.ts +139 -60
  87. package/validate-output.ts +27 -20
  88. package/validate-workflow.ts +5 -3
  89. package/validation-bounds.ts +35 -0
  90. package/load/cache.test.ts +0 -82
  91. package/load/shape-guards.test.ts +0 -77
  92. package/outcomes/collectors/directory-path.test.ts +0 -64
  93. package/outcomes/collectors/tool-call.test.ts +0 -112
  94. package/outcomes/collectors/transcript-path.test.ts +0 -70
  95. package/outcomes/collectors/union.test.ts +0 -113
  96. package/outcomes/collectors/url.test.ts +0 -67
  97. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  98. package/outcomes/git-commit.test.ts +0 -240
  99. package/outcomes/parsers/json-body.test.ts +0 -80
  100. package/runner/by-name.test.ts +0 -95
  101. package/runner/by-run-id.test.ts +0 -115
  102. package/runner/header-write-failure.test.ts +0 -64
  103. package/runner/resume-loop.test.ts +0 -1410
  104. package/runner/resume-session.test.ts +0 -400
  105. package/runner/resume.test.ts +0 -1805
  106. package/sessions/locate.test.ts +0 -77
package/loops/panel.ts ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Panel — N independent judges + a vote fold (the adversarial generalization
3
+ * of a single judge). Construction + the canonical verdict surface live here;
4
+ * execution (cursor sub-state, member dispatch, fold-close publish) lands in the
5
+ * runner behind the one `panelMembers` expander.
6
+ */
7
+
8
+ import { type Static, Type } from "typebox";
9
+ import type { StageDef } from "../api.js";
10
+ import {
11
+ assertShape,
12
+ brandCanonicalFold,
13
+ type FoldFn,
14
+ type Judge,
15
+ judgeShapeIssues,
16
+ marksCanonicalFold,
17
+ type NamedOutcome,
18
+ type PanelJudge,
19
+ } from "../judge.js";
20
+ import { noopCollector } from "../outcomes/index.js";
21
+ import type { Output } from "../output.js";
22
+
23
+ /**
24
+ * The canonical fold output shape — what `majority`/`all`/`any` emit and what
25
+ * a downstream `defineRoute`/`gate`/`match` branches on. `agreement` (|majority|
26
+ * / N) is the first-class disagreement signal; `tie` flags an even split. A
27
+ * custom (raw) fold publishes the author's own schema instead (the XOR rule).
28
+ */
29
+ export const PANEL_VERDICT = Type.Object({
30
+ pass: Type.Boolean(),
31
+ votes: Type.Object({ pass: Type.Integer(), fail: Type.Integer() }),
32
+ agreement: Type.Number(),
33
+ tie: Type.Boolean(),
34
+ });
35
+
36
+ /** Static type of the canonical {@link PANEL_VERDICT} fold output. */
37
+ export type PanelVerdict = Static<typeof PANEL_VERDICT>;
38
+
39
+ /**
40
+ * Built-in named outcome the CANONICAL path publishes under — the default a
41
+ * sugar panel resolves to (`judge.outcome ?? PANEL_VERDICT_OUTCOME`, wired in
42
+ * the panel-close publish phase). Its `name` is a fallback: the live publish
43
+ * overrides it with the per-stage `<stage>-panel` channel, so distinct panel
44
+ * stages never collide. The collector is a no-op — the fold output is
45
+ * manufactured from the member verdicts (data, not a collected artifact), so
46
+ * nothing is ever collected on this outcome.
47
+ */
48
+ export const PANEL_VERDICT_OUTCOME: NamedOutcome = {
49
+ name: "panel-verdict",
50
+ collector: noopCollector,
51
+ };
52
+
53
+ /**
54
+ * Tally the members' per-member `pred` results into the canonical verdict
55
+ * shape. `votes`/`agreement`/`tie` are fold-independent (they describe the
56
+ * split); only `pass` differs per sugar fold, supplied by `passWhen`.
57
+ */
58
+ function tally(
59
+ verdicts: readonly Output[],
60
+ pred: (v: Output) => boolean,
61
+ passWhen: (pass: number, fail: number) => boolean,
62
+ ): PanelVerdict {
63
+ const n = verdicts.length;
64
+ const pass = verdicts.reduce((c, v) => c + (pred(v) ? 1 : 0), 0);
65
+ const fail = n - pass;
66
+ return {
67
+ pass: passWhen(pass, fail),
68
+ votes: { pass, fail },
69
+ agreement: n === 0 ? 0 : Math.max(pass, fail) / n,
70
+ tie: pass === fail,
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Sugar fold — the panel passes iff a STRICT majority of members pass `pred`
76
+ * (an even split is a tie ⇒ fail, surfaced via `tie`/`agreement`). The
77
+ * per-member `pred` interprets each member's OWN verdict schema (no convention
78
+ * on members); the fold's output is the canonical {@link PANEL_VERDICT}. Branded
79
+ * canonical, so pairing it with an explicit `outcome` is a construction error.
80
+ */
81
+ export function majority(pred: (v: Output) => boolean): FoldFn {
82
+ return brandCanonicalFold("majority", (verdicts) => tally(verdicts, pred, (pass, fail) => pass > fail));
83
+ }
84
+
85
+ /** Sugar fold — unanimous: the panel passes iff EVERY member passes `pred` (one fail vetoes). */
86
+ export function all(pred: (v: Output) => boolean): FoldFn {
87
+ return brandCanonicalFold("all", (verdicts) => tally(verdicts, pred, (pass, fail) => pass > 0 && fail === 0));
88
+ }
89
+
90
+ /** Sugar fold — veto/rescue: the panel passes iff ANY member passes `pred` (one pass carries it). */
91
+ export function any(pred: (v: Output) => boolean): FoldFn {
92
+ return brandCanonicalFold("any", (verdicts) => tally(verdicts, pred, (pass) => pass > 0));
93
+ }
94
+
95
+ /**
96
+ * Single rule source for the panel shape — mirrors `judgeShapeIssues` /
97
+ * `verifyShapeIssues`. Returns human-readable violations (empty = valid);
98
+ * `panel()` throws on the first, `validateWorkflow` maps each to a load issue
99
+ * for hand-rolled literals. Takes `unknown` ON PURPOSE: typed call sites are
100
+ * already guarded by the `PanelJudge` type, so everything reaching here is an
101
+ * untyped jiti-loaded literal.
102
+ *
103
+ * Enforces: a non-empty `members` array, each member a VALID single judge with
104
+ * NO nesting (`members` is `Judge[]`), a function `fold`, and the XOR rule
105
+ * (canonical sugar ⊕ `outcome` — exactly one names the verdict schema/channel).
106
+ */
107
+ export function panelShapeIssues(candidate: unknown): string[] {
108
+ if (!candidate || typeof candidate !== "object") return ["a panel object is required"];
109
+ const p = candidate as { members?: unknown; fold?: unknown; outcome?: { name?: unknown } };
110
+ const issues: string[] = [];
111
+
112
+ if (!Array.isArray(p.members) || p.members.length === 0) {
113
+ issues.push("panel.members must be a non-empty array of judges");
114
+ } else {
115
+ for (const m of p.members) {
116
+ if (m && typeof m === "object" && (m as PanelJudge).kind === "panel") {
117
+ issues.push("panel.members may not nest another panel — members are single judges (skill or prompt)");
118
+ continue;
119
+ }
120
+ for (const issue of judgeShapeIssues(m)) issues.push(`panel member: ${issue}`);
121
+ }
122
+ }
123
+
124
+ const foldIsFn = typeof p.fold === "function";
125
+ if (!foldIsFn) {
126
+ issues.push("panel.fold must be a function reducing the member verdicts to the panel's decision");
127
+ }
128
+
129
+ // The XOR rule — a sugar fold OWNS the canonical verdict (no `outcome`); a raw
130
+ // fold REQUIRES an `outcome` to name + validate its channel. Never both.
131
+ const isSugar = foldIsFn && marksCanonicalFold(p.fold as FoldFn);
132
+ const hasOutcome = p.outcome !== undefined;
133
+ if (isSugar && hasOutcome) {
134
+ issues.push(
135
+ "a canonical fold (majority/all/any) publishes the built-in PANEL_VERDICT — drop `outcome` (sugar ⊕ outcome)",
136
+ );
137
+ }
138
+ if (foldIsFn && !isSugar && !hasOutcome) {
139
+ issues.push("a custom (raw) fold requires an `outcome` naming + validating its verdict channel (raw ⊕ outcome)");
140
+ }
141
+ if (hasOutcome && !p.outcome?.name) {
142
+ issues.push("panel.outcome must carry a `name` so the folded verdict publishes to its own named channel");
143
+ }
144
+
145
+ return issues;
146
+ }
147
+
148
+ /** Authoring input for {@link panel} — the `PanelJudge` minus the injected `kind` discriminator. */
149
+ export interface PanelSpec {
150
+ members: readonly Judge[];
151
+ fold: FoldFn;
152
+ outcome?: NamedOutcome;
153
+ }
154
+
155
+ /**
156
+ * Promote a panel literal to a validated `PanelJudge` — injects the
157
+ * `kind: "panel"` discriminator and throws on the first shape issue, so a
158
+ * `panel(...)`-authored value is correct by construction (cf. `judge()` /
159
+ * `defineRoute`). The judge SITES already accept it through the widened
160
+ * `AnyJudge` slot; their member dispatch + fold-close publish arrive in the
161
+ * execution phases, so `assess`/`verify` don't yet route a panel here.
162
+ */
163
+ export function panel(spec: PanelSpec): PanelJudge {
164
+ const candidate: PanelJudge = { kind: "panel", ...spec };
165
+ assertShape("panel", panelShapeIssues(candidate));
166
+ return candidate;
167
+ }
168
+
169
+ /**
170
+ * The channel a panel's FOLDED verdict publishes to — the author's
171
+ * `outcome.name` on the custom path, or the `<stage>-panel` convention on the
172
+ * canonical path (sugar fold, no `outcome`). ONE definition so the load gate
173
+ * (`validateWorkflow`) and the panel-close publish (later phases) can never
174
+ * drift on the name. Member verdicts publish to their OWN `outcome.name`
175
+ * channels; this is only the fold's slot.
176
+ */
177
+ export function panelVerdictChannel(p: PanelJudge, stageName: string): string {
178
+ return p.outcome?.name ?? `${stageName}-panel`;
179
+ }
180
+
181
+ /**
182
+ * Synthetic `produces` def the panel-close publish lands the FOLDED verdict
183
+ * under — the twin of `judgeStageDef` (which a single MEMBER runs on). The
184
+ * publish channel is resolved ONCE through {@link panelVerdictChannel} and baked
185
+ * into `outcome.name`, so the canonical path's per-stage `<stage>-panel` channel
186
+ * OVERRIDES `PANEL_VERDICT_OUTCOME`'s fallback name (distinct panel stages never
187
+ * collide) and the custom path keeps the author's own `outcome`. The folded
188
+ * Output carries no artifact, so `applyCompletedStage` leaves the rolling primary
189
+ * untouched and only appends to the named channel. ONE construction site —
190
+ * the live publish (`loop.ts`) and the resume fold (`runner/resume.ts`) share it,
191
+ * so the two paths can never drift on the def or the channel.
192
+ */
193
+ export function panelVerdictDef(p: PanelJudge, stageName: string): StageDef {
194
+ const base = p.outcome ?? PANEL_VERDICT_OUTCOME;
195
+ return { kind: "produces", outcome: { ...base, name: panelVerdictChannel(p, stageName) }, sessionPolicy: "fresh" };
196
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Verify — the per-stage post-condition desugared to a degenerate assess loop.
3
+ * `verify()` builds the `VerifySpec` a stage carries on its `verify` field;
4
+ * `synthesizeVerifyLoop` is the desugar the runner consults (via
5
+ * `effectiveLoopOf`). Runner-free — safe on `registration`.
6
+ */
7
+
8
+ import type { AssessLoop, VerifySpec } from "../api.js";
9
+ import { assertShape } from "../judge.js";
10
+ import { judgeSlotShapeIssues, VERIFY_LOOP_DEFAULTS } from "./constructors.js";
11
+
12
+ /**
13
+ * Per-stage post-condition judge: after each attempt of the stage completes,
14
+ * `judge` grades it and `done(verdict)` gates advancement — true → advance
15
+ * with the attempt's producer pair; false → fresh retry attempt (prompt arg
16
+ * from `feedForward`) up to `max` attempts (default 1 = gate-only), then a
17
+ * terminal "verification failed" halt. Requires `kind: "produces"` + an
18
+ * `outcome` with a `name` (workflow-level, checked at load). Composes with
19
+ * `reads` and with `prompt` dispatch (attempt 0 sends the stage's resolved
20
+ * prompt; retries send `feedForward`'s output raw); mutually exclusive with
21
+ * `loop`/`run`/continue.
22
+ *
23
+ * The runner desugars the spec into a degenerate assess loop
24
+ * (`synthesizeVerifyLoop`) run by the ONE driver — verify rides the tested
25
+ * pair-restore / per-attempt-snapshot / resume machinery rather than forking it.
26
+ */
27
+ export function verify(spec: VerifySpec): VerifySpec {
28
+ assertShape("verify", verifyShapeIssues(spec));
29
+ return spec;
30
+ }
31
+
32
+ /**
33
+ * Single rule source for the verify shape. Returns human-readable violations
34
+ * (empty array = valid). `verify()` throws on the first; `validateWorkflow`
35
+ * maps each to a load issue for hand-rolled literals that bypassed the
36
+ * factory (jiti-loaded configs erase TS types). Same pattern as
37
+ * `judgeShapeIssues` / `judge()`.
38
+ */
39
+ export function verifyShapeIssues(candidate: unknown): string[] {
40
+ if (!candidate || typeof candidate !== "object") return ["a verify object is required"];
41
+ const v = candidate as Partial<VerifySpec>;
42
+ // The judge slot is an `AnyJudge` — route the panel-vs-single shape dispatch
43
+ // through the shared `judgeSlotShapeIssues` (one rule source per shape).
44
+ const judgeIssues = judgeSlotShapeIssues(v.judge);
45
+ const issues: string[] = [...judgeIssues];
46
+ if (typeof v.done !== "function") {
47
+ issues.push("verify requires `done` to be a function deciding pass/fail from the verdict");
48
+ }
49
+ if (v.max !== undefined && (!Number.isInteger(v.max) || v.max < 1)) {
50
+ issues.push(`verify.max: ${v.max} — must be an integer >= 1 (run.maxIterations caps the upper bound)`);
51
+ }
52
+ if (v.feedForward !== undefined && typeof v.feedForward !== "function") {
53
+ issues.push("verify `feedForward` must be a function building the next attempt's prompt arg");
54
+ }
55
+ if ((v.max ?? 1) > 1 && v.feedForward === undefined) {
56
+ issues.push(
57
+ "verify.max > 1 requires `feedForward` — without it the retried prompt would be byte-identical to the original",
58
+ );
59
+ }
60
+ return issues;
61
+ }
62
+
63
+ /**
64
+ * Unreachable by construction: the driver's cap check precedes the
65
+ * feedForward call (loop.ts pullNext), so a gate-only verify (`max` 1, the
66
+ * only shape allowed to omit `feedForward`) caps before a second attempt
67
+ * could ever ask for an arg. A throw here means that invariant broke
68
+ * — fail loudly (propagates to the runner's single catch) rather than
69
+ * silently dispatching an empty-arg prompt.
70
+ */
71
+ const NEVER_FEED_FORWARD = (): string => {
72
+ throw new Error("verify: feedForward invoked on a gate-only verify (max 1) — driver invariant violated");
73
+ };
74
+
75
+ /**
76
+ * The desugar: a `VerifySpec` as a degenerate assess loop — the shared
77
+ * `JudgedRepetition` fields flow straight through (`max` defaulted to 1 for
78
+ * the gate-only shape); the cap policy is always `"halt"`
79
+ * (a failing final verdict = "verification failed"; `done` wins over the cap
80
+ * so a pass on the final attempt is a normal completion), and `result:
81
+ * "last"` restores the last attempt's producer pair at loop advance.
82
+ * Allocates per call — callers cache (LoopEntry live; OpenGeneration on the
83
+ * fold), and nothing compares loop identity.
84
+ *
85
+ * NOT re-exported from registration.ts — runtime plumbing, not authoring
86
+ * surface (precedent: `judgeStageDef`).
87
+ */
88
+ export function synthesizeVerifyLoop(v: VerifySpec): AssessLoop {
89
+ const d = VERIFY_LOOP_DEFAULTS;
90
+ return {
91
+ kind: "assess",
92
+ judge: v.judge,
93
+ done: v.done,
94
+ feedForward: v.feedForward ?? NEVER_FEED_FORWARD,
95
+ max: v.max ?? d.max,
96
+ onCap: d.onCap,
97
+ result: d.result,
98
+ };
99
+ }
package/messages.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  /**
2
2
  * User-facing message constants.
3
- * - `STATUS_*` via `ctx.ui.setStatus` — persists across `newSession`.
4
3
  * - `MSG_*` / `ERR_*` via `ctx.ui.notify` — one-shot; may be repainted by
5
- * Pi's session transition (the status line is the durable channel).
4
+ * Pi's session transition.
6
5
  * - `FAIL_*` — structured terminal-failure descriptors (see `FailureText`).
7
6
  *
8
7
  * Audience split: this module is the UI/runtime constants. The
@@ -11,15 +10,12 @@
11
10
  * `/wf` usage strings live in command.ts / preview.ts.
12
11
  */
13
12
 
14
- export const STATUS_KEY = "rpiv-workflow";
15
-
16
13
  /**
17
14
  * One structured descriptor per terminal-failure kind — the `toast` (the
18
15
  * one-shot `ctx.ui.notify` line) and the `error` (what lands in
19
16
  * `state.termination.error` + the JSONL row's `errMsg`) rendered from ONE
20
- * factory so the two channels can never drift again (D5 — the old MSG_/ERR_
21
- * twin constants had already diverged in content). Halt sites hand the
22
- * descriptor to `failedArgs`/`abortedArgs` (audit.ts) or spread it into
17
+ * factory so the two channels can't drift. Halt sites hand the
18
+ * descriptor to `failedArgs`/`abortedArgs` (messages.ts) or spread it into
23
19
  * `StagePreflightError`.
24
20
  */
25
21
  export interface FailureText {
@@ -27,9 +23,6 @@ export interface FailureText {
27
23
  error: string;
28
24
  }
29
25
 
30
- export const STATUS_STAGE = (stage: number, total: number, skill: string) => `rpiv: stage ${stage}/${total} — ${skill}`;
31
-
32
- export const MSG_STAGE_COMPLETE = (skill: string) => `✓ ${skill} completed`;
33
26
  export const MSG_STAGE_FAILED = (skill: string) => `✗ ${skill} failed — stopping workflow`;
34
27
 
35
28
  export const FAIL_STAGE_ABORTED = (skill: string): FailureText => ({
@@ -58,8 +51,6 @@ export const FAIL_WORKFLOW_ABORTED = (stage: string): FailureText => ({
58
51
  error: `workflow aborted before stage "${stage}" (signal)`,
59
52
  });
60
53
 
61
- export const MSG_VALIDATION_RETRY = (skill: string, attempt: number) =>
62
- `rpiv: ${skill} output validation failed — asking agent to fix (attempt ${attempt})`;
63
54
  export const FAIL_VALIDATION_EXHAUSTED = (skill: string, failures: string): FailureText => ({
64
55
  toast: `rpiv: ${skill} output validation exhausted retries`,
65
56
  error: `${skill} output validation failed after retries: ${failures}`,
@@ -99,29 +90,11 @@ export const FAIL_MISSING_NAMED_READ = (currentSkill: string, name: string, stag
99
90
  error: `Stage ${stageNumber} (${currentSkill}) reads "${name}" but state.named["${name}"] is empty; check that an upstream produces stage publishes this name`,
100
91
  });
101
92
 
102
- export const FAIL_BACKWARD_JUMP_EXHAUSTED = (jumps: number, max: number): FailureText => ({
103
- toast: `rpiv: backward-jump limit exceeded (${jumps}/${max}) — stopping workflow to prevent infinite loop`,
104
- error: `Backward-jump limit exceeded: ${jumps} backward jumps (max ${max})`,
93
+ export const FAIL_BACKWARD_JUMP_EXHAUSTED = (stage: string, revisits: number, max: number): FailureText => ({
94
+ toast: `rpiv: backward-jump limit exceeded — "${stage}" re-entered ${revisits} times (max ${max}) — stopping workflow to prevent infinite loop`,
95
+ error: `Backward-jump limit exceeded: stage "${stage}" re-entered ${revisits} times (max ${max})`,
105
96
  });
106
97
 
107
- /**
108
- * Status line for one loop unit. `skill` is the unit's dispatched skill body
109
- * (the judge's skill — or the synthetic `<parent>-judge` label — on a judge
110
- * unit); `label` is the unit's display tag (`"phase 2/5"`, `"r0·judge"`).
111
- * One template for all three loop kinds — the retired fanout/iterate
112
- * templates were byte-identical; assess threads its round/phase cursor as
113
- * the label.
114
- */
115
- export const STATUS_LOOP_UNIT = (stage: number, total: number, skill: string, label: string) =>
116
- `rpiv: stage ${stage}/${total} — ${skill} (${label})`;
117
-
118
- /**
119
- * Per-unit completion toast — labeled so eight units of one fanout read as
120
- * eight distinct completions, not eight copies of the stage banner (the loop
121
- * end still owns MSG_STAGE_COMPLETE).
122
- */
123
- export const MSG_UNIT_COMPLETE = (skill: string, label: string) => `✓ ${skill} (${label})`;
124
-
125
98
  /**
126
99
  * A loop produced zero units (push: empty array handled upstream as
127
100
  * single-stage fall-through, so this fires only for a pull loop whose FIRST
@@ -316,6 +289,15 @@ export const MSG_RESUME_REATTACHED = (skill: string) => `↻ ${skill}: reattache
316
289
  export const MSG_RESUME_SESSION_FALLBACK = (skill: string, why: string) =>
317
290
  `rpiv: ${skill} — ${why}; re-running the stage from scratch`;
318
291
 
292
+ /**
293
+ * One notice when a `sessionPolicy: "continue"` stage has no predecessor session
294
+ * to fork — the start stage (nothing to continue), a stage right after a loop
295
+ * with no prior single session, or the predecessor's session file is gone. The
296
+ * stage degrades to a fresh dispatch rather than refusing.
297
+ */
298
+ export const MSG_CONTINUE_FALLBACK = (skill: string) =>
299
+ `rpiv: ${skill} — no prior session to continue; running the stage fresh`;
300
+
319
301
  /**
320
302
  * Sent to the AGENT when a stage reattaches to its interrupted session
321
303
  * (model-facing prompt text — promotion already missed, so the artifact
@@ -375,3 +357,46 @@ export const MSG_WORKFLOW_NOT_FOUND = (name: string) => `/wf: workflow "${name}"
375
357
  */
376
358
  export const MSG_NO_WORKFLOWS_REGISTERED =
377
359
  "/wf: no workflows registered — install a sibling that bundles workflows or author one in `.rpiv/workflows/config.ts`";
360
+
361
+ /**
362
+ * The toast + JSONL halves of a terminal failure, paired by construction.
363
+ * Build via `failedArgs` / `abortedArgs` (or `stopFailureArgs`' switch, in
364
+ * audit.ts) so a halt site can't mismatch status and notify level.
365
+ */
366
+ export interface TerminalFailureArgs {
367
+ status: "failed" | "aborted";
368
+ notifyMsg: string;
369
+ notifyLevel: "warning" | "error";
370
+ errMsg: string;
371
+ }
372
+
373
+ /**
374
+ * The ONE `(status, notifyLevel)` pairing — notifyLevel is DERIVED from status
375
+ * (failed → error, aborted → warning), so a mismatch is unrepresentable. The
376
+ * overload-resolution body for `failedArgs`/`abortedArgs` lives here once.
377
+ * Modeled after `stopFailureArgs` (parameterize by status).
378
+ */
379
+ function terminalArgsOf(status: "failed" | "aborted", a: FailureText | string, b?: string): TerminalFailureArgs {
380
+ const f = typeof a === "string" ? { toast: a, error: b as string } : a;
381
+ return { status, notifyMsg: f.toast, notifyLevel: status === "failed" ? "error" : "warning", errMsg: f.error };
382
+ }
383
+
384
+ /**
385
+ * Argument constructors for `recordTerminalFailure` — the
386
+ * `{status, notifyMsg, notifyLevel, errMsg}` quadruple every halt site used
387
+ * to spell by hand. One per terminal status: failures notify at `"error"`,
388
+ * aborts at `"warning"` (cooperative cancellation is expected, not
389
+ * exceptional). 1-line facades over `terminalArgsOf` so the status/level
390
+ * pairing lives once.
391
+ */
392
+ export function failedArgs(failure: FailureText): TerminalFailureArgs;
393
+ export function failedArgs(notifyMsg: string, errMsg: string): TerminalFailureArgs;
394
+ export function failedArgs(a: FailureText | string, b?: string): TerminalFailureArgs {
395
+ return terminalArgsOf("failed", a, b);
396
+ }
397
+
398
+ export function abortedArgs(failure: FailureText): TerminalFailureArgs;
399
+ export function abortedArgs(notifyMsg: string, errMsg: string): TerminalFailureArgs;
400
+ export function abortedArgs(a: FailureText | string, b?: string): TerminalFailureArgs {
401
+ return terminalArgsOf("aborted", a, b);
402
+ }
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  export { type DirectoryPathCollectorOpts, directoryPathCollector } from "./directory-path.js";
13
+ export { type TextScanCollectorOpts, textScanCollector } from "./text-scan.js";
13
14
  export { type ToolCall, type ToolCallCollectorOpts, toolCallCollector } from "./tool-call.js";
14
15
  export { type TranscriptPathCollectorOpts, transcriptPathCollector } from "./transcript-path.js";
15
16
  export { unionCollectors } from "./union.js";
@@ -0,0 +1,47 @@
1
+ /**
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
6
+ * domain-specific collectors by wrapping this + supplying a pattern + handle
7
+ * constructor (`directoryPathCollector` already delegates this way to
8
+ * `transcriptPathCollector`).
9
+ *
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.
13
+ */
14
+
15
+ import type { ArtifactHandle } from "../../handle.js";
16
+ import type { ArtifactCollector } from "../../output-spec.js";
17
+ import { defineCollector } from "../../output-spec.js";
18
+ import { lastMatchInBranch } from "../../transcript.js";
19
+
20
+ export interface TextScanCollectorOpts {
21
+ /**
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.
25
+ */
26
+ pattern: RegExp;
27
+ /** Constructs the artifact handle from the matched string (e.g. `fs`, `url`). */
28
+ toHandle: (hit: string) => ArtifactHandle;
29
+ /** Noun for the fatal-on-miss message ("path" / "URL"). */
30
+ noun: string;
31
+ }
32
+
33
+ export function textScanCollector(opts: TextScanCollectorOpts): ArtifactCollector {
34
+ const { pattern, toHandle, noun } = opts;
35
+ return defineCollector({
36
+ collect: (ctx) => {
37
+ const hit = lastMatchInBranch(ctx.branch, pattern, ctx.branchOffset);
38
+ if (!hit) {
39
+ return {
40
+ kind: "fatal",
41
+ message: `${ctx.skill} finished without producing a ${noun} matching ${pattern.source}`,
42
+ };
43
+ }
44
+ return { kind: "ok", artifacts: [{ handle: toHandle(hit), role: "primary" }] };
45
+ },
46
+ });
47
+ }
@@ -20,9 +20,8 @@
20
20
 
21
21
  import { fs } from "../../handle.js";
22
22
  import type { ArtifactCollector } from "../../output-spec.js";
23
- import { defineCollector } from "../../output-spec.js";
24
- import { lastMatchInBranch } from "../../transcript.js";
25
23
  import { requireOpt } from "./require-opt.js";
24
+ import { textScanCollector } from "./text-scan.js";
26
25
 
27
26
  export interface TranscriptPathCollectorOpts {
28
27
  /**
@@ -36,17 +35,5 @@ export interface TranscriptPathCollectorOpts {
36
35
 
37
36
  export function transcriptPathCollector(opts: TranscriptPathCollectorOpts): ArtifactCollector {
38
37
  requireOpt("transcriptPathCollector", "pattern", "is required and must be a RegExp", opts.pattern instanceof RegExp);
39
- const pattern = opts.pattern;
40
- return defineCollector({
41
- collect: (ctx) => {
42
- const path = lastMatchInBranch(ctx.branch, pattern, ctx.branchOffset);
43
- if (!path) {
44
- return {
45
- kind: "fatal",
46
- message: `${ctx.skill} finished without producing a path matching ${pattern.source}`,
47
- };
48
- }
49
- return { kind: "ok", artifacts: [{ handle: fs(path), role: "primary" }] };
50
- },
51
- });
38
+ return textScanCollector({ pattern: opts.pattern, toHandle: fs, noun: "path" });
52
39
  }
@@ -29,6 +29,7 @@
29
29
  */
30
30
 
31
31
  import type { Artifact } from "../../handle.js";
32
+ import { throwInvalid } from "../../internal-utils.js";
32
33
  import type { ArtifactCollector, CollectResult } from "../../output-spec.js";
33
34
  import { defineCollector } from "../../output-spec.js";
34
35
 
@@ -37,7 +38,7 @@ export type UnionSnapshot = unknown[] | undefined;
37
38
 
38
39
  export function unionCollectors(...collectors: ArtifactCollector[]): ArtifactCollector<UnionSnapshot> {
39
40
  if (collectors.length === 0) {
40
- throw new Error("unionCollectors: at least one collector is required");
41
+ throwInvalid("unionCollectors", "at least one collector is required");
41
42
  }
42
43
  const anySnapshots = collectors.some((c) => typeof c.snapshot === "function");
43
44
  return defineCollector<UnionSnapshot>({
@@ -12,9 +12,8 @@
12
12
 
13
13
  import { url } from "../../handle.js";
14
14
  import type { ArtifactCollector } from "../../output-spec.js";
15
- import { defineCollector } from "../../output-spec.js";
16
- import { lastMatchInBranch } from "../../transcript.js";
17
15
  import { requireOpt } from "./require-opt.js";
16
+ import { textScanCollector } from "./text-scan.js";
18
17
 
19
18
  /**
20
19
  * Conservative URL matcher — `https?://` plus non-whitespace, stopping
@@ -37,16 +36,5 @@ export function urlCollector(opts: UrlCollectorOpts = {}): ArtifactCollector {
37
36
  opts.pattern === undefined || opts.pattern instanceof RegExp,
38
37
  );
39
38
  const pattern = opts.pattern ?? DEFAULT_URL_PATTERN;
40
- return defineCollector({
41
- collect: (ctx) => {
42
- const href = lastMatchInBranch(ctx.branch, pattern, ctx.branchOffset);
43
- if (!href) {
44
- return {
45
- kind: "fatal",
46
- message: `${ctx.skill} finished without producing a URL matching ${pattern.source}`,
47
- };
48
- }
49
- return { kind: "ok", artifacts: [{ handle: url(href), role: "primary" }] };
50
- },
51
- });
39
+ return textScanCollector({ pattern, toHandle: url, noun: "URL" });
52
40
  }
@@ -72,7 +72,7 @@ async function collectDiffArtifacts(
72
72
  if (status === undefined) {
73
73
  // git worked at snapshot time and fails now — an environment break,
74
74
  // not "no changes." `ok []` here would route downstream logic on
75
- // fabricated nothing-happened data (T10).
75
+ // fabricated nothing-happened data.
76
76
  return {
77
77
  kind: "fatal",
78
78
  message: `${ctx.skill}: git status worked at snapshot time but failed after the stage — cannot diff the workspace`,