@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/runner/runner.ts CHANGED
@@ -1,171 +1,54 @@
1
1
  /**
2
- * Workflow orchestration entry point. `runWorkflow` walks a `Workflow`'s
3
- * edge graph stage-by-stage; per-stage work (sessions, extraction,
4
- * validation, audit row writes) lives in sessions.ts + audit.ts. This
5
- * directory owns graph traversal, per-stage prerequisites, and routing.
2
+ * Workflow orchestration entry points. `runWorkflow` walks a `Workflow`'s
3
+ * edge graph stage-by-stage; `resumeWorkflow` rebuilds state from a past
4
+ * run's JSONL trail and re-enters the chain at the right seam. Per-stage
5
+ * work (sessions, extraction, validation, audit row writes) lives in
6
+ * sessions.ts + audit.ts; this directory owns graph traversal, per-stage
7
+ * prerequisites, and routing; imports point strictly downward — the walk's
8
+ * mutual recursion is composed by injection in run-stage.ts, never as a
9
+ * module cycle.
6
10
  *
7
- * Modules:
8
- * - runner.ts — runWorkflow + resumeWorkflow + executeRun (shared
9
- * tail) + countReachableStages +
10
- * runStageOrRecordFailure + finalizeWorkflow.
11
- * - stage-lifecycle.ts — runStage + StagePreflightError + preflight
12
- * pipeline + outcome.collector.snapshot hook.
13
- * - chain-advance.ts — advanceChain + routing audit + backward-jump
14
- * guard + halt-on-error.
15
- * - resume.ts — reconstructState: pure RunState rebuild from a
16
- * past run's JSONL trail (consumed by resumeWorkflow).
17
- *
18
- * Ctx lifecycle: every level only touches the ctx it was handed.
19
- * - `newSession({cancelled: false})` invalidates the outer ctx; all
20
- * further work runs on `freshCtx` inside `withSession`, and the
21
- * outer function simply unwinds.
22
- * - `cancelled: true` means no replacement happened — outer ctx remains
23
- * valid.
24
- * - Continue policy has no newSession — same ctx throughout.
11
+ * Ctx lifecycle: the launcher ctx threaded into `runWorkflow`/`resumeWorkflow`
12
+ * STAYS VALID for the whole run — it is never swapped. Every stage runs in its
13
+ * own detached child session opened via `ctx.spawnChild({ withSession })`; the
14
+ * parent ctx only observes (progress, status). Continue policy spawns a child
15
+ * like any other stage — its only divergence is the preserved branch offset.
25
16
  *
26
17
  * Vocabulary: "stage" = one stage activation in this run; "phase" = one
27
18
  * `## Phase N:` subdivision inside an implement plan artifact.
28
19
  */
29
20
 
30
21
  import type { Workflow } from "../api.js";
31
- import { auditCtxFor, notifyPartialArtifacts, nowIso, recordTerminalFailure } from "../audit.js";
32
- import type { FanoutDeps } from "../fanout.js";
22
+ import { currentPrimaryArtifact } from "../chain-state.js";
23
+ import { type LifecycleListeners, lifecycleCtxFor } from "../events.js";
24
+ import { getWorkflowExecutionProvider } from "../execution-host.js";
33
25
  import { handleToString } from "../handle.js";
34
- import type { WorkflowHost, WorkflowHostContext } from "../host.js";
35
- import { currentPrimaryArtifact } from "../internal-utils.js";
36
- import type { IterateDeps } from "../iterate.js";
37
- import { buildLifecycleContext, LifecycleDispatcher, type LifecycleListeners } from "../lifecycle.js";
26
+ import type { ModelSelection, WorkflowHost, WorkflowHostContext } from "../host.js";
27
+ import { nowIso } from "../internal-utils.js";
38
28
  import {
39
- ERR_RESUME_NO_ROWS,
40
- ERR_RESUME_STAGE_GONE,
41
- ERR_WORKFLOW_ABORTED,
29
+ MSG_HEADER_WRITE_FAILED,
42
30
  MSG_NAME_COLLISION,
43
31
  MSG_NAME_INDEX_WRITE_FAILED,
44
32
  MSG_NAME_INVALID,
45
- MSG_STAGE_THREW,
46
- MSG_WORKFLOW_ABORTED,
47
- MSG_WORKFLOW_COMPLETE,
48
- STATUS_KEY,
49
33
  } from "../messages.js";
