@juicesharp/rpiv-workflow 1.19.1 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -1,71 +1,51 @@
1
1
  /**
2
- * Load-time graph validation for `Workflow` objects.
2
+ * Load-time graph validation for `Workflow` objects — the thin orchestrator.
3
3
  *
4
4
  * Catches the wiring mistakes a TS type system can't reach on its own:
5
5
  * unknown edge sources/targets, unreachable stages, missing terminals,
6
6
  * predicate functions that return targets outside the stage set.
7
7
  *
8
- * `validateWorkflow` returns a flat array of `WorkflowValidationIssue`s — errors
9
- * for problems that would crash the runner, warnings for shapes that
10
- * work but probably aren't what the author intended (unreachable stages,
11
- * implicit terminals via missing edges). The load pipeline can choose
12
- * to halt on any error and surface warnings non-fatally.
8
+ * `validateWorkflow` returns a flat array of `WorkflowValidationIssue`s —
9
+ * each carrying a machine-readable `code` (the stable contract — filter and
10
+ * assert on codes, never message text), structured `params`, and prose
11
+ * rendered by the ONE renderer in `validate/issue.ts`. Errors are problems
12
+ * that would crash the runner; warnings are shapes that work but probably
13
+ * aren't what the author intended. The load pipeline can choose to halt on
14
+ * any error and surface warnings non-fatally.
13
15
  *
14
16
  * No I/O, no throws — purely a graph walk + predicate probe.
15
17
  *
16
- * Enforcement layers (where each contract channel is adjudicated):
17
- * - reads / wiring → LOAD-TIME, complete (`checkReadsChannelCompat`, all
18
- * publishers, errors on signed mismatch — all stage kinds).
19
- * - linear `data` + `status` → RUNTIME (`ensureContractInputValid`).
20
- * - produces self-check → PRODUCE-TIME (`extraction.ts:effectiveOutputSchema`).
18
+ * Module map (mirrors the `load/` decomposition):
19
+ * ./validate/issue.ts — codes, params, severity table, reporter, renderer
20
+ * ./validate/graph.ts — graph topology (names, edges, reachability)
21
+ * ./validate/stage-rules.ts — per-stage semantics + named-channel wiring
22
+ * ./validate/contract-compat.ts — skill-contract / JSON-Schema compatibility
21
23
  */
22
24
 
25
+ import type { Workflow } from "./api.js";
26
+ import type { SkillContractMap } from "./skill-contract.js";
27
+ import { checkEdgeSchemaCompat, checkPredicateSchemas, checkReadsChannelCompat } from "./validate/contract-compat.js";
23
28
  import {
24
- type EdgeTarget,
25
- marksReadsData,
26
- ON_INVALID_VALUES,
27
- SESSION_POLICIES,
28
- STAGE_KINDS,
29
- STOP,
30
- type StageDef,
31
- type Workflow,
32
- } from "./api.js";
33
- import { fanoutSpecOf, iterateSpecOf } from "./control-flow.js";
34
- import { resolvePublishName, resolveSkill } from "./internal-utils.js";
35
- import { extractJsonSchema } from "./json-schema.js";
36
- import type { ConfigLayer } from "./layers.js";
37
- import { isSchemaCompatible } from "./schema-compat.js";
38
- import type { ProducesSpec, SkillContractMap } from "./skill-contract.js";
39
- import { getCompositionComparators } from "./skill-contracts/index.js";
29
+ checkEdgeKeys,
30
+ checkEdgeTargets,
31
+ checkMissingEdges,
32
+ checkReachability,
33
+ checkStartStage,
34
+ checkWorkflowName,
35
+ } from "./validate/graph.js";
36
+ import { issueReporter, type WorkflowValidationIssue } from "./validate/issue.js";
40
37
  import {
41
- MAX_VALIDATION_RETRIES,
42
- MAX_VALIDATION_RETRY_TIMEOUT_MS,
43
- MIN_VALIDATION_RETRIES,
44
- MIN_VALIDATION_RETRY_TIMEOUT_MS,
45
- } from "./validate-output.js";
38
+ checkFanoutSource,
39
+ checkReadsReferences,
40
+ checkStageSemantics,
41
+ publishedNamesOf,
42
+ } from "./validate/stage-rules.js";
46
43
 
47
- // ===========================================================================
48
- // Issue shape
49
- // ===========================================================================
50
-
51
- export interface WorkflowValidationIssue {
52
- workflow: string;
53
- stage?: string;
54
- severity: "error" | "warning";
55
- message: string;
56
- /**
57
- * Populated by `load.ts` after aggregation — the layer the workflow came
58
- * from. `validateWorkflow` itself doesn't know about layers; the loader
59
- * is the seam that has both `workflowSources` and the issue list in scope.
60
- */
61
- layer?: ConfigLayer;
62
- /** Source path (rpiv.config.ts) when the layer is user or project. */
63
- path?: string;
64
- }
65
-
66
- // ===========================================================================
67
- // Public — validateWorkflow
68
- // ===========================================================================
44
+ export type {
45
+ ValidationIssueCode,
46
+ ValidationIssueParamsOf,
47
+ WorkflowValidationIssue,
48
+ } from "./validate/issue.js";
69
49
 
