@juicesharp/rpiv-workflow 1.19.0 → 1.20.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 (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
package/messages.ts CHANGED
@@ -3,72 +3,72 @@
3
3
  * - `STATUS_*` via `ctx.ui.setStatus` — persists across `newSession`.
4
4
  * - `MSG_*` / `ERR_*` via `ctx.ui.notify` — one-shot; may be repainted by
5
5
  * Pi's session transition (the status line is the durable channel).
6
+ * - `FAIL_*` — structured terminal-failure descriptors (see `FailureText`).
7
+ *
8
+ * Audience split: this module is the UI/runtime constants. The
9
+ * model-facing validation-retry prompt lives beside its only consumer
10
+ * (sessions/extraction.ts); legacy-migration notices live in load/legacy.ts;
11
+ * `/wf` usage strings live in command.ts / preview.ts.
6
12
  */
7
13
 
8
- import { join } from "node:path";
9
-
10
14
  export const STATUS_KEY = "rpiv-workflow";
11
15
 
12
- export const STATUS_STAGE = (stage: number, total: number, skill: string) => `rpiv: stage ${stage}/${total} — ${skill}`;
13
-
14
16
  /**
15
- * Status line for a fanout unit. `skill` is the node's resolved skill body,
16
- * `label` is whatever the user's `FanoutFn` returned for this unit
17
- * (`"phase 2/5"`, `"task 3/8"`, ...). The runner adds no implicit wording.
17
+ * One structured descriptor per terminal-failure kind — the `toast` (the
18
+ * one-shot `ctx.ui.notify` line) and the `error` (what lands in
19
+ * `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
23
+ * `StagePreflightError`.
18
24
  */
19
- export const STATUS_FANOUT_UNIT = (stage: number, total: number, skill: string, label: string) =>
20
- `rpiv: stage ${stage}/${total} — ${skill} (${label})`;
25
+ export interface FailureText {
26
+ toast: string;
27
+ error: string;
28
+ }
21
29
 
22
- /**
23
- * Status line for an iterate unit. Same shape as `STATUS_FANOUT_UNIT` — the
24
- * status denominator is the reachable-stage count, so the stage number repeats
25
- * across units and `label` (e.g. `"phase 2/3 — Vocabulary"`) disambiguates.
26
- */
27
- export const STATUS_ITERATE_UNIT = (stage: number, total: number, skill: string, label: string) =>
28
- `rpiv: stage ${stage}/${total} — ${skill} (${label})`;
30
+ export const STATUS_STAGE = (stage: number, total: number, skill: string) => `rpiv: stage ${stage}/${total} — ${skill}`;
29
31
 
30
32
  export const MSG_STAGE_COMPLETE = (skill: string) => `✓ ${skill} completed`;
31
33
  export const MSG_STAGE_FAILED = (skill: string) => `✗ ${skill} failed — stopping workflow`;
32
- export const MSG_STAGE_ABORTED = (skill: string) => `⏸ ${skill} aborted (ESC) — stopping workflow`;
33
- export const MSG_STAGE_TRUNCATED = (skill: string) =>
34
- `✗ ${skill} truncated — model hit output cap mid-reply, stopping workflow`;
35
- export const MSG_STAGE_TOOL_STALLED = (skill: string) => `✗ ${skill} tool loop did not settle — stopping workflow`;
36
- export const MSG_STAGE_NO_RESPONSE = (skill: string) => `✗ ${skill} produced no response — stopping workflow`;
37
-
38
- export const ERR_STAGE_ABORTED = (skill: string) => `${skill} aborted by user (ESC)`;
39
- export const ERR_STAGE_TRUNCATED = (skill: string) => `${skill} truncated — model hit output-length cap mid-reply`;
40
- export const ERR_STAGE_TOOL_STALLED = (skill: string) =>
41
- `${skill} tool loop did not settle before the orchestrator inspected the branch`;
42
- export const ERR_STAGE_NO_RESPONSE = (skill: string) => `${skill} produced no assistant message`;
34
+
35
+ export const FAIL_STAGE_ABORTED = (skill: string): FailureText => ({
36
+ toast: `⏸ ${skill} aborted (ESC) — stopping workflow`,
37
+ error: `${skill} aborted by user (ESC)`,
38
+ });
39
+ export const FAIL_STAGE_TRUNCATED = (skill: string): FailureText => ({
40
+ toast: `✗ ${skill} truncated — model hit output cap mid-reply, stopping workflow`,
41
+ error: `${skill} truncated — model hit output-length cap mid-reply`,
42
+ });
43
+ export const FAIL_STAGE_TOOL_STALLED = (skill: string): FailureText => ({
44
+ toast: `✗ ${skill} tool loop did not settle — stopping workflow`,
45
+ error: `${skill} tool loop did not settle before the orchestrator inspected the branch`,
46
+ });
47
+ export const FAIL_STAGE_NO_RESPONSE = (skill: string): FailureText => ({
48
+ toast: `✗ ${skill} produced no response — stopping workflow`,
49
+ error: `${skill} produced no assistant message`,
50
+ });
43
51
 
44
52
  export const MSG_WORKFLOW_COMPLETE = (stages: number) => `rpiv: workflow complete (${stages} stages)`;
45
53
  export const MSG_WORKFLOW_CANCELLED = "rpiv: workflow cancelled";
46
54
 
47
55
  // Programmatic abort via RunWorkflowOptions.signal — checked between stages.
48
- export const MSG_WORKFLOW_ABORTED = "rpiv: workflow aborted";
49
- export const ERR_WORKFLOW_ABORTED = (stage: string) => `workflow aborted before stage "${stage}" (signal)`;
56
+ export const FAIL_WORKFLOW_ABORTED = (stage: string): FailureText => ({
57
+ toast: "rpiv: workflow aborted",
58
+ error: `workflow aborted before stage "${stage}" (signal)`,
59
+ });
50
60
 
51
61
  export const MSG_VALIDATION_RETRY = (skill: string, attempt: number) =>
52
62
  `rpiv: ${skill} output validation failed — asking agent to fix (attempt ${attempt})`;
53
- export const MSG_VALIDATION_EXHAUSTED = (skill: string) => `rpiv: ${skill} output validation exhausted retries`;
54
- export const ERR_VALIDATION_FAILED = (skill: string, failures: string) =>
55
- `${skill} output validation failed after retries: ${failures}`;
63
+ export const FAIL_VALIDATION_EXHAUSTED = (skill: string, failures: string): FailureText => ({
64
+ toast: `rpiv: ${skill} output validation exhausted retries`,
65
+ error: `${skill} output validation failed after retries: ${failures}`,
66
+ });
56
67
 
57
- /**
58
- * Sent to the agent as a follow-up message when an output-schema validation
59
- * fails — instructs the agent to re-write the artifact at the same path with
60
- * a corrected frontmatter. `errorLines` is a pre-joined bullet list (one
61
- * line per failure) so the factory stays single-arg-typed.
62
- */
63
- export const MSG_VALIDATION_RETRY_PROMPT = (skill: string, errorLines: string) =>
64
- `The ${skill} artifact's frontmatter doesn't satisfy the expected output schema. ` +
65
- "Fix only the fields listed below, then re-write the artifact at the same path (don't move it):\n\n" +
66
- `${errorLines}`;
67
-
68
- export const MSG_INPUT_VALIDATION_FAILED = (currentSkill: string, prevSkill: string) =>
69
- `✗ ${currentSkill} input validation failed — upstream ${prevSkill} produced invalid data`;
70
- export const ERR_INPUT_VALIDATION_FAILED = (currentSkill: string, prevSkill: string, failures: string) =>
71
- `Input validation failed for '${currentSkill}': upstream '${prevSkill}' produced invalid data: ${failures}`;
68
+ export const FAIL_INPUT_VALIDATION = (currentSkill: string, prevSkill: string, failures: string): FailureText => ({
69
+ toast: `✗ ${currentSkill} input validation failed — upstream ${prevSkill} produced invalid data`,
70
+ error: `Input validation failed for '${currentSkill}': upstream '${prevSkill}' produced invalid data: ${failures}`,
71
+ });
72
72
 
73
73
  /**
74
74
  * Bound on a single schema-validate call. Sync schemas resolve in one
@@ -81,10 +81,10 @@ export const ERR_INPUT_VALIDATION_FAILED = (currentSkill: string, prevSkill: str
81
81
  export const ERR_SCHEMA_TIMEOUT = (slot: "outputSchema" | "inputSchema", ms: number) =>
82
82
  `${slot} validation exceeded ${ms}ms — schema's ~standard.validate did not settle`;
83
83
 
84
- export const MSG_MISSING_ARTIFACT = (currentSkill: string) =>
85
- `✗ ${currentSkill} has no upstream artifact to consume — stopping workflow`;
86
- export const ERR_MISSING_ARTIFACT = (currentSkill: string, stageNumber: number) =>
87
- `Stage ${stageNumber} (${currentSkill}) has no upstream artifactPath; only stage 1 may consume the user's original input`;
84
+ export const FAIL_MISSING_ARTIFACT = (currentSkill: string, stageNumber: number): FailureText => ({
85
+ toast: `✗ ${currentSkill} has no upstream artifact to consume — stopping workflow`,
86
+ error: `Stage ${stageNumber} (${currentSkill}) has no upstream artifactPath; only stage 1 may consume the user's original input`,
87
+ });
88
88
 
89
89
  /**
90
90
  * A stage declares `reads: [..., name, ...]` but `state.named[name]` is
@@ -94,42 +94,87 @@ export const ERR_MISSING_ARTIFACT = (currentSkill: string, stageNumber: number)
94
94
  * the producer was authored with no outcome and a name that doesn't
95
95
  * match any stage record key.
96
96
  */
97
- export const MSG_MISSING_NAMED_READ = (currentSkill: string, name: string) =>
98
- `✗ ${currentSkill} reads "${name}" but no upstream produces stage has published it yet — stopping workflow`;
99
- export const ERR_MISSING_NAMED_READ = (currentSkill: string, name: string, stageNumber: number) =>
100
- `Stage ${stageNumber} (${currentSkill}) reads "${name}" but state.named["${name}"] is empty; check that an upstream produces stage publishes this name`;
97
+ export const FAIL_MISSING_NAMED_READ = (currentSkill: string, name: string, stageNumber: number): FailureText => ({
98
+ toast: `✗ ${currentSkill} reads "${name}" but no upstream produces stage has published it yet — stopping workflow`,
99
+ error: `Stage ${stageNumber} (${currentSkill}) reads "${name}" but state.named["${name}"] is empty; check that an upstream produces stage publishes this name`,
100
+ });
101
101
 
102
- export const MSG_BACKWARD_JUMP_EXHAUSTED = (jumps: number, max: number) =>
103
- `rpiv: backward-jump limit exceeded (${jumps}/${max}) — stopping workflow to prevent infinite loop`;
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})`,
105
+ });
104
106
 
105
- export const ERR_BACKWARD_JUMP_EXHAUSTED = (jumps: number, max: number) =>
106
- `Backward-jump limit exceeded: ${jumps} backward jumps (max ${max})`;
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})`;
107
117
 