50
- import { runFanoutSession, runStageSession } from "../sessions/index.js";
51
- import { getSkillContracts } from "../skill-contracts/index.js";
52
- import { type ClaimResult, claimName, generateRunId, writeHeader } from "../state/index.js";
53
- import type { WorkflowHeader } from "../state/state.js";
54
- import { DEFAULT_TRIGGER, type RunTrigger } from "../triggers.js";
55
- import type { RunContext, RunState } from "../types.js";
56
- import { advanceChain } from "./chain-advance.js";
34
+ import { pruneOrphanedChildSessions } from "../sessions/index.js";
57
35
  import {
58
- fanoutStageNames,
59
- iterateStageNames,
60
- matchFanoutParent,
61
- type ReconstructResult,
62
- reconstructState,
63
- } from "./resume.js";
64
- import { resumeFanoutStage } from "./resume-fanout.js";
65
- import { resumeIterateStage } from "./resume-iterate.js";
66
- import { captureStageSnapshot, haltIterations, runStage, StagePreflightError } from "./stage-lifecycle.js";
67
-
68
- // ---------------------------------------------------------------------------
69
- // Policy constants
70
- // ---------------------------------------------------------------------------
71
-
72
- /**
73
- * Per-loop cap on decision-edge retries. A "backward jump" is a *decision*
74
- * resolving to an already-visited stage — i.e. the user's predicate chose to
75
- * retry. Deterministic edges through a cycle (the loop body) are NOT
76
- * counted; the budget is per retry iteration, not per hop. A decision
77
- * escaping the loop (target not visited) resets the counter so each
78
- * independent loop in the workflow gets its own fresh budget. With 2: the
79
- * loop runs once unconditionally and may retry up to 2 more times.
80
- */
81
- export const MAX_BACKWARD_JUMPS = 2;
82
-
83
- /**
84
- * Run-wide safety cap on `iterate`-stage units — the backstop for a generator
85
- * that never returns `null`. Mirrors rpiv-pi's `MAX_PHASES` (the convention
86
- * cap a fanout author would self-impose); 32 is comfortably above any
87
- * realistic per-stage unit count while still halting a runaway loop.
88
- */
89
- export const MAX_ITERATIONS = 32;
90
-
91
- // ---------------------------------------------------------------------------
92
- // Public surface
93
- // ---------------------------------------------------------------------------
94
-
95
- export interface RunWorkflowOptions {
96
- /** Workflow to execute — caller resolves by name from `LoadedWorkflows`. */
97
- workflow: Workflow;
98
- /** Passed to the start stage as its argument. */
99
- input: string;
100
- /** Required for "continue"-policy stages (host.sendUserMessage). */
101
- host?: WorkflowHost;
102
- /** Defaults to MAX_BACKWARD_JUMPS. */
103
- maxBackwardJumps?: number;
104
- /** Run-wide safety cap on iterate-stage units. Defaults to MAX_ITERATIONS. */
105
- maxIterations?: number;
106
- /**
107
- * What triggered this run. `/wf` sets `{ kind: "command", name: "wf" }`;
108
- * programmatic embedders default to `DEFAULT_TRIGGER`. Recorded in the
109
- * JSONL header and surfaced on every lifecycle callback via
110
- * `LifecycleContext.trigger`.
111
- */
112
- trigger?: RunTrigger;
113
- /**
114
- * Per-call lifecycle listener bundle. Fires AFTER every globally
115
- * registered bundle (see `registerLifecycle`). Listener throws are
116
- * caught + logged via `ctx.ui.notify(..., "warning")`; never halt the
117
- * run.
118
- */
119
- lifecycle?: LifecycleListeners;
120
- /**
121
- * Cooperative cancellation. When the signal is aborted, the runner stops at
122
- * the next between-stage seam — it records an `"aborted"` terminal row for
123
- * the stage about to run and returns `{ success: false }` with an aborted
124
- * error. It does NOT interrupt a stage already streaming (Pi owns the live
125
- * session), so cancellation takes effect at the next stage boundary, not
126
- * mid-stage.
127
- */
128
- signal?: AbortSignal;
129
- /**
130
- * Human-readable alias for this run. Stored in the JSONL header and the
131
- * sidecar names.json index. Rejected if already in use — the error
132
- * identifies the conflicting runId.
133
- */
134
- name?: string;
135
- }
136
-
137
- export interface RunWorkflowResult {
138
- /**
139
- * The run's identity on disk — the `<run-id>` portion of
140
- * `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl`. Live consumers can hand
141
- * this to `readLastStage` / `listArtifacts` / future inspect-past-run
142
- * helpers without recomputing the slug.
143
- *
144
- * Undefined ONLY for pre-flight rejections (start stage not declared,
145
- * continue-policy stages without pi) where no JSONL file was created.
146
- */
147
- runId?: string;
148
- stagesCompleted: number;
149
- success: boolean;
150
- /**
151
- * Primary artifact at run termination, serialised to its handle's
152
- * canonical string form (fs → path, url → href, opaque → id). Undefined
153
- * if no produces stage produced one. Callers that need the full
154
- * structured handle read `output.artifacts[0]` off the run's last
155
- * recorded stage (via `readLastStage`).
156
- */
157
- lastArtifact?: string;
158
- error?: string;
159
- /**
160
- * Routing decisions made in memory but whose JSONL audit row failed to
161
- * persist. Empty in the common case. Surfaced so consumers reading the
162
- * run's JSONL can disambiguate a missing routing row ("deterministic
163
- * edge — never written") from a dropped one ("decision was made, write
164
- * failed"). The run still succeeds — routing rows are telemetry, not
165
- * reconstruction inputs.
166
- */
167
- droppedRoutingRows?: Array<{ fromStageIndex: number; fromStage: string; decision: string }>;
168
- }
36
+ type ClaimResult,
37
+ claimName,
38
+ generateRunId,
39
+ readAllStages,
40
+ releaseName,
41
+ STATE_SCHEMA_VERSION,
42
+ type WorkflowHeader,
43
+ writeHeader,
44
+ } from "../state/index.js";
45
+ import { childSessionsDir } from "../state/paths.js";
46
+ import { DEFAULT_TRIGGER } from "../triggers.js";
47
+ import type { RunContext, RunWorkflowOptions, RunWorkflowResult } from "../types.js";
48
+ import { reconstructState } from "./resume.js";
49
+ import { resumeRefusalError, selectResumeEntry } from "./resume-entry.js";
50
+ import { buildRunContext, freshRunState } from "./run-context.js";
51
+ import { runStageOrRecordFailure } from "./run-stage.js";
169
52
 
