@juicesharp/rpiv-workflow 1.20.0 → 2.1.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 (111) hide show
  1. package/README.md +98 -545
  2. package/api.ts +1 -1
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +18 -0
  5. package/audit.ts +119 -164
  6. package/built-ins.ts +26 -6
  7. package/chain-state.ts +119 -68
  8. package/command-run.ts +35 -30
  9. package/command.ts +10 -4
  10. package/docs/embedding.md +341 -0
  11. package/docs/workflow-authoring.md +70 -16
  12. package/docs/workflow-basics.md +125 -10
  13. package/events.ts +44 -4
  14. package/execution-host.ts +75 -0
  15. package/host.ts +137 -82
  16. package/internal-utils.ts +89 -3
  17. package/internal.ts +1 -0
  18. package/judge.ts +23 -11
  19. package/load/alias.ts +3 -3
  20. package/load/index.ts +15 -1
  21. package/load/issues.ts +2 -2
  22. package/load/legacy.ts +2 -2
  23. package/load/resolve-default.ts +3 -4
  24. package/load/skill-contract-phase.ts +1 -1
  25. package/loop-constructors.ts +19 -618
  26. package/loop-def.ts +60 -15
  27. package/loop-kinds.ts +319 -62
  28. package/loop-parallel.ts +250 -0
  29. package/loop-waves.ts +99 -0
  30. package/loop.ts +106 -80
  31. package/loops/constructors.ts +334 -0
  32. package/loops/derivations.ts +65 -0
  33. package/loops/introspection.ts +184 -0
  34. package/loops/panel.ts +196 -0
  35. package/loops/verify.ts +99 -0
  36. package/messages.ts +58 -33
  37. package/outcomes/collectors/index.ts +1 -0
  38. package/outcomes/collectors/text-scan.ts +47 -0
  39. package/outcomes/collectors/transcript-path.ts +2 -15
  40. package/outcomes/collectors/union.ts +2 -1
  41. package/outcomes/collectors/url.ts +2 -14
  42. package/outcomes/collectors/workspace-diff.ts +1 -1
  43. package/outcomes/git-commit.ts +57 -6
  44. package/output-spec.ts +1 -1
  45. package/output.ts +59 -1
  46. package/package.json +19 -6
  47. package/preview.ts +18 -18
  48. package/registration.ts +11 -4
  49. package/routing-dsl.ts +53 -41
  50. package/routing.ts +46 -0
  51. package/runner/chain-advance.ts +30 -17
  52. package/runner/errors.ts +7 -30
  53. package/runner/failure.ts +67 -13
  54. package/runner/input-validation.ts +8 -5
  55. package/runner/preflight.ts +17 -21
  56. package/runner/resume-entry.ts +23 -3
  57. package/runner/resume-loop.ts +50 -29
  58. package/runner/resume.ts +96 -10
  59. package/runner/run-context.ts +20 -16
  60. package/runner/run-stage.ts +125 -91
  61. package/runner/runner.ts +163 -69
  62. package/runner/script-stage.ts +23 -29
  63. package/schema-compat.ts +1 -2
  64. package/semaphore.ts +55 -0
  65. package/sessions/extraction.ts +103 -60
  66. package/sessions/halt-routing.ts +195 -0
  67. package/sessions/index.ts +2 -2
  68. package/sessions/locate.ts +60 -9
  69. package/sessions/reattach.ts +28 -20
  70. package/sessions/sessions.ts +103 -191
  71. package/sessions/spawn.ts +132 -119
  72. package/sessions/success-persist.ts +89 -0
  73. package/skill-contracts/composition.ts +8 -10
  74. package/skill-contracts/harvest.ts +3 -2
  75. package/skill-contracts/registry.ts +1 -1
  76. package/stage-def.ts +115 -47
  77. package/stage-errors.ts +84 -0
  78. package/stage-identity.ts +56 -0
  79. package/startup.ts +1 -0
  80. package/state/paths.ts +11 -3
  81. package/state/raw.ts +2 -3
  82. package/state/resolve.ts +3 -3
  83. package/state/state.ts +26 -3
  84. package/state/writes.ts +1 -1
  85. package/types.ts +97 -43
  86. package/validate/contract-compat.ts +16 -11
  87. package/validate/graph.ts +10 -1
  88. package/validate/issue.ts +20 -6
  89. package/validate/stage-rules.ts +139 -60
  90. package/validate-output.ts +27 -20
  91. package/validate-workflow.ts +5 -3
  92. package/validation-bounds.ts +35 -0
  93. package/docs/cover.png +0 -0
  94. package/docs/cover.svg +0 -120
  95. package/load/cache.test.ts +0 -82
  96. package/load/shape-guards.test.ts +0 -77
  97. package/outcomes/collectors/directory-path.test.ts +0 -64
  98. package/outcomes/collectors/tool-call.test.ts +0 -112
  99. package/outcomes/collectors/transcript-path.test.ts +0 -70
  100. package/outcomes/collectors/union.test.ts +0 -113
  101. package/outcomes/collectors/url.test.ts +0 -67
  102. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  103. package/outcomes/git-commit.test.ts +0 -240
  104. package/outcomes/parsers/json-body.test.ts +0 -80
  105. package/runner/by-name.test.ts +0 -95
  106. package/runner/by-run-id.test.ts +0 -115
  107. package/runner/header-write-failure.test.ts +0 -64
  108. package/runner/resume-loop.test.ts +0 -1410
  109. package/runner/resume-session.test.ts +0 -400
  110. package/runner/resume.test.ts +0 -1805
  111. package/sessions/locate.test.ts +0 -77