70
50
  /**
71
51
  * Validate one workflow. Aggregates all issues; never short-circuits. Caller
@@ -76,714 +56,30 @@ export function validateWorkflow(
76
56
  opts?: { skillContracts?: SkillContractMap },
77
57
  ): WorkflowValidationIssue[] {
78
58
  const issues: WorkflowValidationIssue[] = [];
79
-
80
- checkWorkflowName(workflow, issues);
81
-
82
- if (!workflow.stages[workflow.start]) {
83
- issues.push(error(workflow.name, undefined, `start stage "${workflow.start}" is not declared in stages`));
84
- }
85
-
86
- checkEdgeKeys(workflow, issues);
87
- checkEdgeTargets(workflow, issues);
88
- checkMissingEdges(workflow, issues);
59
+ const label = typeof workflow.name === "string" && workflow.name.length > 0 ? workflow.name : "(anonymous)";
60
+ const r = issueReporter(label, issues);
61
+
62
+ checkWorkflowName(workflow, r);
63
+ checkStartStage(workflow, r);
64
+ checkEdgeKeys(workflow, r);
65
+ checkEdgeTargets(workflow, r);
66
+ checkMissingEdges(workflow, r);
89
67
  // Skip reachability when an EdgeFn lacks `.targets` — the BFS would emit
90
- // "unreachable from start" cascades whose root cause is the upstream error
91
- // already reported by checkEdgeTargets.
92
- const hasUnenumerableEdge = issues.some((i) => /\.targets` metadata/.test(i.message));
93
- if (!hasUnenumerableEdge) checkReachability(workflow, issues);
94
- checkStageSemantics(workflow, issues);
95
- checkPredicateSchemas(workflow, issues, opts?.skillContracts);
96
- checkReadsReferences(workflow, issues);
97
- checkFanoutSource(workflow, issues);
98
- checkEdgeSchemaCompat(workflow, issues, opts?.skillContracts);
99
- checkReadsChannelCompat(workflow, issues, opts?.skillContracts);
100
-
101
- return issues;
102
- }
103
-
104
- // ===========================================================================
105
- // Individual checks
106
- // ===========================================================================
107
-
108
- /** `name` is what users type as `/wf <name>` — empty string makes the workflow unreachable. */
109
- function checkWorkflowName(w: Workflow, issues: WorkflowValidationIssue[]): void {
110
- if (typeof w.name !== "string" || w.name.length === 0) {
111
- issues.push(error("(anonymous)", undefined, "workflow name must be a non-empty string"));
112
- }
113
- }
114
-
115
- /** Every key in `edges` must be a declared stage. */
116
- function checkEdgeKeys(w: Workflow, issues: WorkflowValidationIssue[]): void {
117
- for (const from of Object.keys(w.edges)) {
118
- if (!w.stages[from]) {
119
- issues.push(error(w.name, from, `edges["${from}"] references a stage that's not declared in stages`));
120
- }
121
- }
122
- }
123
-
124
- /**
125
- * Every edge target must resolve to a declared stage or the `"stop"` sentinel.
126
- * String targets are checked directly. `EdgeFn` targets are checked via the
127
- * paired `checkEdgeFnTargets` (emits the no-`.targets` error) and enumerated
128
- * via the pure `enumerateTargets`.
129
- */
130
- function checkEdgeTargets(w: Workflow, issues: WorkflowValidationIssue[]): void {
131
- for (const [from, target] of Object.entries(w.edges)) {
132
- checkEdgeFnTargets(target, { workflow: w.name, from }, issues);
133
- for (const candidate of enumerateTargets(target)) {
134
- if (candidate === STOP) continue;
135
- if (!w.stages[candidate]) {
136
- issues.push(
137
- error(w.name, from, `edges["${from}"] resolves to "${candidate}" which is not declared in stages`),
138
- );
139
- }
140
- }
141
- }
142
- }
143
-
144
- /** Stages with no outgoing edge are implicit terminals — usually a missing connection. */
145
- function checkMissingEdges(w: Workflow, issues: WorkflowValidationIssue[]): void {
146
- for (const name of Object.keys(w.stages)) {
147
- if (!(name in w.edges)) {
148
- issues.push(
149
- warning(
150
- w.name,
151
- name,
152
- `stage "${name}" has no edge — treated as terminal; declare \`${name}: "stop"\` to be explicit`,
153
- ),
154
- );
155
- }
156
- }
157
- }
158
-
159
- /**
160
- * BFS from `start`; every declared stage should be reachable. Orphans aren't
161
- * a runner error (they can't fire) but they're almost always a mistake worth
162
- * surfacing.
163
- */
164
- function checkReachability(w: Workflow, issues: WorkflowValidationIssue[]): void {
165
- if (!w.stages[w.start]) return; // already reported by start-check
166
-
167
- const reachable = new Set<string>();
168
- const frontier: string[] = [w.start];
169
- while (frontier.length > 0) {
170
- const cur = frontier.shift()!;
171
- if (reachable.has(cur)) continue;
172
- reachable.add(cur);
173
-
174
- const target = w.edges[cur];
175
- if (target === undefined || target === STOP) continue;
176
-
177
- for (const next of enumerateTargets(target)) {
178
- if (next !== STOP && w.stages[next] && !reachable.has(next)) frontier.push(next);
179
- }
180
- }
181
-
182
- for (const name of Object.keys(w.stages)) {
183
- if (!reachable.has(name)) {
184
- issues.push(warning(w.name, name, `stage "${name}" is unreachable from start "${w.start}"`));
185
- }
186
- }
187
- }
188
-
189
- /**
190
- * Per-stage semantic checks — bounds and enums that the TS type system narrows
191
- * at edit time but jiti erases at runtime. A user-authored config can ship any
192
- * numeric `maxRetries` or any string for `onInvalid`; this
193
- * pass catches them at load time. Each check is a focused helper so the
194
- * orchestrator reads top-down and individual rules can be exercised in
195
- * isolation.
196
- */
197
- function checkStageSemantics(w: Workflow, issues: WorkflowValidationIssue[]): void {
198
- for (const [name, stage] of Object.entries(w.stages)) {
199
- checkRetryBounds(w, name, stage, issues);
200
- checkTimeoutBounds(w, name, stage, issues);
201
- checkStageEnums(w, name, stage, issues);
202
- checkFanoutContinueInvariant(w, name, stage, issues);
203
- checkIterateInvariants(w, name, stage, issues);
204
- checkPromptInvariants(w, name, stage, issues);
205
- checkInheritsArtifactsKind(w, name, stage, issues);
206
- checkScriptStageInvariants(w, name, stage, issues);
207
- }
208
- }
209
-
210
- function checkRetryBounds(w: Workflow, name: string, stage: StageDef, issues: WorkflowValidationIssue[]): void {
211
- if (stage.maxRetries === undefined) return;
212
- if (stage.maxRetries < MIN_VALIDATION_RETRIES || stage.maxRetries > MAX_VALIDATION_RETRIES) {
213
- issues.push(
214
- error(
215
- w.name,
216
- name,
217
- `maxRetries: ${stage.maxRetries} — must be in [${MIN_VALIDATION_RETRIES}, ${MAX_VALIDATION_RETRIES}]`,
218
- ),
219
- );
220
- }
221
- }
222
-
223
- function checkTimeoutBounds(w: Workflow, name: string, stage: StageDef, issues: WorkflowValidationIssue[]): void {
224
- if (stage.validateTimeoutMs === undefined) return;
225
- if (
226
- stage.validateTimeoutMs < MIN_VALIDATION_RETRY_TIMEOUT_MS ||
227
- stage.validateTimeoutMs > MAX_VALIDATION_RETRY_TIMEOUT_MS
228
- ) {
229
- issues.push(
230
- error(
231
- w.name,
232
- name,
233
- `validateTimeoutMs: ${stage.validateTimeoutMs} — must be in [${MIN_VALIDATION_RETRY_TIMEOUT_MS}, ${MAX_VALIDATION_RETRY_TIMEOUT_MS}]`,
234
- ),
235
- );
236
- }
237
- }
238
-
239
- function checkStageEnums(w: Workflow, name: string, stage: StageDef, issues: WorkflowValidationIssue[]): void {
240
- if (stage.onInvalid !== undefined && !(ON_INVALID_VALUES as readonly string[]).includes(stage.onInvalid)) {
241
- issues.push(
242
- error(w.name, name, `onInvalid: "${stage.onInvalid}" — must be one of ${ON_INVALID_VALUES.join(", ")}`),
243
- );
244
- }
245
- if (!(STAGE_KINDS as readonly string[]).includes(stage.kind)) {
246
- issues.push(error(w.name, name, `kind: "${stage.kind}" — must be one of ${STAGE_KINDS.join(", ")}`));
247
- }
248
- if (!(SESSION_POLICIES as readonly string[]).includes(stage.sessionPolicy)) {
249
- issues.push(
250
- error(w.name, name, `sessionPolicy: "${stage.sessionPolicy}" — must be one of ${SESSION_POLICIES.join(", ")}`),
251
- );
252
- }
253
- if (stage.kind === "produces" && !stage.outcome && !stage.run) {
254
- issues.push(
255
- error(
256
- w.name,
257
- name,
258
- `stage "${name}" has kind "produces" but no \`outcome\` — ` +
259
- "there is no framework default for produces stages. Wire `outcome: rpivArtifactMdOutcome` " +
260
- "(from @juicesharp/rpiv-pi) or supply your own `{ collector, parser? }`.",
261
- ),
262
- );
263
- }
264
- }
265
-
266
- /**
267
- * Fanout requires per-unit session isolation — `continue` would replay the
268
- * prior unit's branch into the next unit's session. The runner enforces
269
- * this at dispatch (`enforceSessionInvariants`); surfacing it at load
270
- * time gives user-authored configs a targeted error instead of a generic
271
- * chain-advance failure on first invocation.
272
- *
273
- * The invariant is keyed on the stage's `fanout` field — not on a skill
274
- * name — keeping the package skill-agnostic: any stage opting into
275
- * fanout must use `sessionPolicy: "fresh"` regardless of what skill it
276
- * dispatches.
277
- */
278
- function checkFanoutContinueInvariant(
279
- w: Workflow,
280
- name: string,
281
- stage: StageDef,
282
- issues: WorkflowValidationIssue[],
283
- ): void {
284
- if (stage.fanout && stage.sessionPolicy === "continue") {
285
- issues.push(
286
- error(
287
- w.name,
288
- name,
289
- `stage "${name}" cannot combine fanout with sessionPolicy "continue" — fanout requires per-unit session isolation`,
290
- ),
291
- );
292
- }
293
- }
294
-
295
- /**
296
- * `iterate` is the sequential, accumulating dual of `fanout`. Its invariants
297
- * are stricter because each unit runs the stage's collector and publishes to a
298
- * single named slot:
299
- *
300
- * - mutually exclusive with `fanout` (push vs pull — a stage is one or the
301
- * other) and with `run` (a script stage writes its own loop);
302
- * - incompatible with `sessionPolicy: "continue"` — like fanout, each unit
303
- * needs an isolated session (also mirrored at preflight);
304
- * - requires `kind: "produces"` — units run an `outcome` collector;
305
- * - requires `outcome.name` — every unit publishes to the SAME
306
- * `state.named` slot via `resolvePublishName`, and the per-unit audit row
307
- * is decorated, so without an explicit name the decoration would split the
308
- * slot across units.
309
- *
310
- * The `fanout`/`run`/`kind`/`outcome.name` rules are authoring-time-knowable,
311
- * so load validation is the primary gate; only the `continue` rule needs a
312
- * runtime mirror (embedders may bypass load validation).
313
- */
314
- function checkIterateInvariants(w: Workflow, name: string, stage: StageDef, issues: WorkflowValidationIssue[]): void {
315
- if (!stage.iterate) return;
316
- if (stage.fanout) {
317
- issues.push(error(w.name, name, `stage "${name}": iterate and fanout are mutually exclusive (pull vs push)`));
318
- }
319
- // iterate + run is reported by checkScriptStageInvariants (mirrors fanout + run).
320
- if (stage.sessionPolicy === "continue") {
321
- issues.push(
322
- error(
323
- w.name,
324
- name,
325
- `stage "${name}" cannot combine iterate with sessionPolicy "continue" — each unit requires an isolated session`,
326
- ),
327
- );
328
- }
329
- if (stage.kind !== "produces") {
330
- issues.push(
331
- error(w.name, name, `stage "${name}": iterate requires kind "produces" — each unit runs an outcome collector`),
332
- );
333
- }
334
- if (!stage.outcome?.name) {
335
- issues.push(
336
- error(
337
- w.name,
338
- name,
339
- `stage "${name}": iterate requires an \`outcome\` with a \`name\` so accumulated units publish to a stable named slot`,
340
- ),
341
- );
342
- }
343
- }
344
-
345
- /**
346
- * `prompt` is the raw-text dispatch — the third option alongside skill
347
- * (`/skill:<name>`) and script `run`. Its invariants keep the dispatch
348
- * discriminator unambiguous and the input model single:
349
- *
350
- * - mutually exclusive with an explicit `skill` (you're either invoking a
351
- * skill or sending raw text — `skill` defaulting to the record key does
352
- * NOT trip this, only an explicitly-set `skill`);
353
- * - mutually exclusive with `fanout`/`iterate` in v1 (chat fan-out is a
354
- * deferred composition);
355
- * - mutually exclusive with `reads` — a skill stage's `reads` auto-builds a
356
- * labelled-flag arg, but a prompt stage's text is author-owned; rather than
357
- * give `reads` two meanings, require the prompt to read `state.named`
358
- * itself via its `PromptFn`;
359
- * - a literal empty/whitespace string is a no-op dispatch → author error.
360
- *
361
- * (`prompt` + `run` is reported by checkScriptStageInvariants, mirroring
362
- * fanout/iterate + run. `produces` + `prompt` with no `outcome` is already
363
- * caught by the produces-requires-outcome rule — `prompt`, unlike `run`, is not
364
- * carved out of it.)
365
- *
366
- * A `continue` prompt stage used as the workflow START gets a WARNING: a
367
- * follow-up turn with no prior context to lean on is almost certainly an
368
- * authoring mistake (the continue session would have nothing to continue).
369
- */
370
- function checkPromptInvariants(w: Workflow, name: string, stage: StageDef, issues: WorkflowValidationIssue[]): void {
371
- if (stage.prompt === undefined) return;
372
- if (stage.skill !== undefined) {
373
- issues.push(
374
- error(
375
- w.name,
376
- name,
377
- `stage "${name}": a prompt stage cannot also set \`skill\` — it dispatches raw text, not /skill:<skill>`,
378
- ),
379
- );
380
- }
381
- if (stage.fanout) {
382
- issues.push(
383
- error(w.name, name, `stage "${name}": prompt and fanout are mutually exclusive (chat fan-out is deferred)`),
384
- );
385
- }
386
- if (stage.iterate) {
387
- issues.push(
388
- error(w.name, name, `stage "${name}": prompt and iterate are mutually exclusive (chat iterate is deferred)`),
389
- );
390
- }
391
- if (stage.reads?.length) {
392
- issues.push(
393
- error(
394
- w.name,
395
- name,
396
- `stage "${name}": a prompt stage cannot set \`reads\` — read state.named from the PromptFn instead`,
397
- ),
398
- );
399
- }
400
- if (typeof stage.prompt === "string" && stage.prompt.trim() === "") {
401
- issues.push(error(w.name, name, `stage "${name}": prompt is an empty string — nothing would be dispatched`));
402
- }
403
- if (stage.sessionPolicy === "continue" && name === w.start) {
404
- issues.push(
405
- warning(
406
- w.name,
407
- name,
408
- `stage "${name}": a continue prompt stage is the workflow start — there is no prior session to continue; it will open a fresh one`,
409
- ),
410
- );
411
- }
412
- }
413
-
414
- /**
415
- * `inheritsArtifacts: false` is the `terminal()` factory's mechanism — it
416
- * tells the runner to bypass upstream-artifact inheritance for a
417
- * side-effect stage. Setting it on a `produces` stage is meaningless: a
418
- * `produces` stage emits its own outcome and never consumes the upstream
419
- * primary artifact in `inputForStage` (the first stage always uses
420
- * originalInput, and inheritance only affects the prompt arg). Surface
421
- * the redundancy as a warning so users don't author "off" flags they
422
- * think are doing something.
423
- */
424
- function checkInheritsArtifactsKind(
425
- w: Workflow,
426
- name: string,
427
- stage: StageDef,
428
- issues: WorkflowValidationIssue[],
429
- ): void {
430
- if (stage.inheritsArtifacts === false && stage.kind === "produces") {
431
- issues.push(
432
- warning(
433
- w.name,
434
- name,
435
- `stage "${name}" sets \`inheritsArtifacts: false\` on a \`produces\` stage — the flag is the \`terminal()\` factory's mechanism and is only meaningful on side-effect stages`,
436
- ),
437
- );
438
- }
439
- }
440
-
441
- /**
442
- * Skillless script stages: presence of `stage.run` declares "the runner
443
- * calls this TS function instead of dispatching a Pi skill." Four fields
444
- * are categorically incompatible with that contract — fail loudly at
445
- * load time so the runner branch can assume the invariant.
446
- *
447
- * Mutual-exclusion rules:
448
- *
449
- * - `skill` — the function IS the work; a skill body would never
450
- * be dispatched.
451
- * - `outcome` — the function returns the `Output` envelope directly;
452
- * there is no transcript / tool-use stream for a
453
- * collector to scan.
454
- * - `fanout` — a TS function can write its own loop; the runner's
455
- * per-unit session machinery doesn't apply.
456
- * - `sessionPolicy: "continue"` — there is no Pi session at all on a
457
- * script stage; nothing to continue.
458
- *
459
- * Side-effect script stages with an `outputSchema` get a warning — the
460
- * function returns `void`, so no data ever flows through the validator.
461
- *
462
- * The existing `produces` + `inheritsArtifacts: false` warning
463
- * (`checkInheritsArtifactsKind`) fires uniformly for both skill and
464
- * script variants — same author error, same message.
465
- */
466
- function checkScriptStageInvariants(
467
- w: Workflow,
468
- name: string,
469
- stage: StageDef,
470
- issues: WorkflowValidationIssue[],
471
- ): void {
472
- if (!stage.run) return;
473
-
474
- if (stage.skill !== undefined) {
475
- issues.push(
476
- error(w.name, name, `stage "${name}": script stages cannot set "skill" (the run function IS the work)`),
477
- );
478
- }
479
- if (stage.outcome) {
480
- issues.push(
481
- error(
482
- w.name,
483
- name,
484
- `stage "${name}": script stages cannot set "outcome" (the run function IS the OutputSpec)`,
485
- ),
486
- );
487
- }
488
- if (stage.fanout) {
489
- issues.push(
490
- error(w.name, name, `stage "${name}": script stages cannot fanout — write a loop inside run() instead`),
491
- );
492
- }
493
- if (stage.iterate) {
494
- issues.push(
495
- error(w.name, name, `stage "${name}": script stages cannot iterate — write a loop inside run() instead`),
496
- );
497
- }
498
- if (stage.prompt !== undefined) {
499
- issues.push(
500
- error(w.name, name, `stage "${name}": script stages cannot set a raw prompt — the run function IS the work`),
501
- );
502
- }
503
- if (stage.sessionPolicy === "continue") {
504
- issues.push(
505
- error(
506
- w.name,
507
- name,
508
- `stage "${name}": script stages cannot use sessionPolicy "continue" (no session to continue)`,
509
- ),
510
- );
511
- }
512
- if (stage.kind === "side-effect" && stage.outputSchema) {
513
- issues.push(
514
- warning(
515
- w.name,
516
- name,
517
- `stage "${name}": outputSchema is meaningless on side-effect script stages — no data to validate`,
518
- ),
519
- );
520
- }
521
- }
522
-
523
- /**
524
- * Every name in a stage's `reads:` must be filled by some `produces` stage
525
- * in the workflow. The publish key is `stage.outcome?.name ?? <record-key>`
526
- * — same rule the runner enforces at write time (see
527
- * `resolvePublishName`). Reachability isn't checked here: validating that
528
- * the producer can actually reach the consumer in the edge graph is a
529
- * larger graph problem and the static check is intentionally narrow —
530
- * it answers "does this name correspond to something in the workflow at
531
- * all?", catching typos and renames; the runtime `ensureNamedReads`
532
- * preflight handles the "haven't fired yet" case.
533
- */
534
- function checkReadsReferences(w: Workflow, issues: WorkflowValidationIssue[]): void {
535
- const publishedNames = new Set<string>();
536
- for (const [name, stage] of Object.entries(w.stages)) {
537
- if (stage.kind !== "produces") continue;
538
- publishedNames.add(stage.outcome?.name ?? name);
539
- }
540
- for (const [name, stage] of Object.entries(w.stages)) {
541
- if (!stage.reads?.length) continue;
542
- for (const read of stage.reads) {
543
- if (publishedNames.has(read)) continue;
544
- issues.push(
545
- error(
546
- w.name,
547
- name,
548
- `stage "${name}" reads "${read}" but no produces stage in this workflow publishes it (check outcome.name or stage record key)`,
549
- ),
550
- );
551
- }
552
- }
553
- }
554
-
555
- /**
556
- * Load-time fanout/iterate source check (Phase 3 — control-flow as data). A stage
557
- * whose `fanout`/`iterate` carries a declarative `.spec` (via `fanoutOver`/
558
- * `iterateOver`) with a `source` channel must have that channel published by some
559
- * `produces` stage in this workflow — otherwise the stage splits over a channel
560
- * nothing fills. Same publisher model as `checkReadsReferences`
561
- * (`stage.outcome?.name ?? <record-key>`).
562
- *
563
- * WARNS (never errors): `source` is an introspective hint, and a raw/opaque fanout
564
- * (no `.spec`) or a spec without `source` degrades silently — mirrors the
565
- * edge-compat posture. When the source is already in the stage's `reads`,
566
- * `checkReadsReferences` owns it (errors) — skip to avoid double-reporting. The
567
- * additive value is the `iterate`/closure-sourced case, which declares no `reads:`
568
- * and is otherwise unchecked.
569
- */
570
- function checkFanoutSource(w: Workflow, issues: WorkflowValidationIssue[]): void {
571
- const published = new Set<string>();
572
- for (const [name, stage] of Object.entries(w.stages)) {
573
- if (stage.kind === "produces") published.add(stage.outcome?.name ?? name);
574
- }
575
- for (const [name, stage] of Object.entries(w.stages)) {
576
- const spec = fanoutSpecOf(stage.fanout) ?? iterateSpecOf(stage.iterate);
577
- const source = spec?.source;
578
- if (!source || published.has(source)) continue; // opaque / no source / satisfied → degrade
579
- if (stage.reads?.includes(source)) continue; // checkReadsReferences owns this channel
580
- issues.push(
581
- warning(
582
- w.name,
583
- name,
584
- `stage "${name}" ${spec.kind === "fanout" ? "fans out" : "iterates"} over source "${source}" but no produces stage in this workflow publishes it`,
585
- ),
586
- );
587
- }
588
- }
589
-
590
- /**
591
- * Route edges that read `output.data[field]` (i.e. `defineRoute(...)` with
592
- * the default `readsData: true`, `gate(...)`, and any future factory that
593
- * auto-attaches the `READS_DATA` marker) should fire on data the source
594
- * stage has validated against its `outputSchema`. If the schema is absent,
595
- * the validation-retry loop never runs and the route may read an undefined
596
- * field — routing decisions silently default.
597
- *
598
- * A stage carrying no `outputSchema` is still covered when its dispatched
599
- * skill declares a contract `produces.data` — output validation sources that
600
- * schema at runtime (`effectiveOutputSchema` in extraction.ts), so the route
601
- * fires on validated data. Such stages are exempt from this lint.
602
- *
603
- * Routes authored via `defineRoute(targets, fn, { readsData: false })`
604
- * consult only `state` or `output.meta` and carry no marker — exempt from
605
- * this lint.
606
- */
607
- function checkPredicateSchemas(
608
- w: Workflow,
609
- issues: WorkflowValidationIssue[],
610
- skillContracts: SkillContractMap | undefined,
611
- ): void {
612
- for (const [from, target] of Object.entries(w.edges)) {
613
- if (typeof target === "string") continue;
614
- if (!marksReadsData(target)) continue;
615
- const stage = w.stages[from];
616
- if (!stage || stage.outputSchema) continue;
617
- // Contract-sourced output schema covers the stage like its own `outputSchema`
618
- // would — mirror `effectiveOutputSchema`'s fallback (same `resolveSkill` key).
619
- const contractData = skillContracts?.get(resolveSkill(stage, from))?.produces?.data;
620
- if (contractData) continue;
621
- issues.push(
622
- warning(
623
- w.name,
624
- from,
625
- `route edge from "${from}" reads output.data but the stage has no outputSchema — routing may fire on un-validated data`,
626
- ),
627
- );
628
- }
629
- }
630
-
631
- /**
632
- * Load-time compat for the LINEAR `data` channel: for each string edge from→to,
633
- * compare the producer's `produces.data` to the consumer's `consumes.data`
634
- * (registry-sourced, falling back to the stage's own output/input schema). Warns
635
- * on a definite mismatch; degrades on predicate/STOP edges and opaque schemas.
636
- *
637
- * Edge-local is correct here — the rolling primary flows along edges. The
638
- * many-to-one NAMED (`reads`) channel is handled by `checkReadsChannelCompat`.
639
- * Runtime mirror: `ensureContractInputValid`.
640
- */
641
- function checkEdgeSchemaCompat(
642
- w: Workflow,
643
- issues: WorkflowValidationIssue[],
644
- skillContracts: SkillContractMap | undefined,
645
- ): void {
646
- for (const [from, target] of Object.entries(w.edges)) {
647
- if (typeof target !== "string" || target === STOP) continue; // degrade on predicate/STOP edges
648
- const fromStage = w.stages[from];
649
- const toStage = w.stages[target];
650
- if (!fromStage || !toStage) continue; // unknown stages already reported by edge-target checks
651
- const producerContract = skillContracts?.get(resolveSkill(fromStage, from));
652
- const consumerContract = skillContracts?.get(resolveSkill(toStage, target));
68
+ // "unreachable from start" cascades whose root cause is the metadata error
69
+ // already reported. Gated on the issue CODE (machine-readable — the
70
+ // message-regex this replaced was finding C5).
71
+ if (!issues.some((i) => i.code === "edge-fn-no-targets")) checkReachability(workflow, r);
653
72
 
654
- const producer = producerContract?.produces?.data ?? extractJsonSchema(fromStage.outputSchema);
655
- const consumer = consumerContract?.consumes?.data ?? extractJsonSchema(toStage.inputSchema);
656
- if (producer && consumer) {
657
- const compat = isSchemaCompatible(producer, consumer);
658
- if (!compat.ok) {
659
- issues.push(
660
- warning(w.name, from, `edge "${from}" → "${target}": schema incompatibility — ${compat.reason}`),
661
- );
662
- }
663
- }
664
- }
665
- }
73
+ checkStageSemantics(workflow, r);
666
74
 