108
118
  /**
109
- * An `iterate` stage's generator kept returning units past the run-wide
110
- * `maxIterations` safety cap (the backstop for a generator that never returns
111
- * `null`). Stops the stage with a terminal failure, mirroring the
112
- * backward-jump guard.
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).
113
122
  */
114
- export const MSG_ITERATIONS_EXHAUSTED = (count: number, max: number) =>
115
- `rpiv: iterate limit exceeded (${count}/${max}) — stopping workflow to prevent an unbounded generator`;
123
+ export const MSG_UNIT_COMPLETE = (skill: string, label: string) => `✓ ${skill} (${label})`;
116
124
 
117
- export const ERR_ITERATIONS_EXHAUSTED = (count: number, max: number) =>
118
- `Iterate limit exceeded: generator produced ${count} units (max ${max})`;
125
+ /**
126
+ * A loop produced zero units (push: empty array handled upstream as
127
+ * single-stage fall-through, so this fires only for a pull loop whose FIRST
128
+ * call returned null). Not an error — nothing published, the primary stays at
129
+ * the entry pair; warn so the author notices the empty input.
130
+ */
131
+ export const MSG_LOOP_ZERO_UNITS = (skill: string) =>
132
+ `rpiv: ${skill} iterate loop produced zero units — nothing published, advancing`;
119
133
 
