@juicesharp/rpiv-workflow 1.19.0 → 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
package/preview.ts
CHANGED
|
@@ -5,12 +5,21 @@
|
|
|
5
5
|
* string that `command.ts` hands straight to `ctx.ui.notify(..., "info")`.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import
|
|
8
|
+
import { STOP, type StageDef } from "./api.js";
|
|
9
9
|
import { type ConfigLayer, renderConfigLayer } from "./layers.js";
|
|
10
10
|
import type { LoadedWorkflows } from "./load/index.js";
|
|
11
|
-
import {
|
|
11
|
+
import { type AnyJudgeSpec, describeFlow, type StageShape } from "./loop-constructors.js";
|
|
12
12
|
import type { SkillContractMap } from "./skill-contract.js";
|
|
13
13
|
|
|
14
|
+
/** No-args listing footer — generic usage hint. */
|
|
15
|
+
export const CMD_USAGE_LIST = "Usage: /wf [workflow] <description>";
|
|
16
|
+
|
|
17
|
+
/** No-args listing footer — preview-mode hint paired with CMD_USAGE_LIST. */
|
|
18
|
+
export const CMD_USAGE_PREVIEW = "/wf <workflow> — preview stages";
|
|
19
|
+
|
|
20
|
+
/** Per-workflow details footer — narrowed to the workflow the user previewed. */
|
|
21
|
+
export const CMD_USAGE_RUN = (name: string) => `Usage: /wf ${name} <description>`;
|
|
22
|
+
|
|
14
23
|
// ===========================================================================
|
|
15
24
|
// Public formatters
|
|
16
25
|
// ===========================================================================
|
|
@@ -78,8 +87,12 @@ export function formatWorkflowDetails(loaded: LoadedWorkflows, name: string): st
|
|
|
78
87
|
const layer = loaded.workflowSources.get(name) ?? "built-in";
|
|
79
88
|
const heading = formatWorkflowHeading(name, layer, name === loaded.default);
|
|
80
89
|
const descriptionLine = workflow.description ? [workflow.description] : [];
|
|
90
|
+
// Flow facets (loop / verify / edge) come from `describeFlow` — the ONE
|
|
91
|
+
// introspector, so preview never lags a new loop kind. Per-stage knobs
|
|
92
|
+
// (kind, policy, outcome, schemas) are plain field reads off the def.
|
|
93
|
+
const shapeByStage = new Map(describeFlow(workflow).map((shape) => [shape.stage, shape]));
|
|
81
94
|
const stageRows = Object.entries(workflow.stages).map(([stageName, stage], i) =>
|
|
82
|
-
formatStageRow(i + 1, stageName, stage, workflow),
|
|
95
|
+
formatStageRow(i + 1, stageName, stage, shapeByStage.get(stageName)!, stageName in workflow.edges),
|
|
83
96
|
);
|
|
84
97
|
const aliasBanner = formatAliasBanner(loaded.skillAliases);
|
|
85
98
|
|
|
@@ -106,20 +119,27 @@ function formatWorkflowHeading(name: string, layer: ConfigLayer, isDefault: bool
|
|
|
106
119
|
}
|
|
107
120
|
|
|
108
121
|
/** Numbered row showing the stage + its outgoing edge target(s). */
|
|
109
|
-
function formatStageRow(
|
|
122
|
+
function formatStageRow(
|
|
123
|
+
idx: number,
|
|
124
|
+
stageName: string,
|
|
125
|
+
stage: StageDef,
|
|
126
|
+
shape: StageShape,
|
|
127
|
+
edgeDeclared: boolean,
|
|
128
|
+
): string {
|
|
110
129
|
const num = `${idx}.`.padEnd(3);
|
|
111
130
|
const decorations = [stage.kind.padEnd(13), stage.sessionPolicy, outcomeTag(stage)];
|
|
112
131
|
if (stage.inputSchema) decorations.push("in-schema");
|
|
113
132
|
if (stage.outputSchema) decorations.push("out-schema");
|
|
133
|
+
if (shape.control.mode !== "single") decorations.push(loopTag(shape.control));
|
|
134
|
+
if (shape.verify) decorations.push(verifyTag(shape.verify));
|
|
114
135
|
|
|
115
|
-
const displayName =
|
|
116
|
-
const arrow = formatEdge(
|
|
136
|
+
const displayName = shape.skill && shape.skill !== stageName ? `${stageName} (skill: ${shape.skill})` : stageName;
|
|
137
|
+
const arrow = formatEdge(shape.edge, edgeDeclared);
|
|
117
138
|
const trailer = arrow ? ` → ${arrow}` : "";
|
|
118
139
|
|
|
119
140
|
return ` ${num} ${displayName.padEnd(36)} ${decorations.join(" · ")}${trailer}`;
|
|
120
141
|
}
|
|
121
142
|
|
|
122
|
-
/**
|
|
123
143
|
/**
|
|
124
144
|
* Single tag per stage encoding the outcome shape. Custom outcomes
|
|
125
145
|
* report `custom` (+`snapshot` when the collector declares a snapshot
|
|
@@ -139,15 +159,55 @@ function outcomeTag(stage: StageDef): string {
|
|
|
139
159
|
return stage.kind === "produces" ? "???" : "side-effect";
|
|
140
160
|
}
|
|
141
161
|
|
|
142
|
-
/**
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
162
|
+
/**
|
|
163
|
+
* Decoration for a loop stage. Assess keeps its exact pre-redesign strings
|
|
164
|
+
* (`assess(judge: skill:<name>)·max=N`, `assess(judge: prompt)·max=N` — the
|
|
165
|
+
* constructor always sets `max`, defaulting to 8). Fanout/iterate gain tags
|
|
166
|
+
* for the first time: `fanout·max=32`, `iterate·max=32`, or the bare kind
|
|
167
|
+
* when no cap is declared (the run-wide maxIterations still backstops).
|
|
168
|
+
*/
|
|
169
|
+
function loopTag(control: StageShape["control"]): string {
|
|
170
|
+
const spec = control.spec;
|
|
171
|
+
if (!spec) return control.mode;
|
|
172
|
+
if (spec.kind === "assess") {
|
|
173
|
+
const judge = spec.judge ? judgeSlotTag(spec.judge) : "prompt";
|
|
174
|
+
return `assess(judge: ${judge})·max=${spec.max}`;
|
|
175
|
+
}
|
|
176
|
+
return spec.max !== undefined ? `${spec.kind}·max=${spec.max}` : spec.kind;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Render a judge SLOT for a stage tag: `skill:<name>` / `prompt` for a single
|
|
181
|
+
* judge, or `panel(<N>, <fold>)` for an N-member panel (`fold` is the sugar
|
|
182
|
+
* name or `custom`) — the fan-in surfaces at a glance.
|
|
183
|
+
*/
|
|
184
|
+
function judgeSlotTag(spec: AnyJudgeSpec): string {
|
|
185
|
+
if ("panel" in spec) return `panel(${spec.panel.length}, ${spec.fold})`;
|
|
186
|
+
return spec.skill ? `skill:${spec.skill}` : "prompt";
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Decoration for a verify-bearing stage: `verify(skill:<name>)` /
|
|
191
|
+
* `verify(prompt)` / `verify(panel(N, fold))`, with the attempt budget appended
|
|
192
|
+
* when retrying (`·attempts=N`); a gate-only verify (the default, max 1) stays
|
|
193
|
+
* compact.
|
|
194
|
+
*/
|
|
195
|
+
function verifyTag(v: NonNullable<StageShape["verify"]>): string {
|
|
196
|
+
const attempts = v.max > 1 ? `·attempts=${v.max}` : "";
|
|
197
|
+
return `verify(${judgeSlotTag(v)})${attempts}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Render the outgoing edge as a human-readable trailer from the introspected
|
|
202
|
+
* `StageShape.edge`. `describeFlow` collapses "no edge declared" and an
|
|
203
|
+
* explicit `STOP` into one `terminal` mode; the declared-or-not distinction
|
|
204
|
+
* is a one-key lookup the caller supplies (it matters to authors — the
|
|
205
|
+
* validator warns on the undeclared form).
|
|
206
|
+
*/
|
|
207
|
+
function formatEdge(edge: StageShape["edge"], declared: boolean): string | undefined {
|
|
208
|
+
if (edge.mode === "terminal") return declared ? STOP : "(terminal — no edge declared)";
|
|
209
|
+
if (edge.mode === "linear") return edge.targets?.[0];
|
|
210
|
+
return edge.targets?.length ? `predicate(${edge.targets.join(" | ")})` : "predicate";
|
|
151
211
|
}
|
|
152
212
|
|
|
153
213
|
/** "Sources: built-in + user + project" — single-line layer banner. */
|
|
@@ -178,7 +238,7 @@ function formatContractsBanner(contracts: SkillContractMap): string | undefined
|
|
|
178
238
|
let harvested = 0;
|
|
179
239
|
for (const c of contracts.values()) {
|
|
180
240
|
if (c.source === "declared") declared++;
|
|
181
|
-
else
|
|
241
|
+
else harvested++;
|
|
182
242
|
}
|
|
183
243
|
return `Skill contracts: ${declared} declared, ${harvested} harvested`;
|
|
184
244
|
}
|
package/registration.ts
CHANGED
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
|
|
10
10
|
export {
|
|
11
11
|
type ActsScriptFn,
|
|
12
|
+
type AssessLoop,
|
|
12
13
|
acts,
|
|
14
|
+
type CapPolicy,
|
|
13
15
|
type DefineRouteOptions,
|
|
14
16
|
defineRoute,
|
|
15
17
|
defineWorkflow,
|
|
@@ -18,44 +20,57 @@ export {
|
|
|
18
20
|
type EdgeTarget,
|
|
19
21
|
type FanoutContext,
|
|
20
22
|
type FanoutFn,
|
|
21
|
-
type
|
|
23
|
+
type FanoutLoop,
|
|
24
|
+
type FeedForwardContext,
|
|
22
25
|
gate,
|
|
23
26
|
type IterateContext,
|
|
24
27
|
type IterateFn,
|
|
25
|
-
type
|
|
28
|
+
type IterateLoop,
|
|
29
|
+
type JudgedRepetition,
|
|
30
|
+
type LoopDef,
|
|
31
|
+
type MatchOptions,
|
|
32
|
+
type MatchValue,
|
|
26
33
|
marksReadsData,
|
|
34
|
+
match,
|
|
27
35
|
ON_INVALID_VALUES,
|
|
28
36
|
type OnInvalid,
|
|
29
37
|
type ProducesScriptFn,
|
|
30
38
|
type PromptFn,
|
|
39
|
+
type PromptStage,
|
|
31
40
|
produces,
|
|
32
41
|
READS_DATA,
|
|
42
|
+
type ResultProjection,
|
|
33
43
|
type ScriptContext,
|
|
44
|
+
type ScriptStage,
|
|
34
45
|
SESSION_POLICIES,
|
|
35
46
|
type SessionPolicy,
|
|
47
|
+
type SkillStage,
|
|
36
48
|
STAGE_KINDS,
|
|
37
49
|
STOP,
|
|
38
50
|
type StageDef,
|
|
39
51
|
type StageKind,
|
|
40
52
|
type StageSchema,
|
|
41
53
|
terminal,
|
|
54
|
+
type Unit,
|
|
55
|
+
type UnitRole,
|
|
56
|
+
type UnitSelector,
|
|
57
|
+
type VerifySpec,
|
|
42
58
|
type Workflow,
|
|
43
59
|
} from "./api.js";
|
|
44
60
|
export { registerBuiltIns, registerBuiltInsProvider } from "./built-ins.js";
|
|
61
|
+
// The shared dispatch predicate (and SkillStage type guard) — public so
|
|
62
|
+
// extension points that key on a stage's skill identity (outcome derivers,
|
|
63
|
+
// contract tooling) apply the same gate the loader/validator/harvest use.
|
|
64
|
+
export { isDispatchingStage } from "./chain-state.js";
|
|
45
65
|
export {
|
|
46
|
-
type
|
|
47
|
-
|
|
48
|
-
type
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
type
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
type SpeccedFanoutFn,
|
|
55
|
-
type SpeccedIterateFn,
|
|
56
|
-
type StageShape,
|
|
57
|
-
type UnitSelector,
|
|
58
|
-
} from "./control-flow.js";
|
|
66
|
+
type LifecycleContext,
|
|
67
|
+
type LifecycleListeners,
|
|
68
|
+
type LoopCapInfo,
|
|
69
|
+
type LoopStartInfo,
|
|
70
|
+
registerLifecycle,
|
|
71
|
+
type StageRef,
|
|
72
|
+
type UnitEvent,
|
|
73
|
+
} from "./events.js";
|
|
59
74
|
export {
|
|
60
75
|
type Artifact,
|
|
61
76
|
type ArtifactHandle,
|
|
@@ -73,9 +88,50 @@ export type { WorkflowHost, WorkflowHostContext, WorkflowSessionContext } from "
|
|
|
73
88
|
// consumer needs them); internal callers import them from their source modules
|
|
74
89
|
// directly.
|
|
75
90
|
export type { JsonSchemaCapable, JsonSchemaObject } from "./json-schema.js";
|
|
76
|
-
export {
|
|
91
|
+
export {
|
|
92
|
+
type AnyJudge,
|
|
93
|
+
type FoldFn,
|
|
94
|
+
isPanel,
|
|
95
|
+
type Judge,
|
|
96
|
+
type JudgeContext,
|
|
97
|
+
type JudgePromptFn,
|
|
98
|
+
judge,
|
|
99
|
+
judgeShapeIssues,
|
|
100
|
+
type NamedOutcome,
|
|
101
|
+
type PanelJudge,
|
|
102
|
+
type PromptJudge,
|
|
103
|
+
panelMembers,
|
|
104
|
+
type SkillJudge,
|
|
105
|
+
} from "./judge.js";
|
|
77
106
|
export type { ConfigLayer, Issue, LoadedWorkflows, LoadIssue, OverlayPaths } from "./load/index.js";
|
|
78
107
|
export { aliasSkills, loadWorkflows, projectOverlayPaths, userOverlayPaths } from "./load/index.js";
|
|
108
|
+
export {
|
|
109
|
+
type AnyJudgeSpec,
|
|
110
|
+
all,
|
|
111
|
+
any,
|
|
112
|
+
assess,
|
|
113
|
+
DEFAULT_ASSESS_MAX,
|
|
114
|
+
describeFlow,
|
|
115
|
+
fanout,
|
|
116
|
+
iterate,
|
|
117
|
+
type JudgeSpec,
|
|
118
|
+
judgeSlotSpecOf,
|
|
119
|
+
judgeSpecOf,
|
|
120
|
+
type LoopSpec,
|
|
121
|
+
loopSpecOf,
|
|
122
|
+
majority,
|
|
123
|
+
PANEL_VERDICT,
|
|
124
|
+
PANEL_VERDICT_OUTCOME,
|
|
125
|
+
type PanelJudgeSpec,
|
|
126
|
+
type PanelSpec,
|
|
127
|
+
type PanelVerdict,
|
|
128
|
+
panel,
|
|
129
|
+
panelShapeIssues,
|
|
130
|
+
panelSpecOf,
|
|
131
|
+
type StageShape,
|
|
132
|
+
verify,
|
|
133
|
+
verifyShapeIssues,
|
|
134
|
+
} from "./loop-constructors.js";
|
|
79
135
|
export {
|
|
80
136
|
type DirectoryPathCollectorOpts,
|
|
81
137
|
directoryPathCollector,
|
|
@@ -100,21 +156,24 @@ export {
|
|
|
100
156
|
type WorkspaceDiffSnapshot,
|
|
101
157
|
workspaceDiffCollector,
|
|
102
158
|
} from "./outcomes/index.js";
|
|
103
|
-
export type {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
159
|
+
export type { Output, OutputMeta, RunView, Verdict } from "./output.js";
|
|
160
|
+
// Producer-side surface — `output-spec.ts` is the ONE canonical import path
|
|
161
|
+
// for collector/parser/outcome authoring types (`output.ts` keeps only the
|
|
162
|
+
// envelope). `OutputSpec` is the deprecated pre-rename alias of `Outcome`.
|
|
163
|
+
export {
|
|
164
|
+
type ArtifactCollector,
|
|
165
|
+
type ArtifactParser,
|
|
166
|
+
type CollectCtx,
|
|
167
|
+
type CollectResult,
|
|
168
|
+
defineCollector,
|
|
169
|
+
defineParser,
|
|
170
|
+
type Outcome,
|
|
171
|
+
type OutputSpec,
|
|
172
|
+
type ParseCtx,
|
|
173
|
+
type ParseResult,
|
|
174
|
+
type SnapshotCtx,
|
|
175
|
+
} from "./output-spec.js";
|
|
176
|
+
export { eq, gt, gte, lt, lte, type NumericPredicate, type Predicate } from "./predicates.js";
|
|
118
177
|
export type {
|
|
119
178
|
ConsumesReadSpec,
|
|
120
179
|
ConsumesSpec,
|
|
@@ -126,27 +185,42 @@ export type {
|
|
|
126
185
|
} from "./skill-contract.js";
|
|
127
186
|
export {
|
|
128
187
|
canCompose,
|
|
188
|
+
getBucketKindMappings,
|
|
129
189
|
legalNextSkills,
|
|
130
190
|
type OutcomeDeriverFn,
|
|
191
|
+
registerBucketKindMapping,
|
|
131
192
|
registerCompositionComparator,
|
|
132
193
|
registerOutcomeDeriver,
|
|
133
194
|
registerSkillContracts,
|
|
134
195
|
registerSkillContractsProvider,
|
|
135
196
|
} from "./skill-contracts/index.js";
|
|
136
197
|
export {
|
|
198
|
+
type LoopCapRow,
|
|
137
199
|
listArtifacts,
|
|
138
200
|
listRuns,
|
|
139
201
|
type RunSummary,
|
|
140
202
|
readHeader,
|
|
141
203
|
readLastStage,
|
|
204
|
+
readLoopCaps,
|
|
142
205
|
resolveRun,
|
|
143
|
-
|
|
144
|
-
stateFilePath
|
|
206
|
+
// Storage layout stays private: `runFileFor` is the one OPAQUE path
|
|
207
|
+
// projection; `runsDir`/`stateFilePath` moved to the test-only internal
|
|
208
|
+
// subpath so external code can't synthesize layout-coupled paths.
|
|
209
|
+
runFileFor,
|
|
210
|
+
type SessionRef,
|
|
211
|
+
STATE_SCHEMA_VERSION,
|
|
145
212
|
type WorkflowHeader,
|
|
146
213
|
type WorkflowStage,
|
|
147
214
|
} from "./state/index.js";
|
|
148
215
|
export { DEFAULT_TRIGGER, type RunTrigger } from "./triggers.js";
|
|
149
216
|
export { typeboxSchema } from "./typebox-adapter.js";
|
|
150
|
-
|
|
217
|
+
// `RunState` is deliberately NOT here — it became runner-private when user
|
|
218
|
+
// contexts switched to the deep-readonly `RunView` (T3). Test fixtures that
|
|
219
|
+
// must construct one import it from `@juicesharp/rpiv-workflow/internal`.
|
|
220
|
+
export type { RunTermination } from "./types.js";
|
|
151
221
|
export { type SchemaValidationFailure, validateOutputData } from "./validate-output.js";
|
|
152
|
-
export {
|
|
222
|
+
export {
|
|
223
|
+
type ValidationIssueCode,
|
|
224
|
+
validateWorkflow,
|
|
225
|
+
type WorkflowValidationIssue,
|
|
226
|
+
} from "./validate-workflow.js";
|
package/routing-dsl.ts
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The routing DSL — edge vocabulary (`EdgeFn` / `EdgeTarget` / `STOP`) and
|
|
3
|
+
* the route builders (`defineRoute`, `gate`) with their structural markers
|
|
4
|
+
* (`READS_DATA`, `ROUTE_NOTE`). Split out of api.ts: how the graph
|
|
5
|
+
* routes is one concept; what a stage is, is another. Runtime edge
|
|
6
|
+
* EXECUTION lives in routing.ts — this module is authoring-surface only.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Output, RunView } from "./output.js";
|
|
10
|
+
import type { NumericPredicate } from "./predicates.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Runtime context handed to an `EdgeFn`. The sole context shape for both
|
|
14
|
+
* data-reading and state-only routes (the single `defineRoute` path covers
|
|
15
|
+
* both via `opts.readsData`).
|
|
16
|
+
*/
|
|
17
|
+
export interface EdgeContext {
|
|
18
|
+
output: Output | undefined;
|
|
19
|
+
state: RunView;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Body-type alias for hand-rolled route picks. Internal — users wrap via
|
|
24
|
+
* `defineRoute`, which returns an `EdgeFn` (this alias plus a `.targets`
|
|
25
|
+
* field).
|
|
26
|
+
*/
|
|
27
|
+
type EdgePredicate = (ctx: EdgeContext) => string;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A function that picks the next stage name given current state + output.
|
|
31
|
+
* Optional `targets` field lets graph introspectors enumerate possible
|
|
32
|
+
* returns — `gate` and other built-in route builders populate it.
|
|
33
|
+
*/
|
|
34
|
+
export type EdgeFn = EdgePredicate & { targets?: readonly string[] };
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Terminal edge sentinel. Single source of truth for the `"stop"` literal
|
|
38
|
+
* embedded in `EdgeTarget`; `validate-workflow.ts` + `routing.ts` import this rather
|
|
39
|
+
* than re-declaring the string.
|
|
40
|
+
*/
|
|
41
|
+
export const STOP = "stop" as const;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* What an `edges` entry resolves to: another stage name (auto-edge), the
|
|
45
|
+
* terminal sentinel `STOP`, or a function chosen at run-time.
|
|
46
|
+
*/
|
|
47
|
+
export type EdgeTarget = string | typeof STOP | EdgeFn;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Marker attached to EdgeFns that read from `output.data`.
|
|
51
|
+
* `validate-workflow.ts:checkPredicateSchemas` warns when a stage feeds a
|
|
52
|
+
* marked route but has no `outputSchema` — routing on un-validated data
|
|
53
|
+
* is a defect.
|
|
54
|
+
*
|
|
55
|
+
* Default is "marked": `defineRoute(targets, fn)` auto-marks. Opt out by
|
|
56
|
+
* passing `{ readsData: false }` for the rare route that consults only
|
|
57
|
+
* `state` or `output.meta`.
|
|
58
|
+
*
|
|
59
|
+
* Exported as a `Symbol.for` so it survives `import` boundaries cleanly.
|
|
60
|
+
*/
|
|
61
|
+
export const READS_DATA: unique symbol = Symbol.for("rpiv.workflow.readsData");
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* True iff `fn` was wrapped by `defineRoute(...)` with the data-reading
|
|
65
|
+
* marker attached (the default; opt out via `{ readsData: false }`). The
|
|
66
|
+
* validator uses this to decide whether an `EdgeFn`'s source stage must
|
|
67
|
+
* declare an `outputSchema` — data-reading routes need a validated output
|
|
68
|
+
* shape; state-only routes don't.
|
|
69
|
+
*
|
|
70
|
+
* Centralises the double-cast required to symbol-key into a function object
|
|
71
|
+
* so consumers don't sprinkle `as unknown as Record<symbol, …>` at every
|
|
72
|
+
* read site.
|
|
73
|
+
*/
|
|
74
|
+
export function marksReadsData(fn: EdgeFn): boolean {
|
|
75
|
+
return Boolean((fn as unknown as Record<symbol, boolean>)[READS_DATA]);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Options for `defineRoute`. */
|
|
79
|
+
export interface DefineRouteOptions {
|
|
80
|
+
/**
|
|
81
|
+
* Whether the route reads `output.data` (the default). Set to `false` for
|
|
82
|
+
* routes that consult only `state` or `output.meta` so the load-time
|
|
83
|
+
* outputSchema lint doesn't warn the source stage lacks an
|
|
84
|
+
* `outputSchema` (a state-derived route has no data-shape contract to
|
|
85
|
+
* validate).
|
|
86
|
+
*/
|
|
87
|
+
readsData?: boolean;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Promote a hand-rolled `EdgePredicate` to an `EdgeFn` by structurally
|
|
92
|
+
* attaching the set of possible returns. `validate-workflow.ts` requires every
|
|
93
|
+
* EdgeFn to carry `.targets` so reachability and load-time edge-target
|
|
94
|
+
* checks see every branch; this factory is the only blessed way to author
|
|
95
|
+
* a multi-branch route.
|
|
96
|
+
*
|
|
97
|
+
* Auto-marks the returned EdgeFn with `READS_DATA` so the outputSchema lint
|
|
98
|
+
* fires when the source stage has no `outputSchema`. If the route consults
|
|
99
|
+
* only `state` / `output.meta` and never reads `output.data`, pass
|
|
100
|
+
* `{ readsData: false }` to suppress the lint.
|
|
101
|
+
*
|
|
102
|
+
* Throws if `targets` is empty — a route that can't return anything
|
|
103
|
+
* declared is by definition a bug.
|
|
104
|
+
*/
|
|
105
|
+
export function defineRoute(targets: readonly string[], fn: EdgePredicate, opts?: DefineRouteOptions): EdgeFn {
|
|
106
|
+
if (targets.length === 0) {
|
|
107
|
+
throw new Error("defineRoute: targets must declare at least one possible return value");
|
|
108
|
+
}
|
|
109
|
+
// Fresh delegating wrapper — NEVER mutate the caller's function. Reusing
|
|
110
|
+
// one predicate across two defineRoute calls must not alias their targets
|
|
111
|
+
// (the second call would overwrite the first's), and `readsData: false`
|
|
112
|
+
// must not inherit a marker a prior call attached.
|
|
113
|
+
const wrapped: EdgeFn = (ctx) => fn(ctx);
|
|
114
|
+
wrapped.targets = [...targets];
|
|
115
|
+
if (opts?.readsData !== false) (wrapped as unknown as Record<symbol, boolean>)[READS_DATA] = true;
|
|
116
|
+
return wrapped;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Symbol under which an `EdgeFn` records a note about its most recent pick —
|
|
121
|
+
* today: `gate`'s "no branch matched, fallback fired" diagnostic. The runner's
|
|
122
|
+
* routing audit reads-and-clears it via `takeRouteNote` right after invoking
|
|
123
|
+
* the edge (same tick — single-threaded, no other decision can interleave)
|
|
124
|
+
* and persists it on the `RoutingDecision` row's `note`.
|
|
125
|
+
*
|
|
126
|
+
* Framework plumbing, not authoring surface — NOT re-exported from
|
|
127
|
+
* `registration.ts`. `Symbol.for` so it survives import boundaries, matching
|
|
128
|
+
* `READS_DATA`.
|
|
129
|
+
*/
|
|
130
|
+
export const ROUTE_NOTE: unique symbol = Symbol.for("rpiv.workflow.routeNote");
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Read-and-clear the note an `EdgeFn` attached to its most recent invocation.
|
|
134
|
+
* Returns undefined when the edge recorded nothing (the common case).
|
|
135
|
+
*/
|
|
136
|
+
export function takeRouteNote(fn: EdgeFn): string | undefined {
|
|
137
|
+
const slot = fn as unknown as Record<symbol, string | undefined>;
|
|
138
|
+
const note = slot[ROUTE_NOTE];
|
|
139
|
+
if (note !== undefined) slot[ROUTE_NOTE] = undefined;
|
|
140
|
+
return note;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Matches the keys JS engines hoist and reorder ahead of string keys
|
|
145
|
+
* (canonical array indices). `gate` evaluates branches in declaration order,
|
|
146
|
+
* so an integer-like stage name would silently change match priority.
|
|
147
|
+
*/
|
|
148
|
+
const INTEGER_LIKE_KEY = /^\d+$/;
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Conditional routing keyed on a numeric field in `output.data`. Each
|
|
152
|
+
* branch's predicate is evaluated against `Number(output.data[field])` in
|
|
153
|
+
* declaration order; the first matching branch wins. When no predicate
|
|
154
|
+
* matches (including a missing or non-numeric field, which coerces to `NaN`),
|
|
155
|
+
* the EXPLICIT `otherwise` branch is taken and the routing-audit row carries
|
|
156
|
+
* a `note` saying the fallback fired — no-match is a visible event, not a
|
|
157
|
+
* silent property of declaration order.
|
|
158
|
+
*
|
|
159
|
+
* ```ts
|
|
160
|
+
* gate("blockers_count", { revise: gt(0), commit: eq(0) }, "commit")
|
|
161
|
+
* // value > 0 → "revise"
|
|
162
|
+
* // value = 0 → "commit"
|
|
163
|
+
* // value < 0, missing, NaN → "commit" (otherwise; audit row notes the fallback)
|
|
164
|
+
* ```
|
|
165
|
+
*
|
|
166
|
+
* Branch keys must not be integer-like (`"2"`): JS object literals hoist
|
|
167
|
+
* array-index keys ahead of declaration order, which would silently reorder
|
|
168
|
+
* match priority — rejected at construction.
|
|
169
|
+
*
|
|
170
|
+
* Built on `defineRoute` so the `.targets` metadata is attached structurally
|
|
171
|
+
* (the `otherwise` target included) and the `READS_DATA` marker auto-applies
|
|
172
|
+
* (routing reads `output.data`).
|
|
173
|
+
*/
|
|
174
|
+
export function gate(field: string, branches: Record<string, NumericPredicate>, otherwise: string): EdgeFn {
|
|
175
|
+
const branchTargets = Object.keys(branches);
|
|
176
|
+
if (branchTargets.length === 0) {
|
|
177
|
+
throw new Error("gate: branches must declare at least one possible return value");
|
|
178
|
+
}
|
|
179
|
+
if (typeof otherwise !== "string" || otherwise.length === 0) {
|
|
180
|
+
throw new Error("gate: an explicit `otherwise` branch is required — the no-match fallback must be deliberate");
|
|
181
|
+
}
|
|
182
|
+
for (const key of branchTargets) {
|
|
183
|
+
if (INTEGER_LIKE_KEY.test(key)) {
|
|
184
|
+
throw new Error(
|
|
185
|
+
`gate: branch key "${key}" is integer-like — JS reorders such keys ahead of declaration order, ` +
|
|
186
|
+
`silently changing match priority. Rename the stage or route to it via \`otherwise\`.`,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const targets = [...new Set([...branchTargets, otherwise])];
|
|
191
|
+
const route: EdgeFn = defineRoute(targets, ({ output }) => {
|
|
192
|
+
const value = Number((output?.data as Record<string, unknown> | undefined)?.[field]);
|
|
193
|
+
for (const target of branchTargets) {
|
|
194
|
+
if (branches[target]!(value)) return target;
|
|
195
|
+
}
|
|
196
|
+
(route as unknown as Record<symbol, string>)[ROUTE_NOTE] =
|
|
197
|
+
`gate("${field}"): no branch matched value ${value} — fell back to "${otherwise}"`;
|
|
198
|
+
return otherwise;
|
|
199
|
+
});
|
|
200
|
+
return route;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** A discrete value a `match` branch compares its field against (strict `===`). */
|
|
204
|
+
export type MatchValue = string | number | boolean;
|
|
205
|
+
|
|
206
|
+
/** Options for `match`. */
|
|
207
|
+
export interface MatchOptions {
|
|
208
|
+
/**
|
|
209
|
+
* Stage to route to when no branch value matches. Optional: when omitted, an
|
|
210
|
+
* unmatched value TERMINATES the chain (`STOP`). Either way the no-match is a
|
|
211
|
+
* visible event — the routing-audit row carries a `note`. Provide a fallback
|
|
212
|
+
* to keep the run going on an unexpected value (the roadmap-P4 `triage` shape).
|
|
213
|
+
*/
|
|
214
|
+
fallback?: string;
|
|
215
|
+
/**
|
|
216
|
+
* Read the matched field from a NAMED CHANNEL's latest output
|
|
217
|
+
* (`state.named[from].at(-1).data[field]`) instead of the stage's projected
|
|
218
|
+
* `output.data`. This is how a `match` routes on a panel's PUBLISHED verdict
|
|
219
|
+
* (the `<stage>-panel` channel) — the fold lands on a channel, never on the
|
|
220
|
+
* stage's projected output (which stays the producer artifact). A
|
|
221
|
+
* channel-sourced route validates the channel's data, not the source stage's
|
|
222
|
+
* output, so it does NOT mark the source stage `READS_DATA`.
|
|
223
|
+
*/
|
|
224
|
+
from?: string;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Conditional routing keyed on an ENUM field — the string/boolean companion to
|
|
229
|
+
* the numeric `gate`. Each branch maps a target stage to the discrete value that
|
|
230
|
+
* routes to it; the field is compared by strict `===` in declaration order and
|
|
231
|
+
* the first match wins:
|
|
232
|
+
*
|
|
233
|
+
* ```ts
|
|
234
|
+
* match("severity", { escalate: "p0", fix: "p1", backlog: "p2" })
|
|
235
|
+
* match("tie", { escalate: true }, { fallback: "keep", from: "review-panel" })
|
|
236
|
+
* ```
|
|
237
|
+
*
|
|
238
|
+
* Sourcing (`opts.from`) lets a `match` branch on a panel's published verdict —
|
|
239
|
+
* `match("tie", …, { from: "<stage>-panel" })` reads the folded `PANEL_VERDICT`
|
|
240
|
+
* off its channel, the disagreement-routing companion to `panel()`.
|
|
241
|
+
*
|
|
242
|
+
* No-match handling is EXPLICIT, never silent: with an `opts.fallback` the
|
|
243
|
+
* unmatched value routes there; without one it terminates (`STOP`). Both record
|
|
244
|
+
* a routing-audit `note`.
|
|
245
|
+
*
|
|
246
|
+
* Each enum value must map to exactly one stage (a duplicate value is ambiguous
|
|
247
|
+
* → construction error), and branch keys must not be integer-like (`"2"`) — JS
|
|
248
|
+
* hoists array-index keys ahead of declaration order, silently reordering match
|
|
249
|
+
* priority. Built on `defineRoute`, so `.targets` is attached structurally
|
|
250
|
+
* (reachability BFS sees every branch incl. the fallback) and `READS_DATA`
|
|
251
|
+
* auto-applies (unless `from` sources a channel instead of the stage output).
|
|
252
|
+
*/
|
|
253
|
+
export function match(field: string, branches: Record<string, MatchValue>, opts?: MatchOptions): EdgeFn {
|
|
254
|
+
const branchTargets = Object.keys(branches);
|
|
255
|
+
if (branchTargets.length === 0) {
|
|
256
|
+
throw new Error("match: branches must declare at least one possible return value");
|
|
257
|
+
}
|
|
258
|
+
const claimedBy = new Map<string, string>();
|
|
259
|
+
for (const key of branchTargets) {
|
|
260
|
+
if (INTEGER_LIKE_KEY.test(key)) {
|
|
261
|
+
throw new Error(
|
|
262
|
+
`match: branch key "${key}" is integer-like — JS reorders such keys ahead of declaration order, ` +
|
|
263
|
+
`silently changing match priority. Rename the stage.`,
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
// Type-tag the value so 0/"0"/false stay distinct when deduping.
|
|
267
|
+
const value = branches[key]!;
|
|
268
|
+
const valueKey = `${typeof value}:${String(value)}`;
|
|
269
|
+
const prior = claimedBy.get(valueKey);
|
|
270
|
+
if (prior !== undefined) {
|
|
271
|
+
throw new Error(
|
|
272
|
+
`match: value ${JSON.stringify(value)} is claimed by both "${prior}" and "${key}" — ` +
|
|
273
|
+
`each enum value must map to exactly one stage`,
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
claimedBy.set(valueKey, key);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const fallback = opts?.fallback;
|
|
280
|
+
if (fallback !== undefined && (typeof fallback !== "string" || fallback.length === 0)) {
|
|
281
|
+
throw new Error("match: `fallback`, when provided, must be a non-empty stage name");
|
|
282
|
+
}
|
|
283
|
+
const noMatch = fallback ?? STOP;
|
|
284
|
+
const targets = [...new Set([...branchTargets, noMatch])];
|
|
285
|
+
|
|
286
|
+
const from = opts?.from;
|
|
287
|
+
const route: EdgeFn = defineRoute(
|
|
288
|
+
targets,
|
|
289
|
+
({ output, state }) => {
|
|
290
|
+
const source =
|
|
291
|
+
from !== undefined
|
|
292
|
+
? (state.named[from]?.at(-1)?.data as Record<string, unknown> | undefined)
|
|
293
|
+
: (output?.data as Record<string, unknown> | undefined);
|
|
294
|
+
const raw = source?.[field];
|
|
295
|
+
for (const target of branchTargets) {
|
|
296
|
+
if (raw === branches[target]) return target;
|
|
297
|
+
}
|
|
298
|
+
(route as unknown as Record<symbol, string>)[ROUTE_NOTE] =
|
|
299
|
+
`match("${field}"): value ${JSON.stringify(raw ?? null)} matched no branch — ${
|
|
300
|
+
fallback ? `fell back to "${fallback}"` : `terminated (no fallback)`
|
|
301
|
+
}`;
|
|
302
|
+
return noMatch;
|
|
303
|
+
},
|
|
304
|
+
// A channel-sourced match validates the CHANNEL's data, not the source
|
|
305
|
+
// stage's projected output — so don't demand the source stage carry an
|
|
306
|
+
// outputSchema. A stage-output match reads `output.data` (default mark).
|
|
307
|
+
from !== undefined ? { readsData: false } : undefined,
|
|
308
|
+
);
|
|
309
|
+
return route;
|
|
310
|
+
}
|