@juicesharp/rpiv-workflow 1.19.1 → 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 (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
package/messages.ts CHANGED
@@ -1,74 +1,65 @@
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).
6
- */
7
-
8
- import { join } from "node:path";
9
-
10
- export const STATUS_KEY = "rpiv-workflow";
11
-
12
- export const STATUS_STAGE = (stage: number, total: number, skill: string) => `rpiv: stage ${stage}/${total} — ${skill}`;
13
-
14
- /**
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.
4
+ * Pi's session transition.
5
+ * - `FAIL_*` — structured terminal-failure descriptors (see `FailureText`).
6
+ *
7
+ * Audience split: this module is the UI/runtime constants. The
8
+ * model-facing validation-retry prompt lives beside its only consumer
9
+ * (sessions/extraction.ts); legacy-migration notices live in load/legacy.ts;
10
+ * `/wf` usage strings live in command.ts / preview.ts.
18
11
  */
19
- export const STATUS_FANOUT_UNIT = (stage: number, total: number, skill: string, label: string) =>
20
- `rpiv: stage ${stage}/${total} — ${skill} (${label})`;
21
12
 
22
13
  /**
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.
14
+ * One structured descriptor per terminal-failure kind — the `toast` (the
15
+ * one-shot `ctx.ui.notify` line) and the `error` (what lands in
16
+ * `state.termination.error` + the JSONL row's `errMsg`) rendered from ONE
17
+ * factory so the two channels can't drift. Halt sites hand the
18
+ * descriptor to `failedArgs`/`abortedArgs` (messages.ts) or spread it into
19
+ * `StagePreflightError`.
26
20
  */
27
- export const STATUS_ITERATE_UNIT = (stage: number, total: number, skill: string, label: string) =>
28
- `rpiv: stage ${stage}/${total} — ${skill} (${label})`;
21
+ export interface FailureText {
22
+ toast: string;
23
+ error: string;
24
+ }
29
25
 
30
- export const MSG_STAGE_COMPLETE = (skill: string) => `✓ ${skill} completed`;
31
26
  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`;
27
+
28
+ export const FAIL_STAGE_ABORTED = (skill: string): FailureText => ({
29
+ toast: `⏸ ${skill} aborted (ESC) — stopping workflow`,
30
+ error: `${skill} aborted by user (ESC)`,
31
+ });
32
+ export const FAIL_STAGE_TRUNCATED = (skill: string): FailureText => ({
33
+ toast: `✗ ${skill} truncated — model hit output cap mid-reply, stopping workflow`,
34
+ error: `${skill} truncated — model hit output-length cap mid-reply`,
35
+ });
36
+ export const FAIL_STAGE_TOOL_STALLED = (skill: string): FailureText => ({
37
+ toast: `✗ ${skill} tool loop did not settle — stopping workflow`,
38
+ error: `${skill} tool loop did not settle before the orchestrator inspected the branch`,
39
+ });
40
+ export const FAIL_STAGE_NO_RESPONSE = (skill: string): FailureText => ({
41
+ toast: `✗ ${skill} produced no response — stopping workflow`,
42
+ error: `${skill} produced no assistant message`,
43
+ });
43
44
 
44
45
  export const MSG_WORKFLOW_COMPLETE = (stages: number) => `rpiv: workflow complete (${stages} stages)`;
45
46
  export const MSG_WORKFLOW_CANCELLED = "rpiv: workflow cancelled";
46
47
 
47
48
  // 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)`;
50
-
51
- export const MSG_VALIDATION_RETRY = (skill: string, attempt: number) =>
52
- `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}`;
49
+ export const FAIL_WORKFLOW_ABORTED = (stage: string): FailureText => ({
50
+ toast: "rpiv: workflow aborted",
51
+ error: `workflow aborted before stage "${stage}" (signal)`,
52
+ });
56
53
 
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}`;
54
+ export const FAIL_VALIDATION_EXHAUSTED = (skill: string, failures: string): FailureText => ({
55
+ toast: `rpiv: ${skill} output validation exhausted retries`,
56
+ error: `${skill} output validation failed after retries: ${failures}`,
57
+ });
67
58
 
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}`;
59
+ export const FAIL_INPUT_VALIDATION = (currentSkill: string, prevSkill: string, failures: string): FailureText => ({
60
+ toast: `✗ ${currentSkill} input validation failed — upstream ${prevSkill} produced invalid data`,
61
+ error: `Input validation failed for '${currentSkill}': upstream '${prevSkill}' produced invalid data: ${failures}`,
62
+ });
72
63
 
