@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/triggers.ts CHANGED
@@ -16,12 +16,20 @@
16
16
  * Concurrency note: Pi is single-active-session. External triggers
17
17
  * (cron, webhook, sibling-extension spawn) MUST gate their own
18
18
  * spawning if a run is already in flight — the runtime does not
19
- * enforce a process-wide mutex.
19
+ * enforce a process-wide mutex. The same applies across PROCESSES:
20
+ * the `names.json` claim protocol (state/names.ts) is atomic per write
21
+ * (temp file + rename) but has no cross-process lock, so two concurrent
22
+ * triggering processes claiming run names can race the read-modify-write
23
+ * (lost update / duplicate claim; recoverable via `rebuildIndex`).
20
24
  */
21
25
  export type RunTrigger =
22
26
  | { kind: "command"; name: string; meta?: Record<string, unknown> }
23
27
  | { kind: "programmatic"; source?: string; meta?: Record<string, unknown> }
24
28
  | { kind: "external"; source: string; ref?: string; meta?: Record<string, unknown> };
25
29
 
26
- /** Default when `RunWorkflowOptions.trigger` is omitted. */
27
- export const DEFAULT_TRIGGER: RunTrigger = { kind: "programmatic" };
30
+ /**
31
+ * Default when `RunWorkflowOptions.trigger` is omitted. Frozen — the literal
32
+ * is shared by every run that omits `trigger`, so a mutation (e.g. via the
33
+ * open `meta` escape hatch) would silently leak into unrelated runs.
34
+ */
35
+ export const DEFAULT_TRIGGER: RunTrigger = Object.freeze({ kind: "programmatic" });
package/types.ts CHANGED
@@ -2,13 +2,14 @@
2
2
  * Runtime types. Three nouns flow through the workflow runtime:
3
3
  *
4
4
  * - `RunContext` — per-run carry (cwd, runId, workflow, state, visited,
5
- * continueHost, registeredSkills, maxBackwardJumps). Read by every
5
+ * registeredSkills, resolveModel, maxBackwardJumps). Read by every
6
6
  * layer; mutated only by the runner.
7
7
  * - `RunState` — mutable bookkeeping (output, counters, telemetry,
8
- * termination). Read by every layer; mutated by the runner + the audit
9
- * layer. Always read the chain's primary artifact via
10
- * `currentPrimaryArtifact(state)` (internal-utils.ts) — it prefers
11
- * `output.artifacts[0]` and falls back to `fallbackPrimaryArtifact`.
8
+ * termination). Read by every layer; mutated through the chain-state
9
+ * authorities (chain-state.ts) by the runner, the loop driver, the audit
10
+ * layer, and the resume fold — external consumers get the deep-readonly
11
+ * `RunView` projection instead. Always read the chain's primary artifact
12
+ * via `currentPrimaryArtifact(state)` (chain-state.ts).
12
13
  * - `WorkflowHostContext` — the host port (defined in `host.js`, re-exported
13
14
  * here) threaded from `withSession` callbacks down through stage/phase
14
15
  * helpers, so the runtime layers import all three nouns from one module.
@@ -23,16 +24,22 @@
23
24
  */
24
25
 
25
26
  import type { StageDef, Workflow } from "./api.js";
27
+ import type { LifecycleDispatcher, LifecycleListeners } from "./events.js";
26
28
  import type { Artifact } from "./handle.js";
27
- import type { WorkflowHost, WorkflowHostContext } from "./host.js";
28
- import type { LifecycleDispatcher } from "./lifecycle.js";
29
+ import type { ModelSelection, WorkflowHost, WorkflowHostContext } from "./host.js";
29
30
  import type { Output } from "./output.js";
30
31
  import type { SkillContractMap } from "./skill-contract.js";
32
+ import type { SessionRef } from "./state/index.js";
31
33
  import type { RunTrigger } from "./triggers.js";
32
34
 
33
35
  // Re-export the host port so runtime layers can pull `RunContext`,