@@ -5,22 +5,62 @@ A workflow chains Pi skills into a typed multi-stage graph with audited JSONL st
5
5
  ## Table of Contents
6
6
 
7
7
  - [Running workflows](#running-workflows)
8
+ - [When `/wf` refuses](#when-wf-refuses)
8
9
  - [File structure](#file-structure)
10
+ - [Where files resolve](#where-files-resolve)
9
11
  - [Layer merging](#layer-merging)
10
12
  - [Config files](#config-files)
11
13
  - [Pack files](#pack-files)
12
14
  - [Skill aliases](#skill-aliases)
15
+ - [Run state](#run-state)
16
+ - [Run caps](#run-caps)
17
+ - [Trusting overlay files](#trusting-overlay-files)
18
+ - [Legacy layouts](#legacy-layouts)
13
19
  - [Example](#example)
20
+ - [Glossary](#glossary)
14
21
 
15
22
  ## Running workflows
16
23
 
17
24
  ```bash
18
- /wf # Preview every loaded workflow
19
- /wf <name> # Preview one workflow's stage graph
20
- /wf <name> <input> # Run a workflow with <input> piped to the start stage
25
+ /wf # Preview every loaded workflow
26
+ /wf <name> # Preview one workflow's stage graph
27
+ /wf <name> <input> # Run a workflow with <input> piped to the start stage
28
+ /wf <input> # Run the default workflow with <input>
29
+ /wf <name> <input> --name <slug> # Run under a human-readable alias
30
+ /wf @<ref> # Resume a past run
21
31
  ```
22
32
 
23
- Running `/wf` without arguments shows a list of every loaded workflow and its stages. Running `/wf <name>` without input shows that workflow's stage graph in detail. The `<input>` string becomes the start stage's prompt.
33
+ Running `/wf` without arguments shows a list of every loaded workflow and its stages. Running `/wf <name>` without input shows that workflow's stage graph in detail. The `<input>` string becomes the start stage's prompt. When the first token is not a recognised workflow name, the whole argument is treated as input for the resolved default workflow.
34
+
35
+ `/wf` floats the run off the prompt and returns immediately — stages execute detached in their own child sessions.
36
+
37
+ ### `--name <slug>`
38
+
39
+ Assigns a human-readable alias to the run, stored in the JSONL header and the sidecar `names.json` index. It is honored **only** in the leading or trailing token position (leading wins if both are present) — a `--name` in the middle of your input stays as prompt text (`/wf fix the --name handling bug`) and `/wf` warns that the flag was ignored.
40
+
41
+ Slugs must match `/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/`. A slug already in use is rejected, and the error names the run that holds it.
42
+
43
+ ### `@<ref>` — resume
44
+
45
+ ```bash
46
+ /wf @2026-07-21_14-03-22-9f2a
47
+ /wf @nightly-docs
48
+ /wf @.rpiv/workflows/runs/2026-07-21_14-03-22-9f2a.jsonl
49
+ ```
50
+
51
+ The `@` sigil on the first token resumes a past run. `<ref>` is a run-id, a run name assigned with `--name`, or a path to a `.jsonl` trail. A leading space after `@` is tolerated; trailing tokens are ignored. `--name` has no meaning on a resume — it is dropped with a warning.
52
+
53
+ Resume folds the JSONL trail back into run state and re-enters at the pending step. Completed fan-out units replay from their journaled output instead of re-running.
54
+
55
+ ## When `/wf` refuses
56
+
57
+ | Condition | What you see |
58
+ | --- | --- |
59
+ | Non-interactive session | `/wf requires interactive mode` |
60
+ | No workflows registered | A message telling you to install a sibling that bundles workflows or author one in `.rpiv/workflows/config.ts`. This is the standalone-install default state — the package ships zero workflows |
61
+ | Any load issue with `severity: "error"` | `/wf: N config errors — see warnings above (fix and re-run)`; execution is blocked until the config loads clean |
62
+ | A run recorded under an older state schema | Resume is refused with a version mismatch. `STATE_SCHEMA_VERSION` is `2`; there is no in-place migration |
63
+ | First `/wf` before the runtime pre-warms | One toast: `rpiv: loading workflow runtime (first /wf after load)…`. The runtime pre-warms 2000 ms after extension load |
24
64
 
25
65
  ## File structure
26
66
 
@@ -30,7 +70,10 @@ Running `/wf` without arguments shows a list of every loaded workflow and its st
30
70
  ├── packs/ # Pack files (installable bundles)
31
71
  │ ├── my-pipeline.ts
32
72
  │ └── ship.ts
33
- └── runs/ # Audited JSONL run state (<run-id>.jsonl)
73
+ └── runs/ # Audited JSONL run state
74
+ ├── <run-id>.jsonl
75
+ ├── names.json # --name → run-id index
76
+ └── <run-id>/sessions/ # Child session files for the run's stages
34
77
 
35
78
  ~/.config/rpiv-workflow/
36
79
  ├── config.ts # User-level config
@@ -43,6 +86,18 @@ Every workflow file is TypeScript, loaded via `jiti` (no build step required). I
43
86
  import { defineWorkflow, produces, acts, gate, gt, eq } from "@juicesharp/rpiv-workflow";
44
87
  ```
45
88
 
89
+ ## Where files resolve
90
+
91
+ | Layer | Path |
92
+ | --- | --- |
93
+ | User config | `$XDG_CONFIG_HOME/rpiv-workflow/config.ts`, defaulting to `~/.config/rpiv-workflow/config.ts` |
94
+ | User packs | `$XDG_CONFIG_HOME/rpiv-workflow/packs/*.ts`, defaulting to `~/.config/rpiv-workflow/packs/*.ts` |
95
+ | Project config | `<cwd>/.rpiv/workflows/config.ts` |
96
+ | Project packs | `<cwd>/.rpiv/workflows/packs/*.ts` |
97
+ | Run state | `<cwd>/.rpiv/workflows/runs/` |
98
+
99
+ `XDG_CONFIG_HOME` governs the **user** layer only. Unset, empty after trimming, whitespace-only, or **relative** values fall back to `~/.config`. `~` and `~/…` are tilde-expanded and then required to resolve absolute; `~user/…` is not expanded and routes to the default. Absolute values are used verbatim. Pi's own paths (`~/.pi/…`, `PI_CODING_AGENT_DIR`) are deliberately *not* unified with this. `XDG_CONFIG_HOME` is the only environment variable this package reads.
100
+
46
101
  ## Layer merging
47
102
 
48
103
  The loader merges workflows from five layers. Each later layer overrides earlier by workflow name:
@@ -55,7 +110,7 @@ built-in (registered by sibling packages like rpiv-pi)
55
110
  ← project config (<cwd>/.rpiv/workflows/config.ts)
56
111
  ```
57
112
 
58
- Within a layer, the config file wins by workflow name over pack files. Only the config file may set the `default` workflow (the one `/wf <input>` runs without specifying a name). Defaults cascade: `project config > user config > first registered workflow`.
113
+ Within a layer, the config file wins by workflow name over pack files. Only the config file may set the `default` workflow (the one `/wf <input>` runs without specifying a name). Defaults cascade: `project config > user config > first registered workflow`. With nothing registered anywhere, there is no default.
59
114
 
60
115
  ## Config files
61
116
 
@@ -81,12 +136,14 @@ export default {
81
136
  };
82
137
  ```
83
138
 
139
+ The envelope needs at least one of `workflows`, `default`, or `skillAliases`.
140
+
84
141
  ## Pack files
85
142
 
86
- Pack files (`packs/*.ts`) are installable bundles others can drop in. They accept only `Workflow | Workflow[]`. Packs **cannot** set `default` — that lives in the config file.
143
+ Pack files (`packs/*.ts`) are installable bundles others can drop in. They accept only `Workflow | Workflow[]` — the envelope form is rejected, and both `default` and `skillAliases` are hard-rejected.
87
144
 
88
145
  ```typescript
89
- // workflows/my-pipeline.ts
146
+ // .rpiv/workflows/packs/my-pipeline.ts
90
147
  import { defineWorkflow, produces, acts } from "@juicesharp/rpiv-workflow";
91
148
  export default defineWorkflow({
92
149
  name: "my-pipeline",
@@ -100,7 +157,7 @@ This is what makes installable workflow packs safe: a pack contributes new workf
100
157
 
101
158
  ## Skill aliases
102
159
 
103
- `skillAliases` remaps a skill name everywhere — across built-in, user, and project workflows — with one declarative config entry. It lives in the config-file envelope (packs can't set it) and is applied at load time, so `/wf` preview, the JSONL audit, and the runtime skill-registry preflight all see the final skill:
160
+ `skillAliases` remaps a skill name everywhere — across built-in, user, and project workflows — with one declarative config entry. It lives in the config-file envelope (packs can't set it) and is applied at load time **before validation**, so `/wf` preview, the JSONL audit, and the runtime skill-registry preflight all see the final skill:
104
161
 
105
162
  ```typescript
106
163
  // .rpiv/workflows/config.ts
@@ -118,6 +175,48 @@ export default {
118
175
 
119
176
  Every dispatching stage whose effective skill (`stage.skill ?? <stage key>`) matches an alias key is remapped to the target — note the key is the **skill** name, not the stage id. The mapping is one hop only (no transitive chains), skips `run`/`prompt` stages (they don't dispatch a `/skill:`), and merges **project over user** per key. An alias-only config (no `workflows`) is valid. `/wf` shows a `Skill aliases in effect: commit → attributed-commit` banner; an alias key that matches no dispatched skill in any workflow surfaces a load-time warning (a harmless no-op). A bad alias **target** (a skill that doesn't exist) is caught by the existing runtime "skill not found" preflight.
120
177
 
178
+ ## Run state
179
+
180
+ Each `/wf` invocation appends one row per step to `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl` — the append-only system of record that makes runs resumable. Run ids are `YYYY-MM-DD_HH-MM-SS-<4 hex>`, e.g. `2026-07-21_14-03-22-9f2a`.
181
+
182
+ Alongside the trail:
183
+
184
+ - `runs/names.json` — the `--name` slug → run-id index.
185
+ - `runs/<run-id>/sessions/` — the child session files backing that run's stages.
186
+
187
+ Trails carry `STATE_SCHEMA_VERSION`, currently `2`. A run recorded under a different version cannot be resumed.
188
+
189
+ The package sets no explicit file modes; writes use the process umask. If a write fails, the error tells you to check filesystem permissions for `.rpiv/workflows/runs/`.
190
+
191
+ ## Run caps
192
+
193
+ Two backstops bound every run regardless of what a workflow declares:
194
+
195
+ | Cap | Default | Effect |
196
+ | --- | --- | --- |
197
+ | `maxIterations` | `32` | Run-wide ceiling on loop units of every kind. The effective loop cap is `min(loop.max, run.maxIterations)` |
198
+ | Backward-jump budget | `2` per destination stage | At most 3 executions of any one stage across decision-edge loop-backs |
199
+
200
+ ## Trusting overlay files
201
+
202
+ `config.ts` and `packs/*.ts` are TypeScript modules, loaded through `jiti`, which **synchronously evaluates each file's top-level code** on first load and again on every edit (invalidation is mtime-driven). The threat boundary is the same as `npm install` post-install scripts or `tsx script.ts`.
203
+
204
+ If you run Pi in a freshly-cloned repository you do not control, diff `.rpiv/workflows/config.ts` and `.rpiv/workflows/packs/*.ts` before running `/wf`.
205
+
206
+ ## Legacy layouts
207
+
208
+ Three stale layouts from before the unified `.rpiv/workflows/` tree are probed at load time. Each fires a **warning** only — nothing blocks the run — and the old locations are **not** read:
209
+
210
+ | Detected | Migration |
211
+ | --- | --- |
212
+ | `<cwd>/.rpiv-workflow/` | Move `workflows.config.ts` → `.rpiv/workflows/config.ts` and `workflows/*.ts` → `.rpiv/workflows/packs/`, then `rm -rf .rpiv-workflow`. The full shell command is in the warning text |
213
+ | Top-level `*.jsonl` directly under `<cwd>/.rpiv/workflows/` | `mkdir -p .rpiv/workflows/runs && mv .rpiv/workflows/*.jsonl .rpiv/workflows/runs/` |
214
+ | `<userConfigDir>/workflows.config.ts` | `mv <userConfigDir>/workflows.config.ts <userConfigDir>/config.ts` |
215
+
216
+ `.rpiv/workflows/` is commonly gitignored because it holds run state, so a moved `config.ts` may be silently uncommittable. Add `!.rpiv/workflows/config.ts` and `!.rpiv/workflows/packs/` to your `.gitignore` to version-control team workflow config.
217
+
218
+ These advisories sunset roughly three release cycles after 1.0.
219
+
121
220
  ## Example
122
221
 
123
222
  A minimal workflow that chains two skills:
@@ -141,4 +240,20 @@ export default defineWorkflow({
141
240
 
142
241
  Save this as `.rpiv/workflows/config.ts` in your project, then run `/wf review-and-ship implement auth feature`.
143
242
 
144
- For the full DSL reference (all stage factories, routing, outcomes, validators), see [workflow-authoring.md](./workflow-authoring.md).
243
+ ## Glossary
244
+
245
+ One canonical name per concept. Where two words exist for the same thing, the split is deliberate: one is the **authoring surface** (what you type in a workflow file), the other is the **data vocabulary** (what lands in rows, envelopes, and types).
246
+
247
+ | Term | Meaning |
248
+ |------|---------|
249
+ | **Workflow** | The typed graph: a name, a `start` stage, a `stages` record, an `edges` table. Built with `defineWorkflow`, loaded from config layers or registered programmatically. |
250
+ | **Stage** | One node of the graph — a unit of dispatch (skill session, prompt, or script). Two kinds: `"produces"` and `"side-effect"`. |
251
+ | **Kind vs. factory** | `kind` is the persisted data discriminator (`"produces"` \| `"side-effect"`); the factories are authoring verbs: `produces()` → `"produces"`, `acts()` → `"side-effect"`, `terminal()` → `"side-effect"` + `inheritsArtifacts: false`. `acts` is a verb because it reads naturally in a stage record (`commit: acts()`); `"side-effect"` is descriptive because it reads naturally in rows and output envelopes. `terminal` is **not** a third kind — it's `acts` plus an artifact-isolation flag. |
252
+ | **Run** | One execution of a workflow: a `runId`, an append-only JSONL run file (the system of record for resume), and the in-memory state the runner threads. |
253
+ | **Chain** | The path a run walks through the graph — stage activations following `edges` from `start` until `"stop"` or a halt. Loops add generations *within* one chain position. |
254
+ | **Output** | The envelope one stage activation hands downstream: `{ kind, data, meta, artifacts }` (`Output<K, D>`, `output.ts`). What predicates, routes, downstream prompts, and the audit log see. |
255
+ | **Outcome** | The producer-side declaration of *how* a stage's Output gets built from a session: `{ collector, parser? }` (`Outcome`, `output-spec.ts`). The collector enumerates artifacts; the parser interprets them into `data`. |
256
+ | **Verdict** | A judge's Output (`type Verdict = Output`). In `assess` / `verify` loops the judge emits a verdict that `done` reads; verdicts are recorded for resume but never become the stage result. |
257
+ | **Contract** | A skill contract — what a skill `consumes` / `produces`. Declared by the skill's owner or harvested from stage declarations; adjudicated at load time (`canCompose`, the validator) to check composition. |
258
+
259
+ For the full DSL reference (all stage factories, loops, routing, outcomes, validators), see [workflow-authoring.md](./workflow-authoring.md). To drive the runtime from code, see [embedding.md](./embedding.md).
package/events.ts CHANGED
@@ -47,6 +47,21 @@ export interface LifecycleContext {
47
47
  /** What triggered this run; defaulted at `runWorkflow` entry if `options.trigger` was omitted. */
48
48
  trigger: RunTrigger;
49
49
  state: RunView;
50
+ /**
51
+ * Distinct stage names already executed in this run — the engine's
52
+ * authoritative `RunContext.visited`, RECONSTRUCTED from the JSONL trail on a
53
+ * resume. Populated only on the run-level projection (`lifecycleCtxFor`, which
54
+ * backs `onWorkflowStart`/`onWorkflowEnd`, script-stage `onStageStart`, and the
55
+ * loop/route fires); UNDEFINED on session-fired events (`lifecycleCtxFromSession`
56
+ * carries `runIdentity` only, never the live visited set).
57
+ *
58
+ * Exists so a status-line bridge can SEED its own distinct-visited accumulator
59
+ * at `onWorkflowStart`: a resumed run kicks the chain at its reconstructed walk
60
+ * position (a deep `stageNumber`), but only re-fires per-stage events from that
61
+ * point forward — without this, the bridge would recount `visited` from zero and
62
+ * a near-done resume would render a misleadingly tiny `visited/totalStages`.
63
+ */
64
+ visited?: readonly string[];
50
65
  }
51
66
 
52
67
  /**
@@ -133,6 +148,7 @@ export interface LoopCapInfo {
133
148
  * onLoopStart: (stage, info) => console.log(` ⇉ ${stage.name} [${info.kind}]`),
134
149
  * onUnitStart: (stage, u) => console.log(` → ${u.label} (${u.role})`),
135
150
  * onUnitEnd: (stage, u) => console.log(` · ${stage.name} #${u.index}`),
151
+ * onUnitHalt: (stage, u, reason) => console.warn(` ✗ ${stage.name} #${u.index}: ${reason}`),
136
152
  * onLoopCap: (stage, c) => console.warn(` ⚠ ${stage.name} capped at ${c.max}`),
137
153
  * onWorkflowEnd: (result) =>
138
154
  * console.log(result.success ? "✓ done" : `✗ ${result.error ?? "halted"}`),
@@ -167,8 +183,15 @@ export interface LifecycleListeners {
167
183
  /** After the stage's "failed"/"aborted" row lands in JSONL. Terminal for the run. */
168
184
  onStageError?(stage: StageRef, error: string, ctx: LifecycleContext): void | Promise<void>;
169
185
 
170
- /** After an `EdgeFn` picks and its routing-decision row lands. `to` may be the `STOP` sentinel literal `"stop"`. */
171
- onRoute?(from: StageRef, to: string, ctx: LifecycleContext): void | Promise<void>;
186
+ /**
187
+ * After an `EdgeFn` picks and its routing-decision row lands. `to` may be the
188
+ * `STOP` sentinel literal `"stop"`. `bypassed` lists the decision edge's
189
+ * not-taken RECOVERY arms — failure loops the chosen arm skipped for good (see
190
+ * `bypassedRecoveryArms` in routing.ts). A progress listener credits them so
191
+ * the bar reaches full while the terminal stage runs; empty for deterministic
192
+ * (string) edges and gates with no loop-back alternative.
193
+ */
194
+ onRoute?(from: StageRef, to: string, ctx: LifecycleContext, bypassed?: readonly string[]): void | Promise<void>;
172
195
 
173
196
  /** After `onStageStart`, before unit 1's session (after the unit list is computed for fanout). */
174
197
  onLoopStart?(stage: StageRef, info: LoopStartInfo, ctx: LifecycleContext): void | Promise<void>;
@@ -184,6 +207,18 @@ export interface LifecycleListeners {
184
207
  /** Per unit, after the unit's JSONL row lands. Loop units never fire `onStageEnd`. */
185
208
  onUnitEnd?(stage: StageRef, unit: UnitEvent, output: Output, ctx: LifecycleContext): void | Promise<void>;
186
209
 
210
+ /**
211
+ * Per unit, after a collect-all fanout unit's NON-TERMINAL `collected:true`
212
+ * failed row lands — the unit halted but the run survives (the synthesis fold
213
+ * skips its sentinel slot). Fired ONLY on the soft-halt path; a fail-fast unit
214
+ * fires `onStageError` (terminal) instead, and a successful unit fires
215
+ * `onUnitEnd`. Distinct from both so a lane surface can flip the unit's sub-row
216
+ * ✗ rather than leaving it to spin (then be swept ✓ at `onWorkflowEnd`).
217
+ * `reason` is the halt cause — the same text the `collected:true` row's
218
+ * `errMsg` carries.
219
+ */
220
+ onUnitHalt?(stage: StageRef, unit: UnitEvent, reason: string, ctx: LifecycleContext): void | Promise<void>;
221
+
187
222
  /** After an `onCap: "advance"` trip — fired after the `{type:"loop-cap"}` telemetry row append attempt. */
188
223
  onLoopCap?(stage: StageRef, info: LoopCapInfo, ctx: LifecycleContext): void | Promise<void>;
189
224
 
@@ -295,6 +330,7 @@ export function buildLifecycleContext(args: {
295
330
  totalStages: number;
296
331
  trigger: RunTrigger;
297
332
  state: RunView;
333
+ visited?: readonly string[];
298
334
  }): LifecycleContext {
299
335
  return args;
300
336
  }
@@ -304,8 +340,8 @@ export function buildLifecycleContext(args: {
304
340
  * structurally so this base-layer module never imports the runtime types).
305
341
  * Captured per fire so listeners always see the latest `state` snapshot.
306
342
  * THE one RunContext → LifecycleContext projection — the runner, the loop
307
- * driver, and the resume entries all share it (the old per-module clones
308
- * were kept aligned only by convention).
343
+ * driver, and the resume entries all share it; no per-module clones to keep
344
+ * aligned by convention.
309
345
  */
310
346
  export function lifecycleCtxFor(run: {
311
347
  cwd: string;
@@ -314,6 +350,7 @@ export function lifecycleCtxFor(run: {
314
350
  totalStages: number;
315
351
  trigger: RunTrigger;
316
352
  state: RunView;
353
+ visited: ReadonlySet<string>;
317
354
  }): LifecycleContext {
318
355
  return buildLifecycleContext({
319
356
  cwd: run.cwd,
@@ -322,6 +359,9 @@ export function lifecycleCtxFor(run: {
322
359
  totalStages: run.totalStages,
323
360
  trigger: run.trigger,
324
361
  state: run.state,
362
+ // Snapshot the live set — listeners must not mutate the engine's accumulator,
363
+ // and a fired ctx is captured per fire so a later `visited.add` is irrelevant.
364
+ visited: [...run.visited],
325
365
  });
326
366
  }
327
367
 
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Execution-host injection seam. The /wf launcher + runner are Pi-agnostic; the
3
+ * SDK-backed executor (`SdkWorkflowHost`) lives in rpiv-pi. rpiv-pi registers a
4
+ * provider at startup; `runWorkflow` looks it up, builds the executor from the
5
+ * live observer ctx, and threads it for stage execution (the executor relays UI
6
+ * back to the live session). Absent provider ⇒ the live ctx executes directly
7
+ * (graceful degrade for non-Pi embedders / tests).
8
+ */
9
+ import type { ModelSelection, WorkflowHostContext } from "./host.js";
10
+ import { globalSlot } from "./internal-utils.js";
11
+
12
+ /** What the provider hands back per run: the detached executor, an optional
13
+ * cancellation `signal` (rpiv-pi wires it from `ctx.ui.onTerminalInput`),
14
+ * and a `dispose` the runner calls in `finally` to unsubscribe the keystroke
15
+ * tap. `signal`/`dispose` are absent in headless mode (no UI ⇒ no abort). */
16
+ export interface WorkflowExecution {
17
+ host: WorkflowHostContext;
18
+ signal?: AbortSignal;
19
+ dispose?: () => void;
20
+ }
21
+
22
+ export interface WorkflowExecutionProvider {
23
+ /** Build the detached executor host (+ abort signal/teardown) from the live
24
+ * observer ctx + run identity. `childSessionsDir` is the RESOLVED run-scoped
25
+ * session dir — the runner computes it from its internal layout helper so
26
+ * rpiv-pi never imports a layout function across the package boundary. */
27
+ createHost(
28
+ observer: WorkflowHostContext,
29
+ opts: {
30
+ runId: string;
31
+ childSessionsDir: string;
32
+ name?: string;
33
+ /** Workflow name — lets the lane dock render a `workflow:` tag. Threaded
34
+ * from workflow.name (run path) / header.workflow (resume path). */
35
+ workflow?: string;
36
+ /** The run's original `/wf` input (the user prompt) — the dock renders it as the
37
+ * descriptor label when no `--name` alias is set. Threaded from options.input /
38
+ * header.input. */
39
+ input?: string;
40
+ },
41
+ ): WorkflowExecution | Promise<WorkflowExecution>;
42
+ /** Per-stage model resolution (rpiv-pi's resolveStageModel) — threaded onto
43
+ * RunContext.resolveModel so the dispatcher fills each child's ModelSelection. */
44
+ resolveModel?(id: { stage: string; skill: string }): ModelSelection | undefined;
45
+ }
46
+
47
+ // Use the SAME globalThis[Symbol.for(...)] slot mechanism as
48
+ // `registerLifecycle`/the built-in registry (internal-utils.globalSlot), NOT a
49
+ // plain module-level `let`. rpiv-pi reaches this seam via a dynamic
50
+ // `import("@juicesharp/rpiv-workflow/startup")` while the runner reaches it via a
51
+ // static `../execution-host.js`; if those ever resolve to two module instances
52
+ // of rpiv-workflow (peer-dependency duplication), a module-local `let` would put
53
+ // `register` and `get` on DIFFERENT slots and the lookup would silently return
54
+ // `undefined` (degrade-to-live — a quiet correctness bug, not a crash). A
55
+ // process-global Symbol slot is instance-independent and matches the precedent
56
+ // this seam claims to mirror.
57
+ //
58
+ // globalSlot signature: `globalSlot<T>(key: symbol, init: () => T): () => T` — a
59
+ // lazily-initialised getter. Because the provider must be resettable to
60
+ // `undefined` (and globalSlot never re-runs init once seeded), anchor a MUTABLE
61
+ // BOX, exactly like the lifecycle flush-box pattern (internal-utils.ts).
62
+ const getProviderBox = globalSlot(Symbol.for("@juicesharp/rpiv-workflow:executionHostProvider"), () => ({
63
+ provider: undefined as WorkflowExecutionProvider | undefined,
64
+ }));
65
+
66
+ export function registerWorkflowExecutionHost(p: WorkflowExecutionProvider): void {
67
+ getProviderBox().provider = p;
68
+ }
69
+ export function getWorkflowExecutionProvider(): WorkflowExecutionProvider | undefined {
70
+ return getProviderBox().provider;
71
+ }
72
+ /** Test reset — re-exported from `internal.ts` and called in `test/setup.ts` beforeEach. */
73
+ export function __resetWorkflowExecutionHost(): void {
74
+ getProviderBox().provider = undefined;
75
+ }