73
64
  /**
74
65
  * Bound on a single schema-validate call. Sync schemas resolve in one
@@ -81,10 +72,10 @@ export const ERR_INPUT_VALIDATION_FAILED = (currentSkill: string, prevSkill: str
81
72
  export const ERR_SCHEMA_TIMEOUT = (slot: "outputSchema" | "inputSchema", ms: number) =>
82
73
  `${slot} validation exceeded ${ms}ms — schema's ~standard.validate did not settle`;
83
74
 
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`;
75
+ export const FAIL_MISSING_ARTIFACT = (currentSkill: string, stageNumber: number): FailureText => ({
76
+ toast: `✗ ${currentSkill} has no upstream artifact to consume — stopping workflow`,
77
+ error: `Stage ${stageNumber} (${currentSkill}) has no upstream artifactPath; only stage 1 may consume the user's original input`,
78
+ });
88
79
 
89
80
  /**
90
81
  * A stage declares `reads: [..., name, ...]` but `state.named[name]` is
@@ -94,42 +85,69 @@ export const ERR_MISSING_ARTIFACT = (currentSkill: string, stageNumber: number)
94
85
  * the producer was authored with no outcome and a name that doesn't
95
86
  * match any stage record key.
96
87
  */
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`;
88
+ export const FAIL_MISSING_NAMED_READ = (currentSkill: string, name: string, stageNumber: number): FailureText => ({
89
+ toast: `✗ ${currentSkill} reads "${name}" but no upstream produces stage has published it yet — stopping workflow`,
90
+ error: `Stage ${stageNumber} (${currentSkill}) reads "${name}" but state.named["${name}"] is empty; check that an upstream produces stage publishes this name`,
91
+ });
101
92
 
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`;
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})`,
96
+ });
104
97
 
105
- export const ERR_BACKWARD_JUMP_EXHAUSTED = (jumps: number, max: number) =>
106
- `Backward-jump limit exceeded: ${jumps} backward jumps (max ${max})`;
98
+ /**
99
+ * A loop produced zero units (push: empty array handled upstream as
100
+ * single-stage fall-through, so this fires only for a pull loop whose FIRST
101
+ * call returned null). Not an error — nothing published, the primary stays at
102
+ * the entry pair; warn so the author notices the empty input.
103
+ */
104
+ export const MSG_LOOP_ZERO_UNITS = (skill: string) =>
105
+ `rpiv: ${skill} iterate loop produced zero units — nothing published, advancing`;
107
106
 
108
107
  /**
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.
108
+ * A loop hit its effective cap (`min(loop.max, run.maxIterations)`) under
109
+ * `onCap: "halt"` — terminal failure, mirroring the backward-jump guard.
113
110
  */
114
- export const MSG_ITERATIONS_EXHAUSTED = (count: number, max: number) =>
115
- `rpiv: iterate limit exceeded (${count}/${max}) — stopping workflow to prevent an unbounded generator`;
111
+ export const FAIL_LOOP_CAP_HALT = (count: number, max: number): FailureText => ({
112
+ toast: `rpiv: loop cap exceeded (${count}/${max}) — stopping workflow to prevent an unbounded loop`,
113
+ error: `Loop cap exceeded: ${count} units (max ${max})`,
114
+ });
116
115
 
117
- export const ERR_ITERATIONS_EXHAUSTED = (count: number, max: number) =>
118
- `Iterate limit exceeded: generator produced ${count} units (max ${max})`;
116
+ /**
117
+ * A loop hit its effective cap under `onCap: "advance"` — soft-stop: warn,
118
+ * land the {type:"loop-cap"} telemetry row, keep the projected result,
119
+ * advance. Deliberately no ERR_ twin (not a failure).
120
+ */
121
+ export const MSG_LOOP_CAP_ADVANCE = (skill: string, max: number) =>
122
+ `rpiv: ${skill} loop reached its cap (${max}) — projecting the configured result and advancing`;
119
123
 
120
124
  /**
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.
125
+ * A verify-bearing stage exhausted its attempt budget without a passing
126
+ * verdict (the synthesized loop's `onCap: "halt"` tripped). Verify-worded —
127
+ * the author declared a post-condition, not a loop, so the loop-cap pair
128
+ * would misattribute the failure. A pass on the final attempt never reaches
129
+ * this (`done` wins over the cap).
125
130
  */
126
- export const MSG_ITERATE_ZERO_UNITS = (skill: string) =>
127
- `rpiv: ${skill} iterate produced zero units — nothing published, advancing`;
131
+ export const FAIL_VERIFY_FAILED = (stage: string, attempts: number): FailureText => ({
132
+ toast: `✗ ${stage} verification failed after ${attempts} attempt${attempts === 1 ? "" : "s"} — stopping workflow`,
133
+ error: `Verification failed for "${stage}": the judge's verdict did not satisfy \`pass\` after ${attempts} attempt${attempts === 1 ? "" : "s"}`,
134
+ });
135
+
136
+ export const FAIL_AUDIT_WRITE = (skill: string): FailureText => ({
137
+ toast: `✗ ${skill} completed but audit row could not be written — stopping workflow`,
138
+ error: `${skill} completed but the JSONL audit row could not be appended; halting to keep in-memory state aligned with disk`,
139
+ });
128
140
 
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`;
141
+ /**
142
+ * Notified when a TERMINAL failure/aborted row could not be appended. Unlike
143
+ * routing rows this is a reconstruction input: without it the trail's last
144
+ * row reads "completed" and a later resume would route onward past the stage
145
+ * that actually failed. The run is already halting — the user (and the
146
+ * result envelope's `droppedFailureRows`) must know the trail is unsafe to
147
+ * resume from.
148
+ */
149
+ export const MSG_FAILURE_ROW_DROPPED = (stage: string) =>
150
+ `⚠ rpiv: failure row for ${stage} not persisted to audit trail — do not resume this run from disk`;
133
151
 
134
152
  export const MSG_CHAIN_ADVANCE_FAILED = (fromStage: string, reason: string) =>
135
153
  `✗ chain advance after ${fromStage} failed: ${reason} — stopping workflow`;
@@ -139,11 +157,31 @@ export const MSG_CHAIN_ADVANCE_FAILED = (fromStage: string, reason: string) =>
139
157
  * `enforceSessionInvariants` violations, session-machinery errors, and any
140
158
  * other path that escapes `runStage` directly. Distinguished from
141
159
  * `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.