120
134
  /**
121
- * An `iterate` stage's generator returned null on its FIRST call — the stage
122
- * produced zero units. Not an error (a legitimately empty input is valid), but
123
- * the stage published nothing and left the primary artifact untouched, so warn
124
- * the author rather than silently advancing.
135
+ * A loop hit its effective cap (`min(loop.max, run.maxIterations)`) under
136
+ * `onCap: "halt"` — terminal failure, mirroring the backward-jump guard.
125
137
  */
126
- export const MSG_ITERATE_ZERO_UNITS = (skill: string) =>
127
- `rpiv: ${skill} iterate produced zero units — nothing published, advancing`;
138
+ export const FAIL_LOOP_CAP_HALT = (count: number, max: number): FailureText => ({
139
+ toast: `rpiv: loop cap exceeded (${count}/${max}) — stopping workflow to prevent an unbounded loop`,
140
+ error: `Loop cap exceeded: ${count} units (max ${max})`,
141
+ });
128
142
 
129
- export const MSG_AUDIT_WRITE_FAILED = (skill: string) =>
130
- `✗ ${skill} completed but audit row could not be written — stopping workflow`;
131
- export const ERR_AUDIT_WRITE_FAILED = (skill: string) =>
132
- `${skill} completed but the JSONL audit row could not be appended; halting to keep in-memory state aligned with disk`;
143
+ /**
144
+ * A loop hit its effective cap under `onCap: "advance"` — soft-stop: warn,
145
+ * land the {type:"loop-cap"} telemetry row, keep the projected result,
146
+ * advance. Deliberately no ERR_ twin (not a failure).
147
+ */
148
+ export const MSG_LOOP_CAP_ADVANCE = (skill: string, max: number) =>
149
+ `rpiv: ${skill} loop reached its cap (${max}) — projecting the configured result and advancing`;
150
+
151
+ /**
152
+ * A verify-bearing stage exhausted its attempt budget without a passing
153
+ * verdict (the synthesized loop's `onCap: "halt"` tripped). Verify-worded —
154
+ * the author declared a post-condition, not a loop, so the loop-cap pair
155
+ * would misattribute the failure. A pass on the final attempt never reaches
156
+ * this (`done` wins over the cap).
157
+ */
158
+ export const FAIL_VERIFY_FAILED = (stage: string, attempts: number): FailureText => ({
159
+ toast: `✗ ${stage} verification failed after ${attempts} attempt${attempts === 1 ? "" : "s"} — stopping workflow`,
160
+ error: `Verification failed for "${stage}": the judge's verdict did not satisfy \`pass\` after ${attempts} attempt${attempts === 1 ? "" : "s"}`,
161
+ });
162
+
163
+ export const FAIL_AUDIT_WRITE = (skill: string): FailureText => ({
164
+ toast: `✗ ${skill} completed but audit row could not be written — stopping workflow`,
165
+ error: `${skill} completed but the JSONL audit row could not be appended; halting to keep in-memory state aligned with disk`,
166
+ });
167
+
168
+ /**
169
+ * Notified when a TERMINAL failure/aborted row could not be appended. Unlike
170
+ * routing rows this is a reconstruction input: without it the trail's last
171
+ * row reads "completed" and a later resume would route onward past the stage
172
+ * that actually failed. The run is already halting — the user (and the
173
+ * result envelope's `droppedFailureRows`) must know the trail is unsafe to
174
+ * resume from.
175
+ */
176
+ export const MSG_FAILURE_ROW_DROPPED = (stage: string) =>
177
+ `⚠ rpiv: failure row for ${stage} not persisted to audit trail — do not resume this run from disk`;
133
178
 
