@juicesharp/rpiv-workflow 1.19.1 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -8
- package/api.ts +18 -703
- package/audit-rows.ts +136 -0
- package/audit.ts +139 -126
- package/built-ins.ts +20 -45
- package/chain-state.ts +169 -0
- package/command-run.ts +31 -3
- package/command.ts +116 -20
- package/docs/workflow-authoring.md +322 -61
- package/{lifecycle.ts → events.ts} +119 -35
- package/host.ts +30 -0
- package/index.ts +25 -81
- package/internal-utils.ts +92 -78
- package/internal.ts +21 -1
- package/judge.ts +229 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +16 -109
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/shape-guards.test.ts +4 -1
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +623 -0
- package/loop-def.ts +240 -0
- package/loop-kinds.ts +493 -0
- package/loop.ts +304 -0
- package/messages.ts +225 -157
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/tool-call.test.ts +3 -1
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +2 -3
- package/outcomes/collectors/union.test.ts +54 -0
- package/outcomes/collectors/union.ts +28 -9
- package/outcomes/collectors/url.ts +7 -0
- package/outcomes/collectors/workspace-diff.test.ts +13 -0
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.test.ts +76 -30
- package/outcomes/git-commit.ts +139 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +40 -20
- package/package.json +13 -7
- package/predicates.ts +11 -8
- package/preview.ts +77 -17
- package/registration.ts +109 -35
- package/routing-dsl.ts +310 -0
- package/routing.ts +2 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +59 -44
- package/runner/errors.ts +33 -0
- package/runner/failure.ts +109 -0
- package/runner/header-write-failure.test.ts +64 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +11 -21
- package/runner/preflight.ts +173 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +101 -0
- package/runner/resume-loop.test.ts +1410 -0
- package/runner/resume-loop.ts +110 -0
- package/runner/resume-session.test.ts +400 -0
- package/runner/resume.test.ts +881 -206
- package/runner/resume.ts +281 -261
- package/runner/run-context.ts +161 -0
- package/runner/run-stage.ts +456 -0
- package/runner/runner.ts +59 -400
- package/runner/script-stage.ts +103 -105
- package/schema-compat.ts +13 -1
- package/sessions/extraction.ts +53 -31
- package/sessions/index.ts +3 -1
- package/sessions/locate.test.ts +77 -0
- package/sessions/locate.ts +90 -0
- package/sessions/reattach.ts +63 -0
- package/sessions/sessions.ts +130 -127
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +88 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +2 -3
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +527 -0
- package/startup.ts +3 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +12 -0
- package/state/raw.ts +78 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +112 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +202 -44
- package/validate/contract-compat.ts +193 -0
- package/validate/graph.ts +125 -0
- package/validate/issue.ts +314 -0
- package/validate/stage-rules.ts +420 -0
- package/validate-output.ts +69 -1
- package/validate-workflow.ts +55 -759
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- 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
|
-
];
|