160
+ * succeeded) — the user needs to see *which* stage failed, not which one
161
+ * preceded the failure. Wording is deliberately neutral ("failed", not
162
+ * "failed to start"): throws from mid-stage machinery land here too.
144
163
  */
145
164
  export const MSG_STAGE_THREW = (skill: string, reason: string) =>
146
- `✗ stage ${skill} failed to start: ${reason} — stopping workflow`;
165
+ `✗ stage ${skill} failed: ${reason} — stopping workflow`;
166
+
167
+ /**
168
+ * Loop cursor reached a state its state machine forbids (e.g. a judge step
169
+ * with no completed produce behind it). `advanceCursor` makes these states
170
+ * unreachable and the resume fold's shape guards refuse corrupted trails, so
171
+ * a throw here is an internal bug surfaced with stage attribution instead of
172
+ * a bare `TypeError`.
173
+ */
174
+ export const MSG_LOOP_CURSOR_CORRUPT = (stage: string, detail: string) =>
175
+ `✗ loop stage ${stage}: cursor invariant violated — ${detail}`;
176
+
177
+ /**
178
+ * Collector/parser throws — `collect`/`parse` are the PRIMARY user extension
179
+ * points, so a throw is attributed to the throwing half (not folded into the
180
+ * generic stage-machinery wording). Lands in `state.termination.error` via
181
+ * the extraction fatal arm.
182
+ */
183
+ export const ERR_COLLECTOR_THREW = (skill: string, reason: string) => `${skill}: outcome collector threw: ${reason}`;
184
+ export const ERR_PARSER_THREW = (skill: string, reason: string) => `${skill}: outcome parser threw: ${reason}`;
147
185
 
