@juicesharp/rpiv-workflow 1.19.1 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
package/state/state.ts CHANGED
@@ -4,6 +4,12 @@
4
4
  * fail-soft (logs via console.warn with `[rpiv-workflow]` prefix, never
5
5
  * throws).
6
6
  *
7
+ * The trail is resume's SYSTEM OF RECORD — `runner/resume.ts` folds the rows
8
+ * back into a `RunState`, so the on-disk shape is a versioned contract, not a
9
+ * debug artifact. The header carries `v` (see `STATE_SCHEMA_VERSION`); resume
10
+ * refuses files written under a different version rather than mis-replaying
11
+ * them. Display readers stay lenient (shape-filtered, skip-on-mismatch).
12
+ *
7
13
  * Internally split into three modules:
8
14
  * - paths.ts — runsDir + stateFilePath + generateRunId
9
15
  * - writes.ts — tryAppendJsonl + writeHeader + appendStage +
@@ -15,6 +21,7 @@
15
21
  * else lives in a focused module.
16
22
  */
17
23
 
24
+ import type { UnitRole } from "../api.js";
18
25
  import type { Output } from "../output.js";
19
26
  import type { RunTrigger } from "../triggers.js";
20
27
 
@@ -25,18 +32,54 @@ import type { RunTrigger } from "../triggers.js";
25
32
  export type StageStatus = "completed" | "failed" | "skipped" | "aborted";
26
33
 
27
34
  /**
28
- * Audit files are debug artifacts — no migration provided. Readers
29
- * shape-filter on `stageNumber`, so any rows that don't satisfy the
30
- * current shape are silently skipped.
35
+ * The Pi session that backed a stage activation — a value object the row
36
+ * serializes verbatim (wire shape = domain shape). Produced by
37
+ * `readSessionRef` (transcript.ts — the reader produces the value the row
38
+ * stores; one definition, no parallel type).
39
+ *
40
+ * - `id` — session identity. Forever.
41
+ * - `file` — `getSessionFile()` at capture time; a location HINT.
42
+ * Absent for non-persisting (in-memory) sessions. A stale
43
+ * path is recoverable: resume falls back to searching its
44
+ * dirname for `*_<id>.jsonl`, then to a header scan, then
45
+ * to cold re-run (see `sessions/locate.ts`).
46
+ * - `branchOffset` — the offset the activation ran under (continue-policy
47
+ * stages only); promotion/reattach scope extraction with
48
+ * it, exactly as the live path did.
49
+ *
50
+ * Nested deliberately — unlike `parent`/`role`/`unitId`/`unitIndex`
51
+ * (independent dispatch keys, hence flat), `file`/`branchOffset` are
52
+ * meaningless without `id` and are always consumed together; nesting makes
53
+ * the invalid states unrepresentable.
54
+ */
55
+ export interface SessionRef {
56
+ id: string;
57
+ file?: string;
58
+ branchOffset?: number;
59
+ }
60
+
61
+ /**
62
+ * One stage activation's row. DISPLAY readers shape-filter on `stageNumber`
63
+ * and silently skip rows that don't satisfy the current shape; the RESUME
64
+ * reader (`readAllStagesForResume`) refuses instead — the fold replays these
65
+ * rows as the run's system of record (see the module header).
31
66
  *
32
- * Two identity fields:
33
- * - `stage` — the workflow stage's record key. Always present. The
34
- * audit row's "which step ran" answer; stable across skill-body
35
- * overrides and aliased stages.
36
- * - `skill?` — the Pi skill body invoked, when this row records a
37
- * skill stage. Absent for script stages (`StageDef.run`); equal to
38
- * `stage` in the common case where `produces()` / `acts()` defaults
39
- * the skill body to the record key.
67
+ * Identity fields:
68
+ * - `stage` — DISPLAY identity. For single stages this is the workflow
69
+ * record key; for loop-unit rows it is the decorated human string
70
+ * (`"implement (phase-2)"`, `"breakdown (r0·judge)"`). Machine readers
71
+ * must NOT parse it — the structured fields below are the only machine
72
+ * channel.
73
+ * - `skill?` — the Pi skill body invoked. Absent for script stages; the
74
+ * judge's own skill on judge-unit rows.
75
+ * - `parent?` / `role?` / `unitId?` / `unitIndex?` — present iff the row
76
+ * records a loop unit. `parent` is the loop stage's record key (the
77
+ * resume fold + dispatch key on it); `role` says produce vs judge;
78
+ * `unitIndex` is the 0-based cursor within the generation (== the round
79
+ * for assess loops); `unitId` is the author-stable unit identity
80
+ * (`unit.id ?? unit.label`) for fanout/iterate, absent for assess
81
+ * (identity there is `(role, unitIndex)`). Present on FAILURE rows too —
82
+ * the resume drift guard consumes failed-trailer identity.
40
83
  *
41
84
  * The row no longer carries a top-level `artifact` field — discovery
42
85
  * moved into the collector, and the canonical artifact list lives on
@@ -57,14 +100,60 @@ export interface WorkflowStage {
57
100
  * JSONL alone, without depending on a transient `ctx.ui.notify` toast.
58
101
  */