34
- // `RunState`, and the threaded ctx from this single runtime-types module.
35
- export type { WorkflowHostContext } from "./host.js";
36
+ // `RunState`, and the threaded ctx + model type from this single
37
+ // runtime-types module.
38
+ export type {
39
+ ModelSelection,
40
+ WorkflowHostContext,
41
+ WorkflowSessionContext,
42
+ } from "./host.js";
36
43
 
37
44
  /** Mutable per-run bookkeeping threaded through the chain by reference. */
38
45
  export interface RunState {
@@ -74,9 +81,27 @@ export interface RunState {
74
81
  stagesCompleted: number;
75
82
  /** Most recently allocated stageNumber. Advances on every recordStage call. */
76
83
  lastAllocatedStageNumber: number;
84
+ /**
85
+ * The `SessionRef` of the most recently completed SINGLE stage — what a
86
+ * downstream `sessionPolicy: "continue"` stage forks from (its predecessor's
87
+ * persisted child session). Rolls forward like `output`: set on every
88
+ * single-stage success (`recordStageSuccess`) and reconstructed by the resume
89
+ * fold from the last completed single-stage row. Loop UNITS never touch it
90
+ * (they take the unit branch of `recordStageSuccess` and fold via
91
+ * `foldUnitRow`), so a `continue` right after a loop forks the last single
92
+ * stage — the loop was a fan-out excursion with no single session to continue.
93
+ * Undefined at run start or when the predecessor persisted no session (an
94
+ * in-memory host); either degrades a `continue` stage to a fresh dispatch.
95
+ */
96
+ lastSession?: SessionRef;
77
97
 
78
98
  // ── Telemetry (post-hoc only; not consulted by chain advancement) ──
79
99
  telemetry: {
100
+ /**
101
+ * Run-wide cumulative count of backward jumps (decision-edge routes to
102
+ * an already-visited stage). Never reset. The halt decision reads the
103
+ * per-destination `RunContext.revisits` ledger, not this total.
104
+ */
80
105
  backwardJumps: number;
81
106
  /**
82
107
  * Routing rows whose JSONL append failed mid-run. The chain advanced
@@ -87,13 +112,157 @@ export interface RunState {
87
112
  * in the common case.
88
113
  */
89
114
  droppedRoutingRows: Array<{ fromStageIndex: number; fromStage: string; decision: string }>;
115
+ /**
116
+ * Stages whose terminal failure/aborted row failed to append. Unlike
117
+ * routing rows these ARE reconstruction inputs — a trail missing its
118
+ * failure row reads "completed" at the tail and a later resume would
119
+ * route onward past the stage that actually failed. Surfaced in
120
+ * `RunWorkflowResult.droppedFailureRows`; consumers holding entries
121
+ * must not resume the run from disk. Empty in the common case.
122
+ */
123
+ droppedFailureRows: string[];
90
124
  };
91
125
 
92
126
  // ── Termination (set once at end-of-run) ───────────────────────────
93
- termination: {
94
- success: boolean;
95
- error: string | undefined;
96
- };
127
+ /**
128
+ * How the run ended — `"running"` until the single end-of-run write via
129
+ * `terminate()` (audit.ts), the ONLY sanctioned mutator. Discriminated so
130
+ * every outcome is representable — cancellation is its own status, not
131
+ * smuggled through the error string — and so a halt site can't set half
132
+ * the shape.
133
+ */
134
+ termination: RunTermination;
135
+ }
136
+
137
+ /**
138
+ * Run-termination outcome — the discriminated form behind
139
+ * `RunState.termination` and `RunWorkflowResult.termination`.
140
+ *
141
+ * - `"running"` — not terminated yet (also: the runner unwound without
142
+ * reaching any terminal write — treated as failure).
143
+ * - `"completed"` — the chain reached `stop`.
144
+ * - `"failed"` — a stage/preflight/routing halt; `error` carries the cause.
145
+ * - `"aborted"` — cooperative cancellation via `RunWorkflowOptions.signal`,
146
+ * or the model aborted the stage.
147
+ * - `"cancelled"` — the user dismissed the live session mid-stage. Recorded
148
+ * on disk as the legacy FROZEN `StageStatus: "skipped"` (state/state.ts),
149
+ * written solely by `recordCancellation` (audit.ts); the canonical name
150
+ * (`"cancelled"`) and the frozen row value (`"skipped"`) differ by design.
151
+ */
152
+ export type RunTermination =
153
+ | { status: "running"; error?: undefined }
154
+ | { status: "completed"; error?: undefined }
155
+ | { status: "failed"; error: string }
156
+ | { status: "aborted"; error: string }
157
+ | { status: "cancelled"; error: string };
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // Public run envelope — options in, result out
161
+ // ---------------------------------------------------------------------------
162
+ // Lives here (the runtime-types leaf), NOT in runner/runner.ts: the result
163
+ // envelope is public surface consumed by events.ts (`onWorkflowEnd`) and
164
+ // every embedder — a base-layer module must not import the deepest engine
165
+ // module to name it.
166
+
167
+ export interface RunWorkflowOptions {
168
+ /** Workflow to execute — caller resolves by name from `LoadedWorkflows`. */
169
+ workflow: Workflow;
170
+ /** Passed to the start stage as its argument. */
171
+ input: string;
172
+ /** Registry-level host — enumerated once for the skill-registration snapshot. */
173
+ host?: WorkflowHost;
174
+ /** Per-destination decision-edge re-entry cap. Defaults to MAX_BACKWARD_JUMPS. */
175
+ maxBackwardJumps?: number;
176
+ /** Run-wide safety cap on loop units (all kinds). Defaults to MAX_ITERATIONS. */
177
+ maxIterations?: number;
178
+ /**
179
+ * What triggered this run. `/wf` sets `{ kind: "command", name: "wf" }`;
180
+ * programmatic embedders default to `DEFAULT_TRIGGER`. Recorded in the
181
+ * JSONL header and surfaced on every lifecycle callback via
182
+ * `LifecycleContext.trigger`.
183
+ */
184
+ trigger?: RunTrigger;
185
+ /**
186
+ * Per-call lifecycle listener bundle. Fires AFTER every globally
187
+ * registered bundle (see `registerLifecycle`). Listener throws are
188
+ * caught + logged via `ctx.ui.notify(..., "warning")`; never halt the
189
+ * run.
190
+ */
191
+ lifecycle?: LifecycleListeners;
192
+ /**
193
+ * Cooperative cancellation. When the signal is aborted, the runner stops at
194
+ * the next between-stage seam — it records an `"aborted"` terminal row for
195
+ * the stage about to run and returns `{ success: false }` with an aborted
196
+ * error. It does NOT interrupt a stage already streaming (Pi owns the live
197
+ * session), so cancellation takes effect at the next stage boundary, not
198
+ * mid-stage.
199
+ */
200
+ signal?: AbortSignal;
201
+ /**
202
+ * Per-stage model-override resolver, injected by the embedder. Threaded onto
203
+ * `RunContext.resolveModel` → every `StageSession.model`; the host applies it
204
+ * at child-session creation. Undefined ⇒ host default for every stage.
205
+ */
206
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
207
+ /**
208
+ * Human-readable alias for this run. Stored in the JSONL header and the
209
+ * sidecar names.json index. Rejected if already in use — the error
210
+ * identifies the conflicting runId.
211
+ */
212
+ name?: string;
213
+ }
214
+
215
+ export interface RunWorkflowResult {
216
+ /**
217
+ * The run's identity on disk — the `<run-id>` portion of
218
+ * `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl`. Live consumers can hand
219
+ * this to `readLastStage` / `listArtifacts` / future inspect-past-run
220
+ * helpers without recomputing the slug.
221
+ *
222
+ * Undefined ONLY for pre-flight rejections (e.g. start stage not declared,
223
+ * name collision) where no JSONL file was created.
224
+ */
225
+ runId?: string;
226
+ stagesCompleted: number;
227
+ success: boolean;
228
+ /**
229
+ * Primary artifact at run termination, serialised to its handle's
230
+ * canonical string form (fs → path, url → href, opaque → id). Undefined
231
+ * if no produces stage produced one. Callers that need the full
232
+ * structured handle read `output.artifacts[0]` off the run's last
233
+ * recorded stage (via `readLastStage`).
234
+ */
235
+ lastArtifact?: string;
236
+ error?: string;
237
+ /**
238
+ * Discriminated termination outcome — the full-fidelity form behind the
239
+ * `success`/`error` projections above (which can't represent "cancelled"
240
+ * vs "aborted" vs "failed"). `{ status: "running" }` means the runner
241
+ * unwound without reaching any terminal write — callers treat it as
242
+ * failure, same as the `success: false` projection does.
243
+ *
244
+ * Undefined ONLY for pre-flight rejections (no run was constructed) —
245
+ * same rule as `runId`.
246
+ */
247
+ termination?: RunTermination;
248
+ /**
249
+ * Routing decisions made in memory but whose JSONL audit row failed to
250
+ * persist. Empty in the common case. Surfaced so consumers reading the
251
+ * run's JSONL can disambiguate a missing routing row ("deterministic
252
+ * edge — never written") from a dropped one ("decision was made, write
253
+ * failed"). The run still succeeds — routing rows are telemetry, not
254
+ * reconstruction inputs.
255
+ */
256
+ droppedRoutingRows?: Array<{ fromStageIndex: number; fromStage: string; decision: string }>;
257
+ /**
258
+ * Stages whose terminal failure/aborted row failed to persist. Empty in
259
+ * the common case. Unlike routing rows, failure rows ARE reconstruction
260
+ * inputs: a trail missing its failure row reads as if the run stopped
261
+ * after its last successful stage, so a later resume would route onward
262
+ * past the stage that actually failed. Consumers holding this list should
263
+ * not resume the run from disk.
264
+ */
265
+ droppedFailureRows?: string[];
97
266
  }
98
267
 
99
268
  /** Per-run context the chain carries from stage to stage. */
@@ -102,20 +271,30 @@ export interface RunContext {
102
271
  runId: string;
103
272
  workflow: Workflow;
104
273
  /**
105
- * Upper bound for stage status display — count of stages reachable from
274
+ * Upper bound for stage-progress display — count of stages reachable from
106
275
  * `workflow.start`, computed once at run start. The actual stage count
107
- * is path-dependent (a predicate edge may short-circuit), so this is
108
- * the denominator users see; the numerator is the live stage index.
276
+ * is path-dependent (a predicate edge may short-circuit), so this is the
277
+ * denominator surfaced through the lifecycle `LifecycleContext.totalStages`
278
+ * (e.g. the lane-dock `visited/totalStages` progress bar); the numerator is
279
+ * the live stage index.
109
280
  */
110
281
  totalStages: number;
111
282
  state: RunState;
112
283
  /**
113
- * Stage names already executed in this run. The backward-jump guard
114
- * increments `state.telemetry.backwardJumps` on every re-entry; revise →
115
- * implement loops legitimately revisit stages, but unbounded loops trip
116
- * the cap.
284
+ * Stage names already executed in this run. A decision edge resolving to
285
+ * a visited stage is a backward jump; revise → implement loops
286
+ * legitimately revisit stages, but unbounded loops trip the cap.
117
287
  */
118
288
  visited: Set<string>;
289
+ /**
290
+ * Decision-edge re-entry count per destination stage — the backward-jump
291
+ * guard's ledger. Each stage may be re-entered at most `maxBackwardJumps`
292
+ * times; counting per destination (not as a shared streak) keeps the
293
+ * retry budget invariant to how many decision edges a fix cycle crosses
294
+ * per iteration, and gives unrelated loops independent budgets by
295
+ * construction.
296
+ */
297
+ revisits: Map<string, number>;
119
298
  /**
120
299
  * Set of bare skill names registered with Pi at workflow start (e.g.
121
300
  * "research", "blueprint" — the `skill:` prefix is stripped). Snapshot
@@ -130,9 +309,9 @@ export interface RunContext {
130
309
  */
131
310
  registeredSkills?: ReadonlySet<string>;
132
311
  /**
133
- * Snapshot of the declared/injected skill-contract registry, taken once in
312
+ * Snapshot of the registered skill-contract registry, taken once in
134
313
  * `buildRunContext` (mirrors `registeredSkills`). This is the
135
- * declared/injected registry — NOT the harvested-merged
314
+ * registered (`declared`-source) registry — NOT the harvested-merged
136
315
  * `LoadedWorkflows.skillContracts` — because both runtime uses only add
137
316
  * value over a declared contract:
138
317
  * - `ensureContractInputValid` mirrors a declared `consumes.data` that
@@ -146,36 +325,24 @@ export interface RunContext {
146
325
  */
147
326
  skillContracts?: SkillContractMap;
148
327
  /**
149
- * Pi `ExtensionAPI` handle, retained as the FALLBACK send-path for
150
- * continue-policy stages — used only when the live inner ctx lacks
151
- * `sendUserMessage` (i.e. the workflow's first stage is continue and
152
- * the runtime is still on the outer command ctx). Everywhere else,
153
- * `CONTINUE_HANDLER` prefers `ctx.sendUserMessage` because Pi marks
154
- * this handle stale after the first `ctx.newSession()`. Touching it
155
- * for anything other than the fallback path will throw "extension
156
- * ctx is stale" on every workflow whose first stage is fresh.
157
- *
158
- * Read-only registry needs go through `registeredSkills` (snapshotted
159
- * at workflow start). Continue-policy presence checks
160
- * (`enforceSessionInvariants`) still gate on this field so the
161
- * fallback path has a working host when the start-stage path needs it.
162
- *
163
- * Naming: deliberately NOT called `host`. Future code-readers see the
164
- * field name and know the constraint without reading the JSDoc.
328
+ * Resolve a per-stage model override, injected by the embedder (rpiv-pi maps
329
+ * each `{ stage, skill }` to its model/effort override). The runner threads
330
+ * the result onto every `StageSession.model`; the host applies it at child
331
+ * creation (NOT via global mutation). Undefined ⇒ host default.
165
332
  */
166
- continueHost?: WorkflowHost;
333
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
167
334
  maxBackwardJumps: number;
168
335
  /**
169
- * Run-wide safety cap on `iterate`-stage units. The generator is
170
- * loop-terminated (returns `null`), not array-bounded like `fanout`, so the
171
- * runner backstops a runaway generator: when `accumulated.length` reaches
172
- * this, the stage halts with a terminal failure. Defaults to
173
- * `MAX_ITERATIONS`.
336
+ * Run-wide safety cap on loop units — clamps the effective cap of EVERY
337
+ * loop kind (`min(loop.max, run.maxIterations)`), the backstop for a
338
+ * source that never terminates (a pull generator that never returns
339
+ * `null`, an assess `done` that never trips). What happens at the cap is
340
+ * the loop's `CapPolicy`. Defaults to `MAX_ITERATIONS`.
174
341
  */
175
342
  maxIterations: number;
176
343
  /** What triggered the run; defaulted at `runWorkflow` entry. */
177
344
  trigger: RunTrigger;
178
- /** Lifecycle event dispatcher — see `lifecycle.ts`. Threaded by reference. */
345
+ /** Lifecycle event dispatcher — see `events.ts`. Threaded by reference. */
179
346
  lifecycle: LifecycleDispatcher;
180
347
  /**
181
348
  * Optional cooperative-cancellation signal from `RunWorkflowOptions.signal`.
@@ -188,10 +355,10 @@ export interface RunContext {
188
355
  }
189
356
 
190
357
  /**
191
- * Per-stage / per-unit common base. Extended by `StageSession` and
192
- * `FanoutSession`; consumed in pick form by `AuditCtx` (audit.ts) so the audit
193
- * layer pins its dependency on this shape structurally instead of
194
- * duplicating the field list.
358
+ * Per-stage / per-unit common base. Extended by `StageSession` (loop units
359
+ * thread their identity through `StageSession.unit`); consumed in pick form by
360
+ * `AuditCtx` (audit.ts) so the audit layer pins its dependency on this shape
361
+ * structurally instead of duplicating the field list.
195
362
  *
196
363
  * `stageName` is the workflow stage's record key — the value that lands
197
364
  * in `WorkflowStage.stage`. `skill` is the Pi skill body the runner
@@ -210,7 +377,7 @@ export interface SessionContext {
210
377
  stageName: string;
211
378
  /** Pi skill body — `/skill:<skill>` dispatch + status-line label + JSONL `WorkflowStage.skill`. */
212
379
  skill: string;
213
- /** Shared lifecycle dispatcher. Threaded from `RunContext` so the audit layer can fire `onStageEnd` / `onStageError` / `onFanoutUnitEnd` without re-importing it. */
380
+ /** Shared lifecycle dispatcher. Threaded from `RunContext` so the audit layer can fire `onStageEnd` / `onStageError` / `onUnitEnd` without re-importing it. */
214
381
  lifecycle: LifecycleDispatcher;
215
382
  /**
216
383
  * Read-only run identity passed to lifecycle callbacks. Captured at
@@ -222,12 +389,39 @@ export interface SessionContext {
222
389
  totalStages: number;
223
390
  trigger: RunTrigger;
224
391
  };
392
+ /**
393
+ * The activation's allocated JSONL stage number. Assigned ONCE (via
394
+ * `allocateStageNumber`) when output production begins, BEFORE the output
395
+ * envelope is built — the envelope's `meta.stageNumber`, the audit row
396
+ * (success or failure), and every lifecycle ref for this activation then
397
+ * agree on one explicit value. Undefined until the activation reaches
398
+ * output production; pre-output halts allocate at record time instead.
399
+ */
400
+ allocatedStageNumber?: number;
401
+ }
402
+
403
+ /**
404
+ * Unit identity threaded onto a loop unit's session. Source of the
405
+ * structured JSONL row fields (`unitRowFields`, audit.ts) and the public
406
+ * `UnitEvent` lifecycle payload. `parent` is the loop stage's record key —
407
+ * the value resume dispatch and the fold key on; `label` feeds the decorated
408
+ * display string, the status line, and the per-unit toast.
409
+ */
410
+ export interface UnitRef {
411
+ parent: string;
412
+ role: import("./api.js").UnitRole;
413
+ /** 0-based generation cursor (== the round index for assess loops). */
414
+ index: number;
415
+ /** Stable audit identity (`unit.id ?? unit.label` for fanout/iterate; undefined for assess). */
416
+ id?: string;
417
+ /** Display tag. */
418
+ label: string;
225
419
  }
226
420
 
227
421
  export interface StageSession extends SessionContext {
228
422
  stage: StageDef;
229
423
  /**
230
- * Declared/injected skill-contract registry, threaded from
424
+ * Registered skill-contract registry, threaded from
231
425
  * `RunContext.skillContracts` at session construction. Lets output
232
426
  * validation fall back to the dispatched skill's `produces.data` when the
233
427
  * stage carries no `outputSchema` of its own. Fail-soft: absent for
@@ -239,37 +433,55 @@ export interface StageSession extends SessionContext {
239
433
  /** Pre-stage snapshot value (undefined if the stage's `outcome` has no `snapshot`). */
240
434
  snapshot: unknown;
241
435
  /**
242
- * Pi `ExtensionAPI` handle reserved for the continue-policy handler
243
- * (`spawn.ts`). Required iff `stage.sessionPolicy === "continue"`.
244
- * Same constraint as `RunContext.continueHost`: stale after any prior
245
- * `ctx.newSession()`, so the runner MUST NOT read it for registry
246
- * inspection. See `RunContext.continueHost` JSDoc.
436
+ * Resolved per-unit model override (from `RunContext.resolveModel`), applied
437
+ * by the host at child-session creation — NOT via global mutation. Undefined
438
+ * ⇒ host default.
439
+ */
440
+ model?: ModelSelection;
441
+ /**
442
+ * Per-child cooperative-abort signal. Threaded from `RunContext.signal` (the
443
+ * fanout dispatcher narrows it to a per-generation controller) so
444
+ * an aborted run interrupts an in-flight child, not just the between-stage
445
+ * seam.
247
446
  */
248
- continueHost?: WorkflowHost;
447
+ signal?: AbortSignal;
448
+ /**
449
+ * When true (a collect-all fanout unit), a unit failure soft-halts THIS unit
450
+ * (non-terminal failed-output sentinel handed to `onSuccess`) instead of
451
+ * terminating the whole run. Set by `buildUnitSession` for non-fail-fast
452
+ * fanout; the soft-halt routing lives in `postStage`.
453
+ */
454
+ collectAll?: boolean;
455
+ /**
456
+ * The per-unit lane key for rpiv-pi's lane dock/viewer — set ONLY for fan-out
457
+ * units (`e.loop.kind === "fanout"`), to the unit's declared `index`. Undefined for
458
+ * sequential loop units (iterate/assess) and single stages, which collapse onto the
459
+ * host's reserved single-unit slot so the lane (parent) row keeps showing the one
460
+ * live session. Distinct from `unit.index` (the audit identity threaded for every
461
+ * loop unit): this field exists purely so the host can decide which spawns become
462
+ * individually-addressable concurrent sub-lanes. `openChild` threads it into
463
+ * `spawnChild`'s `unitIndex`; inert on a non-lane host.
464
+ */
465
+ laneUnitIndex?: number;
249
466
  /** Only set for continue stages — branch slice offset. */
250
467
  branchOffset?: number;
468
+ /**
469
+ * Present iff this session IS one loop unit. Pre-decorated at session
470
+ * construction by the driver (`stageName` carries the DISPLAY decoration;
471
+ * this field carries the machine identity). Drives: structured row fields,
472
+ * `onUnitEnd` instead of `onStageEnd`, the labeled per-unit toast, and
473
+ * unit-attributed failure rows.
474
+ */
475
+ unit?: UnitRef;
251
476
  onFailure?: (ctx: WorkflowHostContext) => void;
252
- onSuccess: (ctx: WorkflowHostContext, artifact: Artifact | undefined) => Promise<void>;
253
- }
254
-
255
- /**
256
- * One unit of a fanout iteration. `label` is the user-supplied
257
- * disambiguating tag from `FanoutUnit.label`; it's woven into the status
258
- * line (`STATUS_FANOUT_UNIT`). The JSONL row's `stage` value (built by
259
- * `fanoutRowStage`) prefixes the parent's `stageName` with `id ?? label`
260
- * so the runner adds no implicit wording.
261
- */
262
- export interface FanoutSession extends SessionContext {
263
- /** 1-based position within the run's fanout array — for halt diagnostics. */
264
- unitIndex: number;
265
- /** From `FanoutUnit.label` — already disambiguating, e.g. `"phase 2/5"`. */
266
- label: string;
267
477
  /**
268
- * From `FanoutUnit.id` when set — stable audit identifier preferred
269
- * over `label` in JSONL rows. Undefined when the user supplied none.
478
+ * Receives the stage's VALIDATED Output envelope (not just
479
+ * `artifacts[0]`) — loop continuations thread it into `accumulated` /
480
+ * `feedForward` directly, with no `run.state.output!` back-read.
481
+ *
482
+ * Return type is `Promise<unknown>` (not `void`) so the chain walk's
483
+ * `ChainOutcome`-returning continuations plug in directly; the session
484
+ * layer only awaits settlement.
270
485
  */
271
- id?: string;
272
- /** Parent stage's 0-based index. */
273
- stageIndex: number;
274
- onSuccess: (ctx: WorkflowHostContext) => Promise<void>;
486
+ onSuccess: (ctx: WorkflowHostContext, output: Output) => Promise<unknown>;
275
487
  }