134
179
  export const MSG_CHAIN_ADVANCE_FAILED = (fromStage: string, reason: string) =>
135
180
  `✗ chain advance after ${fromStage} failed: ${reason} — stopping workflow`;
@@ -139,11 +184,31 @@ export const MSG_CHAIN_ADVANCE_FAILED = (fromStage: string, reason: string) =>
139
184
  * `enforceSessionInvariants` violations, session-machinery errors, and any
140
185
  * other path that escapes `runStage` directly. Distinguished from
141
186
  * `MSG_CHAIN_ADVANCE_FAILED` (which is about an edge throwing AFTER a stage
142
- * succeeded) — the user needs to see *which* stage failed to start, not
143
- * which one preceded the failure.
187
+ * succeeded) — the user needs to see *which* stage failed, not which one
188
+ * preceded the failure. Wording is deliberately neutral ("failed", not
189
+ * "failed to start"): throws from mid-stage machinery land here too.
144
190
  */
145
191
  export const MSG_STAGE_THREW = (skill: string, reason: string) =>
146
- `✗ stage ${skill} failed to start: ${reason} — stopping workflow`;
192
+ `✗ stage ${skill} failed: ${reason} — stopping workflow`;
193
+
194
+ /**
195
+ * Loop cursor reached a state its state machine forbids (e.g. a judge step
196
+ * with no completed produce behind it). `advanceCursor` makes these states
197
+ * unreachable and the resume fold's shape guards refuse corrupted trails, so
198
+ * a throw here is an internal bug surfaced with stage attribution instead of
199
+ * a bare `TypeError`.
200
+ */
201
+ export const MSG_LOOP_CURSOR_CORRUPT = (stage: string, detail: string) =>
202
+ `✗ loop stage ${stage}: cursor invariant violated — ${detail}`;
203
+
204
+ /**
205
+ * Collector/parser throws — `collect`/`parse` are the PRIMARY user extension
206
+ * points, so a throw is attributed to the throwing half (not folded into the
207
+ * generic stage-machinery wording). Lands in `state.termination.error` via
208
+ * the extraction fatal arm.
209
+ */
210
+ export const ERR_COLLECTOR_THREW = (skill: string, reason: string) => `${skill}: outcome collector threw: ${reason}`;
211
+ export const ERR_PARSER_THREW = (skill: string, reason: string) => `${skill}: outcome parser threw: ${reason}`;
147
212
 
148
213
  /**
149
214
  * Stage references a Pi skill that isn't registered with the running Pi
@@ -153,10 +218,10 @@ export const MSG_STAGE_THREW = (skill: string, reason: string) =>
153
218
  * unknown skill name would otherwise reach the model as a bare user-message
154
219
  * imperative outside the `<skill>...</skill>` contract.
155
220
  */
