@juicesharp/rpiv-workflow 1.19.1 → 2.0.0

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