170
53
  // ---------------------------------------------------------------------------
171
54
  // Shared tail — executeRun
@@ -180,31 +63,118 @@ export interface RunWorkflowResult {
180
63
  async function executeRun(
181
64
  ctx: WorkflowHostContext,
182
65
  run: RunContext,
183
- entry: () => Promise<void>,
66
+ entry: () => Promise<unknown>,
184
67
  ): Promise<RunWorkflowResult> {
185
68
  await run.lifecycle.fire(ctx, "onWorkflowStart", lifecycleCtxFor(run));
186
69
 
187
70
  await entry();
188
71
 
72
+ // Run settled — every child torn down, every row persisted. Sweep child-session
73
+ // files no row references (chiefly a `continue` fork whose stage threw before its
74
+ // first row write — the failure row pins session:null, orphaning the fork). Safe:
75
+ // resume only reattaches/forks files a persisted row references. Best-effort.
76
+ pruneOrphanedChildSessions(run.cwd, run.runId, referencedSessionIds(run));
77
+
189
78
  const { state } = run;
190
79
  const result: RunWorkflowResult = {
191
80
  runId: run.runId,
192
81
  stagesCompleted: state.stagesCompleted,
193
- success: state.termination.success,
82
+ success: state.termination.status === "completed",
194
83
  lastArtifact: (() => {
195
84
  const a = currentPrimaryArtifact(state);
196
85
  return a ? handleToString(a.handle) : undefined;
197
86
  })(),
198
87
  error: state.termination.error,
88
+ termination: state.termination,
199
89
  ...(state.telemetry.droppedRoutingRows.length > 0
200
90
  ? { droppedRoutingRows: state.telemetry.droppedRoutingRows }
201
91
  : {}),
92
+ ...(state.telemetry.droppedFailureRows.length > 0
93
+ ? { droppedFailureRows: state.telemetry.droppedFailureRows }
94
+ : {}),
202
95
  };
203
96
 
204
97
  await run.lifecycle.fire(ctx, "onWorkflowEnd", result, lifecycleCtxFor(run));
205
98
  return result;
206
99
  }
207
100
 
101
+ /**
102
+ * The keep-set for the run-end orphan sweep. Failed/aborted rows that carry a
103
+ * session are reattach targets on resume, so every row's `session.id` is read
104
+ * from the durable trail (success OR failure) and unioned with `lastSession`
105
+ * (the live predecessor a resumed `continue` would fork). Anything NOT here is
106
+ * a child-session file no row points at — safe to delete.
107
+ */
108
+ function referencedSessionIds(run: RunContext): Set<string> {
109
+ const ids = new Set<string>();
110
+ for (const row of readAllStages(run.cwd, run.runId)) {
111
+ if (row.session) ids.add(row.session.id);
112
+ }
113
+ if (run.state.lastSession) ids.add(run.state.lastSession.id);
114
+ return ids;
115
+ }
116
+
117
+ /** What `detachExecutor` resolves: the executor ctx to run against, the
118
+ * per-stage model resolver + abort signal to thread onto `RunContext`, and the
119
+ * teardown the caller invokes in `finally`. */
120
+ interface DetachedExecutor {
121
+ execCtx: WorkflowHostContext;
122
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
123
+ signal?: AbortSignal;
124
+ dispose?: () => void;
125
+ }
126
+
127
+ /**
128
+ * Detach to the executor host — the SHARED detach BOTH entry points run through,
129
+ * so a resumed stage's `spawnChild` / reattach / fork runs against the SAME real
130
+ * executor as a live run. Building the host HERE for both paths keeps resume
131
+ * off the bare launcher ctx (a `WorkflowLauncherContext` with no
132
+ * `spawnChild`/`maxConcurrency`) — the only place such a gap could hide is a
133
+ * test injecting a `spawnChild` directly.
134
+ *
135
+ * Threads the provider's `resolveModel` + abort `signal` too, so resumed children
136
+ * get per-stage models and cooperative cancellation exactly like live. The
137
+ * `childSessionsDir` is keyed by `runId`, so a resume reuses the SAME run-scoped
138
+ * dir the original run persisted its children into — what reattach/fork resolve
139
+ * against.
140
+ *
141
+ * No provider ⇒ execute on the live `ctx` (graceful degrade for non-Pi embedders
142
+ * / tests — the caller is contracted to pass an executor-capable ctx there).
143
+ * `dispose` unsubscribes the keystroke tap; the caller MUST call it in `finally`.
144
+ */
145
+ async function detachExecutor(
146
+ ctx: WorkflowHostContext,
147
+ cwd: string,
148
+ runId: string,
149
+ options: {
150
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
151
+ signal?: AbortSignal;
152
+ name?: string; // lane display name (run --name ?? workflow name)
153
+ /** Workflow name (the dock's dim `workflow:` tag); threaded from workflow.name / header.workflow. */
154
+ workflow?: string;
155
+ /** The run's original input (user prompt); threaded from options.input / header.input. */
156
+ input?: string;
157
+ },
158
+ ): Promise<DetachedExecutor> {
159
+ const provider = getWorkflowExecutionProvider();
160
+ if (!provider) return { execCtx: ctx, resolveModel: options.resolveModel, signal: options.signal };
161
+ // Resolve the run-scoped session dir here (internal layout helper) and hand the
162
+ // provider a concrete string; rpiv-pi never imports childSessionsDir.
163
+ const exec = await provider.createHost(ctx, {
164
+ runId,
165
+ childSessionsDir: childSessionsDir(cwd, runId),
166
+ name: options.name, // rpiv-pi records the lane under this name
167
+ workflow: options.workflow, // dock tag (the workflow name)
168
+ input: options.input, // dock descriptor (the user prompt)
169
+ });
170
+ return {
171
+ execCtx: exec.host,
172
+ dispose: exec.dispose,
173
+ resolveModel: options.resolveModel ?? provider.resolveModel,
174
+ signal: options.signal ?? exec.signal, // provider-owned abort handle
175
+ };
176
+ }
177
+
208
178
  // ---------------------------------------------------------------------------
209
179
  // runWorkflow — workflow entry point
210
180
  // ---------------------------------------------------------------------------
@@ -222,9 +192,9 @@ function nameClaimError(name: string, claim: Extract<ClaimResult, { ok: false }>
222
192
  }
223
193
 
224
194
  /**
225
- * Each subsequent `newSession()` is invoked on the freshCtx returned by the
226
- * previous withSession — never on a captured outer ctx (which Pi invalidates
227
- * as soon as the session is replaced).
195
+ * Walks the workflow's edge graph from `workflow.start`. The launcher `ctx`
196
+ * stays valid throughout — each stage opens (and disposes) its own detached
197
+ * child session via `spawnChild`, so the outer ctx is never swapped.
228
198
  */
229
199
  export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflowOptions): Promise<RunWorkflowResult> {
230
200
  const { workflow } = options;
@@ -236,9 +206,6 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
236
206
  };
