@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.
Files changed (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Contract / schema compatibility checks — the validator's only modules that
3
+ * reach into the skill-contract domain (`adjudicateChannel`,
4
+ * `compareDataChannel`, comparator registry) and the JSON-Schema bridge.
5
+ * Kept apart from `stage-rules.ts` because the dependency footprint is
6
+ * entirely different: these checks need the effective contract registry; the
7
+ * stage rules need only the stage records.
8
+ *
9
+ * Enforcement layers (where each contract channel is adjudicated):
10
+ * - reads / wiring → LOAD-TIME, complete (`checkReadsChannelCompat`, all
11
+ * publishers, errors on signed mismatch — all stage kinds).
12
+ * - linear `data` + `status` → RUNTIME (`ensureContractInputValid`).
13
+ * - produces self-check → PRODUCE-TIME (`extraction.ts:effectiveOutputSchema`).
14
+ *
15
+ * Per-stage schema fallback (DECIDED, D4): when a stage carries no contract,
16
+ * `checkEdgeSchemaCompat` falls back to the stage's own
17
+ * `outputSchema`/`inputSchema`. That fallback lives HERE, not in harvest:
18
+ * harvest derives per-SKILL contracts from dispatching stages only
19
+ * (last-writer-wins per skill), while this check is edge-local and must also
20
+ * cover non-dispatching (script/prompt) stages and direct `validateWorkflow`
21
+ * calls that pass no contracts at all.
22
+ */
23
+
24
+ import { marksReadsData, STOP, type Workflow } from "../api.js";
25
+ import { isDispatchingStage, resolvePublishName, resolveSkill } from "../chain-state.js";
26
+ import { extractJsonSchema } from "../json-schema.js";
27
+ import { judgeOf } from "../loop-constructors.js";
28
+ import type { ProducesSpec, SkillContractMap } from "../skill-contract.js";
29
+ import { adjudicateChannel, compareDataChannel, getCompositionComparators } from "../skill-contracts/index.js";
30
+ import type { IssueReporter } from "./issue.js";
31
+
32
+ /**
33
+ * Route edges that read `output.data[field]` (i.e. `defineRoute(...)` with
34
+ * the default `readsData: true`, `gate(...)`, and any future factory that
35
+ * auto-attaches the `READS_DATA` marker) should fire on data the source
36
+ * stage has validated against its `outputSchema`. If the schema is absent,
37
+ * the validation-retry loop never runs and the route may read an undefined
38
+ * field — routing decisions silently default.
39
+ *
40
+ * A stage carrying no `outputSchema` is still covered when its dispatched
41
+ * skill declares a contract `produces.data` — output validation sources that
42
+ * schema at runtime (`effectiveOutputSchema` in extraction.ts), so the route
43
+ * fires on validated data. Such stages are exempt from this lint.
44
+ *
45
+ * Routes authored via `defineRoute(targets, fn, { readsData: false })`
46
+ * consult only `state` or `output.meta` and carry no marker — exempt from
47
+ * this lint.
48
+ */
49
+ export function checkPredicateSchemas(
50
+ w: Workflow,
51
+ r: IssueReporter,
52
+ skillContracts: SkillContractMap | undefined,
53
+ ): void {
54
+ for (const [from, target] of Object.entries(w.edges)) {
55
+ if (typeof target === "string") continue;
56
+ if (!marksReadsData(target)) continue;
57
+ const stage = w.stages[from];
58
+ if (!stage || stage.outputSchema) continue;
59
+ // Contract-sourced output schema covers the stage like its own `outputSchema`
60
+ // would — mirror `effectiveOutputSchema`'s fallback (same `resolveSkill` key).
61
+ // Only DISPATCHING stages have a skill identity: a script/prompt stage whose
62
+ // record key matches a registered skill must not inherit its contract.
63
+ const contractData = isDispatchingStage(stage)
64
+ ? skillContracts?.get(resolveSkill(stage, from))?.produces?.data
65
+ : undefined;
66
+ if (contractData) continue;
67
+ r.forStage(from)("route-reads-unvalidated-data");
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Load-time compat for the LINEAR `data` channel: for each string edge from→to,
73
+ * compare the producer's `produces.data` to the consumer's `consumes.data`
74
+ * (registry-sourced, falling back to the stage's own output/input schema — see
75
+ * the module header for why the fallback lives here). Warns on a definite
76
+ * mismatch; degrades on predicate/STOP edges and opaque schemas via the shared
77
+ * `compareDataChannel` core (same engine `canCompose` consults — D4).
78
+ *
79
+ * Edge-local is correct here — the rolling primary flows along edges. The
80
+ * many-to-one NAMED (`reads`) channel is handled by `checkReadsChannelCompat`.
81
+ * Runtime mirror: `ensureContractInputValid`.
82
+ */
83
+ export function checkEdgeSchemaCompat(
84
+ w: Workflow,
85
+ r: IssueReporter,
86
+ skillContracts: SkillContractMap | undefined,
87
+ ): void {
88
+ for (const [from, target] of Object.entries(w.edges)) {
89
+ if (typeof target !== "string" || target === STOP) continue; // degrade on predicate/STOP edges
90
+ const fromStage = w.stages[from];
91
+ const toStage = w.stages[target];
92
+ if (!fromStage || !toStage) continue; // unknown stages already reported by edge-target checks
93
+ // Contract lookups only for DISPATCHING stages (script/prompt stages have
94
+ // no skill identity); their own output/input schemas still participate.
95
+ const producerContract = isDispatchingStage(fromStage)
96
+ ? skillContracts?.get(resolveSkill(fromStage, from))
97
+ : undefined;
98
+ const consumerContract = isDispatchingStage(toStage)
99
+ ? skillContracts?.get(resolveSkill(toStage, target))
100
+ : undefined;
101
+
102
+ const producer = producerContract?.produces?.data ?? extractJsonSchema(fromStage.outputSchema);
103
+ const consumer = consumerContract?.consumes?.data ?? extractJsonSchema(toStage.inputSchema);
104
+ const compat = compareDataChannel(producer, consumer);
105
+ if (!compat.ok) {
106
+ r.forStage(from)("edge-schema-incompatible", { to: target, reason: compat.reason ?? "provably incompatible" });
107
+ }
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Load-time named-channel (`reads`) compat — the COMPLETE authoring gate for
113
+ * `reads:` wiring. For each consumer with `consumes.reads`, adjudicate
114
+ * against EVERY `produces` stage that publishes the channel
115
+ * (`resolvePublishName === channel`), not just the edge predecessor — named
116
+ * channels are many-to-one (loop-backs, non-adjacent producers). The publisher
117
+ * set is statically computable.
118
+ *
119
+ * ERRORS on a clean comparator incompatibility between two SIGNED contracts —
120
+ * the "mechanically reject invalid wirings" guarantee, uniform across all stage
121
+ * kinds, which is why no runtime reads gate is needed. Degrades (never errors)
122
+ * when either side is unsigned or the shared `adjudicateChannel` gate skips
123
+ * (no comparator registered, or the consumer declares no `meta` requirement
124
+ * for the channel); a comparator throw surfaces as a WARNING (author defect —
125
+ * matching the deriver/provider precedent) rather than silently disabling the
126
+ * gate. "No publisher at all" is `checkReadsReferences`'s job, not this one's.
127
+ */
128
+ export function checkReadsChannelCompat(
129
+ w: Workflow,
130
+ r: IssueReporter,
131
+ skillContracts: SkillContractMap | undefined,
132
+ ): void {
133
+ if (!skillContracts) return;
134
+ const comparators = getCompositionComparators();
135
+ if (comparators.size === 0) return; // no adjudicators registered
136
+
137
+ // Index signed publishers by channel. `kind === "produces"` mirrors the
138
+ // runtime publish rule (`applyCompletedStage`).
139
+ const publishersByChannel = new Map<string, Array<{ stage: string; produces: ProducesSpec }>>();
140
+ const indexPublisher = (channel: string, stage: string, produces: ProducesSpec): void => {
141
+ const list = publishersByChannel.get(channel);
142
+ if (list) list.push({ stage, produces });
143
+ else publishersByChannel.set(channel, [{ stage, produces }]);
144
+ };
145
+ for (const [name, stage] of Object.entries(w.stages)) {
146
+ // Only DISPATCHING produces stages have a skill identity to sign with —
147
+ // a script/prompt stage named after a registered skill must not become
148
+ // a phantom signed publisher.
149
+ if (stage.kind === "produces" && isDispatchingStage(stage)) {
150
+ const produces = skillContracts.get(resolveSkill(stage, name))?.produces;
151
+ if (produces) indexPublisher(resolvePublishName(stage, name), name, produces);
152
+ }
153
+ // A skill judge is a publisher of its verdict channel; unsigned judges degrade.
154
+ const judge = judgeOf(stage);
155
+ if (judge?.skill && judge.outcome?.name) {
156
+ const produces = skillContracts.get(judge.skill)?.produces;
157
+ if (produces) indexPublisher(judge.outcome.name, name, produces);
158
+ }
159
+ }
160
+
161
+ for (const [consumerName, consumer] of Object.entries(w.stages)) {
162
+ if (!consumer.reads?.length) continue;
163
+ // Same dispatching gate as the publisher index — a non-dispatching
164
+ // consumer is unsigned by definition.
165
+ const consumes = isDispatchingStage(consumer)
166
+ ? skillContracts.get(resolveSkill(consumer, consumerName))?.consumes
167
+ : undefined;
168
+ if (!consumes?.reads) continue; // unsigned consumer — degrade
169
+ const report = r.forStage(consumerName);
170
+ for (const channel of consumer.reads) {
171
+ const publishers = publishersByChannel.get(channel);
172
+ if (!publishers) continue; // "no publisher at all" is checkReadsReferences's job
173
+ for (const { stage: producerName, produces } of publishers) {
174
+ // THE shared adjudication rule (`adjudicateChannel`) — same gating and
175
+ // degrade posture as `canCompose`, so the adviser and this load gate
176
+ // can never disagree about one producer/consumer pair.
177
+ const verdict = adjudicateChannel(produces, consumes, channel, comparators);
178
+ if (verdict.kind === "ok" || verdict.kind === "skipped") continue;
179
+ if (verdict.kind === "comparator-threw") {
180
+ // Author-defect in the comparator: surfaced (matching the
181
+ // deriver/provider precedent), never silently disabling the gate.
182
+ report("reads-comparator-threw", { channel, producer: producerName, error: verdict.error });
183
+ continue;
184
+ }
185
+ report("reads-channel-incompatible", {
186
+ channel,
187
+ producer: producerName,
188
+ reason: verdict.reason ?? "named-channel meta incompatibility",
189
+ });
190
+ }
191
+ }
192
+ }
193
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Graph-topology checks — the workflow as a directed graph, nothing about
3
+ * what individual stages mean (that's `stage-rules.ts`) or whether contracts
4
+ * compose (`contract-compat.ts`).
5
+ *
6
+ * Covers: workflow name, start-stage existence, edge keys/targets, implicit
7
+ * terminals, reachability. The edge-target check also emits
8
+ * `edge-fn-no-targets` for hand-rolled EdgeFns missing `.targets` metadata;
9
+ * the orchestrator gates `checkReachability` on that code's presence (a BFS
10
+ * over unenumerable edges would emit "unreachable" cascades whose root cause
11
+ * is the metadata error already reported).
12
+ */
13
+
14
+ import { type EdgeTarget, STOP, type Workflow } from "../api.js";
15
+ import type { IssueReporter } from "./issue.js";
16
+
17
+ /** `name` is what users type as `/wf <name>` — empty string makes the workflow unreachable. */
18
+ export function checkWorkflowName(w: Workflow, r: IssueReporter): void {
19
+ if (typeof w.name !== "string" || w.name.length === 0) {
20
+ r.report("workflow-name-invalid");
21
+ }
22
+ }
23
+
24
+ export function checkStartStage(w: Workflow, r: IssueReporter): void {
25
+ if (!w.stages[w.start]) {
26
+ r.report("start-stage-missing", { start: w.start });
27
+ }
28
+ }
29
+
30
+ /** Every key in `edges` must be a declared stage. */
31
+ export function checkEdgeKeys(w: Workflow, r: IssueReporter): void {
32
+ for (const from of Object.keys(w.edges)) {
33
+ if (!w.stages[from]) {
34
+ r.forStage(from)("edge-key-unknown", { from });
35
+ }
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Every edge target must resolve to a declared stage or the `"stop"` sentinel.
41
+ * String targets are checked directly. `EdgeFn` targets are checked via the
42
+ * paired `checkEdgeFnTargets` (emits `edge-fn-no-targets`) and enumerated via
43
+ * the pure `enumerateTargets`.
44
+ */
45
+ export function checkEdgeTargets(w: Workflow, r: IssueReporter): void {
46
+ for (const [from, target] of Object.entries(w.edges)) {
47
+ checkEdgeFnTargets(target, from, r);
48
+ for (const candidate of enumerateTargets(target)) {
49
+ if (candidate === STOP) continue;
50
+ if (!w.stages[candidate]) {
51
+ r.forStage(from)("edge-target-unknown", { from, target: candidate });
52
+ }
53
+ }
54
+ }
55
+ }
56
+
57
+ /** Stages with no outgoing edge are implicit terminals — usually a missing connection. */
58
+ export function checkMissingEdges(w: Workflow, r: IssueReporter): void {
59
+ for (const name of Object.keys(w.stages)) {
60
+ if (!(name in w.edges)) {
61
+ r.forStage(name)("edge-missing", { stage: name });
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * BFS from `start`; every declared stage should be reachable. Orphans aren't
68
+ * a runner error (they can't fire) but they're almost always a mistake worth
69
+ * surfacing.
70
+ */
71
+ export function checkReachability(w: Workflow, r: IssueReporter): void {
72
+ if (!w.stages[w.start]) return; // already reported by checkStartStage
73
+
74
+ const reachable = new Set<string>();
75
+ const frontier: string[] = [w.start];
76
+ while (frontier.length > 0) {
77
+ const cur = frontier.shift()!;
78
+ if (reachable.has(cur)) continue;
79
+ reachable.add(cur);
80
+
81
+ const target = w.edges[cur];
82
+ if (target === undefined || target === STOP) continue;
83
+
84
+ for (const next of enumerateTargets(target)) {
85
+ if (next !== STOP && w.stages[next] && !reachable.has(next)) frontier.push(next);
86
+ }
87
+ }
88
+
89
+ for (const name of Object.keys(w.stages)) {
90
+ if (!reachable.has(name)) {
91
+ r.forStage(name)("stage-unreachable", { start: w.start });
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Returns the set of possible string targets an `EdgeTarget` could resolve to.
98
+ * Pure — no issue emission.
99
+ *
100
+ * - String → singleton.
101
+ * - `EdgeFn` with `.targets` metadata → declared targets.
102
+ * - `EdgeFn` without `.targets` → empty list. The missing-metadata error is
103
+ * the responsibility of `checkEdgeFnTargets` (paired emit-only function);
104
+ * call it alongside `enumerateTargets` only at sites that lint edges
105
+ * (currently `checkEdgeTargets`). Reachability traversal calls only the
106
+ * pure form.
107
+ */
108
+ function enumerateTargets(target: EdgeTarget): string[] {
109
+ if (typeof target === "string") return [target];
110
+ if (Array.isArray(target.targets) && target.targets.length > 0) return [...target.targets];
111
+ return [];
112
+ }
113
+
114
+ /**
115
+ * Emits `edge-fn-no-targets` for an `EdgeTarget` that's a hand-rolled
116
+ * `EdgeFn` lacking the marker. Pairs with `enumerateTargets`: lint sites
117
+ * call both; reachability calls only the enumerator. Users authoring routes
118
+ * by hand MUST go through `defineRoute(targets, fn)` so the `.targets`
119
+ * metadata is structurally attached.
120
+ */
121
+ function checkEdgeFnTargets(target: EdgeTarget, from: string, r: IssueReporter): void {
122
+ if (typeof target === "string") return;
123
+ if (Array.isArray(target.targets) && target.targets.length > 0) return;
124
+ r.forStage(from)("edge-fn-no-targets", { from });
125
+ }
@@ -0,0 +1,314 @@
1
+ /**
2
+ * The validation issue model — machine-readable codes, structured params,
3
+ * ONE renderer.
4
+ *
5
+ * Every rule the validator enforces has exactly one entry in `ISSUE_DEFS`:
6
+ * its severity (a property of the RULE, not the call site — so severity can
7
+ * never drift between two emissions of the same rule) and its message
8
+ * template. Checks report `(code, params)` through an `IssueReporter`; the
9
+ * reporter renders the prose once, here. Consumers filter/assert on `code`
10
+ * — never on message text (the message-regex control flow this replaces was
11
+ * finding C5).
12
+ *
13
+ * Messages NEVER embed the stage name — `stage` is carried structurally on
14
+ * the issue and display renderers compose the attribution
15
+ * (`[layer] workflow "X" — stage "Y": …`, see `command-run.ts`). Params that
16
+ * name OTHER entities (an edge's target, a publisher stage, a channel) do
17
+ * appear in the prose — they're content, not attribution.
18
+ *
19
+ * Leaf module: no imports from the rest of the package (rule inputs that
20
+ * come from domain tables — enum lists, bounds — arrive pre-rendered as
21
+ * params, keeping this file dependency-free).
22
+ */
23
+
24
+ // ===========================================================================
25
+ // Issue defs — one row per rule: severity + message template
26
+ // ===========================================================================
27
+
28
+ type IssueParams = Record<string, string | number>;
29
+
30
+ interface IssueSpec<P extends IssueParams> {
31
+ severity: "error" | "warning";
32
+ render: (params: P) => string;
33
+ }
34
+
35
+ /**
36
+ * Binds the param shape to the template so `report(code, params)` is
37
+ * compile-checked. The zero-param overload pins `P` to the empty record —
38
+ * without it, inference collapses `P` to `never` and every call site would
39
+ * demand a (useless) params argument.
40
+ */
41
+ function def(severity: "error" | "warning", render: () => string): IssueSpec<Record<never, never>>;
42
+ function def<P extends IssueParams>(severity: "error" | "warning", render: (params: P) => string): IssueSpec<P>;
43
+ function def(severity: "error" | "warning", render: (params: IssueParams) => string): IssueSpec<IssueParams> {
44
+ return { severity, render };
45
+ }
46
+
47
+ export const ISSUE_DEFS = {
48
+ // --- workflow / graph topology -----------------------------------------
49
+ "workflow-name-invalid": def("error", () => "workflow name must be a non-empty string"),
50
+ "start-stage-missing": def<{ start: string }>("error", (p) => `start stage "${p.start}" is not declared in stages`),
51
+ "edge-key-unknown": def<{ from: string }>(
52
+ "error",
53
+ (p) => `edges["${p.from}"] references a stage that's not declared in stages`,
54
+ ),
55
+ "edge-target-unknown": def<{ from: string; target: string }>(
56
+ "error",
57
+ (p) => `edges["${p.from}"] resolves to "${p.target}" which is not declared in stages`,
58
+ ),
59
+ "edge-fn-no-targets": def<{ from: string }>(
60
+ "error",
61
+ (p) =>
62
+ `edges["${p.from}"] is an EdgeFn without \`.targets\` metadata — use defineRoute([...], fn) or gate() so reachability can enumerate branches`,
63
+ ),
64
+ "edge-missing": def<{ stage: string }>(
65
+ "warning",
66
+ (p) => `has no edge — treated as terminal; declare \`${p.stage}: "stop"\` to be explicit`,
67
+ ),
68
+ "stage-unreachable": def<{ start: string }>("warning", (p) => `unreachable from start "${p.start}"`),
69
+
70
+ // --- per-stage bounds & enums -------------------------------------------
71
+ "max-retries-out-of-range": def<{ value: number; min: number; max: number }>(
72
+ "error",
73
+ (p) => `maxRetries: ${p.value} — must be in [${p.min}, ${p.max}]`,
74
+ ),
75
+ "validate-timeout-out-of-range": def<{ value: number; min: number; max: number }>(
76
+ "error",
77
+ (p) => `validateTimeoutMs: ${p.value} — must be in [${p.min}, ${p.max}]`,
78
+ ),
79
+ "on-invalid-unknown": def<{ value: string; allowed: string }>(
80
+ "error",
81
+ (p) => `onInvalid: "${p.value}" — must be one of ${p.allowed}`,
82
+ ),
83
+ "stage-kind-unknown": def<{ value: string; allowed: string }>(
84
+ "error",
85
+ (p) => `kind: "${p.value}" — must be one of ${p.allowed}`,
86
+ ),
87
+ "session-policy-unknown": def<{ value: string; allowed: string }>(
88
+ "error",
89
+ (p) => `sessionPolicy: "${p.value}" — must be one of ${p.allowed}`,
90
+ ),
91
+ "produces-without-outcome": def(
92
+ "error",
93
+ () =>
94
+ 'has kind "produces" but no `outcome` — there is no framework default for produces stages. ' +
95
+ "Wire `outcome: rpivArtifactMdOutcome` (from @juicesharp/rpiv-pi) or supply your own `{ collector, parser? }`.",
96
+ ),
97
+ "inherits-artifacts-on-produces": def(
98
+ "warning",
99
+ () =>
100
+ "sets `inheritsArtifacts: false` on a `produces` stage — the flag is the `terminal()` factory's mechanism and is only meaningful on side-effect stages",
101
+ ),
102
+
103
+ // --- loop invariants ------------------------------------------------------
104
+ "loop-kind-unknown": def<{ kind: string; allowed: string }>(
105
+ "error",
106
+ (p) => `loop.kind: "${p.kind}" — must be one of ${p.allowed}`,
107
+ ),
108
+ "loop-continue-session": def(
109
+ "error",
110
+ () => 'cannot combine a loop with sessionPolicy "continue" — each unit requires an isolated session',
111
+ ),
112
+ "loop-max-invalid": def<{ max: number }>(
113
+ "error",
114
+ (p) => `loop.max: ${p.max} — must be an integer >= 1 (run.maxIterations caps the upper bound)`,
115
+ ),
116
+ "loop-requires-produces": def<{ kind: string }>(
117
+ "error",
118
+ (p) => `${p.kind} requires kind "produces" — each unit runs an outcome collector`,
119
+ ),
120
+ "loop-outcome-name-required": def(
121
+ "error",
122
+ () => "a collecting loop requires an `outcome` with a `name` so units publish to a stable named slot",
123
+ ),
124
+ "loop-source-unpublished": def<{ verb: string; source: string }>(
125
+ "warning",
126
+ (p) => `${p.verb} source "${p.source}" but no produces stage in this workflow publishes it`,
127
+ ),
128
+
129
+ // --- assess invariants ------------------------------------------------------
130
+ "assess-judge-shape": def<{ issue: string }>("error", (p) => `assess ${p.issue}`),
131
+ "assess-done-not-function": def(
132
+ "error",
133
+ () => "assess requires `done` to be a function deciding termination from the verdict",
134
+ ),
135
+ "assess-feed-forward-not-function": def(
136
+ "error",
137
+ () => "assess requires `feedForward` to be a function building the next producer arg",
138
+ ),
139
+ "assess-verdict-channel-collision": def<{ channel: string }>(
140
+ "error",
141
+ (p) =>
142
+ `judge.outcome.name "${p.channel}" collides with the producer's publish name — give the verdict its own channel`,
143
+ ),
144
+
145
+ // --- verify invariants ------------------------------------------------------
146
+ "verify-shape": def<{ issue: string }>("error", (p) => p.issue),
147
+ "verify-with-loop": def(
148
+ "error",
149
+ () => "verify and loop are mutually exclusive in v1 — verify already runs the stage through the loop driver",
150
+ ),
151
+ "verify-with-run": def(
152
+ "error",
153
+ () =>
154
+ "verify and run are mutually exclusive — verify attempts dispatch /skill:<skill>; a script stage has no session",
155
+ ),
156
+ "verify-requires-produces": def(
157
+ "error",
158
+ () => 'verify requires kind "produces" — the judge grades the attempt\'s produced artifact',
159
+ ),
160
+ "verify-continue-session": def(
161
+ "error",
162
+ () => 'verify cannot combine with sessionPolicy "continue" — each attempt requires an isolated session',
163
+ ),
164
+ "verify-outcome-name-required": def(
165
+ "error",
166
+ () => "verify requires an `outcome` with a `name` so attempts publish to a stable named slot",
167
+ ),
168
+ "verify-verdict-channel-collision": def<{ channel: string }>(
169
+ "error",
170
+ (p) =>
171
+ `verify judge.outcome.name "${p.channel}" collides with the producer's publish name — give the verdict its own channel`,
172
+ ),
173
+
174
+ // --- panel invariants -------------------------------------------------------
175
+ "panel-member-channel-collision": def<{ channel: string }>(
176
+ "error",
177
+ (p) =>
178
+ `panel member verdict channel "${p.channel}" is claimed more than once — each member, the producer, and the fold need a distinct channel`,
179
+ ),
180
+ "panel-verdict-channel-collision": def<{ channel: string }>(
181
+ "error",
182
+ (p) =>
183
+ `panel folded-verdict channel "${p.channel}" collides with another published channel in this stage — give the fold its own channel`,
184
+ ),
185
+
186
+ // --- prompt invariants ------------------------------------------------------
187
+ "prompt-with-skill": def(
188
+ "error",
189
+ () => "a prompt stage cannot also set `skill` — it dispatches raw text, not /skill:<skill>",
190
+ ),
191
+ "prompt-with-loop": def<{ kind: string }>(
192
+ "error",
193
+ (p) =>
194
+ `prompt and ${p.kind} loops are mutually exclusive — units own their prompts (only assess loops and verify compose with prompt dispatch)`,
195
+ ),
196
+ "prompt-with-reads": def(
197
+ "error",
198
+ () => "a prompt stage cannot set `reads` — read state.named from the PromptFn instead",
199
+ ),
200
+ "prompt-empty": def("error", () => "prompt is an empty string — nothing would be dispatched"),
201
+ "prompt-continue-at-start": def(
202
+ "warning",
203
+ () =>
204
+ "a continue prompt stage is the workflow start — there is no prior session to continue; it will open a fresh one",
205
+ ),
206
+
207
+ // --- script-stage invariants ------------------------------------------------
208
+ "script-with-skill": def("error", () => 'script stages cannot set "skill" (the run function IS the work)'),
209
+ "script-with-outcome": def("error", () => 'script stages cannot set "outcome" (the run function IS the Outcome)'),
210
+ "script-with-loop": def("error", () => "script stages cannot loop — write a loop inside run() instead"),
211
+ "script-with-prompt": def("error", () => "script stages cannot set a raw prompt — the run function IS the work"),
212
+ "script-continue-session": def(
213
+ "error",
214
+ () => 'script stages cannot use sessionPolicy "continue" (no session to continue)',
215
+ ),
216
+ "script-side-effect-output-schema": def(
217
+ "warning",
218
+ () => "outputSchema is meaningless on side-effect script stages — no data to validate",
219
+ ),
220
+
221
+ // --- named-channel wiring ------------------------------------------------
222
+ "reads-unpublished": def<{ channel: string }>(
223
+ "error",
224
+ (p) =>
225
+ `reads "${p.channel}" but no produces stage in this workflow publishes it (check outcome.name or stage record key)`,
226
+ ),
227
+
228
+ // --- contract / schema compatibility --------------------------------------
229
+ "route-reads-unvalidated-data": def(
230
+ "warning",
231
+ () => "a route edge reads output.data but the stage has no outputSchema — routing may fire on un-validated data",
232
+ ),
233
+ "edge-schema-incompatible": def<{ to: string; reason: string }>(
234
+ "warning",
235
+ (p) => `edge to "${p.to}": schema incompatibility — ${p.reason}`,
236
+ ),
237
+ "reads-comparator-threw": def<{ channel: string; producer: string; error: string }>(
238
+ "warning",
239
+ (p) =>
240
+ `composition comparator for channel "${p.channel}" threw (${p.error}) — reads-compat not adjudicated against publisher "${p.producer}"`,
241
+ ),
242
+ "reads-channel-incompatible": def<{ channel: string; producer: string; reason: string }>(
243
+ "error",
244
+ (p) => `reads channel "${p.channel}" but publisher "${p.producer}" is incompatible — ${p.reason}`,
245
+ ),
246
+ } satisfies Record<string, IssueSpec<never>>;
247
+
248
+ // ===========================================================================
249
+ // Issue shape
250
+ // ===========================================================================
251
+
252
+ /** Machine-readable rule id — the stable contract; filter/assert on this, never on message text. */
253
+ export type ValidationIssueCode = keyof typeof ISSUE_DEFS;
254
+
255
+ /** The structured inputs `code`'s message template was rendered from. */
256
+ export type ValidationIssueParamsOf<C extends ValidationIssueCode> =
257
+ (typeof ISSUE_DEFS)[C] extends IssueSpec<infer P> ? P : never;
258
+
259
+ export interface WorkflowValidationIssue {
260
+ workflow: string;
261
+ stage?: string;
262
+ severity: "error" | "warning";
263
+ /** Machine-readable rule id. Severity is a property of the rule (see `ISSUE_DEFS`). */
264
+ code: ValidationIssueCode;
265
+ /** Structured inputs the message was rendered from — for machine filtering/dedup. */
266
+ params: Readonly<IssueParams>;
267
+ /**
268
+ * Rendered prose. Never embeds the stage name — `stage` is structural; the
269
+ * display renderer (`command-run.ts:formatIssue`) composes the attribution.
270
+ */
271
+ message: string;
272
+ }
273
+
274
+ // ===========================================================================
275
+ // Reporter
276
+ // ===========================================================================
277
+
278
+ /** Params argument is omitted entirely for codes whose template takes none. */
279
+ type ReportArgs<C extends ValidationIssueCode> = keyof ValidationIssueParamsOf<C> extends never
280
+ ? []
281
+ : [params: ValidationIssueParamsOf<C>];
282
+
283
+ export type ReportFn = <C extends ValidationIssueCode>(code: C, ...args: ReportArgs<C>) => void;
284
+
285
+ /**
286
+ * Issue reporter bound to one workflow + one sink — replaces the
287
+ * `(w, name, stage, issues)` four-tuple every check used to thread. Checks
288
+ * hold either the workflow-level `report` or a `forStage(name)` binding;
289
+ * construction (severity lookup + render) happens in exactly one place.
290
+ */
291
+ export interface IssueReporter {
292
+ /** Workflow-level issue (no stage attribution). */
293
+ report: ReportFn;
294
+ /** Reporter bound to one stage — per-stage rule blocks take this. */
295
+ forStage(stage: string): ReportFn;
296
+ }
297
+
298
+ export function issueReporter(workflow: string, sink: WorkflowValidationIssue[]): IssueReporter {
299
+ const emit =
300
+ (stage: string | undefined): ReportFn =>
301
+ (code, ...args) => {
302
+ const spec = ISSUE_DEFS[code];
303
+ const params = (args[0] ?? {}) as IssueParams;
304
+ sink.push({
305
+ workflow,
306
+ stage,
307
+ severity: spec.severity,
308
+ code,
309
+ params,
310
+ message: (spec.render as (p: IssueParams) => string)(params),
311
+ });
312
+ };
313
+ return { report: emit(undefined), forStage: (stage) => emit(stage) };
314
+ }