@juicesharp/rpiv-workflow 1.20.0 → 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/api.ts +1 -1
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +18 -0
- package/audit.ts +119 -164
- package/built-ins.ts +26 -6
- package/chain-state.ts +119 -68
- package/command-run.ts +35 -30
- package/command.ts +10 -4
- package/docs/workflow-authoring.md +34 -2
- package/events.ts +44 -4
- package/execution-host.ts +75 -0
- package/host.ts +137 -82
- package/internal-utils.ts +89 -3
- package/internal.ts +1 -0
- package/judge.ts +23 -11
- package/load/alias.ts +3 -3
- package/load/index.ts +15 -1
- package/load/issues.ts +2 -2
- package/load/legacy.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/skill-contract-phase.ts +1 -1
- package/loop-constructors.ts +19 -618
- package/loop-def.ts +60 -15
- package/loop-kinds.ts +319 -62
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +106 -80
- 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 +58 -33
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/transcript-path.ts +2 -15
- package/outcomes/collectors/union.ts +2 -1
- package/outcomes/collectors/url.ts +2 -14
- package/outcomes/collectors/workspace-diff.ts +1 -1
- package/outcomes/git-commit.ts +57 -6
- package/output-spec.ts +1 -1
- package/output.ts +59 -1
- package/package.json +16 -6
- package/preview.ts +18 -18
- package/registration.ts +11 -4
- package/routing-dsl.ts +53 -41
- package/routing.ts +46 -0
- package/runner/chain-advance.ts +30 -17
- package/runner/errors.ts +7 -30
- package/runner/failure.ts +67 -13
- package/runner/input-validation.ts +8 -5
- package/runner/preflight.ts +17 -21
- package/runner/resume-entry.ts +23 -3
- package/runner/resume-loop.ts +50 -29
- package/runner/resume.ts +96 -10
- package/runner/run-context.ts +20 -16
- package/runner/run-stage.ts +125 -91
- package/runner/runner.ts +163 -69
- package/runner/script-stage.ts +23 -29
- package/schema-compat.ts +1 -2
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +103 -60
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +2 -2
- package/sessions/locate.ts +60 -9
- package/sessions/reattach.ts +28 -20
- package/sessions/sessions.ts +103 -191
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contracts/composition.ts +8 -10
- package/skill-contracts/harvest.ts +3 -2
- package/skill-contracts/registry.ts +1 -1
- package/stage-def.ts +115 -47
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +1 -0
- package/state/paths.ts +11 -3
- package/state/raw.ts +2 -3
- package/state/resolve.ts +3 -3
- package/state/state.ts +26 -3
- package/state/writes.ts +1 -1
- package/types.ts +97 -43
- package/validate/contract-compat.ts +16 -11
- package/validate/graph.ts +10 -1
- package/validate/issue.ts +20 -6
- package/validate/stage-rules.ts +139 -60
- package/validate-output.ts +27 -20
- package/validate-workflow.ts +5 -3
- package/validation-bounds.ts +35 -0
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -77
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -112
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -113
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -120
- package/outcomes/git-commit.test.ts +0 -240
- 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/header-write-failure.test.ts +0 -64
- package/runner/resume-loop.test.ts +0 -1410
- package/runner/resume-session.test.ts +0 -400
- package/runner/resume.test.ts +0 -1805
- package/sessions/locate.test.ts +0 -77
package/chain-state.ts
CHANGED
|
@@ -11,11 +11,19 @@
|
|
|
11
11
|
* `internal-utils.ts`; anything in this file is workflow-chain domain logic.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import type { PromptFn,
|
|
14
|
+
import type { PromptFn, StageDef } from "./api.js";
|
|
15
15
|
import { type Artifact, handleToString } from "./handle.js";
|
|
16
|
-
import type
|
|
16
|
+
import { isFailedOutput, type Output } from "./output.js";
|
|
17
|
+
import { readName, readsAll } from "./stage-def.js";
|
|
18
|
+
import { resolvePublishName } from "./stage-identity.js";
|
|
17
19
|
import type { RunState } from "./types.js";
|
|
18
20
|
|
|
21
|
+
// Stage-identity projections live in the dependency-free `stage-identity.ts`
|
|
22
|
+
// leaf so the load-time validators can consume them without importing this
|
|
23
|
+
// runtime-state module. Re-exported here so this module's own runtime callers
|
|
24
|
+
// (runner/*, registration) keep a single chain-state import.
|
|
25
|
+
export { isDispatchingStage, resolvePublishName, resolveSkill } from "./stage-identity.js";
|
|
26
|
+
|
|
19
27
|
/**
|
|
20
28
|
* Canonical accessor for "the primary artifact the chain is currently
|
|
21
29
|
* carrying." Reads the rolling slot maintained by the runner —
|
|
@@ -27,47 +35,6 @@ export function currentPrimaryArtifact(state: RunState): Artifact | undefined {
|
|
|
27
35
|
return state.primaryArtifact;
|
|
28
36
|
}
|
|
29
37
|
|
|
30
|
-
/**
|
|
31
|
-
* Resolve the `state.named` key a produces stage appends its `Output`
|
|
32
|
-
* envelope onto. Two layers of fallback, in priority order:
|
|
33
|
-
* 1. `stage.outcome?.name` — categorical name carried by the outcome.
|
|
34
|
-
* 2. The stage's record key — always defined.
|
|
35
|
-
*
|
|
36
|
-
* Single source of truth for the key derivation so the skill-stage path
|
|
37
|
-
* and the script-stage path stay in lockstep, and so `validateWorkflow`
|
|
38
|
-
* can compute the same key set at load time.
|
|
39
|
-
*/
|
|
40
|
-
export function resolvePublishName(def: StageDef, stageName: string): string {
|
|
41
|
-
return def.outcome?.name ?? stageName;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Resolve a stage's effective skill — the contract-registry key. Twin of
|
|
46
|
-
* `resolvePublishName`. Single source of truth so the runtime resolution
|
|
47
|
-
* (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
|
|
48
|
-
* registry identically and can't drift.
|
|
49
|
-
*/
|
|
50
|
-
export function resolveSkill(def: StageDef, stageName: string): string {
|
|
51
|
-
return def.skill ?? stageName;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* A stage dispatches a `/skill:<name>` exactly when it carries neither a `run`
|
|
56
|
-
* (script body) nor a `prompt` (raw-text body). `fanout`/`iterate` stages carry
|
|
57
|
-
* neither, so they ARE dispatching stages. The shared predicate for every site
|
|
58
|
-
* that treats `resolveSkill`'s result as a REAL skill identity — the alias
|
|
59
|
-
* remap + its no-op warning, contract harvest, and the validator's contract
|
|
60
|
-
* lookups must all agree, or a script/prompt stage whose record key matches a
|
|
61
|
-
* registered skill inherits that skill's contract by accident.
|
|
62
|
-
*
|
|
63
|
-
* A TYPE GUARD since the StageDef union (T1): a positive narrows to
|
|
64
|
-
* `SkillStage`, so callers that wire skill-derived data onto the stage
|
|
65
|
-
* (the alias remap, outcome derivers) get the writable arm.
|
|
66
|
-
*/
|
|
67
|
-
export function isDispatchingStage(stage: StageDef): stage is SkillStage {
|
|
68
|
-
return stage.run == null && stage.prompt == null;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
38
|
/**
|
|
72
39
|
* Resolve a stage's `prompt` dispatch text — the COMPLETE user message a
|
|
73
40
|
* prompt stage sends (no `/skill:` prefix, no implicit arg). The dynamic form
|
|
@@ -84,23 +51,18 @@ export async function resolveStagePrompt(prompt: string | PromptFn, cwd: string,
|
|
|
84
51
|
return prompt({ cwd, input: state.output, state });
|
|
85
52
|
}
|
|
86
53
|
|
|
54
|
+
const isPromptStage = (def: StageDef): boolean => def.prompt !== undefined;
|
|
55
|
+
|
|
56
|
+
const usesOriginalInput = (def: StageDef, stageName: string, startStage: string): boolean =>
|
|
57
|
+
stageName === startStage || def.inheritsArtifacts === false;
|
|
58
|
+
|
|
59
|
+
const hasReads = (def: StageDef): def is StageDef & { reads: NonNullable<StageDef["reads"]> } =>
|
|
60
|
+
def.reads !== undefined && def.reads.length > 0;
|
|
61
|
+
|
|
87
62
|
/**
|
|
88
63
|
* The single arg-projection authority: the string a stage's
|
|
89
64
|
* `/skill:<name> <args>` prompt carries, derived purely from
|
|
90
|
-
* (def, stageName, startStage, state).
|
|
91
|
-
* 0. A prompt-dispatch stage (`def.prompt` set) owns its WHOLE message —
|
|
92
|
-
* no skill args exist; returns `""` (never `undefined`: the missing-input
|
|
93
|
-
* refusal arms below must not fire for a stage that doesn't consume the
|
|
94
|
-
* rolling primary or named reads). The round-0 producer message of a
|
|
95
|
-
* prompt-dispatch loop is `resolveStagePrompt`, not this projection.
|
|
96
|
-
* 1. The start stage receives `originalInput` (the user's brief).
|
|
97
|
-
* 2. A stage opting out of inheritance (`inheritsArtifacts: false`,
|
|
98
|
-
* i.e. authored via `terminal()`) also receives `originalInput`.
|
|
99
|
-
* 3. A stage with `reads: [...]` receives the labelled multi-flag form
|
|
100
|
-
* `--<name1> <handle1> --<name2> <handle2> …` — each name resolves
|
|
101
|
-
* against `state.named[name].at(-1)`; a multi-artifact entry repeats
|
|
102
|
-
* the flag.
|
|
103
|
-
* 4. Otherwise: the rolling primary artifact's handle string.
|
|
65
|
+
* (def, stageName, startStage, state).
|
|
104
66
|
*
|
|
105
67
|
* Returns `undefined` (instead of non-null-asserting) when a required
|
|
106
68
|
* projection input is missing — the rolling primary is unset, or a `reads`
|
|
@@ -117,16 +79,34 @@ export function stageEntryArgs(
|
|
|
117
79
|
startStage: string,
|
|
118
80
|
state: RunState,
|
|
119
81
|
): string | undefined {
|
|
120
|
-
if (def
|
|
121
|
-
if (stageName
|
|
122
|
-
if (def
|
|
123
|
-
if (def.reads?.length) {
|
|
82
|
+
if (isPromptStage(def)) return "";
|
|
83
|
+
if (usesOriginalInput(def, stageName, startStage)) return state.originalInput;
|
|
84
|
+
if (hasReads(def)) {
|
|
124
85
|
const parts: string[] = [];
|
|
125
|
-
for (const
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
86
|
+
for (const read of def.reads) {
|
|
87
|
+
const name = readName(read);
|
|
88
|
+
const slot = state.named[name];
|
|
89
|
+
if (!slot?.length) return undefined;
|
|
90
|
+
// `all` → every accumulated entry (fan-in); bare string → latest-wins.
|
|
91
|
+
// A produces-fanout channel is PRE-SIZED (length === total) and
|
|
92
|
+
// positionally filled, so a slot can carry `undefined` (pending) or a
|
|
93
|
+
// failed sentinel. The latest-wins branch must NOT `slot[length-1]!`
|
|
94
|
+
// blindly: scan backward for the last REAL entry, and the per-entry loop
|
|
95
|
+
// skips unfilled/failed slots so a `fanin(...)` read contributes no args
|
|
96
|
+
// for them (the `.filter(Boolean)` convention needs no widening).
|
|
97
|
+
//
|
|
98
|
+
// ALL-FAILED FANIN CONTRACT: pre-sizing means the channel is
|
|
99
|
+
// always present once the fold ran, so the `!slot?.length` bail no longer
|
|
100
|
+
// fires for a fanout channel; when EVERY unit failed/unfilled this read
|
|
101
|
+
// contributes ZERO `--name` args and `stageEntryArgs` returns the
|
|
102
|
+
// assembled (possibly empty) string — NEVER `undefined`. Collect-all
|
|
103
|
+
// fanout runs synthesis even when all units failed.
|
|
104
|
+
const entries = readsAll(read) ? slot : [lastReal(slot)];
|
|
105
|
+
for (const entry of entries) {
|
|
106
|
+
if (!entry || isFailedOutput(entry)) continue; // unfilled (pending) or failed → no args
|
|
107
|
+
for (const artifact of entry.artifacts) {
|
|
108
|
+
parts.push(`--${name}`, handleToString(artifact.handle));
|
|
109
|
+
}
|
|
130
110
|
}
|
|
131
111
|
}
|
|
132
112
|
return parts.join(" ");
|
|
@@ -135,6 +115,18 @@ export function stageEntryArgs(
|
|
|
135
115
|
return primary === undefined ? undefined : handleToString(primary.handle);
|
|
136
116
|
}
|
|
137
117
|
|
|
118
|
+
/** The last REAL (filled, non-failed) entry of a channel slot — the latest-wins
|
|
119
|
+
* source. A produces-fanout channel is pre-sized + positionally filled, so its
|
|
120
|
+
* tail can be `undefined` (pending) or a failed sentinel; scan backward instead
|
|
121
|
+
* of asserting `slot[length-1]`. Returns `undefined` for an all-failed/empty slot. */
|
|
122
|
+
function lastReal(slot: readonly (Output | undefined)[]): Output | undefined {
|
|
123
|
+
for (let i = slot.length - 1; i >= 0; i--) {
|
|
124
|
+
const o = slot[i];
|
|
125
|
+
if (o && !isFailedOutput(o)) return o;
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
|
|
138
130
|
/**
|
|
139
131
|
* The single authority for "a completed produces stage mutates the rolling
|
|
140
132
|
* artifact state." Called by the live skill path (sessions/sessions.ts), the
|
|
@@ -151,6 +143,21 @@ export function stageEntryArgs(
|
|
|
151
143
|
* - other side-effect → leave the slot untouched.
|
|
152
144
|
*/
|
|
153
145
|
export function applyCompletedStage(state: RunState, def: StageDef, stageName: string, output: Output): void {
|
|
146
|
+
// Fanout owns its channel through the index-addressed `placeFanoutOutput`
|
|
147
|
+
// fold (foldFanoutCompletion), so the produces-channel push here would
|
|
148
|
+
// double-write. Early-return for fanout. But the acts/side-effect
|
|
149
|
+
// PRIMARY-CLEAR (`inheritsArtifacts === false`) is IDEMPOTENT (it only sets
|
|
150
|
+
// primary = undefined), so run it here for fanout TOO: the SEQUENTIAL path (a
|
|
151
|
+
// resumed/non-pristine acts-fanout that routes through `step` → `dispatchUnit`
|
|
152
|
+
// → `recordStageSuccess` → here, not through foldFanoutCompletion until parallel
|
|
153
|
+
// resume is wired) would otherwise lose the primary-clear the only
|
|
154
|
+
// shipped fanout kind (acts) relies on. Live acts-fanout calls BOTH this and
|
|
155
|
+
// placeFanoutOutput — both set primary = undefined, harmless. Produces-fanout's
|
|
156
|
+
// channel push stays fold-only (non-idempotent → must not double-write).
|
|
157
|
+
if (def.loop?.kind === "fanout") {
|
|
158
|
+
clearPrimaryForActs(state, def);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
154
161
|
if (def.kind === "produces") {
|
|
155
162
|
const next = output.artifacts[0];
|
|
156
163
|
if (next) state.primaryArtifact = next;
|
|
@@ -163,7 +170,51 @@ export function applyCompletedStage(state: RunState, def: StageDef, stageName: s
|
|
|
163
170
|
slot.push(output);
|
|
164
171
|
return;
|
|
165
172
|
}
|
|
166
|
-
|
|
167
|
-
|
|
173
|
+
clearPrimaryForActs(state, def);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The acts/side-effect primary-clear rule, in ONE place: a `terminal()` stage
|
|
178
|
+
* (`inheritsArtifacts === false`) drops the rolling primary; every other
|
|
179
|
+
* side-effect leaves it. Idempotent and produces-safe (the `kind` guard makes it
|
|
180
|
+
* a no-op for produces stages, whose channel arm owns the primary). Shared by
|
|
181
|
+
* `applyCompletedStage` (the fanout early-return AND the sequential acts arm) and
|
|
182
|
+
* `placeFanoutOutput`, so the rule can't drift across the three sites.
|
|
183
|
+
*/
|
|
184
|
+
function clearPrimaryForActs(state: RunState, def: StageDef): void {
|
|
185
|
+
if (def.kind !== "produces" && def.inheritsArtifacts === false) state.primaryArtifact = undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// The fanout fold's SINGLE state-effect site. It subsumes BOTH
|
|
189
|
+
// arms of applyCompletedStage (which early-returns for fanout),
|
|
190
|
+
// index-addressed:
|
|
191
|
+
// • produces-fanout (collecting): pre-size the channel slot to `total`, assign
|
|
192
|
+
// the unit's output at its declared `index`; set primaryArtifact from
|
|
193
|
+
// artifacts[0] unless this is a failed sentinel (no artifacts).
|
|
194
|
+
// • acts-fanout (side-effect, def.kind !== "produces"): no channel; mirror the
|
|
195
|
+
// applyCompletedStage `inheritsArtifacts === false ⇒ clear primary` rule so
|
|
196
|
+
// today's acts-fanout semantics are preserved.
|
|
197
|
+
// Called ONLY by foldFanoutCompletion (live + resume).
|
|
198
|
+
export function placeFanoutOutput(
|
|
199
|
+
state: RunState,
|
|
200
|
+
def: StageDef,
|
|
201
|
+
stageName: string,
|
|
202
|
+
index: number,
|
|
203
|
+
total: number,
|
|
204
|
+
output: Output,
|
|
205
|
+
): void {
|
|
206
|
+
if (def.kind === "produces") {
|
|
207
|
+
const key = resolvePublishName(def, stageName);
|
|
208
|
+
let slot = state.named[key];
|
|
209
|
+
if (!slot || slot.length !== total) {
|
|
210
|
+
slot = new Array<Output | undefined>(total) as Output[];
|
|
211
|
+
state.named[key] = slot;
|
|
212
|
+
}
|
|
213
|
+
slot[index] = output;
|
|
214
|
+
const next = output.artifacts[0];
|
|
215
|
+
if (next && !isFailedOutput(output)) state.primaryArtifact = next;
|
|
216
|
+
return;
|
|
168
217
|
}
|
|
218
|
+
// acts/side-effect fanout — same primary-clear rule as the sequential path.
|
|
219
|
+
clearPrimaryForActs(state, def);
|
|
169
220
|
}
|
package/command-run.ts
CHANGED
|
@@ -111,24 +111,27 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
|
|
|
111
111
|
return;
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
-
//
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
114
|
+
// Float the run off the prompt: /wf returns immediately; the run executes
|
|
115
|
+
// detached and appears as a lane. runWorkflow returns an envelope (never throws on
|
|
116
|
+
// run failure), but a thrown predicate/invariant could still bubble — .catch keeps
|
|
117
|
+
// Pi's dispatcher from printing a raw stack AND a floated promise from going
|
|
118
|
+
// unhandled (NFR).
|
|
119
|
+
void runWorkflow(ctx, {
|
|
120
|
+
workflow,
|
|
121
|
+
input,
|
|
122
|
+
host,
|
|
123
|
+
trigger: { kind: "command", name: "wf" },
|
|
124
|
+
name,
|
|
125
|
+
})
|
|
126
|
+
.then((result) => {
|
|
127
|
+
// Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
|
|
128
|
+
if (!result.success && result.runId === undefined && result.error) {
|
|
129
|
+
ctx.ui.notify(result.error, "error");
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
.catch((e) => {
|
|
133
|
+
ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
|
|
124
134
|
});
|
|
125
|
-
// Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
|
|
126
|
-
if (!result.success && result.runId === undefined && result.error) {
|
|
127
|
-
ctx.ui.notify(result.error, "error");
|
|
128
|
-
}
|
|
129
|
-
} catch (e) {
|
|
130
|
-
ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
|
|
131
|
-
}
|
|
132
135
|
}
|
|
133
136
|
|
|
134
137
|
// ---------------------------------------------------------------------------
|
|
@@ -140,19 +143,21 @@ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: s
|
|
|
140
143
|
ctx.ui.notify(MSG_RESUME_USAGE, "error");
|
|
141
144
|
return;
|
|
142
145
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
146
|
+
// Float the resume off the prompt — identical shape to the run path.
|
|
147
|
+
void resumeWorkflowByRunId(ctx, ref, { host })
|
|
148
|
+
.then((result) => {
|
|
149
|
+
// A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
|
|
150
|
+
// load error, workflow gone, or an unreconstructable trail) — nothing else
|
|
151
|
+
// surfaces it, so notify here. An in-run failure carries a runId and was
|
|
152
|
+
// already notified by the stage machinery via its JSONL failure row;
|
|
153
|
+
// re-notifying would double up.
|
|
154
|
+
if (!result.success && result.runId === undefined && result.error) {
|
|
155
|
+
ctx.ui.notify(result.error, "error");
|
|
156
|
+
}
|
|
157
|
+
})
|
|
158
|
+
.catch((e) => {
|
|
159
|
+
ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
|
|
160
|
+
});
|
|
156
161
|
}
|
|
157
162
|
|
|
158
163
|
// ---------------------------------------------------------------------------
|
package/command.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* `parseArgs` stays here (pure, exported for tests).
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import type { WorkflowHost, WorkflowHostContext } from "./host.js";
|
|
17
|
+
import type { WorkflowHost, WorkflowHostContext, WorkflowLauncherContext } from "./host.js";
|
|
18
18
|
|
|
19
19
|
/** Pi command registry — displayed by Pi's `/?` / command list. */
|
|
20
20
|
export const CMD_DESCRIPTION = "Run a skill workflow: /wf [workflow] [description]";
|
|
@@ -39,7 +39,7 @@ export const PREWARM_DELAY_MS = 2000;
|
|
|
39
39
|
type CommandRunModule = typeof import("./command-run.js");
|
|
40
40
|
|
|
41
41
|
export interface WfCommandHandler {
|
|
42
|
-
(args: string, ctx:
|
|
42
|
+
(args: string, ctx: WorkflowLauncherContext): Promise<void>;
|
|
43
43
|
/** Kick (or join) the memoized command-run import — the pre-warm entry. */
|
|
44
44
|
prewarm(): Promise<void>;
|
|
45
45
|
}
|
|
@@ -71,12 +71,18 @@ export function makeWfHandler(
|
|
|
71
71
|
}
|
|
72
72
|
};
|
|
73
73
|
|
|
74
|
-
const handler = async (args: string, ctx:
|
|
74
|
+
const handler = async (args: string, ctx: WorkflowLauncherContext): Promise<void> => {
|
|
75
75
|
// `ready`, not `memo`: an in-flight pre-warm still leaves the user
|
|
76
76
|
// waiting, so the toast covers that window too.
|
|
77
77
|
if (!ready && ctx.hasUI) ctx.ui.notify(MSG_RUNTIME_LOADING, "info");
|
|
78
78
|
const mod = await load();
|
|
79
|
-
|
|
79
|
+
// The launcher hands us an OBSERVER ctx (Pi's command ctx has no
|
|
80
|
+
// spawnChild/maxConcurrency). The run-path is typed against the executor
|
|
81
|
+
// ctx, but it never executes a stage on this ctx directly: with a provider
|
|
82
|
+
// registered, runWorkflow builds the detached executor; with
|
|
83
|
+
// none, the test/embedder contract guarantees an executor-capable ctx. So
|
|
84
|
+
// narrow here at the single Pi→runtime boundary.
|
|
85
|
+
return mod.handleWorkflowCommand(host, args, ctx as WorkflowHostContext);
|
|
80
86
|
};
|
|
81
87
|
|
|
82
88
|
return Object.assign(handler, {
|
|
@@ -858,6 +858,38 @@ When `reads:` is set the runner replaces the default prompt with a labelled-flag
|
|
|
858
858
|
|
|
859
859
|
Multi-artifact stages get flag repetition: an upstream with two `fs` artifacts expands to `--plans <a> --plans <b>` so skill arg-parsers collect repeated flags into arrays the same way `argparse`/`clap`/shell utilities do.
|
|
860
860
|
|
|
861
|
+
### Fan-in: reading every entry (`fanin` — fanout-and-synthesize)
|
|
862
|
+
|
|
863
|
+
A bare-string read resolves to the channel's **latest** entry (`array.at(-1)`). That is the wrong default for the fan-in half of *fanout-and-synthesize*: a `fanout` produces N per-unit `Output`s on one channel, and the synthesize stage's whole job is to **merge all N into one**. Latest-wins would hand it only the last unit.
|
|
864
|
+
|
|
865
|
+
Wrap a name in `fanin(name)` to read **every accumulated entry** of the channel, in run order:
|
|
866
|
+
|
|
867
|
+
```typescript
|
|
868
|
+
import { acts, fanin, fanout, produces } from "@juicesharp/rpiv-workflow";
|
|
869
|
+
|
|
870
|
+
// fan-out: one collecting unit per plan phase → each appends to state.named["drafts"]
|
|
871
|
+
draft: produces({
|
|
872
|
+
outcome: draftOutcome, // outcome.name === "drafts"
|
|
873
|
+
loop: fanout({ source: "plans", unit: { by: "frontmatter-array", pattern: "phases" } }),
|
|
874
|
+
}),
|
|
875
|
+
|
|
876
|
+
// fan-in (the barrier): read ALL drafts, synthesize one result
|
|
877
|
+
synthesize: produces({
|
|
878
|
+
outcome: summaryOutcome,
|
|
879
|
+
reads: [fanin("drafts")], // every unit's artifacts, not just the last
|
|
880
|
+
}),
|
|
881
|
+
```
|
|
882
|
+
|
|
883
|
+
The synthesize prompt flag-repeats across the whole channel (× each entry's artifacts):
|
|
884
|
+
|
|
885
|
+
```
|
|
886
|
+
/skill:synthesize --drafts <unit1> --drafts <unit2> --drafts <unit3> …
|
|
887
|
+
```
|
|
888
|
+
|
|
889
|
+
`fanin()` is the consumer-side mirror of `fanout()` — fan-out on the producer, fan-in on the consumer. It composes with non-fanout channels too (e.g. reading every `iterate` accumulation), and one `reads:` list may mix forms: `reads: [fanin("drafts"), "spec"]` reads all drafts but only the latest spec. The `reads:` element type is `string | { name; all? }`; `fanin(name)` builds `{ name, all: true }`.
|
|
890
|
+
|
|
891
|
+
A lint backs the idiom: a **bare-string** read of a channel that a `fanout` fills emits the `reads-latest-from-fanout` warning ("wrap it in `fanin(...)`"). It only warns — latest-only is legal — and `fanin()` reads are already opted in, so they're never flagged. `/wf` preview marks a fan-in consumer with `⇉ <names>`, mirroring the `panel(N, fold)` fan-in surfacing.
|
|
892
|
+
|
|
861
893
|
### The named-publish registry — `state.named`
|
|
862
894
|
|
|
863
895
|
Every `produces` stage APPENDS its full `Output` envelope onto `state.named[key]` after each successful run. The key is computed once at write time:
|
|
@@ -871,7 +903,7 @@ Two layers, no override knob:
|
|
|
871
903
|
- **Outcome carries a name.** Multiple stages wiring the same outcome converge — both stages append onto the same slot, latest-wins on read. This is how a workflow expresses "two stages both produce the canonical plan" without restating the name on each stage.
|
|
872
904
|
- **Outcome has no name.** Stages publish under their record key. Downstream `reads: ["blueprint", "code-review"]` references stage record keys directly.
|
|
873
905
|
|
|
874
|
-
Slots are **arrays** — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)
|
|
906
|
+
Slots are **arrays** — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)` (latest-wins), while a `fanin(name)` read consumes the whole slot (see [Fan-in](#fan-in-reading-every-entry-fanin--fanout-and-synthesize)). Side-effect stages don't write to the registry. The slot is never cleared by `terminal()` either: it's an additive channel orthogonal to the rolling primary.
|
|
875
907
|
|
|
876
908
|
### Validation + preflight
|
|
877
909
|
|
|
@@ -892,7 +924,7 @@ A fresh-session stage starts a clean Pi conversation. It only sees (1) the rolli
|
|
|
892
924
|
| 2 | `workspaceDiffCollector` outcome on the upstream stage | Every file the stage touched, as `fs` artifacts | Free when the work IS files on disk. Captures *what*, not *why*. |
|
|
893
925
|
| 3 | `transcriptPathCollector` outcome on the upstream stage | The last regex-matched chunk of assistant text, written to disk | Captures narrative knowledge. Needs the skill to emit a recognizable marker. |
|
|
894
926
|
| 4 | Custom collector / parser (+ optional `outputSchema`) | Author-defined typed shape | Most precise; most authoring effort. Enables gate routing. |
|
|
895
|
-
| 5 | `reads:` on the downstream stage referencing named-publish slots | Latest `Output` per declared name, woven into a labelled-flag prompt | Reaches further back than the rolling primary; survives intermediate produces stages overwriting the chain. See [Multi-input stages](#multi-input-stages). |
|
|
927
|
+
| 5 | `reads:` on the downstream stage referencing named-publish slots | Latest `Output` per declared name (or **all** entries via `fanin(name)`), woven into a labelled-flag prompt | Reaches further back than the rolling primary; survives intermediate produces stages overwriting the chain. `fanin()` is the fanout-and-synthesize barrier. See [Multi-input stages](#multi-input-stages). |
|
|
896
928
|
|
|
897
929
|
**Picking between them — where does the knowledge live after the stage finishes?**
|
|
898
930
|
|
package/events.ts
CHANGED
|
@@ -47,6 +47,21 @@ export interface LifecycleContext {
|
|
|
47
47
|
/** What triggered this run; defaulted at `runWorkflow` entry if `options.trigger` was omitted. */
|
|
48
48
|
trigger: RunTrigger;
|
|
49
49
|
state: RunView;
|
|
50
|
+
/**
|
|
51
|
+
* Distinct stage names already executed in this run — the engine's
|
|
52
|
+
* authoritative `RunContext.visited`, RECONSTRUCTED from the JSONL trail on a
|
|
53
|
+
* resume. Populated only on the run-level projection (`lifecycleCtxFor`, which
|
|
54
|
+
* backs `onWorkflowStart`/`onWorkflowEnd`, script-stage `onStageStart`, and the
|
|
55
|
+
* loop/route fires); UNDEFINED on session-fired events (`lifecycleCtxFromSession`
|
|
56
|
+
* carries `runIdentity` only, never the live visited set).
|
|
57
|
+
*
|
|
58
|
+
* Exists so a status-line bridge can SEED its own distinct-visited accumulator
|
|
59
|
+
* at `onWorkflowStart`: a resumed run kicks the chain at its reconstructed walk
|
|
60
|
+
* position (a deep `stageNumber`), but only re-fires per-stage events from that
|
|
61
|
+
* point forward — without this, the bridge would recount `visited` from zero and
|
|
62
|
+
* a near-done resume would render a misleadingly tiny `visited/totalStages`.
|
|
63
|
+
*/
|
|
64
|
+
visited?: readonly string[];
|
|
50
65
|
}
|
|
51
66
|
|
|
52
67
|
/**
|
|
@@ -133,6 +148,7 @@ export interface LoopCapInfo {
|
|
|
133
148
|
* onLoopStart: (stage, info) => console.log(` ⇉ ${stage.name} [${info.kind}]`),
|
|
134
149
|
* onUnitStart: (stage, u) => console.log(` → ${u.label} (${u.role})`),
|
|
135
150
|
* onUnitEnd: (stage, u) => console.log(` · ${stage.name} #${u.index}`),
|
|
151
|
+
* onUnitHalt: (stage, u, reason) => console.warn(` ✗ ${stage.name} #${u.index}: ${reason}`),
|
|
136
152
|
* onLoopCap: (stage, c) => console.warn(` ⚠ ${stage.name} capped at ${c.max}`),
|
|
137
153
|
* onWorkflowEnd: (result) =>
|
|
138
154
|
* console.log(result.success ? "✓ done" : `✗ ${result.error ?? "halted"}`),
|
|
@@ -167,8 +183,15 @@ export interface LifecycleListeners {
|
|
|
167
183
|
/** After the stage's "failed"/"aborted" row lands in JSONL. Terminal for the run. */
|
|
168
184
|
onStageError?(stage: StageRef, error: string, ctx: LifecycleContext): void | Promise<void>;
|
|
169
185
|
|
|
170
|
-
/**
|
|
171
|
-
|
|
186
|
+
/**
|
|
187
|
+
* After an `EdgeFn` picks and its routing-decision row lands. `to` may be the
|
|
188
|
+
* `STOP` sentinel literal `"stop"`. `bypassed` lists the decision edge's
|
|
189
|
+
* not-taken RECOVERY arms — failure loops the chosen arm skipped for good (see
|
|
190
|
+
* `bypassedRecoveryArms` in routing.ts). A progress listener credits them so
|
|
191
|
+
* the bar reaches full while the terminal stage runs; empty for deterministic
|
|
192
|
+
* (string) edges and gates with no loop-back alternative.
|
|
193
|
+
*/
|
|
194
|
+
onRoute?(from: StageRef, to: string, ctx: LifecycleContext, bypassed?: readonly string[]): void | Promise<void>;
|
|
172
195
|
|
|
173
196
|
/** After `onStageStart`, before unit 1's session (after the unit list is computed for fanout). */
|
|
174
197
|
onLoopStart?(stage: StageRef, info: LoopStartInfo, ctx: LifecycleContext): void | Promise<void>;
|
|
@@ -184,6 +207,18 @@ export interface LifecycleListeners {
|
|
|
184
207
|
/** Per unit, after the unit's JSONL row lands. Loop units never fire `onStageEnd`. */
|
|
185
208
|
onUnitEnd?(stage: StageRef, unit: UnitEvent, output: Output, ctx: LifecycleContext): void | Promise<void>;
|
|
186
209
|
|
|
210
|
+
/**
|
|
211
|
+
* Per unit, after a collect-all fanout unit's NON-TERMINAL `collected:true`
|
|
212
|
+
* failed row lands — the unit halted but the run survives (the synthesis fold
|
|
213
|
+
* skips its sentinel slot). Fired ONLY on the soft-halt path; a fail-fast unit
|
|
214
|
+
* fires `onStageError` (terminal) instead, and a successful unit fires
|
|
215
|
+
* `onUnitEnd`. Distinct from both so a lane surface can flip the unit's sub-row
|
|
216
|
+
* ✗ rather than leaving it to spin (then be swept ✓ at `onWorkflowEnd`).
|
|
217
|
+
* `reason` is the halt cause — the same text the `collected:true` row's
|
|
218
|
+
* `errMsg` carries.
|
|
219
|
+
*/
|
|
220
|
+
onUnitHalt?(stage: StageRef, unit: UnitEvent, reason: string, ctx: LifecycleContext): void | Promise<void>;
|
|
221
|
+
|
|
187
222
|
/** After an `onCap: "advance"` trip — fired after the `{type:"loop-cap"}` telemetry row append attempt. */
|
|
188
223
|
onLoopCap?(stage: StageRef, info: LoopCapInfo, ctx: LifecycleContext): void | Promise<void>;
|
|
189
224
|
|
|
@@ -295,6 +330,7 @@ export function buildLifecycleContext(args: {
|
|
|
295
330
|
totalStages: number;
|
|
296
331
|
trigger: RunTrigger;
|
|
297
332
|
state: RunView;
|
|
333
|
+
visited?: readonly string[];
|
|
298
334
|
}): LifecycleContext {
|
|
299
335
|
return args;
|
|
300
336
|
}
|
|
@@ -304,8 +340,8 @@ export function buildLifecycleContext(args: {
|
|
|
304
340
|
* structurally so this base-layer module never imports the runtime types).
|
|
305
341
|
* Captured per fire so listeners always see the latest `state` snapshot.
|
|
306
342
|
* THE one RunContext → LifecycleContext projection — the runner, the loop
|
|
307
|
-
* driver, and the resume entries all share it
|
|
308
|
-
*
|
|
343
|
+
* driver, and the resume entries all share it; no per-module clones to keep
|
|
344
|
+
* aligned by convention.
|
|
309
345
|
*/
|
|
310
346
|
export function lifecycleCtxFor(run: {
|
|
311
347
|
cwd: string;
|
|
@@ -314,6 +350,7 @@ export function lifecycleCtxFor(run: {
|
|
|
314
350
|
totalStages: number;
|
|
315
351
|
trigger: RunTrigger;
|
|
316
352
|
state: RunView;
|
|
353
|
+
visited: ReadonlySet<string>;
|
|
317
354
|
}): LifecycleContext {
|
|
318
355
|
return buildLifecycleContext({
|
|
319
356
|
cwd: run.cwd,
|
|
@@ -322,6 +359,9 @@ export function lifecycleCtxFor(run: {
|
|
|
322
359
|
totalStages: run.totalStages,
|
|
323
360
|
trigger: run.trigger,
|
|
324
361
|
state: run.state,
|
|
362
|
+
// Snapshot the live set — listeners must not mutate the engine's accumulator,
|
|
363
|
+
// and a fired ctx is captured per fire so a later `visited.add` is irrelevant.
|
|
364
|
+
visited: [...run.visited],
|
|
325
365
|
});
|
|
326
366
|
}
|
|
327
367
|
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Execution-host injection seam. The /wf launcher + runner are Pi-agnostic; the
|
|
3
|
+
* SDK-backed executor (`SdkWorkflowHost`) lives in rpiv-pi. rpiv-pi registers a
|
|
4
|
+
* provider at startup; `runWorkflow` looks it up, builds the executor from the
|
|
5
|
+
* live observer ctx, and threads it for stage execution (the executor relays UI
|
|
6
|
+
* back to the live session). Absent provider ⇒ the live ctx executes directly
|
|
7
|
+
* (graceful degrade for non-Pi embedders / tests).
|
|
8
|
+
*/
|
|
9
|
+
import type { ModelSelection, WorkflowHostContext } from "./host.js";
|
|
10
|
+
import { globalSlot } from "./internal-utils.js";
|
|
11
|
+
|
|
12
|
+
/** What the provider hands back per run: the detached executor, an optional
|
|
13
|
+
* cancellation `signal` (rpiv-pi wires it from `ctx.ui.onTerminalInput`),
|
|
14
|
+
* and a `dispose` the runner calls in `finally` to unsubscribe the keystroke
|
|
15
|
+
* tap. `signal`/`dispose` are absent in headless mode (no UI ⇒ no abort). */
|
|
16
|
+
export interface WorkflowExecution {
|
|
17
|
+
host: WorkflowHostContext;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
dispose?: () => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface WorkflowExecutionProvider {
|
|
23
|
+
/** Build the detached executor host (+ abort signal/teardown) from the live
|
|
24
|
+
* observer ctx + run identity. `childSessionsDir` is the RESOLVED run-scoped
|
|
25
|
+
* session dir — the runner computes it from its internal layout helper so
|
|
26
|
+
* rpiv-pi never imports a layout function across the package boundary. */
|
|
27
|
+
createHost(
|
|
28
|
+
observer: WorkflowHostContext,
|
|
29
|
+
opts: {
|
|
30
|
+
runId: string;
|
|
31
|
+
childSessionsDir: string;
|
|
32
|
+
name?: string;
|
|
33
|
+
/** Workflow name — lets the lane dock render a `workflow:` tag. Threaded
|
|
34
|
+
* from workflow.name (run path) / header.workflow (resume path). */
|
|
35
|
+
workflow?: string;
|
|
36
|
+
/** The run's original `/wf` input (the user prompt) — the dock renders it as the
|
|
37
|
+
* descriptor label when no `--name` alias is set. Threaded from options.input /
|
|
38
|
+
* header.input. */
|
|
39
|
+
input?: string;
|
|
40
|
+
},
|
|
41
|
+
): WorkflowExecution | Promise<WorkflowExecution>;
|
|
42
|
+
/** Per-stage model resolution (rpiv-pi's resolveStageModel) — threaded onto
|
|
43
|
+
* RunContext.resolveModel so the dispatcher fills each child's ModelSelection. */
|
|
44
|
+
resolveModel?(id: { stage: string; skill: string }): ModelSelection | undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Use the SAME globalThis[Symbol.for(...)] slot mechanism as
|
|
48
|
+
// `registerLifecycle`/the built-in registry (internal-utils.globalSlot), NOT a
|
|
49
|
+
// plain module-level `let`. rpiv-pi reaches this seam via a dynamic
|
|
50
|
+
// `import("@juicesharp/rpiv-workflow/startup")` while the runner reaches it via a
|
|
51
|
+
// static `../execution-host.js`; if those ever resolve to two module instances
|
|
52
|
+
// of rpiv-workflow (peer-dependency duplication), a module-local `let` would put
|
|
53
|
+
// `register` and `get` on DIFFERENT slots and the lookup would silently return
|
|
54
|
+
// `undefined` (degrade-to-live — a quiet correctness bug, not a crash). A
|
|
55
|
+
// process-global Symbol slot is instance-independent and matches the precedent
|
|
56
|
+
// this seam claims to mirror.
|
|
57
|
+
//
|
|
58
|
+
// globalSlot signature: `globalSlot<T>(key: symbol, init: () => T): () => T` — a
|
|
59
|
+
// lazily-initialised getter. Because the provider must be resettable to
|
|
60
|
+
// `undefined` (and globalSlot never re-runs init once seeded), anchor a MUTABLE
|
|
61
|
+
// BOX, exactly like the lifecycle flush-box pattern (internal-utils.ts).
|
|
62
|
+
const getProviderBox = globalSlot(Symbol.for("@juicesharp/rpiv-workflow:executionHostProvider"), () => ({
|
|
63
|
+
provider: undefined as WorkflowExecutionProvider | undefined,
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
export function registerWorkflowExecutionHost(p: WorkflowExecutionProvider): void {
|
|
67
|
+
getProviderBox().provider = p;
|
|
68
|
+
}
|
|
69
|
+
export function getWorkflowExecutionProvider(): WorkflowExecutionProvider | undefined {
|
|
70
|
+
return getProviderBox().provider;
|
|
71
|
+
}
|
|
72
|
+
/** Test reset — re-exported from `internal.ts` and called in `test/setup.ts` beforeEach. */
|
|
73
|
+
export function __resetWorkflowExecutionHost(): void {
|
|
74
|
+
getProviderBox().provider = undefined;
|
|
75
|
+
}
|