237
207
  }
238
208
 
239
- const continueGuard = hostMissingForContinueStages(workflow, options.host);
240
- if (continueGuard) return { stagesCompleted: 0, success: false, error: continueGuard };
241
-
242
209
  const cwd = ctx.cwd;
243
210
  const runId = generateRunId();
244
211
  const trigger = options.trigger ?? DEFAULT_TRIGGER;
@@ -251,23 +218,51 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
251
218
  if (!claim.ok) return { stagesCompleted: 0, success: false, error: nameClaimError(options.name, claim) };
252
219
  }
253
220
 
254
- writeHeader(cwd, {
221
+ // Nothing has executed yet — the cheapest moment to refuse. A lost header
222
+ // makes the run unlistable and unresumable while its stage rows land, so a
223
+ // failed append rejects the start and rolls back the name claim (the index
224
+ // must not point at a run that never existed).
225
+ const headerWritten = writeHeader(cwd, {
255
226
  runId,
256
227
  workflow: workflow.name,
257
228
  input: options.input,
258
229
  ts: nowIso(),
230
+ v: STATE_SCHEMA_VERSION,
259
231
  trigger,
260
232
  name: options.name,
261
233
  });
234
+ if (!headerWritten) {
235
+ if (options.name) releaseName(cwd, options.name, runId);
236
+ return { stagesCompleted: 0, success: false, error: MSG_HEADER_WRITE_FAILED(runId) };
237
+ }
262
238
 
263
- const run = buildRunContext(cwd, workflow, options, {
264
- runId,
265
- state: freshRunState(options.input),
266
- visited: new Set(),
267
- trigger,
239
+ // Detach to the executor host (the executor relays UI back to the live session).
240
+ const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, runId, {
241
+ ...options,
242
+ name: options.name ?? workflow.name,
243
+ workflow: workflow.name,
244
+ input: options.input,
268
245
  });
269
246
 
270
- return executeRun(ctx, run, () => runStageOrRecordFailure(ctx, workflow.start, 0, run));
247
+ // `buildRunContext` is INSIDE the try so a throw there (e.g. countReachableStages
248
+ // on a malformed EdgeFn that bypassed load-time validation) still runs `dispose`
249
+ // — otherwise the onTerminalInput tap leaks, accumulating one per failed run.
250
+ try {
251
+ const run = buildRunContext(
252
+ cwd,
253
+ workflow,
254
+ { ...options, resolveModel, signal },
255
+ {
256
+ runId,
257
+ state: freshRunState(options.input),
258
+ visited: new Set(),
259
+ trigger,
260
+ },
261
+ );
262
+ return await executeRun(execCtx, run, () => runStageOrRecordFailure(execCtx, workflow.start, 0, run));
263
+ } finally {
264
+ dispose?.(); // unsubscribe the onTerminalInput tap — leaks accumulate on the TUI otherwise
265
+ }
271
266
  }
272
267
 
273
268
  export interface ResumeWorkflowOptions {
@@ -275,11 +270,11 @@ export interface ResumeWorkflowOptions {
275
270
  workflow: Workflow;
276
271
  /** Header of the run to resume — caller resolves via `resolveRun`. */
277
272
  header: WorkflowHeader;
278
- /** Required for "continue"-policy stages (host.sendUserMessage). */
273
+ /** Registry-level host — enumerated once for the skill-registration snapshot. */
279
274
  host?: WorkflowHost;
280
- /** Defaults to MAX_BACKWARD_JUMPS. */
275
+ /** Per-destination decision-edge re-entry cap. Defaults to MAX_BACKWARD_JUMPS. */
281
276
  maxBackwardJumps?: number;
282
- /** Run-wide safety cap on iterate-stage units. Defaults to MAX_ITERATIONS. */
277
+ /** Run-wide safety cap on loop units (all kinds). Defaults to MAX_ITERATIONS. */
283
278
  maxIterations?: number;
284
279
  /** The user's `@<ref>` — surfaced in trigger.meta + refusal messages. */
285
280
  ref: string;
@@ -287,6 +282,14 @@ export interface ResumeWorkflowOptions {
287
282
  lifecycle?: LifecycleListeners;
288
283
  /** Cooperative cancellation — see `RunWorkflowOptions.signal`. */
289
284
  signal?: AbortSignal;
285
+ /**
286
+ * Per-stage model-override resolver — see `RunWorkflowOptions.resolveModel`.
287
+ * Resumed stages resolve per-child models exactly like live; when omitted the
288
+ * detached executor's own `provider.resolveModel` is used (so a resume from the
289
+ * Pi launcher still honors per-skill overrides without the caller re-threading
290
+ * it). Undefined + no provider ⇒ host default for every resumed stage.
291
+ */
292
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
290
293
  }
291
294
 
292
295
  /**
@@ -305,7 +308,7 @@ export async function resumeWorkflow(
305
308
  const { workflow, header } = options;
306
309
  const cwd = ctx.cwd;
307
310
 
308
- const recon = reconstructState(cwd, workflow, header);
311
+ const recon = await reconstructState(cwd, workflow, header);
309
312
  if (!recon.ok) {
310
313
  // Pure envelope — no self-notify, mirroring `runWorkflow`'s pre-flight
311
314
  // rejections. A reconstruct refusal writes no JSONL, so the caller surfaces
@@ -315,285 +318,35 @@ export async function resumeWorkflow(
315
318
  return { stagesCompleted: 0, success: false, error: resumeRefusalError(recon, header.workflow) };
316
319
  }
317
320
 
318
- const continueGuard = hostMissingForContinueStages(workflow, options.host);
319
- if (continueGuard) return { stagesCompleted: 0, success: false, error: continueGuard };
320
-
321
- const run = buildRunContext(cwd, workflow, options, {
322
- runId: header.runId, // SAME run — new rows append to the same file
323
- state: recon.state,
324
- visited: recon.visited,
325
- trigger: { kind: "command", name: "wf", meta: { resumedFrom: options.ref } },
326
- });
327
-
328
- return executeRun(ctx, run, selectResumeEntry(ctx, workflow, recon, run));
329
- }
330
-
331
- // ---------------------------------------------------------------------------
332
- // Run-construction helpers (shared by runWorkflow + resumeWorkflow)
333
- // ---------------------------------------------------------------------------
334
-
335
- /**
336
- * Continue-policy stages thread the prior session via the host's
337
- * `sendUserMessage`; with no host, `enforceSessionInvariants` would throw at
338
- * the first such stage. Reject at workflow entry so embedders get a clean
339
- * envelope instead of a throw. Returns the error message, or undefined if the
340
- * workflow is safe to run.
341
- */
342
- function hostMissingForContinueStages(workflow: Workflow, host: WorkflowHost | undefined): string | undefined {
343
- if (host !== undefined) return undefined;
344
- if (!Object.values(workflow.stages).some((s) => s.sessionPolicy === "continue")) return undefined;
345
- return "workflow contains continue-policy stages which require a workflow host";
346
- }
347
-
348
- /** A pristine `RunState` for a brand-new run (resumes rebuild theirs via `reconstructState`). */
349
- function freshRunState(originalInput: string): RunState {
350
- return {
351
- originalInput,
352
- primaryArtifact: undefined,
353
- output: undefined,
354
- named: {},
355
- stagesCompleted: 0,
356
- lastAllocatedStageNumber: 0,
357
- telemetry: { backwardJumps: 0, droppedRoutingRows: [] },
358
- termination: { success: false, error: undefined },
359
- };
360
- }
361
-
362
- /**
363
- * Assemble the `RunContext` shared by both entry points. `identity` carries the
364
- * four fields that differ between a new run (fresh id/state/visited, caller
365
- * trigger) and a resume (same run id, reconstructed state/visited, resume
366
- * trigger); everything else derives identically from `options`.
367
- *
368
- * The skill-registry snapshot happens here, BEFORE any stage opens a fresh
369
- * session — Pi invalidates the `WorkflowHost` handle on the first
370
- * `ctx.newSession()`, so this is the only safe moment to enumerate. After this
371
- * the runner reads `run.registeredSkills`; `options.host` survives only on
372
- * `run.continueHost` for the continue-policy session handler.
373
- */
374
- function buildRunContext(
375
- cwd: string,
376
- workflow: Workflow,
377
- options: {
378
- host?: WorkflowHost;
379
- maxBackwardJumps?: number;
380
- maxIterations?: number;
381
- lifecycle?: LifecycleListeners;
382
- signal?: AbortSignal;
383
- },
384
- identity: { runId: string; state: RunState; visited: Set<string>; trigger: RunTrigger },
385
- ): RunContext {
386
- return {
387
- cwd,
388
- runId: identity.runId,
389
- workflow,
390
- totalStages: countReachableStages(workflow),
391
- state: identity.state,
392
- visited: identity.visited,
393
- registeredSkills: options.host ? snapshotRegisteredSkills(options.host) : undefined,
394
- // Defensive COPY (not the live global Map) so a later registerSkillContracts
395
- // call cannot mutate this run's snapshot mid-run — parity with the fresh-Set
396
- // copy snapshotRegisteredSkills makes.
397
- skillContracts: new Map(getSkillContracts()),
398
- continueHost: options.host,
399
- maxBackwardJumps: options.maxBackwardJumps ?? MAX_BACKWARD_JUMPS,
400
- maxIterations: options.maxIterations ?? MAX_ITERATIONS,
401
- trigger: identity.trigger,
402
- lifecycle: new LifecycleDispatcher(options.lifecycle),
403
- signal: options.signal,
404
- };
405
- }
406
-
407
- /**
408
- * Pick the chain re-entry thunk for a resumed run from its trail trailer:
409
- * - decorated fanout-unit trailer → resume the fanout from the next unit
410
- * (`resumeFanoutStage`);
411
- * - decorated iterate-unit trailer → re-enter the pull loop at the next unit
412
- * (`resumeIterateStage`) — catches BOTH a completed and a failed iterate-unit
413
- * trailer, since a completed unit may still have remaining units to pull;
414
- * - completed normal trailer → route onward (a finished run hits stop ⇒ no-op);
415
- * - failed/aborted trailer → re-run that stage.
416
- *
417
- * A decorated unit row has a `stage` key absent from `workflow.stages` matching a
418
- * fanout/iterate parent — meaning the run died inside that stage. The
419
- * `workflow.stages[last.stage] === undefined` outer guard keeps normal trailers on
420
- * the binary arms; a normal trailer after a fully-completed fanout/iterate falls
421
- * through to them.
422
- */
423
- function selectResumeEntry(
424
- ctx: WorkflowHostContext,
425
- workflow: Workflow,
426
- recon: Extract<ReconstructResult, { ok: true }>,
427
- run: RunContext,
428
- ): () => Promise<void> {
429
- const last = recon.rows[recon.rows.length - 1]!;
430
- const idx = last.stageNumber - 1; // status-line / routing index; JSONL number comes from the allocator
431
-
432
- if (workflow.stages[last.stage] === undefined) {
433
- const fanoutParent = matchFanoutParent(last.stage, fanoutStageNames(workflow));
434
- if (fanoutParent) {
435
- const fanoutDeps: FanoutDeps = {
436
- runFanoutSession,
437
- advanceAfter: (freshCtx, name, completedIdx, r) => advanceChain(freshCtx, name, completedIdx, r),
438
- };
439
- const completed = recon.fanoutProgress.get(fanoutParent) ?? [];
440
- return () => resumeFanoutStage(ctx, fanoutParent, idx, completed, run, fanoutDeps);
441
- }
442
- const iterateParent = matchFanoutParent(last.stage, iterateStageNames(workflow));
443
- if (iterateParent) {
444
- const iterateDeps: IterateDeps = {
445
- runStageSession,
446
- advanceAfter: (freshCtx, name, completedIdx, r) => advanceChain(freshCtx, name, completedIdx, r),
447
- captureSnapshot: (d, i, r) => captureStageSnapshot(d, i, r),
448
- haltIterations,
449
- };
450
- const point = recon.iterateProgress.get(iterateParent) ?? { entryArtifact: undefined, accumulated: [] };
451
- const pendingDecorated = last.status !== "completed" ? last.stage : undefined;
452
- return () => resumeIterateStage(ctx, iterateParent, idx, point, pendingDecorated, run, iterateDeps);
453
- }
454
- }
455
-
456
- if (last.status === "completed") {
457
- return () => advanceChain(ctx, last.stage, idx, run); // route onward; finished run ⇒ hits stop ⇒ no-op
458
- }
459
- return () => runStageOrRecordFailure(ctx, last.stage, idx, run); // re-run the failed/aborted stage
460
- }
461
-
462
- function resumeRefusalError(recon: Extract<ReconstructResult, { ok: false }>, workflow: string): string {
463
- switch (recon.reason) {
464
- case "no-rows":
465
- return ERR_RESUME_NO_ROWS(recon.detail);
466
- case "stage-gone":
467
- return ERR_RESUME_STAGE_GONE(recon.detail, workflow);
468
- }
469
- }
470
-
471
- /** Build a `LifecycleContext` from the current `RunContext`. Captured per fire so listeners always see the latest `state` snapshot. */
472
- export function lifecycleCtxFor(run: RunContext) {
473
- return buildLifecycleContext({
474
- cwd: run.cwd,
475
- runId: run.runId,
476
- workflow: run.workflow.name,
477
- totalStages: run.totalStages,
478
- trigger: run.trigger,
479
- state: run.state,
321
+ // Detach to the executor host — the SAME wiring as live (L4-01). After the
322
+ // reconstruct refusal so a refused resume builds no host, but BEFORE
323
+ // `buildRunContext`/`executeRun` so every resumed stage (single-stage reattach,
324
+ // pending-fanout re-dispatch, or a cold-routed continue fork) runs against the
325
+ // real executor, not the bare launcher ctx. Same run id ⇒ same childSessionsDir,
326
+ // so reattach/fork resolve the original run's persisted child sessions.
327
+ const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, header.runId, {
328
+ ...options,
329
+ name: header.name ?? header.workflow,
330
+ workflow: header.workflow,
331
+ input: header.input,
480
332
  });
481
- }
482
-
483
- /**
484
- * Upper bound for the status-line denominator — BFS reach from `workflow.start`.
485
- *
486
- * Relies on every `EdgeFn` carrying `.targets`. `validate-workflow.ts` enforces
487
- * this at load time, so by the time the runner sees a workflow the contract
488
- * holds. A `.targets`-less EdgeFn here means validation was bypassed (test
489
- * fixture or programmatic embedder) — surface loudly instead of silently
490
- * counting all declared stages.
491
- */
492
- function countReachableStages(workflow: Workflow): number {
493
- const seen = new Set<string>();
494
- const frontier: string[] = [workflow.start];
495
- while (frontier.length > 0) {
496
- const cur = frontier.shift()!;
497
- if (seen.has(cur)) continue;
498
- seen.add(cur);
499
- const edge = workflow.edges[cur];
500
- if (edge === undefined || edge === "stop") continue;
501
- if (typeof edge === "string") {
502
- if (workflow.stages[edge] && !seen.has(edge)) frontier.push(edge);
503
- } else if (Array.isArray(edge.targets)) {
504
- for (const t of edge.targets) {
505
- if (t !== "stop" && workflow.stages[t] && !seen.has(t)) frontier.push(t);
506
- }
507
- } else {
508
- throw new Error(
509
- `countReachableStages: edge from "${cur}" is an EdgeFn without .targets — validateWorkflow should have rejected this workflow`,
510
- );
511
- }
512
- }
513
- return seen.size;
514
- }
515
333
 
516
- /**
517
- * Wraps `runStage` so a thrown stage records a JSONL failure row attributed
518
- * to the stage that actually threw — not to the prior stage in the chain.
519
- * Used by both `runWorkflow` (start stage) and `advanceChain` (next stage)
520
- * so there's exactly one place that translates "stage threw" →
521
- * `state.termination.error` + JSONL row. Without this, the start-stage call
522
- * leaves a header-only file and `advanceChain`'s own catch mis-attributes
523
- * the failure to the prior stage (`currentName` is still bound to the
524
- * iteration that just succeeded).
525
- *
526
- * Two flavours of throw are caught here:
527
- *
528
- * - `StagePreflightError` — a known preflight failure carrying its own
529
- * attribution + messages. Recorded with the carried payload exactly.
530
- * - Any other `Error` — unexpected machinery failure; recorded with the
531
- * generic `MSG_STAGE_THREW` shape attributed to the stage id.
532
- */
533
- export async function runStageOrRecordFailure(
534
- curCtx: WorkflowHostContext,
535
- name: string,
536
- idx: number,
537
- run: RunContext,
538
- ): Promise<void> {
539
- // Cooperative cancellation seam. Checked before the start stage and before
540
- // every routed next stage (advanceChain funnels through here), so an aborted
541
- // signal stops the chain at the next stage boundary without interrupting a
542
- // stage already streaming. Records an "aborted" terminal row + halts.
543
- if (run.signal?.aborted) {
544
- await recordTerminalFailure(curCtx, auditCtxFor(run, name, name), {
545
- status: "aborted",
546
- notifyMsg: MSG_WORKFLOW_ABORTED,
547
- notifyLevel: "warning",
548
- errMsg: ERR_WORKFLOW_ABORTED(name),
549
- });
550
- return;
551
- }
334
+ // `buildRunContext` + `selectResumeEntry` are INSIDE the try so a throw in either
335
+ // still runs `dispose` (tap-leak parity with `runWorkflow`).
552
336
  try {
553
- await runStage(curCtx, name, idx, run);
554
- } catch (e) {
555
- if (e instanceof StagePreflightError) {
556
- await recordTerminalFailure(
557
- curCtx,
558
- auditCtxFor(run, name, e.skill),
559
- { status: "failed", notifyMsg: e.notifyMsg, notifyLevel: "error", errMsg: e.errMsg },
560
- e.notifyPartial ? (ctx) => notifyPartialArtifacts(ctx, run.cwd, run.runId) : undefined,
561
- );
562
- return;
563
- }
564
- const reason = e instanceof Error ? e.message : String(e);
565
- await recordTerminalFailure(curCtx, auditCtxFor(run, name, name), {
566
- status: "failed",
567
- notifyMsg: MSG_STAGE_THREW(name, reason),
568
- notifyLevel: "error",
569
- errMsg: reason,
570
- });
571
- }
572
- }
573
-
574
- export function finalizeWorkflow(curCtx: WorkflowHostContext, run: RunContext): void {
575
- curCtx.ui.setStatus(STATUS_KEY, undefined);
576
- curCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
577
- run.state.termination.success = true;
578
- }
579
-
580
- /**
581
- * Build the `registeredSkills` snapshot consumed by `ensureSkillRegistered`.
582
- *
583
- * Pi prefixes skill-source commands with `"skill:"` (agent-session.js); we
584
- * strip the prefix so the set keys match `stage.skill` directly. Called
585
- * exactly once per run, before any `ctx.newSession()` opens (which is when
586
- * Pi marks the `WorkflowHost` handle stale).
587
- *
588
- * Non-skill commands (slash commands registered by extensions) are filtered
589
- * out — the preflight only cares about skills.
590
- */
591
- function snapshotRegisteredSkills(host: WorkflowHost): ReadonlySet<string> {
592
- const skills = new Set<string>();
593
- for (const cmd of host.getCommands()) {
594
- if (cmd.source !== "skill") continue;
595
- const name = cmd.name.startsWith("skill:") ? cmd.name.slice("skill:".length) : cmd.name;
596
- skills.add(name);
337
+ const run = buildRunContext(
338
+ cwd,
339
+ workflow,
340
+ { ...options, resolveModel, signal },
341
+ {
342
+ runId: header.runId, // SAME run — new rows append to the same file
343
+ state: recon.state,
344
+ visited: recon.visited,
345
+ trigger: { kind: "command", name: "wf", meta: { resumedFrom: options.ref } },
346
+ },
347
+ );
348
+ return await executeRun(execCtx, run, selectResumeEntry(execCtx, recon, run));
349
+ } finally {
350
+ dispose?.(); // unsubscribe the onTerminalInput tap — parity with runWorkflow
597
351
  }
598
- return skills;
599
352
  }