@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.
- package/README.md +81 -8
- package/api.ts +18 -703
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +154 -0
- package/audit.ts +158 -190
- package/built-ins.ts +40 -45
- package/chain-state.ts +220 -0
- package/command-run.ts +64 -31
- package/command.ts +123 -21
- package/docs/workflow-authoring.md +356 -63
- package/{lifecycle.ts → events.ts} +161 -37
- package/execution-host.ts +75 -0
- package/host.ts +149 -64
- package/index.ts +25 -81
- package/internal-utils.ts +171 -71
- package/internal.ts +22 -1
- package/judge.ts +241 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +27 -106
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +24 -0
- package/loop-def.ts +285 -0
- package/loop-kinds.ts +750 -0
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +330 -0
- package/loops/constructors.ts +334 -0
- package/loops/derivations.ts +65 -0
- package/loops/introspection.ts +184 -0
- package/loops/panel.ts +196 -0
- package/loops/verify.ts +99 -0
- package/messages.ts +249 -156
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +4 -18
- package/outcomes/collectors/union.ts +30 -10
- package/outcomes/collectors/url.ts +9 -14
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.ts +190 -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 +98 -20
- package/package.json +27 -11
- package/predicates.ts +11 -8
- package/preview.ts +81 -21
- package/registration.ts +117 -36
- package/routing-dsl.ts +322 -0
- package/routing.ts +48 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +84 -56
- package/runner/errors.ts +10 -0
- package/runner/failure.ts +163 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +16 -23
- package/runner/preflight.ts +169 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +121 -0
- package/runner/resume-loop.ts +131 -0
- package/runner/resume.ts +368 -262
- package/runner/run-context.ts +165 -0
- package/runner/run-stage.ts +490 -0
- package/runner/runner.ts +202 -449
- package/runner/script-stage.ts +104 -112
- package/schema-compat.ts +12 -1
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +146 -81
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +3 -1
- package/sessions/locate.ts +141 -0
- package/sessions/reattach.ts +71 -0
- package/sessions/sessions.ts +114 -199
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +86 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +4 -4
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +595 -0
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +4 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +20 -0
- package/state/raw.ts +77 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +135 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +290 -78
- package/validate/contract-compat.ts +198 -0
- package/validate/graph.ts +134 -0
- package/validate/issue.ts +328 -0
- package/validate/stage-rules.ts +499 -0
- package/validate-output.ts +82 -7
- package/validate-workflow.ts +57 -759
- package/validation-bounds.ts +35 -0
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -74
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -110
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -59
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -107
- package/outcomes/git-commit.test.ts +0 -194
- package/outcomes/parsers/json-body.test.ts +0 -80
- package/runner/by-name.test.ts +0 -95
- package/runner/by-run-id.test.ts +0 -115
- 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/resume.test.ts +0 -1130
- package/runner/stage-lifecycle.ts +0 -500
package/runner/chain-advance.ts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Routing layer after a stage completes successfully: pick the next stage,
|
|
3
3
|
* audit predicate-mediated decisions, enforce the backward-jump guard,
|
|
4
|
-
* then recurse via `
|
|
4
|
+
* then recurse via the injected `deps.runNext`.
|
|
5
5
|
*
|
|
6
6
|
* `nextStage` returns a tagged union; `advanceChain` switches on `kind`
|
|
7
|
-
* instead of catching.
|
|
8
|
-
* downstream-stage throws
|
|
7
|
+
* instead of catching. The injected runner owns the catch for
|
|
8
|
+
* downstream-stage throws — the `ChainDeps` injection (the `LoopDeps`
|
|
9
|
+
* pattern) keeps this module's imports strictly downward: the chain walk's
|
|
10
|
+
* runStage ↔ advanceChain recursion is composed in run-stage.ts, not
|
|
11
|
+
* spelled as a module cycle.
|
|
9
12
|
*/
|
|
10
13
|
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
MSG_ROUTING_AUDIT_DROPPED,
|
|
19
|
-
} from "../messages.js";
|
|
20
|
-
import { edgeIsDecision, nextStage } from "../routing.js";
|
|
14
|
+
import { takeRouteNote } from "../api.js";
|
|
15
|
+
import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
|
|
16
|
+
import { resolveSkill } from "../chain-state.js";
|
|
17
|
+
import { lifecycleCtxFor, skillStageRef } from "../events.js";
|
|
18
|
+
import { nowIso } from "../internal-utils.js";
|
|
19
|
+
import { FAIL_BACKWARD_JUMP_EXHAUSTED, MSG_CHAIN_ADVANCE_FAILED, MSG_ROUTING_AUDIT_DROPPED } from "../messages.js";
|
|
20
|
+
import { bypassedRecoveryArms, edgeIsDecision, nextStage } from "../routing.js";
|
|
21
21
|
import { appendRoutingDecision } from "../state/index.js";
|
|
22
22
|
import type { RunContext, WorkflowHostContext } from "../types.js";
|
|
23
|
-
import {
|
|
23
|
+
import { type ChainOutcome, finalizeWorkflow } from "./failure.js";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The walk continuation injected by the composition site
|
|
27
|
+
* (run-stage.ts): run the routed next stage through the single catch
|
|
28
|
+
* site. Injected so this module never imports the per-stage pipeline back —
|
|
29
|
+
* the mutual recursion of the chain walk lives in ONE composing module.
|
|
30
|
+
*/
|
|
31
|
+
export interface ChainDeps {
|
|
32
|
+
runNext: (curCtx: WorkflowHostContext, name: string, idx: number, run: RunContext) => Promise<ChainOutcome>;
|
|
33
|
+
}
|
|
24
34
|
|
|
25
35
|
/**
|
|
26
36
|
* Decomposed into three helpers — `auditRoutingDecision`,
|
|
@@ -32,7 +42,8 @@ export async function advanceChain(
|
|
|
32
42
|
currentName: string,
|
|
33
43
|
idx: number,
|
|
34
44
|
run: RunContext,
|
|
35
|
-
|
|
45
|
+
deps: ChainDeps,
|
|
46
|
+
): Promise<ChainOutcome> {
|
|
36
47
|
// Mark the just-completed stage as visited BEFORE consulting the next edge.
|
|
37
48
|
// A thrown EdgeFn would otherwise leave currentName un-marked, opening a
|
|
38
49
|
// (narrow) window where a recovery path could under-count revisits.
|
|
@@ -42,34 +53,39 @@ export async function advanceChain(
|
|
|
42
53
|
const result = nextStage(run.workflow, currentName, { output: run.state.output, state: run.state });
|
|
43
54
|
|
|
44
55
|
if (result.kind === "err") {
|
|
45
|
-
|
|
46
|
-
return;
|
|
56
|
+
return haltOnRoutingError(curCtx, run, currentName, result.reason);
|
|
47
57
|
}
|
|
48
58
|
|
|
49
59
|
const fromRef = skillStageRef(currentName, idx + 1, resolveSkill(run.workflow.stages[currentName]!, currentName));
|
|
50
60
|
|
|
61
|
+
// Recovery arms this decision passed over for good — credited toward progress
|
|
62
|
+
// "coverage" by the bridge so a clean run's bar isn't frozen one-below until the
|
|
63
|
+
// end (build's slice-fix/plan-fix/code-fix). Empty for deterministic edges (no alternatives).
|
|
64
|
+
const chosen = result.kind === "stop" ? "stop" : result.stage;
|
|
65
|
+
const bypassed = wasDecision ? bypassedRecoveryArms(run.workflow, currentName, chosen, run.visited) : [];
|
|
66
|
+
|
|
51
67
|
if (result.kind === "stop") {
|
|
52
|
-
await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
|
|
53
|
-
finalizeWorkflow(curCtx, run);
|
|
54
|
-
return;
|
|
68
|
+
await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run), bypassed);
|
|
69
|
+
return finalizeWorkflow(curCtx, run);
|
|
55
70
|
}
|
|
56
71
|
|
|
57
72
|
const nextName = result.stage;
|
|
58
73
|
if (wasDecision) {
|
|
59
74
|
auditRoutingDecision(curCtx, run, idx, currentName, nextName);
|
|
60
|
-
|
|
75
|
+
const guard = await checkBackwardJumpGuard(curCtx, run, nextName);
|
|
76
|
+
if (guard !== "continue") return guard;
|
|
61
77
|
}
|
|
62
78
|
|
|
63
79
|
// Fire onRoute after the routing decision has been audited (when applicable),
|
|
64
80
|
// before the next stage runs. Deterministic auto-edges still fire so
|
|
65
81
|
// listeners see every transition.
|
|
66
|
-
await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run));
|
|
82
|
+
await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run), bypassed);
|
|
67
83
|
|
|
68
|
-
//
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
|
|
84
|
+
// deps.runNext owns the catch for throws out of the *next* stage, so the
|
|
85
|
+
// JSONL row records `nextName` (the stage that actually threw) rather than
|
|
86
|
+
// `currentName` (which would mis-attribute the failure to the prior stage
|
|
87
|
+
// that already completed successfully).
|
|
88
|
+
return deps.runNext(curCtx, nextName, idx + 1, run);
|
|
73
89
|
}
|
|
74
90
|
|
|
75
91
|
/**
|
|
@@ -90,12 +106,18 @@ function auditRoutingDecision(
|
|
|
90
106
|
currentName: string,
|
|
91
107
|
nextName: string,
|
|
92
108
|
): void {
|
|
109
|
+
// Read-and-clear any note the edge attached to THIS pick (e.g. gate's
|
|
110
|
+
// fallback-fired diagnostic). Same tick as the invocation — no other
|
|
111
|
+
// decision can interleave. `undefined` is dropped by JSON.stringify.
|
|
112
|
+
const edge = run.workflow.edges[currentName];
|
|
113
|
+
const note = typeof edge === "function" ? takeRouteNote(edge) : undefined;
|
|
93
114
|
const fromStageIndex = idx + 1;
|
|
94
115
|
const wrote = appendRoutingDecision(run.cwd, run.runId, {
|
|
95
116
|
type: "routing",
|
|
96
117
|
fromStageIndex,
|
|
97
118
|
fromStage: currentName,
|
|
98
119
|
decision: nextName,
|
|
120
|
+
note,
|
|
99
121
|
ts: nowIso(),
|
|
100
122
|
});
|
|
101
123
|
if (!wrote) {
|
|
@@ -105,9 +127,9 @@ function auditRoutingDecision(
|
|
|
105
127
|
}
|
|
106
128
|
|
|
107
129
|
/**
|
|
108
|
-
* Per-
|
|
109
|
-
*
|
|
110
|
-
* been recorded).
|
|
130
|
+
* Per-DESTINATION cap on decision-edge retries. Returns `"continue"` when the
|
|
131
|
+
* run may proceed, or the `"halted"` outcome when the cap tripped (and the
|
|
132
|
+
* terminal failure has been recorded).
|
|
111
133
|
*
|
|
112
134
|
* A "backward jump" is a *decision-edge* resolving to an already-visited
|
|
113
135
|
* stage — i.e. a deliberate retry choice. Deterministic forward edges that
|
|
@@ -117,10 +139,19 @@ function auditRoutingDecision(
|
|
|
117
139
|
* mid-loop on any cycle longer than 2 stages, burning the entire budget
|
|
118
140
|
* on a single retry iteration's deterministic hops.
|
|
119
141
|
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
142
|
+
* Each destination owns its budget (`run.revisits`): a stage may be
|
|
143
|
+
* re-entered via decision edges at most `maxBackwardJumps` times, regardless
|
|
144
|
+
* of how many OTHER decision edges the cycle crosses on the way. A shared
|
|
145
|
+
* streak counter would make the effective retry budget a function of the
|
|
146
|
+
* cycle's hop count — inserting a checking stage into a fix loop (a
|
|
147
|
+
* deterministic-floor edge, a confirm arm) silently taxed the fix budget.
|
|
148
|
+
* Per-destination counts are invariant to the cycle's shape, and unrelated
|
|
149
|
+
* loops are independent by construction (different destinations), which is
|
|
150
|
+
* what the old reset-on-escape rule existed to approximate.
|
|
151
|
+
*
|
|
152
|
+
* `state.telemetry.backwardJumps` stays the run-wide cumulative total of
|
|
153
|
+
* counted backward jumps (post-hoc telemetry only — never consulted for the
|
|
154
|
+
* halt decision, never reset).
|
|
124
155
|
*
|
|
125
156
|
* Trip attribution targets `nextName` (the stage the guard refused to
|
|
126
157
|
* re-enter), not the just-completed stage.
|
|
@@ -129,21 +160,18 @@ async function checkBackwardJumpGuard(
|
|
|
129
160
|
curCtx: WorkflowHostContext,
|
|
130
161
|
run: RunContext,
|
|
131
162
|
nextName: string,
|
|
132
|
-
): Promise<
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
errMsg: ERR_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps),
|
|
145
|
-
});
|
|
146
|
-
return false;
|
|
163
|
+
): Promise<"continue" | ChainOutcome> {
|
|
164
|
+
if (!run.visited.has(nextName)) return "continue";
|
|
165
|
+
const revisits = (run.revisits.get(nextName) ?? 0) + 1;
|
|
166
|
+
run.revisits.set(nextName, revisits);
|
|
167
|
+
run.state.telemetry.backwardJumps++;
|
|
168
|
+
if (revisits <= run.maxBackwardJumps) return "continue";
|
|
169
|
+
await recordTerminalFailure(
|
|
170
|
+
curCtx,
|
|
171
|
+
auditCtxFor(run, nextName, nextName),
|
|
172
|
+
failedArgs(FAIL_BACKWARD_JUMP_EXHAUSTED(nextName, revisits, run.maxBackwardJumps)),
|
|
173
|
+
);
|
|
174
|
+
return "halted";
|
|
147
175
|
}
|
|
148
176
|
|
|
149
177
|
/**
|
|
@@ -156,11 +184,11 @@ async function haltOnRoutingError(
|
|
|
156
184
|
run: RunContext,
|
|
157
185
|
currentName: string,
|
|
158
186
|
reason: string,
|
|
159
|
-
): Promise<
|
|
160
|
-
await recordTerminalFailure(
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
187
|
+
): Promise<ChainOutcome> {
|
|
188
|
+
await recordTerminalFailure(
|
|
189
|
+
curCtx,
|
|
190
|
+
auditCtxFor(run, currentName, currentName),
|
|
191
|
+
failedArgs(MSG_CHAIN_ADVANCE_FAILED(currentName, reason), reason),
|
|
192
|
+
);
|
|
193
|
+
return "halted";
|
|
166
194
|
}
|
package/runner/errors.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The runner's typed-throw vocabulary. The error type itself is a package-root
|
|
3
|
+
* shared kernel (`../stage-errors.ts`) so the engine's loop layer can throw it
|
|
4
|
+
* without importing into `runner/`; this module re-exports it so every layer of
|
|
5
|
+
* the per-stage pipeline (preflights, input validation, the loop shortcut) keeps
|
|
6
|
+
* its local `./errors.js` spelling and the single catch site
|
|
7
|
+
* (`runStageOrRecordFailure`, run-stage.ts) catches it as before.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export { haltPreflight, invariantPreflight, StagePreflightError } from "../stage-errors.js";
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal-outcome translation for the chain walk — a LEAF imported downward
|
|
3
|
+
* by runner.ts, chain-advance.ts, and run-stage.ts. Owns the ONE
|
|
4
|
+
* "entry threw" → failure-row translation and the run-completion finalizer,
|
|
5
|
+
* plus the `ChainOutcome` vocabulary the whole walk returns.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
abortedArgs,
|
|
10
|
+
auditCtxFor,
|
|
11
|
+
failedArgs,
|
|
12
|
+
notifyPartialArtifacts,
|
|
13
|
+
recordTerminalFailure,
|
|
14
|
+
terminate,
|
|
15
|
+
} from "../audit.js";
|
|
16
|
+
import { formatError, isAbortError } from "../internal-utils.js";
|
|
17
|
+
import { FAIL_WORKFLOW_ABORTED, MSG_STAGE_THREW, MSG_WORKFLOW_COMPLETE } from "../messages.js";
|
|
18
|
+
import type { RunContext, UnitRef, WorkflowHostContext } from "../types.js";
|
|
19
|
+
import { StagePreflightError } from "./errors.js";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Explicit result of one chain-walk step, threaded up through
|
|
23
|
+
* `advanceChain` / `runStage` / `runStageOrRecordFailure`. The walk's halt
|
|
24
|
+
* protocol is record-then-halt, not record-then-quietly-unwind: with a
|
|
25
|
+
* non-void return type, a branch that records a failure but forgets to stop
|
|
26
|
+
* the walk no longer typechecks — every arm must RETURN an outcome, and
|
|
27
|
+
* halts read `return haltChain(...)`.
|
|
28
|
+
*
|
|
29
|
+
* - `"halted"` — a terminal failure/abort row was recorded; the walk
|
|
30
|
+
* stops here and unwinds.
|
|
31
|
+
* - `"completed"` — the chain reached `stop`; `finalizeWorkflow` ran.
|
|
32
|
+
* - `"dispatched"` — the walk handed off to a session/loop continuation
|
|
33
|
+
* (Pi owns the live session; the eventual outcome
|
|
34
|
+
* resolves inside the continuation's own walk frames).
|
|
35
|
+
*/
|
|
36
|
+
export type ChainOutcome = "halted" | "completed" | "dispatched";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The composed chain-advance continuation (run-stage.ts wires it) —
|
|
40
|
+
* injected into stage runners that advance the chain themselves (the script
|
|
41
|
+
* path) so they never import the composition site back.
|
|
42
|
+
*/
|
|
43
|
+
export type AdvanceFn = (
|
|
44
|
+
curCtx: WorkflowHostContext,
|
|
45
|
+
completedName: string,
|
|
46
|
+
completedIdx: number,
|
|
47
|
+
run: RunContext,
|
|
48
|
+
) => Promise<ChainOutcome>;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Record a terminal failure and yield the `"halted"` outcome — the standard
|
|
52
|
+
* halt idiom for walk arms: `return haltChain(...)`.
|
|
53
|
+
*/
|
|
54
|
+
export async function haltChain(
|
|
55
|
+
curCtx: WorkflowHostContext,
|
|
56
|
+
run: RunContext,
|
|
57
|
+
stageName: string,
|
|
58
|
+
skill: string,
|
|
59
|
+
args: Parameters<typeof recordTerminalFailure>[2],
|
|
60
|
+
onFailure?: (ctx: WorkflowHostContext) => void,
|
|
61
|
+
unit?: UnitRef,
|
|
62
|
+
): Promise<ChainOutcome> {
|
|
63
|
+
await recordTerminalFailure(
|
|
64
|
+
curCtx,
|
|
65
|
+
auditCtxFor(run, stageName, skill, unit ? { unit } : undefined),
|
|
66
|
+
args,
|
|
67
|
+
onFailure,
|
|
68
|
+
);
|
|
69
|
+
return "halted";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The ONE "entry threw" → terminal-failure-row translation (live + resume
|
|
74
|
+
* entries). Two flavours of throw land here:
|
|
75
|
+
*
|
|
76
|
+
* - `StagePreflightError` — a known preflight failure carrying its own
|
|
77
|
+
* attribution + messages. Recorded with the carried payload exactly.
|
|
78
|
+
* - Any other `Error` — unexpected machinery failure; recorded with the
|
|
79
|
+
* generic `MSG_STAGE_THREW` shape attributed to the stage id.
|
|
80
|
+
*
|
|
81
|
+
* `unit` is present only for the fanout worker-throw sink (`recordWorkerThrow`):
|
|
82
|
+
* its `{ ref, skill }` lands the unit's structured identity on the row
|
|
83
|
+
* (`parent`/`role`/`unitId`/`unitIndex` via `unitRowFields`) and the fanned
|
|
84
|
+
* `skill`, so the unit's identity is NOT folded into the `stage` name string.
|
|
85
|
+
*/
|
|
86
|
+
export async function recordEntryThrow(
|
|
87
|
+
curCtx: WorkflowHostContext,
|
|
88
|
+
name: string,
|
|
89
|
+
run: RunContext,
|
|
90
|
+
e: unknown,
|
|
91
|
+
unit?: { ref: UnitRef; skill: string },
|
|
92
|
+
): Promise<ChainOutcome> {
|
|
93
|
+
if (e instanceof StagePreflightError) {
|
|
94
|
+
return haltChain(
|
|
95
|
+
curCtx,
|
|
96
|
+
run,
|
|
97
|
+
name,
|
|
98
|
+
e.skill,
|
|
99
|
+
failedArgs(e.notifyMsg, e.errMsg),
|
|
100
|
+
e.notifyPartial ? (ctx) => notifyPartialArtifacts(ctx, run.cwd, run.runId) : undefined,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
const reason = formatError(e);
|
|
104
|
+
return haltChain(
|
|
105
|
+
curCtx,
|
|
106
|
+
run,
|
|
107
|
+
name,
|
|
108
|
+
unit?.skill ?? name,
|
|
109
|
+
failedArgs(MSG_STAGE_THREW(name, reason), reason),
|
|
110
|
+
undefined,
|
|
111
|
+
unit?.ref,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Record the `"aborted"` terminal row for a cooperative-cancellation stop — at
|
|
117
|
+
* the between-stage seam (`run.signal` aborted before `name` ran) OR when a
|
|
118
|
+
* mid-stage `postStage` throws `WorkflowAbortError`. Mirrors the error
|
|
119
|
+
* path's partial-artifacts recap (`recordEntryThrow` → `notifyPartialArtifacts`):
|
|
120
|
+
* artifacts produced by earlier stages are surfaced so the operator sees them
|
|
121
|
+
* instead of grepping the JSONL. No-op when no artifacts exist.
|
|
122
|
+
*/
|
|
123
|
+
export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, run: RunContext): Promise<ChainOutcome> {
|
|
124
|
+
return haltChain(curCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)), (ctx) =>
|
|
125
|
+
notifyPartialArtifacts(ctx, run.cwd, run.runId),
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* THE stage-entry guard — the ONE classify-then-record policy both single-stage
|
|
131
|
+
* entries share: pre-check the cooperative-abort signal, run `inner`, and on a
|
|
132
|
+
* throw classify it (mid-stage `WorkflowAbortError` → envelope-safe abort;
|
|
133
|
+
* anything else → terminal entry-throw row). Modeled after `advanceCursor`
|
|
134
|
+
* (loop.ts): one shared authority, callers hold their own preconditions.
|
|
135
|
+
*
|
|
136
|
+
* The two call sites (`runStageOrRecordFailure` live, `resumeStageWithSession`
|
|
137
|
+
* resume) cover DISJOINT scopes — the resume catch protects the reattach ladder
|
|
138
|
+
* (`resumeWithSessionLadder`) the live catch cannot reach — so both must exist.
|
|
139
|
+
* This wrapper merges the CLASSIFICATION POLICY (which throw is an abort vs a
|
|
140
|
+
* real entry-throw), not the scopes: each caller invokes it with its own `inner`
|
|
141
|
+
* + `name`, so a future widening of "what counts as abort" (a new cooperative-
|
|
142
|
+
* cancel signal beyond `WorkflowAbortError`) is one edit, here.
|
|
143
|
+
*/
|
|
144
|
+
export async function withStageEntryGuard(
|
|
145
|
+
curCtx: WorkflowHostContext,
|
|
146
|
+
name: string,
|
|
147
|
+
run: RunContext,
|
|
148
|
+
inner: () => Promise<ChainOutcome>,
|
|
149
|
+
): Promise<ChainOutcome> {
|
|
150
|
+
if (run.signal?.aborted) return recordAbortedAtSeam(curCtx, name, run);
|
|
151
|
+
try {
|
|
152
|
+
return await inner();
|
|
153
|
+
} catch (e) {
|
|
154
|
+
if (isAbortError(e)) return recordAbortedAtSeam(curCtx, name, run);
|
|
155
|
+
return recordEntryThrow(curCtx, name, run, e);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function finalizeWorkflow(curCtx: WorkflowHostContext, run: RunContext): ChainOutcome {
|
|
160
|
+
curCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
|
|
161
|
+
terminate(run.state, { status: "completed" });
|
|
162
|
+
return "completed";
|
|
163
|
+
}
|
package/runner/index.ts
CHANGED
|
@@ -1,18 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Workflow runner public surface. The runner is internally split
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Workflow runner public surface. The runner is internally split by concern
|
|
3
|
+
* (see `runner.ts`'s header for the module map); this barrel re-exports only
|
|
4
|
+
* the symbols the package itself needs to publish.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
export type { RunWorkflowOptions, RunWorkflowResult } from "../types.js";
|
|
7
8
|
export { type RunWorkflowByNameOptions, runWorkflowByName } from "./by-name.js";
|
|
8
9
|
export { type ResumeWorkflowByRunIdOptions, resumeWorkflowByRunId } from "./by-run-id.js";
|
|
9
|
-
export {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
type RunWorkflowOptions,
|
|
13
|
-
type RunWorkflowResult,
|
|
14
|
-
resumeWorkflow,
|
|
15
|
-
runWorkflow,
|
|
16
|
-
} from "./runner.js";
|
|
17
|
-
|
|
18
|
-
export { StagePreflightError } from "./stage-lifecycle.js";
|
|
10
|
+
export { StagePreflightError } from "./errors.js";
|
|
11
|
+
export { MAX_BACKWARD_JUMPS } from "./run-context.js";
|
|
12
|
+
export { type ResumeWorkflowOptions, resumeWorkflow, runWorkflow } from "./runner.js";
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Input-validation preflights for the runner's per-stage pipeline.
|
|
3
3
|
*
|
|
4
|
-
* Two validators run
|
|
4
|
+
* Two validators run after prompt prep in the single-stage pipeline
|
|
5
|
+
* (`runSingleStage`, run-stage.ts):
|
|
5
6
|
* - `ensureInputValid` — validates upstream output against the stage's
|
|
6
7
|
* declared `inputSchema`.
|
|
7
8
|
* - `ensureContractInputValid` — validates upstream output against the
|
|
@@ -15,20 +16,22 @@
|
|
|
15
16
|
* halting only on timeouts.
|
|
16
17
|
*/
|
|
17
18
|
|
|
18
|
-
import {
|
|
19
|
+
import { formatError, withTimeout } from "../internal-utils.js";
|
|
19
20
|
import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
|
|
20
|
-
import {
|
|
21
|
+
import { ERR_SCHEMA_TIMEOUT, FAIL_INPUT_VALIDATION } from "../messages.js";
|
|
21
22
|
import type { RunContext } from "../types.js";
|
|
22
23
|
import {
|
|
23
24
|
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
24
25
|
describeFailure,
|
|
25
26
|
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
26
27
|
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
28
|
+
SchemaTimeoutError,
|
|
27
29
|
type ValidationResult,
|
|
28
30
|
validateOutputData,
|
|
29
31
|
} from "../validate-output.js";
|
|
30
|
-
import
|
|
31
|
-
import {
|
|
32
|
+
import { clampRange } from "../validation-bounds.js";
|
|
33
|
+
import { haltPreflight } from "./errors.js";
|
|
34
|
+
import type { ResolvedStage } from "./resolve-stage.js";
|
|
32
35
|
|
|
33
36
|
// ---------------------------------------------------------------------------
|
|
34
37
|
// Shared helper
|
|
@@ -75,26 +78,14 @@ async function validateOrThrow(
|
|
|
75
78
|
result = await withTimeout(Promise.resolve(validateOutputData(schema, data)), timeoutMs, timeoutError);
|
|
76
79
|
} catch (e) {
|
|
77
80
|
if (errorPolicy === "degrade-on-non-timeout" && !(e instanceof SchemaTimeoutError)) return;
|
|
78
|
-
const
|
|
79
|
-
throw
|
|
80
|
-
"halt",
|
|
81
|
-
stage.skill,
|
|
82
|
-
MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
|
|
83
|
-
ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, reason),
|
|
84
|
-
true,
|
|
85
|
-
);
|
|
81
|
+
const f = FAIL_INPUT_VALIDATION(stage.skill, prevSkill, formatError(e));
|
|
82
|
+
throw haltPreflight(stage.skill, f);
|
|
86
83
|
}
|
|
87
84
|
|
|
88
85
|
if (result.valid) return;
|
|
89
86
|
|
|
90
|
-
const
|
|
91
|
-
throw
|
|
92
|
-
"halt",
|
|
93
|
-
stage.skill,
|
|
94
|
-
MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
|
|
95
|
-
ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, failureSummary),
|
|
96
|
-
true,
|
|
97
|
-
);
|
|
87
|
+
const f = FAIL_INPUT_VALIDATION(stage.skill, prevSkill, result.failures.map(describeFailure).join("; "));
|
|
88
|
+
throw haltPreflight(stage.skill, f);
|
|
98
89
|
}
|
|
99
90
|
|
|
100
91
|
// ---------------------------------------------------------------------------
|
|
@@ -110,9 +101,11 @@ async function validateOrThrow(
|
|
|
110
101
|
* firing a 100 ms timeout before a real I/O probe gets a chance to settle.
|
|
111
102
|
*/
|
|
112
103
|
function clampValidateTimeoutMs(raw: number | undefined): number {
|
|
113
|
-
return
|
|
104
|
+
return clampRange(
|
|
105
|
+
raw,
|
|
114
106
|
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
115
|
-
|
|
107
|
+
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
108
|
+
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
116
109
|
);
|
|
117
110
|
}
|
|
118
111
|
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime preflights for the per-stage pipeline — every check that gates a
|
|
3
|
+
* stage BEFORE its body dispatches. Each check throws `StagePreflightError`
|
|
4
|
+
* on failure; `runStageOrRecordFailure` (run-stage.ts) catches and
|
|
5
|
+
* records the JSONL row. Schema-backed input validation (the two POST-prompt
|
|
6
|
+
* checks) lives beside this in `input-validation.ts`.
|
|
7
|
+
*
|
|
8
|
+
* Checks switch on the resolved `dispatch` mode (resolve-stage.ts) instead
|
|
9
|
+
* of re-probing `def.prompt` — the slot-priority rule lives in one place.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { currentPrimaryArtifact } from "../chain-state.js";
|
|
13
|
+
import { type AnyJudge, panelMembers } from "../judge.js";
|
|
14
|
+
import {
|
|
15
|
+
FAIL_MISSING_ARTIFACT,
|
|
16
|
+
FAIL_MISSING_NAMED_READ,
|
|
17
|
+
FAIL_SKILL_NOT_REGISTERED,
|
|
18
|
+
MSG_STAGE_THREW,
|
|
19
|
+
} from "../messages.js";
|
|
20
|
+
import { readName } from "../stage-def.js";
|
|
21
|
+
import type { RunContext } from "../types.js";
|
|
22
|
+
import { haltPreflight, invariantPreflight } from "./errors.js";
|
|
23
|
+
import type { ResolvedStage } from "./resolve-stage.js";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The skill-path preflight sequence, in its load-bearing order:
|
|
27
|
+
* 1. ensureUpstreamArtifact — halt: missing inherited artifact.
|
|
28
|
+
* 2. ensureNamedReads — halt: a `reads:` name has no published entry.
|
|
29
|
+
* 3. enforceSessionInvariants — invariant: authoring-time-knowable throws
|
|
30
|
+
* (precede the registry check so the structural violation surfaces
|
|
31
|
+
* regardless of the runtime registry).
|
|
32
|
+
* 4. ensureSkillRegistered — halt: skill not registered in Pi.
|
|
33
|
+
* (Input-schema validation runs after prompt prep — see input-validation.ts.)
|
|
34
|
+
*/
|
|
35
|
+
export function runSingleStagePreflights(stage: ResolvedStage, run: RunContext): void {
|
|
36
|
+
ensureUpstreamArtifact(stage, run);
|
|
37
|
+
ensureNamedReads(stage, run);
|
|
38
|
+
ensureSkillRegistered(stage, run);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The loop ⊕ continue exclusion — runtime mirror of load validation; checked
|
|
43
|
+
* BEFORE the push loop's unit compute (which is itself pinned to run before
|
|
44
|
+
* the remaining loop preflights — a `units()` throw carries its own
|
|
45
|
+
* attribution and must beat any other preflight's halt).
|
|
46
|
+
*/
|
|
47
|
+
export function ensureLoopNotContinue(stage: ResolvedStage): void {
|
|
48
|
+
if (stage.def.sessionPolicy !== "continue") return;
|
|
49
|
+
const reason =
|
|
50
|
+
`runStage: stage "${stage.name}" cannot combine loop with sessionPolicy "continue" — ` +
|
|
51
|
+
"each unit requires an isolated session";
|
|
52
|
+
throw invariantPreflight(stage.name, MSG_STAGE_THREW(stage.name, reason), reason);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Loop-stage preflights, run UNIFORMLY for every loop kind — no kind takes a
|
|
57
|
+
* shortcut:
|
|
58
|
+
* - ensureNamedReads + ensureSkillRegistered for ALL loops (every loop's
|
|
59
|
+
* units dispatch `/skill:<skill>`, and generators read declared channels);
|
|
60
|
+
* - ensureUpstreamArtifact for ASSESS ONLY — the round-0 producer arg is
|
|
61
|
+
* the one loop input that consumes the rolling primary (fanout/iterate
|
|
62
|
+
* unit prompts are author-built; an entry-point loop with no primary is
|
|
63
|
+
* legal for them);
|
|
64
|
+
* - judge-skill registry check for any loop carrying a `.skill` judge.
|
|
65
|
+
*/
|
|
66
|
+
export function runLoopPreflights(stage: ResolvedStage, run: RunContext): void {
|
|
67
|
+
const loop = stage.loop!; // mode === "loop" ⇒ resolveStage set it
|
|
68
|
+
ensureNamedReads(stage, run);
|
|
69
|
+
ensureSkillRegistered(stage, run);
|
|
70
|
+
if (loop.kind === "assess") {
|
|
71
|
+
ensureUpstreamArtifact(stage, run);
|
|
72
|
+
ensureJudgeSkillRegistered(loop.judge, stage, run);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Registry preflight for a judge SLOT (`AnyJudge`) — walks `panelMembers`, so a
|
|
78
|
+
* single judge checks its one `.skill` and a panel checks EVERY member's skill
|
|
79
|
+
* (the first unregistered member halts). `ensureSkillRegistered` only inspects
|
|
80
|
+
* `stage.skill`; this covers the judge dispatch. Fail-soft when
|
|
81
|
+
* `registeredSkills` is undefined (hostless embedder); members without a
|
|
82
|
+
* `.skill` (prompt judges) are skipped.
|
|
83
|
+
*/
|
|
84
|
+
export function ensureJudgeSkillRegistered(judge: AnyJudge, stage: ResolvedStage, run: RunContext): void {
|
|
85
|
+
if (run.registeredSkills === undefined) return;
|
|
86
|
+
for (const member of panelMembers(judge)) {
|
|
87
|
+
if (member.skill === undefined) continue;
|
|
88
|
+
if (run.registeredSkills.has(member.skill)) continue;
|
|
89
|
+
const f = FAIL_SKILL_NOT_REGISTERED(member.skill, stage.stageNumber);
|
|
90
|
+
throw haltPreflight(member.skill, f);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Verify `stage.skill` resolves to a Pi-registered skill BEFORE the prompt
|
|
96
|
+
* is dispatched. The workflow runner emits `/skill:<name>` text via
|
|
97
|
+
* `sendUserMessage` (the programmatic path), which goes through
|
|
98
|
+
* `prompt({expandPromptTemplates: false})` — meaning Pi's built-in
|
|
99
|
+
* `_expandSkillCommand` is skipped and `rpiv-args` is the ONLY expander.
|
|
100
|
+
* If the skill isn't registered, `rpiv-args` returns `{action:"continue"}`
|
|
101
|
+
* and the raw `/skill:<name> …` text reaches the LLM as a bare user-message
|
|
102
|
+
* imperative outside the `<skill>...</skill>` contract — silent LLM-prompt
|
|
103
|
+
* corruption with no diagnostic. Catching it here turns that silent failure
|
|
104
|
+
* into a properly-attributed stage halt.
|
|
105
|
+
*
|
|
106
|
+
* Reads the snapshot in `run.registeredSkills` rather than calling
|
|
107
|
+
* `host.getCommands()` mid-run — the snapshot is built once in
|
|
108
|
+
* `buildRunContext` at run start, off the launcher's registry-level host.
|
|
109
|
+
*
|
|
110
|
+
* Skipped for non-skill dispatch (a prompt stage sends raw text — there is
|
|
111
|
+
* no skill to verify) and when `registeredSkills` is undefined (hostless
|
|
112
|
+
* embedder — same fail-soft posture as the rest of the host-optional
|
|
113
|
+
* surface).
|
|
114
|
+
*/
|
|
115
|
+
function ensureSkillRegistered(stage: ResolvedStage, run: RunContext): void {
|
|
116
|
+
if (stage.dispatch !== "skill") return;
|
|
117
|
+
if (!run.registeredSkills) return;
|
|
118
|
+
if (run.registeredSkills.has(stage.skill)) return;
|
|
119
|
+
|
|
120
|
+
const f = FAIL_SKILL_NOT_REGISTERED(stage.skill, stage.stageNumber);
|
|
121
|
+
throw haltPreflight(stage.skill, f);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The start node consumes the user's brief; subsequent stages MUST inherit
|
|
126
|
+
* an upstream artifactPath. Falling back to originalInput past the start
|
|
127
|
+
* would silently hand a downstream skill the raw feature description.
|
|
128
|
+
*
|
|
129
|
+
* Three opt-outs skip the check:
|
|
130
|
+
* - `inheritsArtifacts: false` (authored via `terminal()`) — stage consumes
|
|
131
|
+
* `originalInput` by design.
|
|
132
|
+
* - `reads: [...]` — stage builds its prompt from the named-publish
|
|
133
|
+
* registry instead of the rolling primary slot; `ensureNamedReads`
|
|
134
|
+
* enforces its own coverage rule.
|
|
135
|
+
* - prompt dispatch — the stage builds its own text and never consumes the
|
|
136
|
+
* rolling primary as an arg (a continue chat turn typically leans on
|
|
137
|
+
* session context, not a handle).
|
|
138
|
+
*/
|
|
139
|
+
function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
|
|
140
|
+
if (stage.name === run.workflow.start) return;
|
|
141
|
+
if (stage.def.inheritsArtifacts === false) return;
|
|
142
|
+
if (stage.def.reads?.length) return;
|
|
143
|
+
if (stage.dispatch === "prompt") return;
|
|
144
|
+
if (currentPrimaryArtifact(run.state)) return;
|
|
145
|
+
const f = FAIL_MISSING_ARTIFACT(stage.skill, stage.stageNumber);
|
|
146
|
+
throw haltPreflight(stage.skill, f);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A stage declaring `reads: [...]` must find every name filled in
|
|
151
|
+
* `state.named` before the prompt is built. `validateWorkflow` already
|
|
152
|
+
* confirms the names CAN exist (some upstream stage publishes them); this
|
|
153
|
+
* catches the runtime path where the producer hasn't fired yet — e.g.
|
|
154
|
+
* the stage was placed before its producer in the edge graph.
|
|
155
|
+
*/
|
|
156
|
+
function ensureNamedReads(stage: ResolvedStage, run: RunContext): void {
|
|
157
|
+
const reads = stage.def.reads;
|
|
158
|
+
if (!reads?.length) return;
|
|
159
|
+
for (const read of reads) {
|
|
160
|
+
const name = readName(read);
|
|
161
|
+
// Reads `.length` of a possibly PRE-SIZED produces-fanout channel as
|
|
162
|
+
// "satisfied". Safe by ordering: this runs at the READING stage's entry,
|
|
163
|
+
// AFTER the upstream fanout stage's fold completed its channel, so it never
|
|
164
|
+
// observes a half-filled produces-fanout channel.
|
|
165
|
+
if (run.state.named[name]?.length) continue;
|
|
166
|
+
const f = FAIL_MISSING_NAMED_READ(stage.skill, name, stage.stageNumber);
|
|
167
|
+
throw haltPreflight(stage.skill, f);
|
|
168
|
+
}
|
|
169
|
+
}
|