@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
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* disposer; multiple registrations fan out per event.
|
|
12
12
|
*
|
|
13
13
|
* Every event fires AFTER the corresponding JSONL row lands on disk
|
|
14
|
-
* (onStageEnd / onStageError / onRoute /
|
|
14
|
+
* (onStageEnd / onStageError / onRoute / onUnitEnd). Listeners
|
|
15
15
|
* thus see consistent state when they read past rows via
|
|
16
16
|
* `readLastStage` / `readAllStages`.
|
|
17
17
|
*
|
|
@@ -26,17 +26,17 @@
|
|
|
26
26
|
* caller through the existing path.
|
|
27
27
|
*/
|
|
28
28
|
|
|
29
|
-
import type {
|
|
29
|
+
import type { CapPolicy, Unit, UnitRole } from "./api.js";
|
|
30
|
+
import { formatError, globalSlot } from "./internal-utils.js";
|
|
30
31
|
import { MSG_LIFECYCLE_THREW } from "./messages.js";
|
|
31
|
-
import type { Output } from "./output.js";
|
|
32
|
-
import type { RunWorkflowResult } from "./runner/runner.js";
|
|
32
|
+
import type { Output, RunView } from "./output.js";
|
|
33
33
|
import type { RunTrigger } from "./triggers.js";
|
|
34
|
-
import type {
|
|
34
|
+
import type { RunWorkflowResult } from "./types.js";
|
|
35
35
|
|
|
36
36
|
/**
|
|
37
37
|
* Run-scoped context shared by every lifecycle callback. Mirrors the
|
|
38
38
|
* shape `EdgeContext` and `FanoutContext` already use (frozen identity
|
|
39
|
-
* + `
|
|
39
|
+
* + the deep-readonly `RunView`) so listeners reconstruct "where am I" without
|
|
40
40
|
* widening the per-event payload.
|
|
41
41
|
*/
|
|
42
42
|
export interface LifecycleContext {
|
|
@@ -46,7 +46,7 @@ export interface LifecycleContext {
|
|
|
46
46
|
totalStages: number;
|
|
47
47
|
/** What triggered this run; defaulted at `runWorkflow` entry if `options.trigger` was omitted. */
|
|
48
48
|
trigger: RunTrigger;
|
|
49
|
-
state:
|
|
49
|
+
state: RunView;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/**
|
|
@@ -63,13 +63,55 @@ export type StageRef =
|
|
|
63
63
|
| { kind: "skill"; name: string; stageNumber: number; skill: string }
|
|
64
64
|
| { kind: "script"; name: string; stageNumber: number };
|
|
65
65
|
|
|
66
|
+
/**
|
|
67
|
+
* Payload for `onLoopStart`. `units` is present only when the loop
|
|
68
|
+
* precomputes its unit list (fanout) — pull loops (iterate/assess) discover
|
|
69
|
+
* units one at a time, so listeners observe them via `onUnitStart`.
|
|
70
|
+
* `kind: "verify"` is a verify-bearing stage (a desugared attempt→verify
|
|
71
|
+
* loop) — verified stages follow loop semantics: observe units, not
|
|
72
|
+
* `onStageEnd`.
|
|
73
|
+
*/
|
|
74
|
+
export interface LoopStartInfo {
|
|
75
|
+
kind: "fanout" | "iterate" | "assess" | "verify";
|
|
76
|
+
units?: readonly Unit[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Per-unit event payload. `skill` is the unit's DISPATCHED skill body — the
|
|
81
|
+
* parent stage's skill for produce units, the judge's own skill (or the
|
|
82
|
+
* synthetic `<parent>-judge` label for prompt judges) for judge units — so a
|
|
83
|
+
* model-override listener can resolve a per-unit model through the existing
|
|
84
|
+
* `models.json` cascade (`skills.<name>`) without new configuration axes.
|
|
85
|
+
*/
|
|
86
|
+
export interface UnitEvent {
|
|
87
|
+
role: UnitRole;
|
|
88
|
+
/** 0-based generation cursor (== the round index for assess loops). */
|
|
89
|
+
index: number;
|
|
90
|
+
/** Stable audit identity (`unit.id ?? unit.label`); undefined for assess units. */
|
|
91
|
+
unitId?: string;
|
|
92
|
+
/** Display tag (`"phase 2/5"`, `"r0·judge"`). */
|
|
93
|
+
label: string;
|
|
94
|
+
/** Dispatched skill body. */
|
|
95
|
+
skill: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Payload for `onLoopCap` — fired when a loop's effective cap trips. */
|
|
99
|
+
export interface LoopCapInfo {
|
|
100
|
+
kind: LoopStartInfo["kind"];
|
|
101
|
+
/** Units run (fanout/iterate) or rounds run (assess) when the cap tripped. */
|
|
102
|
+
count: number;
|
|
103
|
+
/** The effective cap: `min(loop.max, run.maxIterations)`. */
|
|
104
|
+
max: number;
|
|
105
|
+
policy: CapPolicy;
|
|
106
|
+
}
|
|
107
|
+
|
|
66
108
|
/**
|
|
67
109
|
* Opt-in lifecycle listeners. Single subscriber per slot per bundle —
|
|
68
110
|
* fan-out is a userland wrapper. Every callback may return a Promise;
|
|
69
111
|
* the runner awaits it before advancing (back-pressure for free).
|
|
70
112
|
*
|
|
71
113
|
* Every event fires AFTER its corresponding JSONL row lands on disk
|
|
72
|
-
* (onStageEnd / onStageError / onRoute /
|
|
114
|
+
* (onStageEnd / onStageError / onRoute / onUnitEnd), so a
|
|
73
115
|
* listener that calls `readLastStage(cwd, ctx.runId)` from inside the
|
|
74
116
|
* callback is guaranteed to observe the just-recorded row.
|
|
75
117
|
*
|
|
@@ -88,8 +130,10 @@ export type StageRef =
|
|
|
88
130
|
* onStageRetry: (stage, attempt) => console.warn(` ⟲ ${stage.name} retry #${attempt}`),
|
|
89
131
|
* onStageError: (stage, error) => console.error(` ✗ ${stage.name}: ${error}`),
|
|
90
132
|
* onRoute: (from, to) => console.log(` ↪ ${from.name} → ${to}`),
|
|
91
|
-
*
|
|
92
|
-
*
|
|
133
|
+
* onLoopStart: (stage, info) => console.log(` ⇉ ${stage.name} [${info.kind}]`),
|
|
134
|
+
* onUnitStart: (stage, u) => console.log(` → ${u.label} (${u.role})`),
|
|
135
|
+
* onUnitEnd: (stage, u) => console.log(` · ${stage.name} #${u.index}`),
|
|
136
|
+
* onLoopCap: (stage, c) => console.warn(` ⚠ ${stage.name} capped at ${c.max}`),
|
|
93
137
|
* onWorkflowEnd: (result) =>
|
|
94
138
|
* console.log(result.success ? "✓ done" : `✗ ${result.error ?? "halted"}`),
|
|
95
139
|
* };
|
|
@@ -126,19 +170,22 @@ export interface LifecycleListeners {
|
|
|
126
170
|
/** After an `EdgeFn` picks and its routing-decision row lands. `to` may be the `STOP` sentinel literal `"stop"`. */
|
|
127
171
|
onRoute?(from: StageRef, to: string, ctx: LifecycleContext): void | Promise<void>;
|
|
128
172
|
|
|
129
|
-
/** After
|
|
130
|
-
|
|
173
|
+
/** After `onStageStart`, before unit 1's session (after the unit list is computed for fanout). */
|
|
174
|
+
onLoopStart?(stage: StageRef, info: LoopStartInfo, ctx: LifecycleContext): void | Promise<void>;
|
|
131
175
|
|
|
132
|
-
/**
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
): void | Promise<void>;
|
|
176
|
+
/**
|
|
177
|
+
* Per unit, BEFORE the unit's session opens — fired uniformly for produce
|
|
178
|
+
* AND judge units (closing the judge pre-session gap). This is the seam a
|
|
179
|
+
* model-override listener flips `pi.setModel` on; units run strictly
|
|
180
|
+
* sequentially, so the global flip is race-free.
|
|
181
|
+
*/
|
|
182
|
+
onUnitStart?(stage: StageRef, unit: UnitEvent, ctx: LifecycleContext): void | Promise<void>;
|
|
139
183
|
|
|
140
|
-
/** Per
|
|
141
|
-
|
|
184
|
+
/** Per unit, after the unit's JSONL row lands. Loop units never fire `onStageEnd`. */
|
|
185
|
+
onUnitEnd?(stage: StageRef, unit: UnitEvent, output: Output, ctx: LifecycleContext): void | Promise<void>;
|
|
186
|
+
|
|
187
|
+
/** After an `onCap: "advance"` trip — fired after the `{type:"loop-cap"}` telemetry row append attempt. */
|
|
188
|
+
onLoopCap?(stage: StageRef, info: LoopCapInfo, ctx: LifecycleContext): void | Promise<void>;
|
|
142
189
|
|
|
143
190
|
/** Last call — `result` is the same envelope `runWorkflow` returns. */
|
|
144
191
|
onWorkflowEnd?(result: RunWorkflowResult, ctx: LifecycleContext): void | Promise<void>;
|
|
@@ -180,8 +227,7 @@ export class LifecycleDispatcher {
|
|
|
180
227
|
try {
|
|
181
228
|
await (fn as (...a: unknown[]) => unknown)(...(args as unknown[]));
|
|
182
229
|
} catch (e) {
|
|
183
|
-
|
|
184
|
-
host.ui.notify(MSG_LIFECYCLE_THREW(event, reason), "warning");
|
|
230
|
+
host.ui.notify(MSG_LIFECYCLE_THREW(event, formatError(e)), "warning");
|
|
185
231
|
}
|
|
186
232
|
}
|
|
187
233
|
}
|
|
@@ -198,17 +244,7 @@ export class LifecycleDispatcher {
|
|
|
198
244
|
*/
|
|
199
245
|
const REGISTRY_KEY = Symbol.for("@juicesharp/rpiv-workflow:lifecycle");
|
|
200
246
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
function getRegistry(): LifecycleListeners[] {
|
|
204
|
-
const g = globalThis as unknown as Global;
|
|
205
|
-
let registry = g[REGISTRY_KEY] as LifecycleListeners[] | undefined;
|
|
206
|
-
if (!registry) {
|
|
207
|
-
registry = [];
|
|
208
|
-
g[REGISTRY_KEY] = registry;
|
|
209
|
-
}
|
|
210
|
-
return registry;
|
|
211
|
-
}
|
|
247
|
+
const getRegistry = globalSlot(REGISTRY_KEY, () => [] as LifecycleListeners[]);
|
|
212
248
|
|
|
213
249
|
/**
|
|
214
250
|
* Register a cross-package lifecycle-listener bundle. Returns a disposer
|
|
@@ -258,11 +294,59 @@ export function buildLifecycleContext(args: {
|
|
|
258
294
|
workflow: string;
|
|
259
295
|
totalStages: number;
|
|
260
296
|
trigger: RunTrigger;
|
|
261
|
-
state:
|
|
297
|
+
state: RunView;
|
|
262
298
|
}): LifecycleContext {
|
|
263
299
|
return args;
|
|
264
300
|
}
|
|
265
301
|
|
|
302
|
+
/**
|
|
303
|
+
* Build a `LifecycleContext` from the current `RunContext` (typed
|
|
304
|
+
* structurally so this base-layer module never imports the runtime types).
|
|
305
|
+
* Captured per fire so listeners always see the latest `state` snapshot.
|
|
306
|
+
* THE one RunContext → LifecycleContext projection — the runner, the loop
|
|
307
|
+
* driver, and the resume entries all share it (the old per-module clones
|
|
308
|
+
* were kept aligned only by convention).
|
|
309
|
+
*/
|
|
310
|
+
export function lifecycleCtxFor(run: {
|
|
311
|
+
cwd: string;
|
|
312
|
+
runId: string;
|
|
313
|
+
workflow: { name: string };
|
|
314
|
+
totalStages: number;
|
|
315
|
+
trigger: RunTrigger;
|
|
316
|
+
state: RunView;
|
|
317
|
+
}): LifecycleContext {
|
|
318
|
+
return buildLifecycleContext({
|
|
319
|
+
cwd: run.cwd,
|
|
320
|
+
runId: run.runId,
|
|
321
|
+
workflow: run.workflow.name,
|
|
322
|
+
totalStages: run.totalStages,
|
|
323
|
+
trigger: run.trigger,
|
|
324
|
+
state: run.state,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Build a `LifecycleContext` from any SessionContext/AuditCtx-shaped object
|
|
330
|
+
* (cwd + runId + the frozen `runIdentity` + live state). The session, audit,
|
|
331
|
+
* and extraction layers all fire through this projection instead of
|
|
332
|
+
* re-spelling the six-field literal.
|
|
333
|
+
*/
|
|
334
|
+
export function lifecycleCtxFromSession(s: {
|
|
335
|
+
cwd: string;
|
|
336
|
+
runId: string;
|
|
337
|
+
runIdentity: { workflow: string; totalStages: number; trigger: RunTrigger };
|
|
338
|
+
state: RunView;
|
|
339
|
+
}): LifecycleContext {
|
|
340
|
+
return buildLifecycleContext({
|
|
341
|
+
cwd: s.cwd,
|
|
342
|
+
runId: s.runId,
|
|
343
|
+
workflow: s.runIdentity.workflow,
|
|
344
|
+
totalStages: s.runIdentity.totalStages,
|
|
345
|
+
trigger: s.runIdentity.trigger,
|
|
346
|
+
state: s.state,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
|
|
266
350
|
/** Build the `"skill"` arm of `StageRef`. */
|
|
267
351
|
export function skillStageRef(name: string, stageNumber: number, skill: string): StageRef {
|
|
268
352
|
return { kind: "skill", name, stageNumber, skill };
|
package/host.ts
CHANGED
|
@@ -76,7 +76,25 @@ export interface WorkflowHostContext {
|
|
|
76
76
|
setStatus(key: string, text: string | undefined): void;
|
|
77
77
|
};
|
|
78
78
|
sessionManager: {
|
|
79
|
+
/**
|
|
80
|
+
* The session transcript (Pi: a message-union array with private
|
|
81
|
+
* discriminators). DELIBERATELY `unknown` — naming a workflow-domain
|
|
82
|
+
* type here would break the no-cast structural pass-through of Pi's
|
|
83
|
+
* ctx. The runtime never calls this directly: `readBranch(ctx)`
|
|
84
|
+
* (transcript.ts) is the single boundary that narrows the value to
|
|
85
|
+
* `BranchEntry[]`, the workflow-domain transcript shape.
|
|
86
|
+
*/
|
|
79
87
|
getBranch(): unknown;
|
|
88
|
+
/**
|
|
89
|
+
* Session identity + on-disk location of the active session — read by
|
|
90
|
+
* `readSessionRef` (transcript.ts) so every stage row records which Pi
|
|
91
|
+
* session backed it (`WorkflowStage.session`). `getSessionFile` is
|
|
92
|
+
* `undefined` for non-persisting (in-memory) sessions. Both already
|
|
93
|
+
* exist on Pi's `ReadonlySessionManager` — type-only widening; the
|
|
94
|
+
* tripwire proves it.
|
|
95
|
+
*/
|
|
96
|
+
getSessionId(): string;
|
|
97
|
+
getSessionFile(): string | undefined;
|
|
80
98
|
};
|
|
81
99
|
waitForIdle(): Promise<void>;
|
|
82
100
|
/**
|
|
@@ -94,6 +112,18 @@ export interface WorkflowHostContext {
|
|
|
94
112
|
* Inside a session use `WorkflowSessionContext`, where it is required.
|
|
95
113
|
*/
|
|
96
114
|
sendUserMessage?(content: string): Promise<void>;
|
|
115
|
+
/**
|
|
116
|
+
* Reopen a persisted session file at its leaf and run `withSession` on
|
|
117
|
+
* the replacement ctx — the resume promotion/reattach path
|
|
118
|
+
* (`resumeStageWithSession`, run-stage.ts) adopts an interrupted stage's
|
|
119
|
+
* session through this. Declared exactly like `newSession`; OPTIONAL like
|
|
120
|
+
* `sendUserMessage` — only command-capable contexts carry it, and a host
|
|
121
|
+
* without it degrades to cold re-run (the fallback ladder's rung 3).
|
|
122
|
+
*/
|
|
123
|
+
switchSession?(
|
|
124
|
+
sessionPath: string,
|
|
125
|
+
options: { withSession: (replacement: WorkflowSessionContext) => Promise<void> },
|
|
126
|
+
): Promise<{ cancelled: boolean }>;
|
|
97
127
|
}
|
|
98
128
|
|
|
99
129
|
/**
|
package/index.ts
CHANGED
|
@@ -10,87 +10,31 @@
|
|
|
10
10
|
* like `@juicesharp/rpiv-pi` opt in by calling `registerBuiltIns(...)`
|
|
11
11
|
* from their own extension entry.
|
|
12
12
|
*
|
|
13
|
-
* ───
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* 3. Loader (programmatic embedders) — `./load/index.js`
|
|
39
|
-
* Materialise the merged workflow registry: `loadWorkflows`,
|
|
40
|
-
* `LoadedWorkflows`, `Issue`, `LoadIssue`, `ConfigLayer`,
|
|
41
|
-
* `OverlayPaths`, `projectOverlayPaths`, `userOverlayPaths`,
|
|
42
|
-
* `aliasSkills`. Siblings can apply the same remap to a built-in
|
|
43
|
-
* workflow before handing it to `runWorkflow`.
|
|
44
|
-
*
|
|
45
|
-
* 4. Built-in registry (sibling packages) — `./built-ins.js`
|
|
46
|
-
* Contribute workflows to the lowest config layer:
|
|
47
|
-
* `registerBuiltIns`. (`getBuiltIns` is test-only and lives on
|
|
48
|
-
* `@juicesharp/rpiv-workflow/internal`.)
|
|
49
|
-
*
|
|
50
|
-
* 5. Output envelope + bundled outcomes — `./output.js`,
|
|
51
|
-
* `./outcomes/index.js`, `./handle.js`
|
|
52
|
-
* Inter-stage data channel (`Output<K, D>`, `OutputMeta`,
|
|
53
|
-
* `Artifact`, `ArtifactHandle` + constructors `fs`/`url`/
|
|
54
|
-
* `opaque`/`inline`/`handleToString`) + bundled outcomes
|
|
55
|
-
* (`sideEffectOutcome`, `gitCommitOutcome`, `GitCommitData`,
|
|
56
|
-
* `gitHeadSnapshot`, `GitHeadSnapshot`) + the bundled
|
|
57
|
-
* collector/parser catalog wireable into any custom `OutputSpec`:
|
|
58
|
-
* - collectors: `transcriptPathCollector` (regex over assistant
|
|
59
|
-
* text), `toolCallCollector` (universal tool_use observer),
|
|
60
|
-
* `workspaceDiffCollector` (git status diff pre/post),
|
|
61
|
-
* `gitCommitCollector` (commit detection), the wrappers
|
|
62
|
-
* `directoryPathCollector` / `urlCollector`, plus composition
|
|
63
|
-
* `unionCollectors` and the empty-list primitive `noopCollector`.
|
|
64
|
-
* - parsers: `jsonBodyParser` (parses primary fs body),
|
|
65
|
-
* `gitCommitParser`.
|
|
66
|
-
* The `.rpiv/artifacts/<bucket>/<file>.md` outcome + the
|
|
67
|
-
* markdown-frontmatter parser live in `@juicesharp/rpiv-pi`
|
|
68
|
-
* (`rpivArtifactMdOutcome` / `frontmatterParser`) — those are
|
|
69
|
-
* rpiv conventions, not framework defaults.
|
|
70
|
-
*
|
|
71
|
-
* 6. Custom-outcome authoring surface — `./output.js`
|
|
72
|
-
* `OutputSpec<Snapshot, Kind, Data>` (collector + optional parser),
|
|
73
|
-
* `ArtifactCollector`, `ArtifactParser`, `CollectCtx`,
|
|
74
|
-
* `CollectResult`, `ParseCtx`, `ParseResult`, `SnapshotCtx`,
|
|
75
|
-
* `SnapshotFn`. Sugar: `defineCollector` / `defineParser`.
|
|
76
|
-
*
|
|
77
|
-
* 7. Validation surfaces — `./validate-workflow.js`,
|
|
78
|
-
* `./validate-output.js`
|
|
79
|
-
* `validateWorkflow`, `WorkflowValidationIssue`,
|
|
80
|
-
* `validateOutputData`, `SchemaValidationFailure`.
|
|
81
|
-
*
|
|
82
|
-
* 8. Persistence (low-level — JSONL inspect) — `./state/index.js`
|
|
83
|
-
* Read past runs at `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl`:
|
|
84
|
-
* `listRuns`, `readHeader`, `resolveRun` (run-id → header; today an
|
|
85
|
-
* alias of `readHeader`), `readLastStage`, `listArtifacts`,
|
|
86
|
-
* `stateFilePath`, `runsDir`, `RunSummary`,
|
|
87
|
-
* `WorkflowHeader`, `WorkflowStage`. `recordStage` lives on
|
|
88
|
-
* `@juicesharp/rpiv-workflow/internal` (test-only — rpiv-pi's
|
|
89
|
-
* `[I3]` regression test pokes it directly; runner owns row
|
|
90
|
-
* writes, embedders never need it).
|
|
91
|
-
*
|
|
92
|
-
* 9. Runtime types — `./types.js`
|
|
93
|
-
* `RunState`.
|
|
13
|
+
* ─── Audience map ────────────────────────────────────────────────────────
|
|
14
|
+
*
|
|
15
|
+
* `registration.ts` is the SINGLE enumeration of the runner-free public
|
|
16
|
+
* surface — this header only routes you to the right module. (A previous
|
|
17
|
+
* symbol-by-symbol catalog here drifted from reality twice; it is gone on
|
|
18
|
+
* purpose.)
|
|
19
|
+
*
|
|
20
|
+
* - Authoring a workflow (config/pack files) → `./api.js` (DSL barrel:
|
|
21
|
+
* `defineWorkflow` + the stage/loop/routing factories),
|
|
22
|
+
* `./predicates.js`, `./typebox-adapter.js`.
|
|
23
|
+
* - Driving runs programmatically → `./runner/index.js` (`runWorkflow`,
|
|
24
|
+
* `resumeWorkflow` + by-name/by-run-id sugar); host ports in `./host.js`.
|
|
25
|
+
* - Loading the merged registry → `./load/index.js` (`loadWorkflows`).
|
|
26
|
+
* - Contributing built-in workflows (sibling packages) → `./built-ins.js`
|
|
27
|
+
* (`registerBuiltIns`).
|
|
28
|
+
* - Output envelope + bundled collectors/parsers → `./output.js`,
|
|
29
|
+
* `./outcomes/index.js`, `./handle.js`; custom-outcome authoring →
|
|
30
|
+
* `./output-spec.js` (`Outcome`, `defineCollector` / `defineParser`).
|
|
31
|
+
* - Validation → `./validate-workflow.js`, `./validate-output.js`.
|
|
32
|
+
* - Observing runs → `./events.js` (`registerLifecycle`, per-call
|
|
33
|
+
* `RunWorkflowOptions.lifecycle`).
|
|
34
|
+
* - Inspecting past runs (JSONL) → `./state/index.js` (`listRuns`,
|
|
35
|
+
* `readHeader`, `runFileFor`, …). Row WRITES are runner-owned;
|
|
36
|
+
* `recordStage` lives on `@juicesharp/rpiv-workflow/internal`
|
|
37
|
+
* (test-only).
|
|
94
38
|
*
|
|
95
39
|
* Per-module deep imports (`from "@juicesharp/rpiv-workflow/api.js"`)
|
|
96
40
|
* are NOT supported across the package boundary.
|
package/internal-utils.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Internal utilities shared across the rpiv-workflow package
|
|
2
|
+
* Internal utilities shared across the rpiv-workflow package — GENERIC
|
|
3
|
+
* helpers only (error rendering, timeouts, global slots, structural
|
|
4
|
+
* equality). Workflow-domain helpers live in their domain modules:
|
|
5
|
+
* chain/artifact authorities in `chain-state.ts`, audit-row plumbing in
|
|
6
|
+
* `audit-rows.ts`, schema-timeout signalling in `validate-output.ts`.
|
|
3
7
|
*
|
|
4
8
|
* Not part of the public surface — not re-exported from `index.ts`. If a
|
|
5
9
|
* helper graduates into the documented authoring or embedding contract,
|
|
@@ -7,10 +11,6 @@
|
|
|
7
11
|
*/
|
|
8
12
|
|
|
9
13
|
import { isAbsolute, join } from "node:path";
|
|
10
|
-
import type { StageDef } from "./api.js";
|
|
11
|
-
import type { Artifact } from "./handle.js";
|
|
12
|
-
import type { Output } from "./output.js";
|
|
13
|
-
import type { RunState } from "./types.js";
|
|
14
14
|
|
|
15
15
|
/** Exhaustiveness guard for discriminated-union switches. */
|
|
16
16
|
export function assertNever(value: never): never {
|
|
@@ -18,39 +18,16 @@ export function assertNever(value: never): never {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* alone. Replaces the load-bearing single-string artifact_path mirror
|
|
25
|
-
* from the pre-collector shape.
|
|
21
|
+
* Render a caught `unknown` as a human-readable message. The ONE spelling of
|
|
22
|
+
* the `instanceof Error` dance — every catch block that needs the reason as a
|
|
23
|
+
* string calls this instead of inlining the ternary.
|
|
26
24
|
*/
|
|
27
|
-
export function
|
|
28
|
-
return
|
|
25
|
+
export function formatError(e: unknown): string {
|
|
26
|
+
return e instanceof Error ? e.message : String(e);
|
|
29
27
|
}
|
|
30
28
|
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
* envelope onto. Two layers of fallback, in priority order:
|
|
34
|
-
* 1. `stage.outcome?.name` — categorical name carried by the outcome.
|
|
35
|
-
* 2. The stage's record key — always defined.
|
|
36
|
-
*
|
|
37
|
-
* Single source of truth for the key derivation so the skill-stage path
|
|
38
|
-
* and the script-stage path stay in lockstep, and so `validateWorkflow`
|
|
39
|
-
* can compute the same key set at load time.
|
|
40
|
-
*/
|
|
41
|
-
export function resolvePublishName(def: StageDef, stageName: string): string {
|
|
42
|
-
return def.outcome?.name ?? stageName;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Resolve a stage's effective skill — the contract-registry key. Twin of
|
|
47
|
-
* `resolvePublishName`. Single source of truth so the runtime resolution
|
|
48
|
-
* (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
|
|
49
|
-
* registry identically and can't drift.
|
|
50
|
-
*/
|
|
51
|
-
export function resolveSkill(def: StageDef, stageName: string): string {
|
|
52
|
-
return def.skill ?? stageName;
|
|
53
|
-
}
|
|
29
|
+
/** Single source of ISO-8601 timestamps for audit rows + output meta. */
|
|
30
|
+
export const nowIso = (): string => new Date().toISOString();
|
|
54
31
|
|
|
55
32
|
/**
|
|
56
33
|
* Create a lazily-initialised global-slot getter anchored on a `Symbol.for` key.
|
|
@@ -75,11 +52,81 @@ export function globalSlot<T>(key: symbol, init: () => T): () => T {
|
|
|
75
52
|
};
|
|
76
53
|
}
|
|
77
54
|
|
|
78
|
-
/**
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
|
|
55
|
+
/**
|
|
56
|
+
* Register-providers / flush-on-demand lifecycle over global slots —
|
|
57
|
+
* the shared structure behind `registerBuiltInsProvider`/`flushBuiltInProviders`
|
|
58
|
+
* and their skill-contract twins, which were implemented twice near
|
|
59
|
+
* line-for-line (D2). The one real divergence — error posture — is the
|
|
60
|
+
* `onError` parameter: when given, each provider throw is RECORDED via the
|
|
61
|
+
* callback (the registry stays usable, the caller drains and surfaces);
|
|
62
|
+
* when omitted, a throw rejects the flush promise (trusted in-process
|
|
63
|
+
* providers).
|
|
64
|
+
*
|
|
65
|
+
* Flush semantics: each provider runs AT MOST ONCE, but the flush is not a
|
|
66
|
+
* one-shot process latch — providers registered after a flush run on the
|
|
67
|
+
* NEXT flush, chained after everything that already ran. This is what makes
|
|
68
|
+
* `/reload` work: Pi re-runs extension entries (which re-register their
|
|
69
|
+
* providers) while these slots survive on `globalThis`; the next consumer
|
|
70
|
+
* read then flushes the re-registered providers, so owner-scoped
|
|
71
|
+
* registrations refresh (the contract registry's prune-on-reload semantics
|
|
72
|
+
* depend on this).
|
|
73
|
+
*
|
|
74
|
+
* State (provider list + flush chain) is anchored on `Symbol.for` slots
|
|
75
|
+
* derived from `key`, so a duplicate module load shares one process-wide
|
|
76
|
+
* lifecycle — same rationale as `globalSlot` itself. The chain is a mutable
|
|
77
|
+
* box because the slot value must never be reset to `undefined` (globalSlot
|
|
78
|
+
* would re-init), only its contents.
|
|
79
|
+
*/
|
|
80
|
+
export interface LazyProviderRegistry {
|
|
81
|
+
/** Register a lazy thunk — runs once, on the next `flush()`. */
|
|
82
|
+
register(provider: () => void | Promise<void>): void;
|
|
83
|
+
/**
|
|
84
|
+
* Run every not-yet-run provider, chained after prior flushes; memoized
|
|
85
|
+
* when nothing new is pending. Concurrency-safe (callers await the same
|
|
86
|
+
* promise; a provider registered mid-flight runs on the next call). A
|
|
87
|
+
* provider throw (no-onError variant) rejects only that flush — later
|
|
88
|
+
* registrations run on subsequent flushes.
|
|
89
|
+
*/
|
|
90
|
+
flush(): Promise<void>;
|
|
91
|
+
/** Test reset: clears pending providers and the flush chain. */
|
|
92
|
+
reset(): void;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function lazyProviderRegistry(key: string, opts?: { onError: (err: unknown) => void }): LazyProviderRegistry {
|
|
96
|
+
type Provider = () => void | Promise<void>;
|
|
97
|
+
const getProviders = globalSlot(Symbol.for(`${key}:providers`), () => [] as Provider[]);
|
|
98
|
+
const getFlushBox = globalSlot(Symbol.for(`${key}:flush`), () => ({
|
|
99
|
+
flushed: undefined as Promise<void> | undefined,
|
|
100
|
+
}));
|
|
101
|
+
const onError = opts?.onError;
|
|
102
|
+
return {
|
|
103
|
+
register(provider) {
|
|
104
|
+
getProviders().push(provider);
|
|
105
|
+
},
|
|
106
|
+
flush() {
|
|
107
|
+
const box = getFlushBox();
|
|
108
|
+
const pending = getProviders().splice(0);
|
|
109
|
+
if (pending.length === 0) return box.flushed ?? Promise.resolve();
|
|
110
|
+
const run = () =>
|
|
111
|
+
Promise.all(
|
|
112
|
+
pending.map((p) => {
|
|
113
|
+
const r = Promise.resolve().then(p);
|
|
114
|
+
return onError ? r.catch(onError) : r;
|
|
115
|
+
}),
|
|
116
|
+
).then(() => undefined);
|
|
117
|
+
// Chain after the prior flush — settled either way — so registration
|
|
118
|
+
// order is preserved across reload generations and a rejection (no-
|
|
119
|
+
// onError variant) only fails the callers awaiting THAT flush; later
|
|
120
|
+
// registrations still run, so `/reload` can recover from a bad provider.
|
|
121
|
+
box.flushed = box.flushed ? box.flushed.then(run, run) : run();
|
|
122
|
+
return box.flushed;
|
|
123
|
+
},
|
|
124
|
+
reset() {
|
|
125
|
+
getProviders().length = 0;
|
|
126
|
+
getFlushBox().flushed = undefined;
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
83
130
|
|
|
84
131
|
/**
|
|
85
132
|
* Race a promise against `ms`. The inner promise is NOT cancelled — Pi's
|
|
@@ -87,8 +134,9 @@ export class SchemaTimeoutError extends Error {}
|
|
|
87
134
|
* inert when the next stage's `newSession` replaces the ctx.
|
|
88
135
|
*
|
|
89
136
|
* When `message` is a string, a plain `Error` is thrown on timeout
|
|
90
|
-
* (backward-compatible). When `message` is an `Error` (e.g.
|
|
91
|
-
* `SchemaTimeoutError`), it is thrown directly so
|
|
137
|
+
* (backward-compatible). When `message` is an `Error` instance (e.g.
|
|
138
|
+
* `SchemaTimeoutError` from validate-output.ts), it is thrown directly so
|
|
139
|
+
* `instanceof` checks work.
|
|
92
140
|
*/
|
|
93
141
|
export async function withTimeout<T>(promise: Promise<T>, ms: number, message: string | Error): Promise<T> {
|
|
94
142
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -102,40 +150,6 @@ export async function withTimeout<T>(promise: Promise<T>, ms: number, message: s
|
|
|
102
150
|
}
|
|
103
151
|
}
|
|
104
152
|
|
|
105
|
-
/**
|
|
106
|
-
* The single authority for "a completed produces stage mutates the rolling
|
|
107
|
-
* artifact state." Called by the live skill path (sessions/sessions.ts), the
|
|
108
|
-
* live script path (runner/script-stage.ts), and state reconstruction
|
|
109
|
-
* (runner/resume.ts) — keeping all three in lockstep (parity-tested).
|
|
110
|
-
*
|
|
111
|
-
* Scope: primary slot + named-publish registry ONLY. `state.output` and
|
|
112
|
-
* `state.stagesCompleted` stay at call sites — `state.output` lives in the
|
|
113
|
-
* shared, gated `tryRecordStage` (also serving fanout, which never advances
|
|
114
|
-
* the primary), so folding it here would couple fanout to the produces rule.
|
|
115
|
-
*
|
|
116
|
-
* - kind "produces" → first artifact wins the rolling slot; the
|
|
117
|
-
* full Output appends onto state.named[key].
|
|
118
|
-
* - inheritsArtifacts === false → clear the slot (terminal()).
|
|
119
|
-
* - other side-effect → leave the slot untouched.
|
|
120
|
-
*/
|
|
121
|
-
export function applyCompletedStage(state: RunState, def: StageDef, stageName: string, output: Output): void {
|
|
122
|
-
if (def.kind === "produces") {
|
|
123
|
-
const next = output.artifacts[0];
|
|
124
|
-
if (next) state.primaryArtifact = next;
|
|
125
|
-
const key = resolvePublishName(def, stageName);
|
|
126
|
-
let slot = state.named[key];
|
|
127
|
-
if (!slot) {
|
|
128
|
-
slot = [];
|
|
129
|
-
state.named[key] = slot;
|
|
130
|
-
}
|
|
131
|
-
slot.push(output);
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
if (def.inheritsArtifacts === false) {
|
|
135
|
-
state.primaryArtifact = undefined;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
153
|
/**
|
|
140
154
|
* Resolve `p` against `cwd`. Returns `p` unchanged if it is already absolute;
|
|
141
155
|
* otherwise joins `cwd + p` with the platform path separator. Uses
|
|
@@ -148,8 +162,8 @@ export function resolveUnderCwd(cwd: string, p: string): string {
|
|
|
148
162
|
|
|
149
163
|
/**
|
|
150
164
|
* Structural (key-order-independent) deep equality. Used by the
|
|
151
|
-
* cross-owner collision check in `skill-contracts.ts`
|
|
152
|
-
*
|
|
165
|
+
* cross-owner collision check in `skill-contracts/registry.ts`
|
|
166
|
+
* so two semantically-identical contracts
|
|
153
167
|
* built by different code paths (or with different YAML key order) don't
|
|
154
168
|
* read as divergent — `JSON.stringify` is insertion-order dependent and
|
|
155
169
|
* would raise a spurious collision warning. Contracts are plain JSON data
|
package/internal.ts
CHANGED
|
@@ -19,16 +19,36 @@
|
|
|
19
19
|
* Adding a new export here is a signal you have test-coupling to
|
|
20
20
|
* production state. Reach for it sparingly; prefer making the
|
|
21
21
|
* production module itself idempotent across `beforeEach` resets.
|
|
22
|
+
*
|
|
23
|
+
* KNOWN DEBT (deliberately deferred): most of these exist because the
|
|
24
|
+
* built-in/contract registries are process-global singletons (a deliberate
|
|
25
|
+
* choice — siblings register across package-instance boundaries via
|
|
26
|
+
* `Symbol.for` slots). Making them instantiable and threading an instance
|
|
27
|
+
* through `loadWorkflows` would let tests construct fresh registries and
|
|
28
|
+
* shrink this file toward zero; it's an API-design change that must be
|
|
29
|
+
* coordinated with rpiv-pi's internal-subpath regression test, so it ships
|
|
30
|
+
* in a follow-up minor, not the pre-release window.
|
|
22
31
|
*/
|
|
23
32
|
|
|
24
33
|
export { recordStage } from "./audit.js";
|
|
25
34
|
export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins.js";
|
|
26
|
-
export { __resetLifecycleRegistry } from "./
|
|
35
|
+
export { __resetLifecycleRegistry } from "./events.js";
|
|
27
36
|
export { __resetLoadCache } from "./load/cache.js";
|
|
28
37
|
export {
|
|
29
38
|
__resetSkillContracts,
|
|
39
|
+
buildEffectiveContracts,
|
|
40
|
+
drainSkillContractCollisions,
|
|
41
|
+
drainSkillContractProviderErrors,
|
|
30
42
|
flushSkillContractProviders,
|
|
43
|
+
getBucketKindMappings,
|
|
31
44
|
getCompositionComparators,
|
|
32
45
|
getSkillContracts,
|
|
33
46
|
harvestStageContracts,
|
|
47
|
+
registerBucketKindMapping,
|
|
34
48
|
} from "./skill-contracts/index.js";
|
|
49
|
+
// Layout-coupled path helpers — test fixtures that WRITE synthetic run files
|
|
50
|
+
// need them; production consumers use the opaque `runFileFor` instead.
|
|
51
|
+
export { runsDir, stateFilePath } from "./state/index.js";
|
|
52
|
+
// Type-only: lets external test fixtures construct the full mutable run state
|
|
53
|
+
// for direct `recordStage` calls. Production consumers read `RunView` instead.
|
|
54
|
+
export type { RunState } from "./types.js";
|