156
- export const MSG_SKILL_NOT_REGISTERED = (skill: string) =>
157
- `✗ ${skill} is not a registered Pi skill — stopping workflow`;
158
- export const ERR_SKILL_NOT_REGISTERED = (skill: string, stageNumber: number) =>
159
- `Stage ${stageNumber} requires Pi skill "${skill}" but no skill by that name is registered with Pi (check installed sibling packages and \`pi.skills\` manifest entries)`;
221
+ export const FAIL_SKILL_NOT_REGISTERED = (skill: string, stageNumber: number): FailureText => ({
222
+ toast: `✗ ${skill} is not a registered Pi skill — stopping workflow`,
223
+ error: `Stage ${stageNumber} requires Pi skill "${skill}" but no skill by that name is registered with Pi (check installed sibling packages and \`pi.skills\` manifest entries)`,
224
+ });
160
225
 
161
226
  /**
162
227
  * Notified live when a routing-decision row could not be appended. The chain
@@ -174,15 +239,25 @@ export const MSG_PARTIAL_ARTIFACTS = (artifactList: string) => `Artifacts produc
174
239
  export const MSG_LIFECYCLE_THREW = (event: string, reason: string) =>
175
240
  `⚠ rpiv: lifecycle listener (${event}) threw: ${reason}`;
176
241
 
242
+ /**
243
+ * Outcome snapshot hook threw — the stage still runs (snapshot is best-effort)
244
+ * but diff-based collectors will see `snapshot: undefined`. Warned once per
245
+ * run so a consistently-throwing custom snapshot can't silently disable
246
+ * diffing for every stage.
247
+ */
248
+ export const MSG_SNAPSHOT_FAILED = (stage: string, reason: string) =>
249
+ `⚠ rpiv: outcome snapshot for ${stage} threw (${reason}) — pre-stage diff degraded for this stage`;
250
+
177
251
  /**
178
252
  * Script stage's `run()` body threw. Distinct from `MSG_STAGE_THREW`
179
253
  * (which covers session-machinery and preflight throws) so users see
180
254
  * the failure surface attributed to the script function rather than to
181
255
  * the runner.
182
256
  */
183
- export const MSG_SCRIPT_THREW = (stage: string, reason: string) =>
184
- `✗ ${stage} script threw — stopping workflow: ${reason}`;
185
- export const ERR_SCRIPT_THREW = (stage: string, reason: string) => `${stage} script threw: ${reason}`;
257
+ export const FAIL_SCRIPT_THREW = (stage: string, reason: string): FailureText => ({
258
+ toast: `✗ ${stage} script threw — stopping workflow: ${reason}`,
259
+ error: `${stage} script threw: ${reason}`,
260
+ });
186
261
 
187
262
  // ---------------------------------------------------------------------------
188
263
  // Resume-refusal messages — reconstruct refusals returned in the
@@ -190,19 +265,66 @@ export const ERR_SCRIPT_THREW = (stage: string, reason: string) => `${stage} scr
190
265
  // ---------------------------------------------------------------------------
191
266
 
192
267
  export const ERR_RESUME_NO_ROWS = (runId: string) => `rpiv: run ${runId} has no recorded stages — nothing to resume`;
268
+ /**
269
+ * A stage-shaped row failed the deep shape guard. Resume REFUSES rather than
270
+ * skip: the fold replays the trail as its system of record, and a silently
271
+ * dropped row would replay a hole ("this stage never ran") and route onward
272
+ * past it.
273
+ */
274
+ export const ERR_RESUME_MALFORMED_ROW = (detail: string) =>
275
+ `rpiv: cannot resume — the run's trail contains a malformed stage row (${detail}); ` +
276
+ `resume refuses rather than replay an incomplete history`;
277
+ /**
278
+ * The run's header carries a schema version this build doesn't write —
279
+ * resume refuses rather than fold rows whose shapes it may misread.
280
+ * Absent `v` is version 1 (back-compat), so this only fires on a real bump.
281
+ */
282
+ export const ERR_RESUME_VERSION_MISMATCH = (detail: string, expected: number) =>
283
+ `rpiv: cannot resume — ${detail}, but this build reads schema v${expected}; ` +
284
+ `resume refuses rather than misread the trail`;
193
285
  export const ERR_RESUME_STAGE_GONE = (stage: string, workflow: string) =>
194
286
  `rpiv: cannot resume — stage "${stage}" from the run no longer exists in workflow "${workflow}" ` +
195
287
  `(renamed or removed)`;