59
102
  errMsg?: string;
103
+ /**
104
+ * REQUIRED: the Pi session that backed this activation, or `null` as an
105
+ * explicit statement that no session was involved (script stages,
106
+ * preflight halts, seam aborts, drift failures, pre-open cancellations) —
107
+ * writers cannot forget the decision, and an orphan `file`/`branchOffset`
108
+ * without an `id` is unrepresentable. The resume reader refuses rows
109
+ * missing the key (pre-feature files land in the `malformed-row` arm);
110
+ * display readers stay lenient and never touch it.
111
+ */
112
+ session: SessionRef | null;
113
+ parent?: string;
114
+ role?: UnitRole;
115
+ unitId?: string;
116
+ unitIndex?: number;
60
117
  }
61
118
 
119
+ /**
120
+ * Telemetry row appended when a loop's `onCap: "advance"` trips — makes the
121
+ * soft-stop durable (post-hoc readers can distinguish "judge said done" from
122
+ * "cap tripped"). Shape-discriminated like RoutingDecision; stage readers and
123
+ * the resume fold skip it untouched. `count` is units run for fanout/iterate,
124
+ * rounds run for assess; `max` is the effective cap that tripped.
125
+ */
126
+ export interface LoopCapRow {
127
+ type: "loop-cap";
128
+ stage: string;
129
+ count: number;
130
+ max: number;
131
+ ts: string;
132
+ }
133
+
134
+ /**
135
+ * On-disk schema version stamped into every new header's `v`. Bump when a
136
+ * row/envelope shape changes in a way the resume fold cannot replay —
137
+ * `reconstructState` refuses headers carrying any other version
138
+ * (`reason: "version-mismatch"`) instead of silently mis-replaying.
139
+ *
140
+ * BACK-COMPAT RULE: an absent `v` is version 1 — files written before the
141
+ * field existed resume normally. Tested in `runner/resume.test.ts`.
142
+ */
143
+ export const STATE_SCHEMA_VERSION = 1;
144
+
62
145
  /** First line of the JSONL file. */
63
146
  export interface WorkflowHeader {
64
147
  runId: string;
65
148
  workflow: string;
66
149
  input: string;
67
150
  ts: string;
151
+ /**
152
+ * On-disk schema version — see `STATE_SCHEMA_VERSION`. Optional so headers
153
+ * written before the field existed still parse; readers treat `undefined`
154
+ * as version 1.
155
+ */
156
+ v?: number;
68
157
  /**
69
158
  * What triggered the run. Optional so older JSONL files (written
70
159
  * before the trigger field was added) still parse — readers treat
@@ -101,6 +190,12 @@ export interface RoutingDecision {
101
190
  fromStageIndex: number;
102
191
  fromStage: string;
103
192
  decision: string;
193
+ /**
194
+ * Diagnostic the deciding `EdgeFn` attached to this pick (via the
195
+ * `ROUTE_NOTE` channel) — e.g. `gate`'s "no branch matched, fallback
196
+ * fired." Absent for ordinary matched decisions.
197
+ */
198
+ note?: string;
104
199
  ts: string;
105
200
  }
106
201
 