667
- /**
668
- * Load-time named-channel (`reads`) compat — the COMPLETE authoring gate for
669
- * `reads:` wiring. For each consumer with `consumes.reads`, adjudicate
670
- * against EVERY `produces` stage that publishes the channel
671
- * (`resolvePublishName === channel`), not just the edge predecessor — named
672
- * channels are many-to-one (loop-backs, non-adjacent producers). The publisher
673
- * set is statically computable.
674
- *
675
- * ERRORS on a clean comparator incompatibility between two SIGNED contracts —
676
- * the "mechanically reject invalid wirings" guarantee, uniform across all stage
677
- * kinds, which is why no runtime reads gate is needed. Degrades (never errors)
678
- * when either side is unsigned, no comparator is registered, the channel isn't
679
- * declared, or the comparator throws. "No publisher at all" is
680
- * `checkReadsReferences`'s job, not this one's.
681
- */
682
- function checkReadsChannelCompat(
683
- w: Workflow,
684
- issues: WorkflowValidationIssue[],
685
- skillContracts: SkillContractMap | undefined,
686
- ): void {
687
- if (!skillContracts) return;
688
- const comparators = getCompositionComparators();
689
- if (comparators.size === 0) return; // no adjudicators registered
690
-
691
- // Index signed publishers by channel. `kind === "produces"` mirrors the
692
- // runtime publish rule (`applyCompletedStage`).
693
- const publishersByChannel = new Map<string, Array<{ stage: string; produces: ProducesSpec }>>();
694
- for (const [name, stage] of Object.entries(w.stages)) {
695
- if (stage.kind !== "produces") continue;
696
- const produces = skillContracts.get(resolveSkill(stage, name))?.produces;
697
- if (!produces) continue; // unsigned producer — degrade
698
- const channel = resolvePublishName(stage, name);
699
- const list = publishersByChannel.get(channel);
700
- if (list) list.push({ stage: name, produces });
701
- else publishersByChannel.set(channel, [{ stage: name, produces }]);
702
- }
703
-
704
- for (const [consumerName, consumer] of Object.entries(w.stages)) {
705
- if (!consumer.reads?.length) continue;
706
- const consumes = skillContracts.get(resolveSkill(consumer, consumerName))?.consumes;
707
- if (!consumes?.reads) continue; // unsigned consumer — degrade
708
- for (const channel of consumer.reads) {
709
- const comparator = comparators.get(channel);
710
- if (!comparator || !consumes.reads[channel]) continue; // no adjudicator / undeclared channel — degrade
711
- const publishers = publishersByChannel.get(channel);
712
- if (!publishers) continue; // "no publisher at all" is checkReadsReferences's job
713
- for (const { stage: producerName, produces } of publishers) {
714
- let compat: { ok: boolean; reason?: string };
715
- try {
716
- compat = comparator(produces, consumes, channel);
717
- } catch {
718
- continue; // comparator threw — author defect, degrade
719
- }
720
- if (compat.ok) continue;
721
- issues.push(
722
- error(
723
- w.name,
724
- consumerName,
725
- `stage "${consumerName}" reads channel "${channel}" but publisher "${producerName}" is incompatible — ${compat.reason ?? "named-channel meta incompatibility"}`,
726
- ),
727
- );
728
- }
729
- }
730
- }
731
- }
75
+ // The publisher set is computed ONCE and threaded to both consumers (D10).
76
+ const published = publishedNamesOf(workflow);
77
+ checkReadsReferences(workflow, published, r);
78
+ checkFanoutSource(workflow, published, r);
732
79
 