196
- export const ERR_RESUME_FANOUT_MISMATCH = (stage: string) =>
197
- `rpiv: cannot resume — fanout stage "${stage}" recomputed a different unit list than the run recorded ` +
198
- `(the FanoutFn must be deterministic w.r.t. its entry artifact; resume refuses rather than re-run the wrong units)`;
199
- export const MSG_RESUME_FANOUT_MISMATCH = (stage: string) =>
200
- `rpiv: fanout "${stage}" changed on resume — cannot safely continue`;
201
- export const ERR_RESUME_ITERATE_MISMATCH = (stage: string) =>
202
- `rpiv: cannot resume — iterate stage "${stage}" recomputed a different unit than the run recorded at the resume point ` +
203
- `(the IterateFn must be deterministic w.r.t. its entry artifact + accumulated outputs; resume refuses rather than re-run the wrong unit)`;
204
- export const MSG_RESUME_ITERATE_MISMATCH = (stage: string) =>
205
- `rpiv: iterate "${stage}" changed on resume — cannot safely continue`;
288
+ /**
289
+ * Resume drift refusal — one pair for all loop kinds. The unit source
290
+ * recomputed a different unit than the run recorded at a folded boundary
291
+ * (the determinism contract: deterministic w.r.t. the fold-replayed RunState
292
+ * + accumulated outputs). Resume refuses rather than re-run the wrong units.
293
+ */
294
+ export const ERR_RESUME_LOOP_MISMATCH = (stage: string) =>
295
+ `rpiv: cannot resume — loop stage "${stage}" recomputed a different unit than the run recorded ` +
296
+ `(the unit source must be deterministic w.r.t. the replayed run state + accumulated outputs; ` +
297
+ `resume refuses rather than re-run the wrong units)`;
298
+ export const MSG_RESUME_LOOP_MISMATCH = (stage: string) =>
299
+ `rpiv: loop "${stage}" changed on resume — cannot safely continue`;
300
+
301
+ // ---------------------------------------------------------------------------
302
+ // Session-backed resume (promotion + reattach) — notify-only progress toasts
303
+ // + the fallback-ladder notice, plus the one model-facing reattach prompt
304
+ // ---------------------------------------------------------------------------
305
+
306
+ export const MSG_RESUME_PROMOTED = (skill: string) =>
307
+ `✓ ${skill}: interrupted session already produced the artifact — stage promoted to completed`;
308
+
309
+ export const MSG_RESUME_REATTACHED = (skill: string) => `↻ ${skill}: reattached to interrupted session`;
310
+
311
+ /**
312
+ * One ladder-rung notice before a session-backed resume degrades to today's
313
+ * cold re-run. `why` is a short human clause — "session file not found",
314
+ * "host cannot switch sessions" — not a dispatch key (nothing parses it).
315
+ */
316
+ export const MSG_RESUME_SESSION_FALLBACK = (skill: string, why: string) =>
317
+ `rpiv: ${skill} — ${why}; re-running the stage from scratch`;
318
+
319
+ /**
320
+ * Sent to the AGENT when a stage reattaches to its interrupted session
321
+ * (model-facing prompt text — promotion already missed, so the artifact
322
+ * was not announced or not written).
323
+ */
324
+ export const REATTACH_PROMPT = (skill: string) =>
325
+ `The previous run of /skill:${skill} in this session was interrupted. ` +
326
+ "Review the conversation above. If the work is already complete, announce the artifact path. " +
327
+ "Otherwise finish the remaining work and announce the artifact path when done.";
206
328
 
207
329
  // ---------------------------------------------------------------------------
208
330
  // Resume-refusal messages — resumeWorkflowByRef pre-resume guards (resolve →
@@ -230,9 +352,15 @@ export const MSG_NAME_COLLISION = (name: string, runId: string) => `name '${name
230
352
  export const MSG_NAME_INDEX_WRITE_FAILED = (name: string) =>
231
353
  `/wf: could not persist name "${name}" to the names index — run aborted (no run started). Check filesystem permissions for .rpiv/workflows/runs/`;
232
354
 
355
+ export const MSG_HEADER_WRITE_FAILED = (runId: string) =>
356
+ `rpiv: could not write the run header for ${runId} — run aborted (no stage executed). Check filesystem permissions for .rpiv/workflows/runs/`;
357
+
233
358
  export const MSG_NAME_IGNORED_ON_RESUME =
234
359
  "/wf: --name has no effect on @resume (the ref already identifies the run) — ignoring it";
235
360
 
361
+ export const MSG_NAME_FLAG_MID_INPUT =
362
+ "/wf: --name is only honored as the first or last token — a mid-input --name is treated as workflow input text";
363
+
236
364
  export const MSG_LOAD_ABORTED = (count: number) =>
237
365
  `/wf: ${count} ${count === 1 ? "config error" : "config errors"} — see warnings above (fix and re-run)`;
238
366
 
@@ -247,63 +375,3 @@ export const MSG_WORKFLOW_NOT_FOUND = (name: string) => `/wf: workflow "${name}"
247
375
  */