@@ -109,23 +204,25 @@ export interface RoutingDecision {
109
204
  // ---------------------------------------------------------------------------
110
205
 
111
206
  export {
112
- addNameToIndex,
113
207
  type ClaimResult,
114
208
  claimName,
115
209
  isValidName,
116
210
  type NamesIndex,
117
211
  readNamesIndex,
118
212
  rebuildIndex,
213
+ releaseName,
119
214
  VALID_NAME,
120
215
  } from "./names.js";
121
- export { generateRunId, namesFilePath, runsDir, stateFilePath } from "./paths.js";
216
+ export { generateRunId, namesFilePath, runFileFor, runsDir, stateFilePath } from "./paths.js";
122
217
  export {
123
218
  listArtifacts,
124
219
  listRuns,
125
220
  readAllStages,
221
+ readAllStagesForResume,
126
222
  readHeader,
127
223
  readLastStage,
224
+ readLoopCaps,
128
225
  readRoutingDecisions,
129
- resolveRun,
130
226
  } from "./reads.js";
131
- export { appendRoutingDecision, appendStage, writeHeader } from "./writes.js";
227
+ export { resolveRun } from "./resolve.js";
228
+ export { appendLoopCap, appendRoutingDecision, appendStage, writeHeader } from "./writes.js";
package/state/writes.ts CHANGED
@@ -1,25 +1,27 @@
1
1
  /**
2
2
  * Fail-soft JSONL appends. Every public helper here is a thin wrapper
3
- * around `tryAppendJsonl` so the write protocol (mkdirSync + append +
4
- * stderr warn on throw) lives in one place — changes to atomicity,
5
- * checksums, or alternative storage backends touch this file and this
6
- * file only.
3
+ * around `tryAppendJsonl` so the WRITE protocol (mkdirSync + append +
4
+ * stderr warn on throw) lives in one place — changes to append atomicity
5
+ * or checksums touch this file only. This is NOT a full storage-backend
6
+ * seam: `reads.ts`, `raw.ts`, and `names.ts` hit `node:fs` directly, so
7
+ * swapping the backend means touching all of `state/` (a `RunStore` port
8
+ * is a known possible follow-up, deliberately deferred — M13).
7
9
  *
8
- * writeHeader — best-effort; discards the return.
10
+ * writeHeader — boolean; the runner refuses the run start on failure.
9
11
  * appendStage — boolean; allocator gates monotonic counters on it.
10
12
  * appendRoutingDecision — boolean; telemetry-not-state, dropped rows surface up.
11
13
  */
12
14
 
13
15
  import { appendFileSync, mkdirSync } from "node:fs";
16
+ import { formatError } from "../internal-utils.js";
14
17
  import { runsDir, stateFilePath } from "./paths.js";
15
- import type { RoutingDecision, WorkflowHeader, WorkflowStage } from "./state.js";
18
+ import type { LoopCapRow, RoutingDecision, WorkflowHeader, WorkflowStage } from "./state.js";
16
19
 
17
20
  /**
18
21
  * Shared append primitive: ensure the runs directory exists, then
19
22
  * append one JSON-serialised row + newline. Returns true on success;
20
- * on any throw, warns to stderr and returns false. The three public
21
- * append helpers below are thin wrappers — `writeHeader` discards the
22
- * return (best-effort), the others gate counters / telemetry on it.
23
+ * on any throw, warns to stderr and returns false. The public append
24
+ * helpers below are thin wrappers — every caller gates on the boolean.
23
25
  */
24
26
  function tryAppendJsonl(cwd: string, runId: string, row: unknown): boolean {
25
27
  try {
@@ -29,13 +31,19 @@ function tryAppendJsonl(cwd: string, runId: string, row: unknown): boolean {
29
31
  appendFileSync(filePath, `${JSON.stringify(row)}\n`, "utf-8");
30
32
  return true;
31
33
  } catch (e) {
32
- console.warn(`[rpiv-workflow] workflow state: ${e instanceof Error ? e.message : String(e)}`);
34
+ console.warn(`[rpiv-workflow] workflow state: ${formatError(e)}`);
33
35
  return false;
34
36
  }
35
37
  }
36
38
 
37
- export function writeHeader(cwd: string, header: WorkflowHeader): void {
38
- tryAppendJsonl(cwd, header.runId, header);
39
+ /**
40
+ * Returns true on successful write. A lost header makes the run unlistable
41
+ * (`listRuns` keys on line one) and unresumable (`resolveRun` can't find it)
42
+ * while stage rows still land — so `runWorkflow` refuses the run start on
43
+ * false, before anything has executed.
44
+ */
45
+ export function writeHeader(cwd: string, header: WorkflowHeader): boolean {
46
+ return tryAppendJsonl(cwd, header.runId, header);
39
47
  }
40
48
 
41
49
  /** Returns true on successful write — callers gate counters on this. */
@@ -56,3 +64,12 @@ export function appendStage(cwd: string, runId: string, stage: WorkflowStage): b
56
64
  export function appendRoutingDecision(cwd: string, runId: string, row: RoutingDecision): boolean {
57
65
  return tryAppendJsonl(cwd, runId, row);
58
66
  }
67
+
68
+ /**
69
+ * Append a loop-cap telemetry row (an `onCap: "advance"` trip). Telemetry,
70
+ * not a reconstruction input — a dropped write degrades the trail but never
71
+ * gates the chain (the live soft-stop toast is the user-facing signal).
72
+ */
73
+ export function appendLoopCap(cwd: string, runId: string, row: LoopCapRow): boolean {
74
+ return tryAppendJsonl(cwd, runId, row);
75
+ }
package/transcript.ts CHANGED
@@ -12,6 +12,8 @@
12
12
  * "find the last regex match in assistant text" helper they reuse.
13
13
  */
14
14
 
15
+ import type { SessionRef } from "./state/index.js";
16
+
15
17
  /** Mirror of pi-ai's StopReason union — values pi attaches to AssistantMessage. */
16
18
  export type StopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
17
19
 
@@ -69,6 +71,28 @@ export function readBranch(ctx: { sessionManager: { getBranch(): unknown } }): B
69
71
  return ctx.sessionManager.getBranch() as unknown as BranchEntry[];
70
72
  }
71
73
 
74
+ /**
75
+ * Capture the active Pi session's identity as the `SessionRef` value object
76
+ * stage rows store (`WorkflowStage.session`). Lives here, next to
77
+ * `readBranch` — the module that owns narrow structural host reads.
78
+ *
79
+ * `branchOffset` is the policy-derived offset the activation ran under
80
+ * (continue-policy stages); omitted/undefined for fresh sessions so the key
81
+ * is dropped from the serialized row. `file` is likewise dropped for
82
+ * non-persisting sessions (`getSessionFile()` returns `undefined`).
83
+ */
84
+ export function readSessionRef(
85
+ ctx: { sessionManager: { getSessionId(): string; getSessionFile(): string | undefined } },
86
+ branchOffset?: number,
87
+ ): SessionRef {
88
+ const file = ctx.sessionManager.getSessionFile();
89
+ return {
90
+ id: ctx.sessionManager.getSessionId(),
91
+ ...(file !== undefined ? { file } : {}),
92
+ ...(branchOffset !== undefined ? { branchOffset } : {}),
93
+ };
94
+ }
95
+
72
96
  export function hasAssistantMessage(branch: BranchEntry[], offsetStart?: number): boolean {
73
97
  const start = Math.max(offsetStart ?? 0, 0);
74
98
  for (let i = start; i < branch.length; i++) {
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
@@ -5,10 +5,11 @@
5
5
  * continueHost, registeredSkills, 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,9 +24,9 @@
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
29
  import type { WorkflowHost, WorkflowHostContext } from "./host.js";
28
- import type { LifecycleDispatcher } from "./lifecycle.js";
29
30
  import type { Output } from "./output.js";
30
31
  import type { SkillContractMap } from "./skill-contract.js";
31
32
  import type { RunTrigger } from "./triggers.js";
@@ -87,13 +88,147 @@ export interface RunState {
87
88
  * in the common case.
88
89
  */
89
90
  droppedRoutingRows: Array<{ fromStageIndex: number; fromStage: string; decision: string }>;
91
+ /**
92
+ * Stages whose terminal failure/aborted row failed to append. Unlike
93
+ * routing rows these ARE reconstruction inputs — a trail missing its
94
+ * failure row reads "completed" at the tail and a later resume would
95
+ * route onward past the stage that actually failed. Surfaced in
96
+ * `RunWorkflowResult.droppedFailureRows`; consumers holding entries
97
+ * must not resume the run from disk. Empty in the common case.
98
+ */
99
+ droppedFailureRows: string[];
90
100
  };
91
101
 
92
102
  // ── Termination (set once at end-of-run) ───────────────────────────
93
- termination: {
94
- success: boolean;
95
- error: string | undefined;
96
- };
103
+ /**
104
+ * How the run ended — `"running"` until the single end-of-run write via
105
+ * `terminate()` (audit.ts), the ONLY sanctioned mutator. Discriminated so
106
+ * every outcome is representable (cancellation used to be smuggled
107
+ * through the error string) and so a halt site can't set half the shape.
108
+ */
109
+ termination: RunTermination;
110
+ }
111
+
112
+ /**
113
+ * Run-termination outcome — the discriminated form behind
114
+ * `RunState.termination` and `RunWorkflowResult.termination`.
115
+ *
116
+ * - `"running"` — not terminated yet (also: the runner unwound without
117
+ * reaching any terminal write — treated as failure).
118
+ * - `"completed"` — the chain reached `stop`.
119
+ * - `"failed"` — a stage/preflight/routing halt; `error` carries the cause.
120
+ * - `"aborted"` — cooperative cancellation via `RunWorkflowOptions.signal`,
121
+ * or the model aborted the stage.
122
+ * - `"cancelled"` — the user dismissed the live session mid-stage.
123
+ */
124
+ export type RunTermination =
125
+ | { status: "running"; error?: undefined }
126
+ | { status: "completed"; error?: undefined }
127
+ | { status: "failed"; error: string }
128
+ | { status: "aborted"; error: string }
129
+ | { status: "cancelled"; error: string };
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Public run envelope — options in, result out
133
+ // ---------------------------------------------------------------------------
134
+ // Lives here (the runtime-types leaf), NOT in runner/runner.ts: the result
135
+ // envelope is public surface consumed by events.ts (`onWorkflowEnd`) and
136
+ // every embedder — a base-layer module must not import the deepest engine
137
+ // module to name it.
138
+
139
+ export interface RunWorkflowOptions {
140
+ /** Workflow to execute — caller resolves by name from `LoadedWorkflows`. */
141
+ workflow: Workflow;
142
+ /** Passed to the start stage as its argument. */
143
+ input: string;
144
+ /** Required for "continue"-policy stages (host.sendUserMessage). */
145
+ host?: WorkflowHost;
146
+ /** Defaults to MAX_BACKWARD_JUMPS. */
147
+ maxBackwardJumps?: number;
148
+ /** Run-wide safety cap on loop units (all kinds). Defaults to MAX_ITERATIONS. */
149
+ maxIterations?: number;
150
+ /**
151
+ * What triggered this run. `/wf` sets `{ kind: "command", name: "wf" }`;
152
+ * programmatic embedders default to `DEFAULT_TRIGGER`. Recorded in the
153
+ * JSONL header and surfaced on every lifecycle callback via
154
+ * `LifecycleContext.trigger`.
155
+ */
156
+ trigger?: RunTrigger;
157
+ /**
158
+ * Per-call lifecycle listener bundle. Fires AFTER every globally
159
+ * registered bundle (see `registerLifecycle`). Listener throws are
160
+ * caught + logged via `ctx.ui.notify(..., "warning")`; never halt the
161
+ * run.
162
+ */
163
+ lifecycle?: LifecycleListeners;
164
+ /**
165
+ * Cooperative cancellation. When the signal is aborted, the runner stops at
166
+ * the next between-stage seam — it records an `"aborted"` terminal row for
167
+ * the stage about to run and returns `{ success: false }` with an aborted
168
+ * error. It does NOT interrupt a stage already streaming (Pi owns the live
169
+ * session), so cancellation takes effect at the next stage boundary, not
170
+ * mid-stage.
171
+ */
172
+ signal?: AbortSignal;
173
+ /**
174
+ * Human-readable alias for this run. Stored in the JSONL header and the
175
+ * sidecar names.json index. Rejected if already in use — the error
176
+ * identifies the conflicting runId.
177
+ */
178
+ name?: string;
179
+ }
180
+
181
+ export interface RunWorkflowResult {
182
+ /**
183
+ * The run's identity on disk — the `<run-id>` portion of
184
+ * `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl`. Live consumers can hand
185
+ * this to `readLastStage` / `listArtifacts` / future inspect-past-run
186
+ * helpers without recomputing the slug.
187
+ *
188
+ * Undefined ONLY for pre-flight rejections (start stage not declared,
189
+ * continue-policy stages without pi) where no JSONL file was created.
190
+ */
191
+ runId?: string;
192
+ stagesCompleted: number;
193
+ success: boolean;
194
+ /**
195
+ * Primary artifact at run termination, serialised to its handle's
196
+ * canonical string form (fs → path, url → href, opaque → id). Undefined
197
+ * if no produces stage produced one. Callers that need the full
198
+ * structured handle read `output.artifacts[0]` off the run's last
199
+ * recorded stage (via `readLastStage`).
200
+ */
201
+ lastArtifact?: string;
202
+ error?: string;
203
+ /**
204
+ * Discriminated termination outcome — the full-fidelity form behind the
205
+ * `success`/`error` projections above (which can't represent "cancelled"
206
+ * vs "aborted" vs "failed"). `{ status: "running" }` means the runner
207
+ * unwound without reaching any terminal write — callers treat it as
208
+ * failure, same as the `success: false` projection does.
209
+ *
210
+ * Undefined ONLY for pre-flight rejections (no run was constructed) —
211
+ * same rule as `runId`.
212
+ */
213
+ termination?: RunTermination;
214
+ /**
215
+ * Routing decisions made in memory but whose JSONL audit row failed to
216
+ * persist. Empty in the common case. Surfaced so consumers reading the
217
+ * run's JSONL can disambiguate a missing routing row ("deterministic
218
+ * edge — never written") from a dropped one ("decision was made, write
219
+ * failed"). The run still succeeds — routing rows are telemetry, not
220
+ * reconstruction inputs.
221
+ */
222
+ droppedRoutingRows?: Array<{ fromStageIndex: number; fromStage: string; decision: string }>;
223
+ /**
224
+ * Stages whose terminal failure/aborted row failed to persist. Empty in
225
+ * the common case. Unlike routing rows, failure rows ARE reconstruction
226
+ * inputs: a trail missing its failure row reads as if the run stopped
227
+ * after its last successful stage, so a later resume would route onward
228
+ * past the stage that actually failed. Consumers holding this list should
229
+ * not resume the run from disk.
230
+ */
231
+ droppedFailureRows?: string[];
97
232
  }
98
233
 
99
234
  /** Per-run context the chain carries from stage to stage. */
@@ -130,9 +265,9 @@ export interface RunContext {
130
265
  */
131
266
  registeredSkills?: ReadonlySet<string>;
132
267
  /**
133
- * Snapshot of the declared/injected skill-contract registry, taken once in
268
+ * Snapshot of the registered skill-contract registry, taken once in
134
269
  * `buildRunContext` (mirrors `registeredSkills`). This is the
135
- * declared/injected registry — NOT the harvested-merged
270
+ * registered (`declared`-source) registry — NOT the harvested-merged
136
271
  * `LoadedWorkflows.skillContracts` — because both runtime uses only add
137
272
  * value over a declared contract:
138
273
  * - `ensureContractInputValid` mirrors a declared `consumes.data` that
@@ -166,16 +301,16 @@ export interface RunContext {
166
301
  continueHost?: WorkflowHost;
167
302
  maxBackwardJumps: number;
168
303
  /**
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`.
304
+ * Run-wide safety cap on loop units — clamps the effective cap of EVERY
305
+ * loop kind (`min(loop.max, run.maxIterations)`), the backstop for a
306
+ * source that never terminates (a pull generator that never returns
307
+ * `null`, an assess `done` that never trips). What happens at the cap is
308
+ * the loop's `CapPolicy`. Defaults to `MAX_ITERATIONS`.
174
309
  */
175
310
  maxIterations: number;
176
311
  /** What triggered the run; defaulted at `runWorkflow` entry. */
177
312
  trigger: RunTrigger;
178
- /** Lifecycle event dispatcher — see `lifecycle.ts`. Threaded by reference. */
313
+ /** Lifecycle event dispatcher — see `events.ts`. Threaded by reference. */
179
314
  lifecycle: LifecycleDispatcher;
180
315
  /**
181
316
  * Optional cooperative-cancellation signal from `RunWorkflowOptions.signal`.
@@ -188,10 +323,10 @@ export interface RunContext {
188
323
  }
189
324
 
190
325
  /**
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.
326
+ * Per-stage / per-unit common base. Extended by `StageSession` (loop units
327
+ * thread their identity through `StageSession.unit`); consumed in pick form by
328
+ * `AuditCtx` (audit.ts) so the audit layer pins its dependency on this shape
329
+ * structurally instead of duplicating the field list.
195
330
  *
196
331
  * `stageName` is the workflow stage's record key — the value that lands
197
332
  * in `WorkflowStage.stage`. `skill` is the Pi skill body the runner
@@ -210,7 +345,7 @@ export interface SessionContext {
210
345
  stageName: string;
211
346
  /** Pi skill body — `/skill:<skill>` dispatch + status-line label + JSONL `WorkflowStage.skill`. */
212
347
  skill: string;
213
- /** Shared lifecycle dispatcher. Threaded from `RunContext` so the audit layer can fire `onStageEnd` / `onStageError` / `onFanoutUnitEnd` without re-importing it. */
348
+ /** Shared lifecycle dispatcher. Threaded from `RunContext` so the audit layer can fire `onStageEnd` / `onStageError` / `onUnitEnd` without re-importing it. */
214
349
  lifecycle: LifecycleDispatcher;
215
350
  /**
216
351
  * Read-only run identity passed to lifecycle callbacks. Captured at
@@ -222,12 +357,39 @@ export interface SessionContext {
222
357
  totalStages: number;
223
358
  trigger: RunTrigger;
224
359
  };
360
+ /**
361
+ * The activation's allocated JSONL stage number. Assigned ONCE (via
362
+ * `allocateStageNumber`) when output production begins, BEFORE the output
363
+ * envelope is built — the envelope's `meta.stageNumber`, the audit row
364
+ * (success or failure), and every lifecycle ref for this activation then
365
+ * agree on one explicit value. Undefined until the activation reaches
366
+ * output production; pre-output halts allocate at record time instead.
367
+ */
368
+ allocatedStageNumber?: number;
369
+ }
370
+
371
+ /**
372
+ * Unit identity threaded onto a loop unit's session. Source of the
373
+ * structured JSONL row fields (`unitRowFields`, audit.ts) and the public
374
+ * `UnitEvent` lifecycle payload. `parent` is the loop stage's record key —
375
+ * the value resume dispatch and the fold key on; `label` feeds the decorated
376
+ * display string, the status line, and the per-unit toast.
377
+ */
378
+ export interface UnitRef {
379
+ parent: string;
380
+ role: import("./api.js").UnitRole;
381
+ /** 0-based generation cursor (== the round index for assess loops). */
382
+ index: number;
383
+ /** Stable audit identity (`unit.id ?? unit.label` for fanout/iterate; undefined for assess). */
384
+ id?: string;
385
+ /** Display tag. */
386
+ label: string;
225
387
  }
226
388
 
227
389
  export interface StageSession extends SessionContext {
228
390
  stage: StageDef;
229
391
  /**
230
- * Declared/injected skill-contract registry, threaded from
392
+ * Registered skill-contract registry, threaded from
231
393
  * `RunContext.skillContracts` at session construction. Lets output
232
394
  * validation fall back to the dispatched skill's `produces.data` when the
233
395
  * stage carries no `outputSchema` of its own. Fail-soft: absent for
@@ -248,28 +410,24 @@ export interface StageSession extends SessionContext {
248
410
  continueHost?: WorkflowHost;
249
411
  /** Only set for continue stages — branch slice offset. */
250
412
  branchOffset?: number;
413
+ /**
414
+ * Present iff this session IS one loop unit. Pre-decorated at session
415
+ * construction by the driver (`stageName` carries the DISPLAY decoration;
416
+ * this field carries the machine identity). Drives: structured row fields,
417
+ * `onUnitEnd` instead of `onStageEnd`, the labeled per-unit toast, and
418
+ * unit-attributed failure rows.
419
+ */
420
+ unit?: UnitRef;
251
421
  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
422
  /**
268
- * From `FanoutUnit.id` when set — stable audit identifier preferred
269
- * over `label` in JSONL rows. Undefined when the user supplied none.
423
+ * Receives the stage's VALIDATED Output envelope (not just
424
+ * `artifacts[0]`) — loop continuations thread it into `accumulated` /
425
+ * `feedForward` directly, removing the `run.state.output!` back-read
426
+ * pattern the old drivers carried.
427
+ *
428
+ * Return type is `Promise<unknown>` (not `void`) so the chain walk's
429
+ * `ChainOutcome`-returning continuations plug in directly; the session
430
+ * layer only awaits settlement.
270
431
  */
271
- id?: string;
272
- /** Parent stage's 0-based index. */
273
- stageIndex: number;
274
- onSuccess: (ctx: WorkflowHostContext) => Promise<void>;
432
+ onSuccess: (ctx: WorkflowHostContext, output: Output) => Promise<unknown>;
275
433
  }