@juicesharp/rpiv-workflow 1.19.0 → 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/runner/runner.ts CHANGED
@@ -1,19 +1,30 @@
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.
6
8
  *
7
- * Modules:
9
+ * Modules (imports point strictly downward — the walk's mutual recursion is
10
+ * composed by injection in run-stage.ts, never as a module cycle):
8
11
  * - 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.
12
+ * tail).
13
+ * - run-stage.ts — runStage (mode dispatch) + runStageOrRecordFailure
14
+ * (single catch site) + the walk composition.
13
15
  * - chain-advance.ts — advanceChain + routing audit + backward-jump
14
- * guard + halt-on-error.
16
+ * guard + halt-on-error (ChainDeps-injected).
17
+ * - resolve-stage.ts — ResolvedStage: mode/dispatch derived once.
18
+ * - preflight.ts — runtime preflights (throw StagePreflightError).
19
+ * - input-validation.ts— schema-backed input preflights.
20
+ * - script-stage.ts — skillless TS-stage runtime (no session/collector).
21
+ * - failure.ts — ChainOutcome + entry-throw → failure-row + finalize.
22
+ * - run-context.ts — RunContext/RunState construction + policy caps.
23
+ * - errors.ts — StagePreflightError.
15
24
  * - resume.ts — reconstructState: pure RunState rebuild from a
16
25
  * past run's JSONL trail (consumed by resumeWorkflow).
26
+ * - resume-entry.ts — trail trailer → chain re-entry thunk + refusal text.
27
+ * - resume-loop.ts — loop-trailer re-entry + drift refusals.
17
28
  *
18
29
  * Ctx lifecycle: every level only touches the ctx it was handed.
19
30
  * - `newSession({cancelled: false})` invalidates the outer ctx; all
@@ -28,144 +39,32 @@
28
39
  */
29
40
 
30
41
  import type { Workflow } from "../api.js";
31
- import { auditCtxFor, notifyPartialArtifacts, nowIso, recordTerminalFailure } from "../audit.js";
32
- import type { FanoutDeps } from "../fanout.js";
42
+ import { currentPrimaryArtifact } from "../chain-state.js";
43
+ import { type LifecycleListeners, lifecycleCtxFor } from "../events.js";
33
44
  import { handleToString } from "../handle.js";
34
45
  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";
46
+ import { nowIso } from "../internal-utils.js";
38
47
  import {
39
- ERR_RESUME_NO_ROWS,
40
- ERR_RESUME_STAGE_GONE,
41
- ERR_WORKFLOW_ABORTED,
48
+ MSG_HEADER_WRITE_FAILED,
42
49
  MSG_NAME_COLLISION,
43
50
  MSG_NAME_INDEX_WRITE_FAILED,
44
51
  MSG_NAME_INVALID,
45
- MSG_STAGE_THREW,
46
- MSG_WORKFLOW_ABORTED,
47
- MSG_WORKFLOW_COMPLETE,
48
- STATUS_KEY,
49
52
  } 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";
57
53
  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
- }
54
+ type ClaimResult,
55
+ claimName,
56
+ generateRunId,
57
+ releaseName,
58
+ STATE_SCHEMA_VERSION,
59
+ type WorkflowHeader,
60
+ writeHeader,
61
+ } from "../state/index.js";
62
+ import { DEFAULT_TRIGGER } from "../triggers.js";
63
+ import type { RunContext, RunWorkflowOptions, RunWorkflowResult } from "../types.js";
64
+ import { reconstructState } from "./resume.js";
65
+ import { resumeRefusalError, selectResumeEntry } from "./resume-entry.js";
66
+ import { buildRunContext, freshRunState } from "./run-context.js";
67
+ import { runStageOrRecordFailure } from "./run-stage.js";
169
68
 
170
69
  // ---------------------------------------------------------------------------
171
70
  // Shared tail — executeRun