148
186
  /**
149
187
  * Stage references a Pi skill that isn't registered with the running Pi
@@ -153,10 +191,10 @@ export const MSG_STAGE_THREW = (skill: string, reason: string) =>
153
191
  * unknown skill name would otherwise reach the model as a bare user-message
154
192
  * imperative outside the `<skill>...</skill>` contract.
155
193
  */
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)`;
194
+ export const FAIL_SKILL_NOT_REGISTERED = (skill: string, stageNumber: number): FailureText => ({
195
+ toast: `✗ ${skill} is not a registered Pi skill — stopping workflow`,
196
+ 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)`,
197
+ });
160
198
 
161
199
  /**
162
200
  * Notified live when a routing-decision row could not be appended. The chain
@@ -174,15 +212,25 @@ export const MSG_PARTIAL_ARTIFACTS = (artifactList: string) => `Artifacts produc
174
212
  export const MSG_LIFECYCLE_THREW = (event: string, reason: string) =>
175
213
  `⚠ rpiv: lifecycle listener (${event}) threw: ${reason}`;
176
214
 
215
+ /**
216
+ * Outcome snapshot hook threw — the stage still runs (snapshot is best-effort)
217
+ * but diff-based collectors will see `snapshot: undefined`. Warned once per
218
+ * run so a consistently-throwing custom snapshot can't silently disable
219
+ * diffing for every stage.
220
+ */
221
+ export const MSG_SNAPSHOT_FAILED = (stage: string, reason: string) =>
222
+ `⚠ rpiv: outcome snapshot for ${stage} threw (${reason}) — pre-stage diff degraded for this stage`;
223
+
177
224
  /**
178
225
  * Script stage's `run()` body threw. Distinct from `MSG_STAGE_THREW`
179
226
  * (which covers session-machinery and preflight throws) so users see
180
227
  * the failure surface attributed to the script function rather than to
181
228
  * the runner.
182
229
  */
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}`;
230
+ export const FAIL_SCRIPT_THREW = (stage: string, reason: string): FailureText => ({
231
+ toast: `✗ ${stage} script threw — stopping workflow: ${reason}`,
232
+ error: `${stage} script threw: ${reason}`,
233
+ });
186
234
 
187
235
  // ---------------------------------------------------------------------------
188
236
  // Resume-refusal messages — reconstruct refusals returned in the
@@ -190,19 +238,75 @@ export const ERR_SCRIPT_THREW = (stage: string, reason: string) => `${stage} scr
190
238
  // ---------------------------------------------------------------------------
191
239
 
192
240
  export const ERR_RESUME_NO_ROWS = (runId: string) => `rpiv: run ${runId} has no recorded stages — nothing to resume`;
241
+ /**
242
+ * A stage-shaped row failed the deep shape guard. Resume REFUSES rather than
243
+ * skip: the fold replays the trail as its system of record, and a silently
244
+ * dropped row would replay a hole ("this stage never ran") and route onward
245
+ * past it.
246
+ */
247
+ export const ERR_RESUME_MALFORMED_ROW = (detail: string) =>
248
+ `rpiv: cannot resume — the run's trail contains a malformed stage row (${detail}); ` +
249
+ `resume refuses rather than replay an incomplete history`;
250
+ /**
251
+ * The run's header carries a schema version this build doesn't write —
252
+ * resume refuses rather than fold rows whose shapes it may misread.
253
+ * Absent `v` is version 1 (back-compat), so this only fires on a real bump.
254
+ */
255
+ export const ERR_RESUME_VERSION_MISMATCH = (detail: string, expected: number) =>
256
+ `rpiv: cannot resume — ${detail}, but this build reads schema v${expected}; ` +
257
+ `resume refuses rather than misread the trail`;
193
258
  export const ERR_RESUME_STAGE_GONE = (stage: string, workflow: string) =>
194
259
  `rpiv: cannot resume — stage "${stage}" from the run no longer exists in workflow "${workflow}" ` +
195
260
  `(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`;