248
376
  export const MSG_NO_WORKFLOWS_REGISTERED =
249
377
  "/wf: no workflows registered — install a sibling that bundles workflows or author one in `.rpiv/workflows/config.ts`";
250
-
251
- /**
252
- * Legacy `.rpiv-workflow/` overlay directory detected at load time. The
253
- * package moved project config under the unified `.rpiv/workflows/` tree
254
- * (config.ts + packs/) alongside run state. The old directory is NO LONGER
255
- * read — this notice points the user at the new location and the one-line
256
- * `mv` migration. Emitted as a load WARNING (advisory, non-blocking).
257
- *
258
- * The embedded shell is `;`-sequenced (not `&&`-chained) and each move is
259
- * guarded (`[ -f … ]` for the config, `find … 2>/dev/null` for the packs) so
260
- * the terminal `rm -rf` ALWAYS runs — a config-only legacy dir (no `workflows/`
261
- * subdir) no longer halts the chain and re-fires this warning forever.
262
- */
263
- export const LEGACY_OVERLAY_NOTICE = (cwd: string): string =>
264
- `rpiv-workflow: detected legacy \`${join(cwd, ".rpiv-workflow")}\` — project config now lives at ` +
265
- "`.rpiv/workflows/config.ts` + `.rpiv/workflows/packs/` and is the only location read. " +
266
- "Move it: `mkdir -p .rpiv/workflows/packs; " +
267
- "[ -f .rpiv-workflow/workflows.config.ts ] && mv .rpiv-workflow/workflows.config.ts .rpiv/workflows/config.ts; " +
268
- "find .rpiv-workflow/workflows -name '*.ts' -exec mv {} .rpiv/workflows/packs/ \\; 2>/dev/null; " +
269
- "rm -rf .rpiv-workflow` " +
270
- "(the old directory is ignored). " +
271
- "Note: `.rpiv/workflows/` is commonly gitignored (it holds run state), so the moved " +
272
- "`config.ts` + `packs/` may be silently uncommittable — add `!.rpiv/workflows/config.ts` and " +
273
- "`!.rpiv/workflows/packs/` to your `.gitignore` to version-control team workflow config.";
274
-
275
- /**
276
- * Orphaned run JSONLs detected directly under `.rpiv/workflows/` at load time.
277
- * Run state moved one level down into `.rpiv/workflows/runs/`; files written by
278
- * an older version still sit at the parent and are no longer enumerated by
279
- * `listRuns` (so `/wf` past-run inspection silently can't see them). Emitted as
280
- * a load WARNING (advisory, non-blocking) — the files are orphaned, not deleted.
281
- */
282
- export const LEGACY_RUNS_NOTICE = (cwd: string): string =>
283
- `rpiv-workflow: detected legacy run files directly under \`${join(cwd, ".rpiv", "workflows")}\` — ` +
284
- "run state now lives in `.rpiv/workflows/runs/` and these top-level `*.jsonl` files are no longer " +
285
- "read by `/wf`. Move them: `mkdir -p .rpiv/workflows/runs && mv .rpiv/workflows/*.jsonl .rpiv/workflows/runs/`.";
286
-
287
- /**
288
- * Legacy user-layer config filename (`workflows.config.ts`) detected at load
289
- * time. The user overlay's inner name was aligned with the project layer
290
- * (`config.ts`) and is the ONLY name read — a stale `workflows.config.ts` would
291
- * otherwise silently stop contributing its aliases / default / overlay
292
- * workflows. Mirrors `LEGACY_OVERLAY_NOTICE` at the user layer. Load WARNING.
293
- */
294
- export const LEGACY_USER_CONFIG_NOTICE = (dir: string): string =>
295
- `rpiv-workflow: detected legacy \`${join(dir, "workflows.config.ts")}\` — the user-layer config now lives at ` +
296
- `\`${join(dir, "config.ts")}\` and is the only name read. ` +
297
- `Move it: \`mv ${join(dir, "workflows.config.ts")} ${join(dir, "config.ts")}\` (the old name is ignored).`;
298
-
299
- /** Pi command registry — displayed by Pi's `/?` / command list. */
300
- export const CMD_DESCRIPTION = "Run a skill workflow: /wf [workflow] [description]";
301
-
302
- /** No-args listing footer — generic usage hint. */
303
- export const CMD_USAGE_LIST = "Usage: /wf [workflow] <description>";
304
-
305
- /** No-args listing footer — preview-mode hint paired with CMD_USAGE_LIST. */
306
- export const CMD_USAGE_PREVIEW = "/wf <workflow> — preview stages";
307
-
308
- /** Per-workflow details footer — narrowed to the workflow the user previewed. */
309
- export const CMD_USAGE_RUN = (name: string) => `Usage: /wf ${name} <description>`;
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import type { ArtifactCollector } from "../../output-spec.js";
16
+ import { requireOpt } from "./require-opt.js";
16
17
  import { transcriptPathCollector } from "./transcript-path.js";