733
- // ===========================================================================
734
- // Edge-target enumeration
735
- // ===========================================================================
80
+ checkPredicateSchemas(workflow, r, opts?.skillContracts);
81
+ checkEdgeSchemaCompat(workflow, r, opts?.skillContracts);
82
+ checkReadsChannelCompat(workflow, r, opts?.skillContracts);
736
83
 
737
- /**
738
- * Returns the set of possible string targets an `EdgeTarget` could resolve to.
739
- * Pure — no issue emission, no caller-supplied discard buffer.
740
- *
741
- * - String → singleton.
742
- * - `EdgeFn` with `.targets` metadata → declared targets.
743
- * - `EdgeFn` without `.targets` → empty list. The missing-metadata error is
744
- * the responsibility of `checkEdgeFnTargets` (paired emit-only function);
745
- * call it alongside `enumerateTargets` only at sites that lint edges
746
- * (currently `checkEdgeTargets`). Reachability traversal calls only the
747
- * pure form.
748
- */
749
- function enumerateTargets(target: EdgeTarget): string[] {
750
- if (typeof target === "string") return [target];
751
- if (Array.isArray(target.targets) && target.targets.length > 0) return [...target.targets];
752
- return [];
753
- }
754
-
755
- /**
756
- * Emits the "EdgeFn without `.targets` metadata" error for an `EdgeTarget`
757
- * that's a hand-rolled `EdgeFn` lacking the marker. Pairs with
758
- * `enumerateTargets`: lint sites call both; reachability calls only the
759
- * enumerator. Users authoring routes by hand MUST go through
760
- * `defineRoute(targets, fn)` so the `.targets` metadata is structurally
761
- * attached.
762
- */
763
- function checkEdgeFnTargets(
764
- target: EdgeTarget,
765
- ctx: { workflow: string; from: string },
766
- issues: WorkflowValidationIssue[],
767
- ): void {
768
- if (typeof target === "string") return;
769
- if (Array.isArray(target.targets) && target.targets.length > 0) return;
770
- issues.push(
771
- error(
772
- ctx.workflow,
773
- ctx.from,
774
- `edges["${ctx.from}"] is an EdgeFn without \`.targets\` metadata — use defineRoute([...], fn) or gate() so reachability can enumerate branches`,
775
- ),
776
- );
777
- }
778
-
779
- // ===========================================================================
780
- // Issue constructors
781
- // ===========================================================================
782
-
783
- function error(workflow: string, stage: string | undefined, message: string): WorkflowValidationIssue {
784
- return { workflow, stage, severity: "error", message };
785
- }
786
-
787
- function warning(workflow: string, stage: string | undefined, message: string): WorkflowValidationIssue {
788
- return { workflow, stage, severity: "warning", message };
84
+ return issues;
789
85
  }