261
+ /**
262
+ * Resume drift refusal — one pair for all loop kinds. The unit source
263
+ * recomputed a different unit than the run recorded at a folded boundary
264
+ * (the determinism contract: deterministic w.r.t. the fold-replayed RunState
265
+ * + accumulated outputs). Resume refuses rather than re-run the wrong units.
266
+ */
267
+ export const ERR_RESUME_LOOP_MISMATCH = (stage: string) =>
268
+ `rpiv: cannot resume — loop stage "${stage}" recomputed a different unit than the run recorded ` +
269
+ `(the unit source must be deterministic w.r.t. the replayed run state + accumulated outputs; ` +
270
+ `resume refuses rather than re-run the wrong units)`;
271
+ export const MSG_RESUME_LOOP_MISMATCH = (stage: string) =>
272
+ `rpiv: loop "${stage}" changed on resume — cannot safely continue`;
273
+
274
+ // ---------------------------------------------------------------------------
275
+ // Session-backed resume (promotion + reattach) — notify-only progress toasts
276
+ // + the fallback-ladder notice, plus the one model-facing reattach prompt
277
+ // ---------------------------------------------------------------------------
278
+
279
+ export const MSG_RESUME_PROMOTED = (skill: string) =>
280
+ `✓ ${skill}: interrupted session already produced the artifact — stage promoted to completed`;
281
+
282
+ export const MSG_RESUME_REATTACHED = (skill: string) => `↻ ${skill}: reattached to interrupted session`;
283
+
284
+ /**
285
+ * One ladder-rung notice before a session-backed resume degrades to today's
286
+ * cold re-run. `why` is a short human clause — "session file not found",
287
+ * "host cannot switch sessions" — not a dispatch key (nothing parses it).
288
+ */
289
+ export const MSG_RESUME_SESSION_FALLBACK = (skill: string, why: string) =>
290
+ `rpiv: ${skill} — ${why}; re-running the stage from scratch`;
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
+
301
+ /**
302
+ * Sent to the AGENT when a stage reattaches to its interrupted session
303
+ * (model-facing prompt text — promotion already missed, so the artifact
304
+ * was not announced or not written).
305
+ */
306
+ export const REATTACH_PROMPT = (skill: string) =>
307
+ `The previous run of /skill:${skill} in this session was interrupted. ` +
308
+ "Review the conversation above. If the work is already complete, announce the artifact path. " +
309
+ "Otherwise finish the remaining work and announce the artifact path when done.";
206
310
 
207
311
  // ---------------------------------------------------------------------------
208
312
  // Resume-refusal messages — resumeWorkflowByRef pre-resume guards (resolve →
@@ -230,9 +334,15 @@ export const MSG_NAME_COLLISION = (name: string, runId: string) => `name '${name
230
334
  export const MSG_NAME_INDEX_WRITE_FAILED = (name: string) =>
231
335
  `/wf: could not persist name "${name}" to the names index — run aborted (no run started). Check filesystem permissions for .rpiv/workflows/runs/`;
232
336
 
337
+ export const MSG_HEADER_WRITE_FAILED = (runId: string) =>
338
+ `rpiv: could not write the run header for ${runId} — run aborted (no stage executed). Check filesystem permissions for .rpiv/workflows/runs/`;
339
+
233
340
  export const MSG_NAME_IGNORED_ON_RESUME =
234
341
  "/wf: --name has no effect on @resume (the ref already identifies the run) — ignoring it";
235
342
 
343
+ export const MSG_NAME_FLAG_MID_INPUT =
344
+ "/wf: --name is only honored as the first or last token — a mid-input --name is treated as workflow input text";
345
+
236
346
  export const MSG_LOAD_ABORTED = (count: number) =>
237
347
  `/wf: ${count} ${count === 1 ? "config error" : "config errors"} — see warnings above (fix and re-run)`;
238
348
 
@@ -249,61 +359,44 @@ export const MSG_NO_WORKFLOWS_REGISTERED =
249
359
  "/wf: no workflows registered — install a sibling that bundles workflows or author one in `.rpiv/workflows/config.ts`";
250
360
 
251
361
  /**
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.
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.
262
365
  */
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.";
366
+ export interface TerminalFailureArgs {
367
+ status: "failed" | "aborted";
368
+ notifyMsg: string;
369
+ notifyLevel: "warning" | "error";
370
+ errMsg: string;
371
+ }
274
372
 
275
373
  /**
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.
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).
281
378
  */
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/`.";
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
+ }
286
383
 
287
384
  /**
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.
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.
293
391
  */
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>`;
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
+ }
@@ -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");
@@ -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,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
+ }
@@ -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
+ }