17
18
 
18
19
  export interface DirectoryPathCollectorOpts {
@@ -26,9 +27,12 @@ export interface DirectoryPathCollectorOpts {
26
27
  }
27
28
 
28
29
  export function directoryPathCollector(opts: DirectoryPathCollectorOpts): ArtifactCollector {
29
- if (typeof opts.dir !== "string" || opts.dir.length === 0) {
30
- throw new Error("directoryPathCollector: `dir` is required and must be a non-empty string");
31
- }
30
+ requireOpt(
31
+ "directoryPathCollector",
32
+ "dir",
33
+ "is required and must be a non-empty string",
34
+ typeof opts.dir === "string" && opts.dir.length > 0,
35
+ );
32
36
  const escapedDir = escapeRegex(opts.dir);
33
37
  const extPart = opts.ext ? escapeRegex(opts.ext) : "[a-zA-Z0-9]+";
34
38
  const pattern = new RegExp(`${escapedDir}/[\\w.-]+\\.${extPart}`, "g");
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Shared construction-time opts guard for the collector factories.
3
+ *
4
+ * Collector factories validate their opts eagerly (at workflow-definition
5
+ * time) so a malformed option fails loudly where the author wrote it, not
6
+ * as a confusing collect-time fatal mid-run. Each factory states the
7
+ * requirement once; this helper keeps the throw wording uniform.
8
+ */
9
+ export function requireOpt(factory: string, name: string, requirement: string, ok: boolean): void {
10
+ if (!ok) throw new Error(`${factory}: \`${name}\` ${requirement}`);
11
+ }
@@ -25,7 +25,9 @@ const ctxOf = (branch: BranchEntry[]) => ({
25
25
  describe("toolCallCollector", () => {
26
26
  it("throws when match or toArtifact are missing", () => {
27
27
  // @ts-expect-error — intentional misuse
28
- expect(() => toolCallCollector({})).toThrow(/required functions/);
28
+ expect(() => toolCallCollector({})).toThrow(/`match` is required/);
29
+ // @ts-expect-error — intentional misuse
30
+ expect(() => toolCallCollector({ match: () => true })).toThrow(/`toArtifact` is required/);
29
31
  });
30
32
 
31
33
  it("emits one artifact per matching tool call in branch order", async () => {
@@ -22,6 +22,7 @@ import type { Artifact } from "../../handle.js";
22
22
  import type { ArtifactCollector } from "../../output-spec.js";
23
23
  import { defineCollector } from "../../output-spec.js";
24
24
  import { iterToolUses } from "../../transcript.js";
25
+ import { requireOpt } from "./require-opt.js";
25
26
 
26
27
  export interface ToolCall {
27
28
  name: string;
@@ -45,9 +46,13 @@ export interface ToolCallCollectorOpts {
45
46
  }
46
47
 
47
48
  export function toolCallCollector(opts: ToolCallCollectorOpts): ArtifactCollector {
48
- if (typeof opts.match !== "function" || typeof opts.toArtifact !== "function") {
49
- throw new Error("toolCallCollector: `match` and `toArtifact` are required functions");
50
- }
49
+ requireOpt("toolCallCollector", "match", "is required and must be a function", typeof opts.match === "function");
50
+ requireOpt(
51
+ "toolCallCollector",
52
+ "toArtifact",
53
+ "is required and must be a function",
54
+ typeof opts.toArtifact === "function",
55
+ );
51
56
  const { match, toArtifact } = opts;
52
57
  return defineCollector({
53
58
  collect: (ctx) => {
@@ -22,6 +22,7 @@ import { fs } from "../../handle.js";
22
22
  import type { ArtifactCollector } from "../../output-spec.js";
23
23
  import { defineCollector } from "../../output-spec.js";
24
24
  import { lastMatchInBranch } from "../../transcript.js";
25
+ import { requireOpt } from "./require-opt.js";
25
26
 
26
27
  export interface TranscriptPathCollectorOpts {
27
28
  /**
@@ -34,9 +35,7 @@ export interface TranscriptPathCollectorOpts {
34
35
  }
35
36
 
36
37
  export function transcriptPathCollector(opts: TranscriptPathCollectorOpts): ArtifactCollector {
37
- if (!(opts.pattern instanceof RegExp)) {
38
- throw new Error("transcriptPathCollector: `pattern` is required and must be a RegExp");
39
- }
38
+ requireOpt("transcriptPathCollector", "pattern", "is required and must be a RegExp", opts.pattern instanceof RegExp);
40
39
  const pattern = opts.pattern;
41
40
  return defineCollector({
42
41
  collect: (ctx) => {