@@ -180,7 +79,7 @@ export interface RunWorkflowResult {
180
79
  async function executeRun(
181
80
  ctx: WorkflowHostContext,
182
81
  run: RunContext,
183
- entry: () => Promise<void>,
82
+ entry: () => Promise<unknown>,
184
83
  ): Promise<RunWorkflowResult> {
185
84
  await run.lifecycle.fire(ctx, "onWorkflowStart", lifecycleCtxFor(run));
186
85
 
@@ -190,15 +89,19 @@ async function executeRun(
190
89
  const result: RunWorkflowResult = {
191
90
  runId: run.runId,
192
91
  stagesCompleted: state.stagesCompleted,
193
- success: state.termination.success,
92
+ success: state.termination.status === "completed",
194
93
  lastArtifact: (() => {
195
94
  const a = currentPrimaryArtifact(state);
196
95
  return a ? handleToString(a.handle) : undefined;
197
96
  })(),
198
97
  error: state.termination.error,
98
+ termination: state.termination,
199
99
  ...(state.telemetry.droppedRoutingRows.length > 0
200
100
  ? { droppedRoutingRows: state.telemetry.droppedRoutingRows }
201
101
  : {}),
102
+ ...(state.telemetry.droppedFailureRows.length > 0
103
+ ? { droppedFailureRows: state.telemetry.droppedFailureRows }
104
+ : {}),
202
105
  };
203
106
 
204
107
  await run.lifecycle.fire(ctx, "onWorkflowEnd", result, lifecycleCtxFor(run));
@@ -251,14 +154,23 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
251
154
  if (!claim.ok) return { stagesCompleted: 0, success: false, error: nameClaimError(options.name, claim) };
252
155
  }
253
156
 
254
- writeHeader(cwd, {
157
+ // Nothing has executed yet — the cheapest moment to refuse. A lost header
158
+ // makes the run unlistable and unresumable while its stage rows land, so a
159
+ // failed append rejects the start and rolls back the name claim (the index
160
+ // must not point at a run that never existed).
161
+ const headerWritten = writeHeader(cwd, {
255
162
  runId,
256
163
  workflow: workflow.name,
257
164
  input: options.input,
258
165
  ts: nowIso(),
166
+ v: STATE_SCHEMA_VERSION,
259
167
  trigger,
260
168
  name: options.name,
261
169
  });
170
+ if (!headerWritten) {
171
+ if (options.name) releaseName(cwd, options.name, runId);
172
+ return { stagesCompleted: 0, success: false, error: MSG_HEADER_WRITE_FAILED(runId) };
173
+ }
262
174
 
263
175
  const run = buildRunContext(cwd, workflow, options, {
264
176
  runId,
@@ -279,7 +191,7 @@ export interface ResumeWorkflowOptions {
279
191
  host?: WorkflowHost;
280
192
  /** Defaults to MAX_BACKWARD_JUMPS. */
281
193
  maxBackwardJumps?: number;
282
- /** Run-wide safety cap on iterate-stage units. Defaults to MAX_ITERATIONS. */
194
+ /** Run-wide safety cap on loop units (all kinds). Defaults to MAX_ITERATIONS. */
283
195
  maxIterations?: number;
284
196
  /** The user's `@<ref>` — surfaced in trigger.meta + refusal messages. */
285
197
  ref: string;
@@ -305,7 +217,7 @@ export async function resumeWorkflow(
305
217
  const { workflow, header } = options;
306
218
  const cwd = ctx.cwd;
307
219
 
308
- const recon = reconstructState(cwd, workflow, header);
220
+ const recon = await reconstructState(cwd, workflow, header);
309
221
  if (!recon.ok) {
310
222
  // Pure envelope — no self-notify, mirroring `runWorkflow`'s pre-flight
311
223
  // rejections. A reconstruct refusal writes no JSONL, so the caller surfaces
@@ -325,11 +237,11 @@ export async function resumeWorkflow(
325
237
  trigger: { kind: "command", name: "wf", meta: { resumedFrom: options.ref } },
326
238
  });
327
239
 
328
- return executeRun(ctx, run, selectResumeEntry(ctx, workflow, recon, run));
240
+ return executeRun(ctx, run, selectResumeEntry(ctx, recon, run));
329
241
  }
330
242
 
331
243
  // ---------------------------------------------------------------------------
332
- // Run-construction helpers (shared by runWorkflow + resumeWorkflow)
244
+ // Entry helpers
333
245
  // ---------------------------------------------------------------------------
334
246
 
335
247
  /**
@@ -344,256 +256,3 @@ function hostMissingForContinueStages(workflow: Workflow, host: WorkflowHost | u
344
256
  if (!Object.values(workflow.stages).some((s) => s.sessionPolicy === "continue")) return undefined;
345
257
  return "workflow contains continue-policy stages which require a workflow host";
346
258
  }
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,
480
- });
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
-
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
- }
552
- 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);
597
- }
598
- return skills;
599
- }