@juicesharp/rpiv-workflow 1.20.0 → 2.1.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 +98 -545
- 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/embedding.md +341 -0
- package/docs/workflow-authoring.md +70 -16
- package/docs/workflow-basics.md +125 -10
- 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 +19 -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/docs/cover.png +0 -0
- package/docs/cover.svg +0 -120
- 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
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Success-persistence facet — extracted from `sessions.ts`'s
|
|
3
|
+
* SUCCESS-PERSISTENCE HELPERS. `recordStageSuccess` persists a successful
|
|
4
|
+
* stage/unit row and fires the lifecycle signal; `unitEventOf` builds the
|
|
5
|
+
* `UnitEvent` payload used by BOTH the success path and the halt path's
|
|
6
|
+
* soft-halt lifecycle signal (halt-routing.ts value-imports it).
|
|
7
|
+
*
|
|
8
|
+
* Companion modules (see `sessions.ts`'s header for the full map):
|
|
9
|
+
* - halt-routing.ts — the halt pipeline; consumes `unitEventOf`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { currentStageRef, failAuditWrite } from "../audit.js";
|
|
13
|
+
import { persistStageSuccess, rollLastSession } from "../audit-rows.js";
|
|
14
|
+
import { lifecycleCtxFromSession, skillStageRef, type UnitEvent } from "../events.js";
|
|
15
|
+
import type { Output } from "../output.js";
|
|
16
|
+
import type { SessionRef } from "../state/index.js";
|
|
17
|
+
import type { StageSession, WorkflowHostContext } from "../types.js";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Returns true on successful write — caller gates `onSuccess` on this so the
|
|
21
|
+
* chain advances only when the audit row landed. On failure, leaves
|
|
22
|
+
* `state.output` / `state.primaryArtifact` at their prior values ("output is
|
|
23
|
+
* set iff the row that carried it landed") and sets `state.termination.error`
|
|
24
|
+
* to halt the run. Persistence + state apply run through
|
|
25
|
+
* `persistStageSuccess` (audit-rows.ts) — the ONE success pipeline shared
|
|
26
|
+
* with the script path: the row reuses the activation's pre-allocated number
|
|
27
|
+
* so `output.meta.stageNumber` and the row agree, and unit rows carry the
|
|
28
|
+
* structured identity fields alongside the decorated display `stage`.
|
|
29
|
+
*
|
|
30
|
+
* Single stages keep the `onStageEnd` contract verbatim. Loop units fire
|
|
31
|
+
* `onUnitEnd` (NEVER `onStageEnd` — that's reserved for single-stage and
|
|
32
|
+
* loop-level semantics), the ref carrying the PARENT stage name so listeners
|
|
33
|
+
* key on graph identity, not the display decoration. Neither path emits a
|
|
34
|
+
* completion toast — the status line is the live progress channel.
|
|
35
|
+
*
|
|
36
|
+
* Exported to the `reattach.ts` companion — promotion persists through this
|
|
37
|
+
* exact pipeline (one success path, live and adopted alike).
|
|
38
|
+
*/
|
|
39
|
+
export async function recordStageSuccess(
|
|
40
|
+
ctx: WorkflowHostContext,
|
|
41
|
+
s: StageSession,
|
|
42
|
+
output: Output,
|
|
43
|
+
session: SessionRef | null,
|
|
44
|
+
): Promise<boolean> {
|
|
45
|
+
const persisted = persistStageSuccess(
|
|
46
|
+
s.state,
|
|
47
|
+
{
|
|
48
|
+
cwd: s.cwd,
|
|
49
|
+
runId: s.runId,
|
|
50
|
+
stage: s.stageName,
|
|
51
|
+
skill: s.skill,
|
|
52
|
+
output,
|
|
53
|
+
session,
|
|
54
|
+
unit: s.unit,
|
|
55
|
+
preAllocated: s.allocatedStageNumber,
|
|
56
|
+
},
|
|
57
|
+
s.stage,
|
|
58
|
+
);
|
|
59
|
+
if (persisted) {
|
|
60
|
+
if (s.unit) {
|
|
61
|
+
await s.lifecycle.fire(
|
|
62
|
+
ctx,
|
|
63
|
+
"onUnitEnd",
|
|
64
|
+
// Same allocator base as every other ref of this activation; the
|
|
65
|
+
// ref's NAME stays the parent stage key (graph identity).
|
|
66
|
+
skillStageRef(s.unit.parent, s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber, s.skill),
|
|
67
|
+
unitEventOf(s),
|
|
68
|
+
output,
|
|
69
|
+
lifecycleCtxFromSession(s),
|
|
70
|
+
);
|
|
71
|
+
} else {
|
|
72
|
+
// Roll the predecessor session forward: a downstream `continue` stage
|
|
73
|
+
// forks THIS session. Single stages only — loop units take the `if (s.unit)`
|
|
74
|
+
// branch above and never seed a continuation. Shared with the resume fold
|
|
75
|
+
// (`rollLastSession`) so the null-handling can't drift between the paths.
|
|
76
|
+
rollLastSession(s.state, session);
|
|
77
|
+
await s.lifecycle.fire(ctx, "onStageEnd", currentStageRef(s), output, lifecycleCtxFromSession(s));
|
|
78
|
+
}
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
failAuditWrite(ctx, s.state, s.skill);
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Public `UnitEvent` payload from the session's `UnitRef` + dispatched skill. */
|
|
86
|
+
export function unitEventOf(s: StageSession): UnitEvent {
|
|
87
|
+
const u = s.unit!;
|
|
88
|
+
return { role: u.role, index: u.index, unitId: u.id, label: u.label, skill: s.skill };
|
|
89
|
+
}
|
|
@@ -21,7 +21,7 @@ import { getCompositionComparators } from "./extension-points.js";
|
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
23
|
* THE single data-channel comparison core — shared by `canCompose` and the
|
|
24
|
-
* validator's `checkEdgeSchemaCompat
|
|
24
|
+
* validator's `checkEdgeSchemaCompat`, so the adviser and the load gate
|
|
25
25
|
* answer the producer→consumer data question through one engine. Conservative:
|
|
26
26
|
* either side absent/opaque → `{ ok: true }` (not provably incompatible);
|
|
27
27
|
* both present → `isSchemaCompatible`.
|
|
@@ -77,14 +77,12 @@ export function adjudicateChannel(
|
|
|
77
77
|
* Conservative (via `isSchemaCompatible`): returns `{ ok: true }` when either
|
|
78
78
|
* schema is absent/opaque (not provably incompatible).
|
|
79
79
|
*
|
|
80
|
-
* `contracts` is REQUIRED
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* harvested) view, or `getSkillContracts()` when the registered slice
|
|
87
|
-
* is genuinely what you mean.
|
|
80
|
+
* `contracts` is REQUIRED: the GLOBAL registry holds only registered
|
|
81
|
+
* (`declared`-source) contracts — NOT the `harvested` ones, which exist solely
|
|
82
|
+
* on `LoadedWorkflows.skillContracts` (built per load, never written back to the
|
|
83
|
+
* global) — so a default would be the wrong call for any harvest-only skill.
|
|
84
|
+
* Pass `loaded.skillContracts` for the effective (declared ⊕ harvested) view,
|
|
85
|
+
* or `getSkillContracts()` when the registered slice is genuinely what you mean.
|
|
88
86
|
*/
|
|
89
87
|
export function canCompose(
|
|
90
88
|
producerSkill: string,
|
|
@@ -93,7 +91,7 @@ export function canCompose(
|
|
|
93
91
|
): SchemaCompatResult {
|
|
94
92
|
const producerContract = contracts.get(producerSkill);
|
|
95
93
|
const consumerContract = contracts.get(consumerSkill);
|
|
96
|
-
// Data channel: a provable data mismatch is decisive (shared core
|
|
94
|
+
// Data channel: a provable data mismatch is decisive (shared core).
|
|
97
95
|
const dataCompat = compareDataChannel(producerContract?.produces?.data, consumerContract?.consumes?.data);
|
|
98
96
|
if (!dataCompat.ok) return dataCompat;
|
|
99
97
|
// Named-channel (reads) compat — THE shared `adjudicateChannel` rule (same
|
|
@@ -9,9 +9,10 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { Workflow } from "../api.js";
|
|
12
|
-
import { isDispatchingStage, resolveSkill } from "../chain-state.js";
|
|
13
12
|
import { extractJsonSchema } from "../json-schema.js";
|
|
14
13
|
import type { ConsumesSpec, ProducesSpec, SkillContract } from "../skill-contract.js";
|
|
14
|
+
import { readName } from "../stage-def.js";
|
|
15
|
+
import { isDispatchingStage, resolveSkill } from "../stage-identity.js";
|
|
15
16
|
import { getSkillContracts } from "./registry.js";
|
|
16
17
|
|
|
17
18
|
/**
|
|
@@ -43,7 +44,7 @@ export function harvestStageContracts(workflows: readonly Workflow[]): Map<strin
|
|
|
43
44
|
const skill = resolveSkill(stage, stageName);
|
|
44
45
|
const producesData = extractJsonSchema(stage.outputSchema);
|
|
45
46
|
const consumesData = extractJsonSchema(stage.inputSchema);
|
|
46
|
-
const reads = stage.reads?.length ? Object.fromEntries(stage.reads.map((r) => [r, {}])) : undefined;
|
|
47
|
+
const reads = stage.reads?.length ? Object.fromEntries(stage.reads.map((r) => [readName(r), {}])) : undefined;
|
|
47
48
|
const produces: ProducesSpec | undefined =
|
|
48
49
|
stage.kind === "produces" || producesData
|
|
49
50
|
? { kind: stage.kind, ...(producesData ? { data: producesData } : {}) } // real StageKind ("produces" | "side-effect")
|
|
@@ -26,7 +26,7 @@ const getOwners = globalSlot(OWNERS_KEY, () => new Map<string, string>());
|
|
|
26
26
|
const getCollisions = globalSlot(COLLISIONS_KEY, () => [] as string[]);
|
|
27
27
|
const getFailures = globalSlot(FAILURES_KEY, () => [] as unknown[]);
|
|
28
28
|
|
|
29
|
-
// Provider lifecycle via the shared `lazyProviderRegistry
|
|
29
|
+
// Provider lifecycle via the shared `lazyProviderRegistry`. DELIBERATE
|
|
30
30
|
// divergence from the built-ins registry: `onError` RECORDS each provider
|
|
31
31
|
// throw (drained by `drainSkillContractProviderErrors`) instead of
|
|
32
32
|
// propagating. Contract providers read the filesystem / parse frontmatter
|
package/stage-def.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
14
|
+
import { requireNonEmptyString } from "./internal-utils.js";
|
|
14
15
|
import type { AssessLoop, LoopDef, VerifySpec } from "./loop-def.js";
|
|
15
16
|
import type { Output, RunView } from "./output.js";
|
|
16
17
|
import type { Outcome } from "./output-spec.js";
|
|
@@ -59,9 +60,13 @@ export const STAGE_KINDS = ["produces", "side-effect"] as const;
|
|
|
59
60
|
export type StageKind = (typeof STAGE_KINDS)[number];
|
|
60
61
|
|
|
61
62
|
/**
|
|
62
|
-
* - `"fresh"` —
|
|
63
|
-
* - `"continue"` —
|
|
64
|
-
* `
|
|
63
|
+
* - `"fresh"` — the stage runs in a brand-new detached child session.
|
|
64
|
+
* - `"continue"` — the stage FORKS its predecessor's persisted child session
|
|
65
|
+
* (`SessionManager.forkFrom`), so the child carries the prior conversation as
|
|
66
|
+
* context; the continuation turn is then sent into it, and its outcome is
|
|
67
|
+
* sliced past the inherited prefix by a `branchOffset` re-derived from the
|
|
68
|
+
* forked branch. No predecessor session (start stage / after a loop / file
|
|
69
|
+
* gone) degrades to a fresh dispatch.
|
|
65
70
|
*/
|
|
66
71
|
export const SESSION_POLICIES = ["fresh", "continue"] as const;
|
|
67
72
|
export type SessionPolicy = (typeof SESSION_POLICIES)[number];
|
|
@@ -142,7 +147,43 @@ export type ActsScriptFn = (ctx: ScriptContext) => void | Promise<void>;
|
|
|
142
147
|
export type PromptFn = (ctx: ScriptContext) => string | Promise<string>;
|
|
143
148
|
|
|
144
149
|
// ===========================================================================
|
|
145
|
-
//
|
|
150
|
+
// Channel-read declarations for `reads:` stage fields
|
|
151
|
+
// ===========================================================================
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* A single `reads:` entry: a bare channel name (latest-wins, the historical
|
|
155
|
+
* default) or a spec selecting ALL accumulated entries of the channel.
|
|
156
|
+
* `fanin()` builds the all-entries spec — the consumer-side mirror of
|
|
157
|
+
* `fanout()`, the fanout-and-synthesize fan-in idiom.
|
|
158
|
+
*/
|
|
159
|
+
export type StageRead = string | { readonly name: string; readonly all?: boolean };
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Read EVERY accumulated entry of a channel (run order), not just the latest.
|
|
163
|
+
* The canonical consumer side of fanout-and-synthesize:
|
|
164
|
+
* fanout({ ..., outcome: { name: "plans" } })
|
|
165
|
+
* stage({ reads: [fanin("plans")], skill: "synthesize" })
|
|
166
|
+
* Throws on an empty name, mirroring the value-returning loop/routing builders
|
|
167
|
+
* (gate()/match()/assess()) — NOT the pure passthrough factories in this file
|
|
168
|
+
* (produces()/acts()/terminal()), which apply defaults without validating.
|
|
169
|
+
*/
|
|
170
|
+
export function fanin(name: string): { readonly name: string; readonly all: true } {
|
|
171
|
+
requireNonEmptyString(name, "fanin(name)", "name must be a non-empty channel name");
|
|
172
|
+
return { name, all: true };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The channel name of a read, normalizing bare-string and spec forms. */
|
|
176
|
+
export function readName(read: StageRead): string {
|
|
177
|
+
return typeof read === "string" ? read : read.name;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Whether a read consumes ALL accumulated entries (vs. latest-wins). */
|
|
181
|
+
export function readsAll(read: StageRead): boolean {
|
|
182
|
+
return typeof read !== "string" && read.all === true;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ===========================================================================
|
|
186
|
+
// StageDef — the discriminated union over the dispatch axis
|
|
146
187
|
// ===========================================================================
|
|
147
188
|
|
|
148
189
|
/**
|
|
@@ -240,9 +281,13 @@ export interface SkillStage<TIn = unknown, TOut = unknown> extends StageDefBase<
|
|
|
240
281
|
* Names this stage consumes from `state.named` to build its prompt.
|
|
241
282
|
* When set, the runner replaces the default single-artifact prompt
|
|
242
283
|
* (`/skill:<name> <handle>`) with a labelled-flag form
|
|
243
|
-
* (`/skill:<name> --<n1> <h1> --<n2> <h2> …`), reading
|
|
244
|
-
* `Output`
|
|
245
|
-
*
|
|
284
|
+
* (`/skill:<name> --<n1> <h1> --<n2> <h2> …`), reading each name's
|
|
285
|
+
* accumulated `Output` and iterating its `artifacts` list.
|
|
286
|
+
*
|
|
287
|
+
* A bare string reads the channel's LATEST entry (`array.at(-1)`); wrap a
|
|
288
|
+
* name in `fanin("name")` to read EVERY accumulated entry — the
|
|
289
|
+
* fanout-and-synthesize fan-in idiom. Empty (or unset) → default prompt
|
|
290
|
+
* behaviour preserved.
|
|
246
291
|
*
|
|
247
292
|
* Names address `state.named` slots, which are keyed by
|
|
248
293
|
* `stage.outcome?.name ?? stage.<record-key>`. Every name in `reads:`
|
|
@@ -250,7 +295,7 @@ export interface SkillStage<TIn = unknown, TOut = unknown> extends StageDefBase<
|
|
|
250
295
|
* at load time by `validateWorkflow`; the `ensureNamedReads` preflight
|
|
251
296
|
* catches the "haven't reached the producer yet" case at runtime).
|
|
252
297
|
*/
|
|
253
|
-
reads?: ReadonlyArray<
|
|
298
|
+
reads?: ReadonlyArray<StageRead>;
|
|
254
299
|
run?: never;
|
|
255
300
|
prompt?: never;
|
|
256
301
|
}
|
|
@@ -270,8 +315,8 @@ export interface SkillStage<TIn = unknown, TOut = unknown> extends StageDefBase<
|
|
|
270
315
|
*/
|
|
271
316
|
export interface ScriptStage<TIn = unknown, TOut = unknown> extends StageDefBase<TIn, TOut> {
|
|
272
317
|
run: ProducesScriptFn<string, TOut> | ActsScriptFn;
|
|
273
|
-
/** Same named-channel consumption as a skill stage — `ScriptContext.state.named` still needs the producer gate. */
|
|
274
|
-
reads?: ReadonlyArray<
|
|
318
|
+
/** Same named-channel consumption as a skill stage — `ScriptContext.state.named` still needs the producer gate. `fanin()` reads all entries. */
|
|
319
|
+
reads?: ReadonlyArray<StageRead>;
|
|
275
320
|
skill?: never;
|
|
276
321
|
outcome?: never;
|
|
277
322
|
loop?: never;
|
|
@@ -307,7 +352,7 @@ export interface PromptStage<TIn = unknown, TOut = unknown> extends StageDefBase
|
|
|
307
352
|
|
|
308
353
|
/**
|
|
309
354
|
* A stage in the workflow graph — a discriminated union over the DISPATCH
|
|
310
|
-
* axis
|
|
355
|
+
* axis: skill (`SkillStage`, the default), script (`ScriptStage`,
|
|
311
356
|
* `run` present), or raw prompt (`PromptStage`, `prompt` present). The
|
|
312
357
|
* stage's identity is the surrounding `Workflow.stages` record key.
|
|
313
358
|
*
|
|
@@ -317,7 +362,7 @@ export interface PromptStage<TIn = unknown, TOut = unknown> extends StageDefBase
|
|
|
317
362
|
* hand-rolled literals because jiti erases TS types (same posture as the
|
|
318
363
|
* `Judge` union + `judgeShapeIssues`).
|
|
319
364
|
*
|
|
320
|
-
* TYPING MODEL
|
|
365
|
+
* TYPING MODEL: `<TIn, TOut>` are LOCAL inference helpers — they tie a
|
|
321
366
|
* factory call's `inputSchema`/`outputSchema`/`run` together, then erase at
|
|
322
367
|
* the `Workflow.stages` boundary (`Record<string, StageDef>`). They do NOT
|
|
323
368
|
* carry types across edges; inter-stage typing is runtime-contract-based
|
|
@@ -353,7 +398,7 @@ export function defineWorkflow(spec: Workflow): Workflow {
|
|
|
353
398
|
}
|
|
354
399
|
|
|
355
400
|
/**
|
|
356
|
-
* Builder options are PROJECTIONS of the union arms
|
|
401
|
+
* Builder options are PROJECTIONS of the union arms: each interface
|
|
357
402
|
* `Pick`s its fields from the arm the factory constructs, and the factory
|
|
358
403
|
* spreads the options over the arm's fixed fields. Adding a knob to an arm
|
|
359
404
|
* is one edit here (extend the `Pick` key list — a stale key no longer on
|
|
@@ -414,61 +459,70 @@ interface ActsPromptOptions<TIn = unknown> extends Pick<PromptStage<TIn, void>,
|
|
|
414
459
|
sessionPolicy?: SessionPolicy;
|
|
415
460
|
}
|
|
416
461
|
|
|
462
|
+
/**
|
|
463
|
+
* THE stage-defaults authority — owns the load-bearing `as StageDef<TIn, TOut>`
|
|
464
|
+
* cast (a `Partial<StageDef>` union can't be proven to complete a single arm,
|
|
465
|
+
* so the cast is required for the `Partial`-override factories; taming it here
|
|
466
|
+
* means callers don't repeat the concession) + the shared
|
|
467
|
+
* `{ kind, sessionPolicy, ...overrides }` body. Genericized to `<TIn, TOut>` so
|
|
468
|
+
* the four typed factories (`producesScript`/`producesPrompt`/`actsPrompt`/
|
|
469
|
+
* `actsScript`) route through it without widening against their
|
|
470
|
+
* `StageDef<TIn, TOut>` / `StageDef<TIn, void>` return annotations; the two
|
|
471
|
+
* `Partial`-override factories `producesFn`/`actsFn` call it with the default
|
|
472
|
+
* `<unknown, unknown>` params. `overrides.sessionPolicy ?? "fresh"` honors the
|
|
473
|
+
* `"continue"` override the two prompt factories expose (the trailing
|
|
474
|
+
* `...overrides` spread makes a present `sessionPolicy` win regardless). The
|
|
475
|
+
* cast's load-bearingness is documented ONCE here, not on each twin.
|
|
476
|
+
*/
|
|
477
|
+
function withDefaults<TIn = unknown, TOut = unknown>(
|
|
478
|
+
kind: "produces" | "side-effect",
|
|
479
|
+
overrides: Partial<StageDef<TIn, TOut>> & { sessionPolicy?: SessionPolicy } = {},
|
|
480
|
+
): StageDef<TIn, TOut> {
|
|
481
|
+
return { kind, sessionPolicy: overrides.sessionPolicy ?? "fresh", ...overrides } as StageDef<TIn, TOut>;
|
|
482
|
+
}
|
|
483
|
+
|
|
417
484
|
function producesFn(overrides: Partial<StageDef> = {}): StageDef {
|
|
418
|
-
|
|
419
|
-
// proven to complete a single arm. Call sites stay arm-checked (an object
|
|
420
|
-
// literal mixing dispatches fails before it reaches the spread).
|
|
421
|
-
return {
|
|
422
|
-
kind: "produces",
|
|
423
|
-
sessionPolicy: "fresh",
|
|
424
|
-
...overrides,
|
|
425
|
-
} as StageDef;
|
|
485
|
+
return withDefaults("produces", overrides);
|
|
426
486
|
}
|
|
427
487
|
|
|
428
488
|
function producesScript<TIn = unknown, TOut = unknown>(opts: ProducesScriptOptions<TIn, TOut>): StageDef<TIn, TOut> {
|
|
429
|
-
return
|
|
430
|
-
kind: "produces",
|
|
431
|
-
sessionPolicy: "fresh",
|
|
432
|
-
...opts,
|
|
433
|
-
};
|
|
489
|
+
return withDefaults<TIn, TOut>("produces", opts);
|
|
434
490
|
}
|
|
435
491
|
|
|
436
492
|
function producesPrompt<TIn = unknown, TOut = unknown>(opts: ProducesPromptOptions<TIn, TOut>): StageDef<TIn, TOut> {
|
|
437
|
-
return
|
|
438
|
-
kind: "produces",
|
|
439
|
-
...opts,
|
|
440
|
-
sessionPolicy: opts.sessionPolicy ?? "fresh",
|
|
441
|
-
};
|
|
493
|
+
return withDefaults<TIn, TOut>("produces", opts);
|
|
442
494
|
}
|
|
443
495
|
|
|
444
496
|
function actsFn(overrides: Partial<StageDef> = {}): StageDef {
|
|
445
|
-
return
|
|
446
|
-
kind: "side-effect",
|
|
447
|
-
sessionPolicy: "fresh",
|
|
448
|
-
...overrides,
|
|
449
|
-
} as StageDef;
|
|
497
|
+
return withDefaults("side-effect", overrides);
|
|
450
498
|
}
|
|
451
499
|
|
|
452
500
|
function actsPrompt<TIn = unknown>(opts: ActsPromptOptions<TIn>): StageDef<TIn, void> {
|
|
453
|
-
return
|
|
454
|
-
kind: "side-effect",
|
|
455
|
-
...opts,
|
|
456
|
-
sessionPolicy: opts.sessionPolicy ?? "fresh",
|
|
457
|
-
};
|
|
501
|
+
return withDefaults<TIn, void>("side-effect", opts);
|
|
458
502
|
}
|
|
459
503
|
|
|
460
504
|
function actsScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
|
|
461
|
-
return
|
|
462
|
-
kind: "side-effect",
|
|
463
|
-
sessionPolicy: "fresh",
|
|
464
|
-
...opts,
|
|
465
|
-
};
|
|
505
|
+
return withDefaults<TIn, void>("side-effect", opts);
|
|
466
506
|
}
|
|
467
507
|
|
|
508
|
+
// A terminal stage = side-effect + inheritsArtifacts: false (see the `terminal()`
|
|
509
|
+
// public doc). `terminalFn` (Partial path) and `terminalScript` (concrete-opts
|
|
510
|
+
// path below) are the two realizations; both set the same marker.
|
|
511
|
+
//
|
|
512
|
+
// "terminal" SENSE 1 (the factory — this fn + the `terminal` export below): a
|
|
513
|
+
// side-effect stage that does NOT inherit the upstream artifact. Distinct from
|
|
514
|
+
// SENSE 2 (graph sink — `StageShape.edge.mode: "terminal"` in loop-constructors.ts
|
|
515
|
+
// / `{ kind: "stop" }` in routing.ts: no outgoing edge OR explicit `STOP`;
|
|
516
|
+
// orthogonal to this factory — a `terminal()` stage can route onward, and a
|
|
517
|
+
// plain stage can be a sink) and SENSE 3 (run-outcome prose — "terminal
|
|
518
|
+
// failure/outcome" = a halt that ends the run, e.g. audit.ts `writeFailureRow`).
|
|
519
|
+
// See the `terminal` export doc below for the full glossary.
|
|
468
520
|
function terminalFn(overrides: Partial<StageDef> = {}): StageDef {
|
|
469
|
-
return
|
|
521
|
+
return withDefaults("side-effect", { ...overrides, inheritsArtifacts: false });
|
|
470
522
|
}
|
|
471
523
|
|
|
524
|
+
// Concrete-opts twin of `terminalFn` above — both realize "side-effect +
|
|
525
|
+
// inheritsArtifacts: false" via their respective paths (script vs Partial).
|
|
472
526
|
function terminalScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
|
|
473
527
|
return actsScript({ ...opts, inheritsArtifacts: false });
|
|
474
528
|
}
|
|
@@ -523,5 +577,19 @@ export const acts = Object.assign(actsFn, { script: actsScript, prompt: actsProm
|
|
|
523
577
|
* Desugars to `acts({ ...overrides, inheritsArtifacts: false })`. The
|
|
524
578
|
* skillless variant `terminal.script({ run, ... })` desugars to
|
|
525
579
|
* `acts.script({ ...opts, inheritsArtifacts: false })`.
|
|
580
|
+
*
|
|
581
|
+
* ── Glossary: "terminal" has three unrelated senses in this package ──
|
|
582
|
+
* 1. FACTORY (this export, `terminalFn`/`terminalScript`): a side-effect
|
|
583
|
+
* stage that does NOT inherit the upstream artifact (`inheritsArtifacts:
|
|
584
|
+
* false`). A `terminal()` stage may still carry a downstream edge.
|
|
585
|
+
* 2. GRAPH SINK (`StageShape.edge.mode: "terminal"` in loop-constructors.ts;
|
|
586
|
+
* `{ kind: "stop" }` in routing.ts `RoutingResult`; rendered "(terminal)"
|
|
587
|
+
* by preview.ts `formatEdge`; "implicit terminals" in validate/graph.ts):
|
|
588
|
+
* a stage with NO outgoing edge OR an explicit `STOP`. Orthogonal to the
|
|
589
|
+
* factory — a `terminal()` stage can route onward, a plain stage can be a
|
|
590
|
+
* sink.
|
|
591
|
+
* 3. RUN OUTCOME ("terminal failure/outcome" prose, e.g. audit.ts
|
|
592
|
+
* `writeFailureRow` / `recordTerminalFailure`): a failure/cancellation/
|
|
593
|
+
* abort that ends the run.
|
|
526
594
|
*/
|
|
527
595
|
export const terminal = Object.assign(terminalFn, { script: terminalScript });
|
package/stage-errors.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { FailureText } from "./messages.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Shared-kernel stage error vocabulary — a package-root LEAF (zero value
|
|
5
|
+
* imports; only a type-only `FailureText` pull) so
|
|
6
|
+
* both the engine's loop-primitive layer (`loop-kinds.ts`) and the runner's
|
|
7
|
+
* per-stage pipeline (`runner/{preflight,input-validation,failure}.ts`) can
|
|
8
|
+
* throw it without anyone importing across the `runner/` boundary. Homed at
|
|
9
|
+
* the root, the import arrow points strictly downward for every consumer
|
|
10
|
+
* (`loop-kinds.ts` — a module the runner imports FROM — never reaches back
|
|
11
|
+
* UP into `runner/`). `runner/errors.ts` re-exports it so the in-`runner/`
|
|
12
|
+
* call sites keep their local spelling.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Thrown by a preflight check on failure; carries the recorded-row
|
|
17
|
+
* attribution + notify/err messages so `runStageOrRecordFailure` can land
|
|
18
|
+
* a uniform JSONL row regardless of which slot tripped.
|
|
19
|
+
*
|
|
20
|
+
* `kind` annotates the violation class for diagnostics only — control
|
|
21
|
+
* flow at the catch site is uniform:
|
|
22
|
+
* - `"halt"` — runtime-state failure (skill not registered, missing
|
|
23
|
+
* upstream artifact, schema mismatch).
|
|
24
|
+
* - `"invariant"` — authoring-time-knowable violation that
|
|
25
|
+
* `validateWorkflow` should reject at load. A throw
|
|
26
|
+
* here means validation was bypassed or the rule lives
|
|
27
|
+
* only in the runner (continue-without-pi).
|
|
28
|
+
*/
|
|
29
|
+
export class StagePreflightError extends Error {
|
|
30
|
+
constructor(
|
|
31
|
+
public readonly kind: "halt" | "invariant",
|
|
32
|
+
public readonly skill: string,
|
|
33
|
+
public readonly notifyMsg: string,
|
|
34
|
+
public readonly errMsg: string,
|
|
35
|
+
public readonly notifyPartial: boolean,
|
|
36
|
+
) {
|
|
37
|
+
super(errMsg);
|
|
38
|
+
this.name = "StagePreflightError";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// Facade constructors
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The ONE construction site — `notifyPartial` is DERIVED from `kind` (halt →
|
|
48
|
+
* `true`, invariant → `false`), so a status/level mismatch is unrepresentable.
|
|
49
|
+
* Modeled after `audit.ts:terminalArgsOf` (which derives `notifyLevel` from
|
|
50
|
+
* `status`). Halt sites build via `haltPreflight` / `invariantPreflight` so
|
|
51
|
+
* the literal `new StagePreflightError(…)` never re-appears at a call site.
|
|
52
|
+
*/
|
|
53
|
+
function preflightErrorOf(
|
|
54
|
+
kind: "halt" | "invariant",
|
|
55
|
+
skill: string,
|
|
56
|
+
notifyMsg: string,
|
|
57
|
+
errMsg: string,
|
|
58
|
+
): StagePreflightError {
|
|
59
|
+
return new StagePreflightError(kind, skill, notifyMsg, errMsg, kind === "halt");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Pattern A — runtime-state failure (skill not registered, missing upstream
|
|
64
|
+
* artifact, schema mismatch). `notifyPartial: true` (the stage produced a
|
|
65
|
+
* partial worth surfacing). Built from one `FailureText` so the toast/error
|
|
66
|
+
* pairing lives in the `FAIL_*` factory and can't drift.
|
|
67
|
+
*/
|
|
68
|
+
export function haltPreflight(skill: string, failure: FailureText): StagePreflightError {
|
|
69
|
+
return preflightErrorOf("halt", skill, failure.toast, failure.error);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Pattern B — authoring-time-knowable violation that `validateWorkflow` should
|
|
74
|
+
* reject at load (`continue-without-pi`, a corrupted loop cursor). A throw
|
|
75
|
+
* here means validation was bypassed or the rule lives only in the runner.
|
|
76
|
+
* `notifyPartial: false`. Single-message form (notifyMsg === errMsg); the
|
|
77
|
+
* two-arg overload splits them (e.g. a runner wrapper that frames the user
|
|
78
|
+
* message while preserving the raw `reason` as `errMsg`).
|
|
79
|
+
*/
|
|
80
|
+
export function invariantPreflight(name: string, msg: string): StagePreflightError;
|
|
81
|
+
export function invariantPreflight(name: string, notifyMsg: string, errMsg: string): StagePreflightError;
|
|
82
|
+
export function invariantPreflight(name: string, notifyMsg: string, errMsg?: string): StagePreflightError {
|
|
83
|
+
return preflightErrorOf("invariant", name, notifyMsg, errMsg ?? notifyMsg);
|
|
84
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stage-identity derivations — the pure projections off a `StageDef` that the
|
|
3
|
+
* runtime and the load-time validators must agree on (effective skill, publish
|
|
4
|
+
* name, dispatch-vs-body classification).
|
|
5
|
+
*
|
|
6
|
+
* A dependency-free LEAF (imports only `StageDef`/`SkillStage` TYPES): so the
|
|
7
|
+
* definition/compile-time context (`load/`, `validate/`, `skill-contracts/harvest`)
|
|
8
|
+
* can consume these without importing `chain-state.ts` — a RUNTIME-STATE module
|
|
9
|
+
* (it imports `RunState` and houses `applyCompletedStage(state, …)` mutators).
|
|
10
|
+
* Co-locating these projections there forced a structural edge from the loader +
|
|
11
|
+
* validators into the execution context, enforced by nothing but convention.
|
|
12
|
+
* `chain-state.ts` re-exports them so its own runtime callers keep one import.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { SkillStage, StageDef } from "./api.js";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Resolve the `state.named` key a produces stage appends its `Output`
|
|
19
|
+
* envelope onto. Two layers of fallback, in priority order:
|
|
20
|
+
* 1. `stage.outcome?.name` — categorical name carried by the outcome.
|
|
21
|
+
* 2. The stage's record key — always defined.
|
|
22
|
+
*
|
|
23
|
+
* Single source of truth for the key derivation so the skill-stage path
|
|
24
|
+
* and the script-stage path stay in lockstep, and so `validateWorkflow`
|
|
25
|
+
* can compute the same key set at load time.
|
|
26
|
+
*/
|
|
27
|
+
export function resolvePublishName(def: StageDef, stageName: string): string {
|
|
28
|
+
return def.outcome?.name ?? stageName;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Resolve a stage's effective skill — the contract-registry key. Twin of
|
|
33
|
+
* `resolvePublishName`. Single source of truth so the runtime resolution
|
|
34
|
+
* (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
|
|
35
|
+
* registry identically and can't drift.
|
|
36
|
+
*/
|
|
37
|
+
export function resolveSkill(def: StageDef, stageName: string): string {
|
|
38
|
+
return def.skill ?? stageName;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A stage dispatches a `/skill:<name>` exactly when it carries neither a `run`
|
|
43
|
+
* (script body) nor a `prompt` (raw-text body). `fanout`/`iterate` stages carry
|
|
44
|
+
* neither, so they ARE dispatching stages. The shared predicate for every site
|
|
45
|
+
* that treats `resolveSkill`'s result as a REAL skill identity — the alias
|
|
46
|
+
* remap + its no-op warning, contract harvest, and the validator's contract
|
|
47
|
+
* lookups must all agree, or a script/prompt stage whose record key matches a
|
|
48
|
+
* registered skill inherits that skill's contract by accident.
|
|
49
|
+
*
|
|
50
|
+
* A TYPE GUARD since the StageDef union: a positive narrows to
|
|
51
|
+
* `SkillStage`, so callers that wire skill-derived data onto the stage
|
|
52
|
+
* (the alias remap, outcome derivers) get the writable arm.
|
|
53
|
+
*/
|
|
54
|
+
export function isDispatchingStage(stage: StageDef): stage is SkillStage {
|
|
55
|
+
return stage.run == null && stage.prompt == null;
|
|
56
|
+
}
|
package/startup.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
export { registerBuiltIns, registerBuiltInsProvider } from "./built-ins.js";
|
|
9
9
|
export { registerLifecycle } from "./events.js";
|
|
10
|
+
export { registerWorkflowExecutionHost } from "./execution-host.js";
|
|
10
11
|
export {
|
|
11
12
|
getBucketKindMappings,
|
|
12
13
|
registerBucketKindMapping,
|
package/state/paths.ts
CHANGED
|
@@ -49,11 +49,19 @@ export function stateFilePath(cwd: string, runId: string): string {
|
|
|
49
49
|
return join(runsDir(cwd), `${runId}.jsonl`);
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/** Per-run directory holding each detached child's persisted session file,
|
|
53
|
+
* keyed by SessionRef.id — `.rpiv/workflows/runs/<runId>/sessions/`. The flat
|
|
54
|
+
* `<runId>.jsonl` trail stays a sibling under `runsDir`. INTERNAL — not on the
|
|
55
|
+
* public barrel (same encapsulation rule as runsDir/stateFilePath). */
|
|
56
|
+
export function childSessionsDir(cwd: string, runId: string): string {
|
|
57
|
+
return join(runsDir(cwd), runId, "sessions");
|
|
58
|
+
}
|
|
59
|
+
|
|
52
60
|
/**
|
|
53
61
|
* OPAQUE display path of a run's JSONL file — the only layout projection on
|
|
54
|
-
* the public surface (`runsDir`/`stateFilePath`
|
|
55
|
-
*
|
|
56
|
-
*
|
|
62
|
+
* the public surface (exposing `runsDir`/`stateFilePath` invites external code
|
|
63
|
+
* to parse and synthesize run paths, freezing the on-disk layout into the public
|
|
64
|
+
* contract). Takes a `RunSummary`/`WorkflowHeader` (anything carrying
|
|
57
65
|
* `runId`). Consumers show or open the returned path; they MUST NOT derive
|
|
58
66
|
* sibling paths from it — the layout may change between versions.
|
|
59
67
|
*/
|
package/state/raw.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Raw file-level primitives shared by the readers (`reads.ts`) and the names
|
|
3
3
|
* index (`names.ts`) — a LEAF under both, so neither re-implements the other
|
|
4
|
-
* to dodge a cycle
|
|
5
|
-
* and dir scan).
|
|
4
|
+
* to dodge a cycle.
|
|
6
5
|
*
|
|
7
6
|
* Fail-soft like the rest of `state/`: both helpers return empty/undefined
|
|
8
7
|
* on any I/O or parse failure, never throw.
|
|
@@ -21,7 +20,7 @@ const FIRST_LINE_MAX = 256 * 1024;
|
|
|
21
20
|
* (open + chunked `readSync` until the first newline), not a whole-file
|
|
22
21
|
* `readFileSync`. `listRuns` calls this once per run file, so enumerating N
|
|
23
22
|
* past runs costs N small reads regardless of how many stage rows each run
|
|
24
|
-
* accumulated
|
|
23
|
+
* accumulated.
|
|
25
24
|
*
|
|
26
25
|
* Returns the parsed value (caller shape-checks it), or `undefined` when the
|
|
27
26
|
* file is missing/empty/unparseable. The newline search is byte-level
|
package/state/resolve.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Run-reference resolution — the one composer that sits ABOVE both the raw
|
|
3
|
-
* readers (`reads.ts`) and the names index (`names.ts`).
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* readers (`reads.ts`) and the names index (`names.ts`). A name-aware
|
|
4
|
+
* resolver doesn't belong in the raw-reads module, and housing it there
|
|
5
|
+
* would force `reads.ts` to import `names.ts`.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { basename } from "node:path";
|