@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
@@ -1,500 +0,0 @@
1
- /**
2
- * Per-stage lifecycle: resolve the stage def, run the preflight pipeline,
3
- * prepare the prompt + status + branchOffset, capture the outcome's
4
- * snapshot, and hand off to `runStageSession`.
5
- *
6
- * Owns the typed-throw preflight machinery (`StagePreflightError`,
7
- * `PreflightCheck`, `PRE_PROMPT_CHECKS`, `POST_PROMPT_CHECKS`) and the
8
- * six bundled preflight checks. `runStageOrRecordFailure` (runner.ts)
9
- * catches `StagePreflightError` and records the JSONL row.
10
- */
11
-
12
- import type { PromptFn, StageDef } from "../api.js";
13
- import { auditCtxFor, notifyPartialArtifacts, recordTerminalFailure, runIdentityOf } from "../audit.js";
14
- import { runFanout } from "../fanout.js";
15
- import { handleToString } from "../handle.js";
16
- import { currentPrimaryArtifact, resolveSkill } from "../internal-utils.js";
17
- import { runIterate } from "../iterate.js";
18
- import { skillStageRef } from "../lifecycle.js";
19
- import {
20
- ERR_ITERATIONS_EXHAUSTED,
21
- ERR_MISSING_ARTIFACT,
22
- ERR_MISSING_NAMED_READ,
23
- ERR_SKILL_NOT_REGISTERED,
24
- MSG_ITERATIONS_EXHAUSTED,
25
- MSG_MISSING_ARTIFACT,
26
- MSG_MISSING_NAMED_READ,
27
- MSG_SKILL_NOT_REGISTERED,
28
- MSG_STAGE_THREW,
29
- STATUS_KEY,
30
- STATUS_STAGE,
31
- } from "../messages.js";
32
- import { runFanoutSession, runStageSession } from "../sessions/index.js";
33
- import { readBranch } from "../transcript.js";
34
- import type { RunContext, WorkflowHostContext } from "../types.js";
35
- import { advanceChain } from "./chain-advance.js";
36
- import { ensureContractInputValid, ensureInputValid } from "./input-validation.js";
37
- import { lifecycleCtxFor } from "./runner.js";
38
- import { runScript } from "./script-stage.js";
39
-
40
- export interface ResolvedStage {
41
- def: StageDef;
42
- name: string;
43
- /** 1-based; for status line + audit row. */
44
- stageNumber: number;
45
- /** Label written to JSONL + the status line. */
46
- skill: string;
47
- }
48
-
49
- /**
50
- * Thrown by a `PreflightCheck` on failure; carries the recorded-row
51
- * attribution + notify/err messages so `runStageOrRecordFailure` can land
52
- * a uniform JSONL row regardless of which slot tripped.
53
- *
54
- * `kind` annotates the violation class for diagnostics only — control
55
- * flow at the catch site is uniform:
56
- * - `"halt"` — runtime-state failure (skill not registered, missing
57
- * upstream artifact, schema mismatch).
58
- * - `"invariant"` — authoring-time-knowable violation that
59
- * `validateWorkflow` should reject at load. A throw
60
- * here means validation was bypassed or the rule lives
61
- * only in the runner (continue-without-pi).
62
- */
63
- export class StagePreflightError extends Error {
64
- constructor(
65
- public readonly kind: "halt" | "invariant",
66
- public readonly skill: string,
67
- public readonly notifyMsg: string,
68
- public readonly errMsg: string,
69
- public readonly notifyPartial: boolean,
70
- ) {
71
- super(errMsg);
72
- this.name = "StagePreflightError";
73
- }
74
- }
75
-
76
- interface PreflightCheck {
77
- name: string;
78
- kind: "halt" | "invariant";
79
- /**
80
- * Checks may be sync (`enforceSessionInvariants`, `ensureSkillRegistered`,
81
- * `ensureUpstreamArtifact`) or async (`ensureInputValid` once schemas may
82
- * be async). `runStage` awaits the return value, so sync checks pay only
83
- * one microtask and async checks (filesystem-backed, registry-backed,
84
- * async-by-default schema libs) round-trip cleanly.
85
- */
86
- run(stage: ResolvedStage, run: RunContext): void | Promise<void>;
87
- }
88
-
89
- /**
90
- * Builds the `/skill:<name> <args>` line sent into the session. The audit
91
- * label (which used to round-trip through here) is read off `stage.skill`
92
- * by the caller — single source.
93
- */
94
- function buildPrompt(skill: string, inputForStage: string): string {
95
- return `/skill:${skill} ${inputForStage}`;
96
- }
97
-
98
- /**
99
- * Resolve a `prompt`-dispatch stage's text. The whole user message is
100
- * author-owned — no `/skill:` prefix, no implicit arg. The dynamic form gets
101
- * the same `ScriptContext` script stages get, so it can weave in the upstream
102
- * `Output` (`run.state.output`) or `state.named`. A throw here propagates to
103
- * `runStageOrRecordFailure`, which records a terminal failure for the stage.
104
- */
105
- async function resolvePrompt(prompt: string | PromptFn, run: RunContext): Promise<string> {
106
- if (typeof prompt === "string") return prompt;
107
- return prompt({ cwd: run.cwd, input: run.state.output, state: run.state });
108
- }
109
-
110
- /**
111
- * The arg string the stage's `/skill:<name> <args>` prompt carries. Four
112
- * cases (checked in order):
113
- * 1. The start stage always receives `originalInput` (the user's brief).
114
- * 2. A stage opting out of inheritance (`inheritsArtifacts: false`, i.e.
115
- * authored via `terminal()`) also receives `originalInput` — the
116
- * `ensureUpstreamArtifact` preflight is bypassed for the same opt-out.
117
- * 3. A stage with `reads: [...]` receives a labelled multi-flag form:
118
- * `--<name1> <handle1> --<name2> <handle2> …`. Each name resolves
119
- * against `state.named[name].at(-1)` (the latest entry). When that
120
- * entry's `artifacts` array carries multiple handles, the flag
121
- * repeats: `--<name> <h1> --<name> <h2>`. The `ensureNamedReads`
122
- * preflight has already verified every name resolves; the `!` is safe.
123
- * 4. Otherwise: the upstream primary artifact's handle string. The
124
- * `ensureUpstreamArtifact` preflight guarantees the slot is set; the
125
- * `!` is safe.
126
- */
127
- function inputForStage(stage: ResolvedStage, run: RunContext): string {
128
- const isStart = stage.name === run.workflow.start;
129
- if (isStart) return run.state.originalInput;
130
- if (stage.def.inheritsArtifacts === false) return run.state.originalInput;
131
- if (stage.def.reads?.length) return formatNamedInputs(stage.def.reads, run);
132
- return handleToString(currentPrimaryArtifact(run.state)!.handle);
133
- }
134
-
135
- /**
136
- * Build the labelled-flag prompt body for a `reads:`-style stage. Iterates
137
- * declared names in author-supplied order, resolves each to the latest
138
- * `Output` accumulated in `state.named`, and emits one `--<name> <handle>`
139
- * pair per artifact in that output (so multi-artifact stages get
140
- * flag-repetition rather than space-collision).
141
- *
142
- * Pre-condition: every name resolves (enforced by `ensureNamedReads`).
143
- */
144
- function formatNamedInputs(names: ReadonlyArray<string>, run: RunContext): string {
145
- const parts: string[] = [];
146
- for (const name of names) {
147
- const latest = run.state.named[name]?.at(-1);
148
- if (!latest) continue; // unreachable given preflight; defensive
149
- for (const artifact of latest.artifacts) {
150
- parts.push(`--${name}`, handleToString(artifact.handle));
151
- }
152
- }
153
- return parts.join(" ");
154
- }
155
-
156
- /**
157
- * Slot ordering (load-bearing):
158
- *
159
- * 1. tryFanout — shortcut: the stage's FanoutFn returned
160
- * units, runner ran them; subsequent
161
- * slots skipped for this stage.
162
- * 1b. tryIterate — shortcut: the stage's IterateFn pulls units
163
- * sequentially (each a produces pass);
164
- * subsequent slots skipped for this stage.
165
- * 2. PRE_PROMPT_CHECKS — preflights that don't need prompt prep.
166
- * a. ensureUpstreamArtifact — halt: missing inherited artifact.
167
- * b. enforceSessionInvariants — invariant: authoring-time-knowable
168
- * throws (precede the registry check so the structural violation
169
- * surfaces regardless of the runtime registry).
170
- * c. ensureSkillRegistered — halt: skill not registered in Pi.
171
- * 3. prompt + status + branchOffset prep.
172
- * 4. POST_PROMPT_CHECKS — preflights gated on prompt-prep state.
173
- * a. ensureInputValid — halt: upstream output fails inputSchema.
174
- * 5. captureStageSnapshot — outcome.collector.snapshot hook (must run
175
- * before the Pi session so post-stage diffs work).
176
- *
177
- * Each `PreflightCheck` throws `StagePreflightError` on failure;
178
- * `runStageOrRecordFailure` catches and records the JSONL row.
179
- */
180
- export async function runStage(
181
- curCtx: WorkflowHostContext,
182
- currentName: string,
183
- idx: number,
184
- run: RunContext,
185
- ): Promise<void> {
186
- const stage = resolveStage(currentName, idx, run);
187
-
188
- if (await tryFanout(curCtx, stage, idx, run)) return;
189
- if (await tryIterate(curCtx, stage, idx, run)) return;
190
-
191
- // Script stages (`stage.def.run` set) skip the entire skill pipeline —
192
- // no `/skill:<name>` prompt to build, no skill-registry check, no
193
- // session to open, no outcome/collector to snapshot. Input-schema
194
- // validation still applies (`ensureInputValid` runs upstream output
195
- // against `inputSchema` if declared); the script-stage runner owns
196
- // its own status line + lifecycle fires from here.
197
- if (stage.def.run) {
198
- await ensureInputValid(stage, run);
199
- await runScript(curCtx, stage, idx, run);
200
- return;
201
- }
202
-
203
- for (const check of PRE_PROMPT_CHECKS) await check.run(stage, run);
204
-
205
- // Dispatch: a `prompt` stage sends author-owned raw text; a skill stage
206
- // sends `/skill:<name> <inputForStage>`. `stage.skill` already equals the
207
- // record key for a prompt stage (it cannot set an explicit skill — load
208
- // validation forbids it), so the status/session/audit labels are correct
209
- // for both without a separate label.
210
- const prompt =
211
- stage.def.prompt !== undefined
212
- ? await resolvePrompt(stage.def.prompt, run)
213
- : buildPrompt(stage.skill, inputForStage(stage, run));
214
- curCtx.ui.setStatus(STATUS_KEY, STATUS_STAGE(stage.stageNumber, run.totalStages, stage.skill));
215
- const branchOffset = computeBranchOffset(curCtx, stage.def);
216
-
217
- for (const check of POST_PROMPT_CHECKS) await check.run(stage, run);
218
-
219
- const snapshot = await captureStageSnapshot(stage.def, idx, run);
220
-
221
- // onStageStart fires after preflight, before the Pi session opens.
222
- await run.lifecycle.fire(
223
- curCtx,
224
- "onStageStart",
225
- skillStageRef(stage.name, stage.stageNumber, stage.skill),
226
- lifecycleCtxFor(run),
227
- );
228
-
229
- await runStageSession(curCtx, {
230
- cwd: run.cwd,
231
- runId: run.runId,
232
- state: run.state,
233
- prompt,
234
- stageName: stage.name,
235
- skill: stage.skill,
236
- lifecycle: run.lifecycle,
237
- runIdentity: runIdentityOf(run),
238
- stage: stage.def,
239
- skillContracts: run.skillContracts,
240
- stageIndex: idx,
241
- snapshot,
242
- continueHost: run.continueHost,
243
- branchOffset,
244
- onFailure: (freshCtx) => notifyPartialArtifacts(freshCtx, run.cwd, run.runId),
245
- onSuccess: (freshCtx) => advanceChain(freshCtx, currentName, idx, run),
246
- });
247
- }
248
-
249
- function resolveStage(currentName: string, idx: number, run: RunContext): ResolvedStage {
250
- const def = run.workflow.stages[currentName];
251
- if (!def) {
252
- // validateWorkflow should catch this; defensive for tests bypassing validation.
253
- throw new Error(`runStage: stage "${currentName}" referenced by edges but missing from workflow.stages`);
254
- }
255
- // `skill` defaults to the record key; `resolveSkill` is the shared derivation
256
- // the load-time contract lookups also use, so runtime and load can't disagree.
257
- return { def, name: currentName, stageNumber: idx + 1, skill: resolveSkill(def, currentName) };
258
- }
259
-
260
- /**
261
- * A stage that opts into fanout via `StageDef.fanout` expands into one Pi
262
- * session per unit returned by the user's `FanoutFn`. The runner is
263
- * convention-agnostic: it never inspects the artifact, never counts
264
- * headings, never names a skill — every per-unit decision lives in the
265
- * FanoutFn. Returns true iff fanout fired (i.e. at least one unit was
266
- * returned) — caller then returns without running the single-stage path.
267
- */
268
- async function tryFanout(
269
- curCtx: WorkflowHostContext,
270
- stage: ResolvedStage,
271
- idx: number,
272
- run: RunContext,
273
- ): Promise<boolean> {
274
- if (!stage.def.fanout) return false;
275
- const primary = currentPrimaryArtifact(run.state);
276
- const units = await stage.def.fanout({
277
- cwd: run.cwd,
278
- artifact: primary,
279
- state: run.state,
280
- });
281
- if (units.length === 0) return false;
282
- // Fire both onStageStart (the parent fanout stage IS starting) and
283
- // onFanoutStart so listeners receive a coherent stream: every stage gets
284
- // onStageStart, fanout stages additionally get onFanoutStart with the
285
- // unit list.
286
- const ref = skillStageRef(stage.name, stage.stageNumber, stage.skill);
287
- await run.lifecycle.fire(curCtx, "onStageStart", ref, lifecycleCtxFor(run));
288
- await run.lifecycle.fire(curCtx, "onFanoutStart", ref, units, lifecycleCtxFor(run));
289
- await runFanout(curCtx, idx, stage.name, stage.skill, 1, units, run, {
290
- runFanoutSession,
291
- advanceAfter: (freshCtx, name, completedIdx, ctx) => advanceChain(freshCtx, name, completedIdx, ctx),
292
- });
293
- return true;
294
- }
295
-
296
- /**
297
- * A stage that opts into iteration via `StageDef.iterate` expands into one Pi
298
- * session per unit pulled from the user's `IterateFn` — the sequential,
299
- * accumulating dual of fanout. Unlike fanout, each unit runs the stage's
300
- * `outcome` collector (it reuses `runStageSession`), so units accumulate into
301
- * `state.named[outcome.name]` and roll the primary artifact forward. Returns
302
- * true iff this is an iterate stage (always — even a zero-unit no-op handles
303
- * its own chain advance inside `runIterate`), so the caller returns without
304
- * running the single-stage path.
305
- *
306
- * `onStageStart` fires here, ONCE, matching the "stage expands to N units"
307
- * mental model; `onStageEnd` fires per unit via `recordStageSuccess`. The
308
- * stage-entry primary is frozen and threaded as `entryArtifact` so the
309
- * generator keeps seeing its true source even as the rolling primary advances.
310
- */
311
- async function tryIterate(
312
- curCtx: WorkflowHostContext,
313
- stage: ResolvedStage,
314
- idx: number,
315
- run: RunContext,
316
- ): Promise<boolean> {
317
- if (!stage.def.iterate) return false;
318
- // Runtime mirror of the load-time invariant — defense-in-depth for embedders
319
- // that bypass validateWorkflow. iterate dispatches via runStageSession, which
320
- // honors sessionPolicy; a "continue" policy would replay the prior unit's
321
- // branch into the next unit's session, so reject before any dispatch. (This
322
- // lives here, not in enforceSessionInvariants, because the iterate shortcut
323
- // returns before PRE_PROMPT_CHECKS run.)
324
- if (stage.def.sessionPolicy === "continue") {
325
- const reason =
326
- `runStage: stage "${stage.name}" cannot combine iterate with sessionPolicy "continue" — ` +
327
- "each unit requires an isolated session";
328
- throw new StagePreflightError("invariant", stage.name, MSG_STAGE_THREW(stage.name, reason), reason, false);
329
- }
330
- const entryArtifact = currentPrimaryArtifact(run.state); // frozen for the whole loop
331
- await run.lifecycle.fire(
332
- curCtx,
333
- "onStageStart",
334
- skillStageRef(stage.name, stage.stageNumber, stage.skill),
335
- lifecycleCtxFor(run),
336
- );
337
- await runIterate(curCtx, idx, stage.name, stage.skill, stage.def, entryArtifact, [], run, {
338
- runStageSession,
339
- advanceAfter: (freshCtx, name, completedIdx, ctx) => advanceChain(freshCtx, name, completedIdx, ctx),
340
- captureSnapshot: (def, i, r) => captureStageSnapshot(def, i, r),
341
- haltIterations,
342
- });
343
- return true;
344
- }
345
-
346
- /**
347
- * Record the terminal failure when an iterate stage's generator blows past the
348
- * run-wide `maxIterations` cap. Mirrors `checkBackwardJumpGuard`'s terminal
349
- * path (chain-advance.ts): attribution targets the iterate node's real name.
350
- */
351
- export async function haltIterations(
352
- curCtx: WorkflowHostContext,
353
- run: RunContext,
354
- stageName: string,
355
- count: number,
356
- ): Promise<void> {
357
- await recordTerminalFailure(curCtx, auditCtxFor(run, stageName, stageName), {
358
- status: "failed",
359
- notifyMsg: MSG_ITERATIONS_EXHAUSTED(count, run.maxIterations),
360
- notifyLevel: "error",
361
- errMsg: ERR_ITERATIONS_EXHAUSTED(count, run.maxIterations),
362
- });
363
- }
364
-
365
- /**
366
- * Verify `stage.skill` resolves to a Pi-registered skill BEFORE the prompt
367
- * is dispatched. The workflow runner emits `/skill:<name>` text via
368
- * `sendUserMessage` (the programmatic path), which goes through
369
- * `prompt({expandPromptTemplates: false})` — meaning Pi's built-in
370
- * `_expandSkillCommand` is skipped and `rpiv-args` is the ONLY expander.
371
- * If the skill isn't registered, `rpiv-args` returns `{action:"continue"}`
372
- * and the raw `/skill:<name> …` text reaches the LLM as a bare user-message
373
- * imperative outside the `<skill>...</skill>` contract — silent LLM-prompt
374
- * corruption with no diagnostic. Catching it here turns that silent failure
375
- * into a properly-attributed stage halt.
376
- *
377
- * Reads the snapshot in `run.registeredSkills` rather than calling
378
- * `host.getCommands()` mid-run, because Pi marks the `WorkflowHost` handle
379
- * stale on the first `ctx.newSession()` — a registry call after research's
380
- * fresh session opens throws "extension ctx is stale". The snapshot is
381
- * built once in `runWorkflow` before any session replaces the outer ctx.
382
- *
383
- * `registeredSkills` is undefined when the embedder didn't pass a host —
384
- * skip the check (same fail-soft posture as the rest of the host-optional
385
- * surface).
386
- */
387
- function ensureSkillRegistered(stage: ResolvedStage, run: RunContext): void {
388
- // A prompt stage dispatches raw text, not /skill:<name> — there is no skill
389
- // to verify. (Mirrors how the script-stage path skips this check entirely.)
390
- if (stage.def.prompt !== undefined) return;
391
- if (!run.registeredSkills) return;
392
- if (run.registeredSkills.has(stage.skill)) return;
393
-
394
- throw new StagePreflightError(
395
- "halt",
396
- stage.skill,
397
- MSG_SKILL_NOT_REGISTERED(stage.skill),
398
- ERR_SKILL_NOT_REGISTERED(stage.skill, stage.stageNumber),
399
- true,
400
- );
401
- }
402
-
403
- /**
404
- * The start node consumes the user's brief; subsequent stages MUST inherit
405
- * an upstream artifactPath. Falling back to originalInput past the start
406
- * would silently hand a downstream skill the raw feature description.
407
- *
408
- * Two opt-outs skip the check:
409
- * - `inheritsArtifacts: false` (authored via `terminal()`) — stage consumes
410
- * `originalInput` by design.
411
- * - `reads: [...]` — stage builds its prompt from the named-publish
412
- * registry instead of the rolling primary slot; `ensureNamedReads`
413
- * enforces its own coverage rule.
414
- */
415
- function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
416
- if (stage.name === run.workflow.start) return;
417
- if (stage.def.inheritsArtifacts === false) return;
418
- if (stage.def.reads?.length) return;
419
- // A prompt stage builds its own text and never consumes the rolling primary
420
- // as an arg, so it doesn't require an upstream artifact (a continue chat
421
- // turn typically leans on session context, not a handle).
422
- if (stage.def.prompt !== undefined) return;
423
- if (currentPrimaryArtifact(run.state)) return;
424
- throw new StagePreflightError(
425
- "halt",
426
- stage.skill,
427
- MSG_MISSING_ARTIFACT(stage.skill),
428
- ERR_MISSING_ARTIFACT(stage.skill, stage.stageNumber),
429
- true,
430
- );
431
- }
432
-
433
- /**
434
- * A stage declaring `reads: [...]` must find every name filled in
435
- * `state.named` before the prompt is built. `validateWorkflow` already
436
- * confirms the names CAN exist (some upstream stage publishes them); this
437
- * catches the runtime path where the producer hasn't fired yet — e.g.
438
- * the stage was placed before its producer in the edge graph.
439
- */
440
- function ensureNamedReads(stage: ResolvedStage, run: RunContext): void {
441
- const reads = stage.def.reads;
442
- if (!reads?.length) return;
443
- for (const name of reads) {
444
- if (run.state.named[name]?.length) continue;
445
- throw new StagePreflightError(
446
- "halt",
447
- stage.skill,
448
- MSG_MISSING_NAMED_READ(stage.skill, name),
449
- ERR_MISSING_NAMED_READ(stage.skill, name, stage.stageNumber),
450
- true,
451
- );
452
- }
453
- }
454
-
455
- function enforceSessionInvariants(stage: ResolvedStage, run: RunContext): void {
456
- if (stage.def.fanout && stage.def.sessionPolicy === "continue") {
457
- const reason =
458
- `runStage: stage "${stage.name}" cannot combine fanout with sessionPolicy "continue" — ` +
459
- "fanout requires per-unit session isolation";
460
- throw new StagePreflightError("invariant", stage.name, MSG_STAGE_THREW(stage.name, reason), reason, false);
461
- }
462
- if (stage.def.sessionPolicy === "continue" && !run.continueHost) {
463
- const reason = `runStage: stage "${stage.name}" uses sessionPolicy "continue" but no workflow host was provided to runWorkflow`;
464
- throw new StagePreflightError("invariant", stage.name, MSG_STAGE_THREW(stage.name, reason), reason, false);
465
- }
466
- }
467
-
468
- /** Entries before this index belong to prior stages; only meaningful for continue. */
469
- function computeBranchOffset(curCtx: WorkflowHostContext, def: StageDef): number | undefined {
470
- if (def.sessionPolicy !== "continue") return undefined;
471
- return readBranch(curCtx).length;
472
- }
473
-
474
- export async function captureStageSnapshot(def: StageDef, idx: number, run: RunContext): Promise<unknown> {
475
- const snapshot = def.outcome?.collector.snapshot;
476
- if (!snapshot) return undefined;
477
- try {
478
- return await snapshot({
479
- cwd: run.cwd,
480
- runId: run.runId,
481
- stageIndex: idx,
482
- state: run.state,
483
- });
484
- } catch {
485
- // Snapshot capture failure doesn't prevent stage execution.
486
- return undefined;
487
- }
488
- }
489
-
490
- const PRE_PROMPT_CHECKS: readonly PreflightCheck[] = [
491
- { name: "ensureUpstreamArtifact", kind: "halt", run: ensureUpstreamArtifact },
492
- { name: "ensureNamedReads", kind: "halt", run: ensureNamedReads },
493
- { name: "enforceSessionInvariants", kind: "invariant", run: enforceSessionInvariants },
494
- { name: "ensureSkillRegistered", kind: "halt", run: ensureSkillRegistered },
495
- ];
496
-
497
- const POST_PROMPT_CHECKS: readonly PreflightCheck[] = [
498
- { name: "ensureInputValid", kind: "halt", run: ensureInputValid },
499
- { name: "ensureContractInputValid", kind: "halt", run: ensureContractInputValid },
500
- ];