@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
@@ -0,0 +1,420 @@
1
+ /**
2
+ * Per-stage semantic rules — bounds and enums the TS type system narrows at
3
+ * edit time but jiti erases at runtime, plus the loop/verify/prompt/script
4
+ * exclusion matrices and named-channel (`reads`) wiring. A user-authored
5
+ * config can ship any numeric `maxRetries` or any string for `onInvalid`;
6
+ * this pass catches them at load time.
7
+ *
8
+ * Each check is a focused helper taking the stage-bound `ReportFn` so the
9
+ * orchestration loop reads top-down and individual rules can be exercised in
10
+ * isolation. Contract/schema compatibility lives in `contract-compat.ts`
11
+ * (different dependency footprint entirely).
12
+ */
13
+
14
+ import { LOOP_KINDS, ON_INVALID_VALUES, SESSION_POLICIES, STAGE_KINDS, type StageDef, type Workflow } from "../api.js";
15
+ import { resolvePublishName } from "../chain-state.js";
16
+ import { type AnyJudge, isPanel, judgeShapeIssues } from "../judge.js";
17
+ import {
18
+ judgeSlotOf,
19
+ loopSpecOf,
20
+ panelShapeIssues,
21
+ panelVerdictChannel,
22
+ verifyShapeIssues,
23
+ } from "../loop-constructors.js";
24
+ import {
25
+ MAX_VALIDATION_RETRIES,
26
+ MAX_VALIDATION_RETRY_TIMEOUT_MS,
27
+ MIN_VALIDATION_RETRIES,
28
+ MIN_VALIDATION_RETRY_TIMEOUT_MS,
29
+ } from "../validate-output.js";
30
+ import type { IssueReporter, ReportFn } from "./issue.js";
31
+
32
+ /**
33
+ * Orchestrates the per-stage rule blocks. The orchestration loop binds the
34
+ * reporter to each stage once; rules that need workflow context beyond the
35
+ * stage (currently only "is this the start stage") receive it explicitly.
36
+ */
37
+ export function checkStageSemantics(w: Workflow, r: IssueReporter): void {
38
+ for (const [name, stage] of Object.entries(w.stages)) {
39
+ const report = r.forStage(name);
40
+ checkRetryBounds(stage, report);
41
+ checkTimeoutBounds(stage, report);
42
+ checkStageEnums(stage, report);
43
+ checkLoopInvariants(stage, name, report);
44
+ checkVerifyInvariants(stage, name, report);
45
+ checkPromptInvariants(stage, name === w.start, report);
46
+ checkInheritsArtifactsKind(stage, report);
47
+ checkScriptStageInvariants(stage, report);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * One rule block for the single `loop` field. Constructors already threw on
53
+ * these at authoring time; this is the defensive load gate for hand-rolled
54
+ * literals (jiti erases TS types) and programmatic embedders.
55
+ */
56
+ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): void {
57
+ const loop = stage.loop;
58
+ if (!loop) return;
59
+
60
+ if (!(LOOP_KINDS as readonly string[]).includes(loop.kind)) {
61
+ report("loop-kind-unknown", { kind: loop.kind, allowed: LOOP_KINDS.join(", ") });
62
+ return; // kind-specific rules below would misfire on an unknown kind
63
+ }
64
+ // ONE continue rule (was three identical ones).
65
+ if (stage.sessionPolicy === "continue") {
66
+ report("loop-continue-session");
67
+ }
68
+ // Enforced for ALL loops now (was advisory-only for fanout/iterate specs).
69
+ if (loop.max !== undefined && (!Number.isInteger(loop.max) || loop.max < 1)) {
70
+ report("loop-max-invalid", { max: loop.max });
71
+ }
72
+ // Pull loops + assess run the stage's outcome collector per unit.
73
+ if ((loop.kind === "iterate" || loop.kind === "assess") && stage.kind !== "produces") {
74
+ report("loop-requires-produces", { kind: loop.kind });
75
+ }
76
+ // A stable named slot: iterate and assess always (every unit/round runs the
77
+ // produces collector), fanout when COLLECTING (produces kind) — the decorated
78
+ // display string must never split the accumulation slot.
79
+ const needsName =
80
+ loop.kind === "iterate" || loop.kind === "assess" || (loop.kind === "fanout" && stage.kind === "produces");
81
+ if (needsName && !stage.outcome?.name) {
82
+ report("loop-outcome-name-required");
83
+ }
84
+
85
+ if (loop.kind !== "assess") return;
86
+
87
+ // Judge shape — SAME rule sources as the judge()/panel() factories (no
88
+ // wording drift). The slot is an `AnyJudge`: a panel routes through
89
+ // `panelShapeIssues`, a single judge through `judgeShapeIssues`.
90
+ const slot = loop.judge;
91
+ const shapeIssues = slot && isPanel(slot) ? panelShapeIssues(slot) : judgeShapeIssues(slot);
92
+ for (const issue of shapeIssues) {
93
+ report("assess-judge-shape", { issue });
94
+ }
95
+ if (typeof loop.done !== "function") {
96
+ report("assess-done-not-function");
97
+ }
98
+ if (typeof loop.feedForward !== "function") {
99
+ report("assess-feed-forward-not-function");
100
+ }
101
+ // Verdict-channel collisions — STAY workflow-level (need the producer's
102
+ // publish identity, which only the stage knows).
103
+ checkVerdictChannels(slot, name, stage, "assess-verdict-channel-collision", report);
104
+ }
105
+
106
+ /**
107
+ * Verdict-channel collisions for a judge SLOT (`AnyJudge`) — workflow-level
108
+ * because it needs the producer's publish identity (`stage.outcome?.name ??
109
+ * name`). A single judge owns ONE verdict channel; a PANEL owns one channel per
110
+ * member PLUS the folded-verdict channel, and every one of them must be
111
+ * distinct from the others and from the producer's own slot, or two sessions
112
+ * clobber a single `state.named` entry. The SHAPE is checked separately through
113
+ * the matching rule source; this is purely the channel-namespace rule.
114
+ *
115
+ * `singleCode` (assess- vs verify-worded) is the only per-site difference; the
116
+ * panel codes are site-independent.
117
+ */
118
+ function checkVerdictChannels(
119
+ slot: AnyJudge | undefined,
120
+ name: string,
121
+ stage: StageDef,
122
+ singleCode: "assess-verdict-channel-collision" | "verify-verdict-channel-collision",
123
+ report: ReportFn,
124
+ ): void {
125
+ if (!slot) return;
126
+ const producer = stage.outcome?.name ?? name;
127
+ if (!isPanel(slot)) {
128
+ if (slot.outcome?.name && slot.outcome.name === producer) {
129
+ report(singleCode, { channel: slot.outcome.name });
130
+ }
131
+ return;
132
+ }
133
+ // Panel: members + fold share one namespace with the producer. First
134
+ // claimant of a name wins; a later claimant is the collision.
135
+ const claimed = new Set<string>([producer]);
136
+ for (const m of slot.members) {
137
+ const channel = m?.outcome?.name;
138
+ if (!channel) continue; // a member missing outcome.name is a shape issue (panelShapeIssues)
139
+ if (claimed.has(channel)) report("panel-member-channel-collision", { channel });
140
+ else claimed.add(channel);
141
+ }
142
+ const fold = panelVerdictChannel(slot, name);
143
+ if (claimed.has(fold)) report("panel-verdict-channel-collision", { channel: fold });
144
+ }
145
+
146
+ /**
147
+ * One rule block for the `verify` field. The `verify()` constructor already
148
+ * threw on shape violations at authoring time; this is the defensive load
149
+ * gate for hand-rolled literals (jiti erases TS types), plus the
150
+ * workflow-level rules that need the stage's identity. The runtime engine is
151
+ * the loop driver (the desugar), so the structural exclusions mirror the
152
+ * loop rules — but verify-worded, because the author declared a
153
+ * post-condition, not a loop.
154
+ */
155
+ function checkVerifyInvariants(stage: StageDef, name: string, report: ReportFn): void {
156
+ const v = stage.verify;
157
+ if (!v) return;
158
+
159
+ // Shape — SAME rule source as the verify() factory (no wording drift).
160
+ for (const issue of verifyShapeIssues(v)) {
161
+ report("verify-shape", { issue });
162
+ }
163
+ if (stage.loop) {
164
+ report("verify-with-loop");
165
+ }
166
+ if (stage.run) {
167
+ report("verify-with-run");
168
+ }
169
+ if (stage.kind !== "produces") {
170
+ report("verify-requires-produces");
171
+ }
172
+ if (stage.sessionPolicy === "continue") {
173
+ report("verify-continue-session");
174
+ }
175
+ // Attempts publish to a stable named slot — without `outcome.name` the
176
+ // fallback publish key would be the DECORATED unit display string
177
+ // ("build (a0·attempt)"), splitting the accumulation slot per attempt
178
+ // (same rationale as the collecting-loop rule).
179
+ if (stage.kind === "produces" && !stage.run && !stage.outcome?.name) {
180
+ report("verify-outcome-name-required");
181
+ }
182
+ // Verdict-channel collisions — STAY workflow-level (need the producer's
183
+ // publish identity, which only the stage knows). Mirrors the assess rule;
184
+ // `checkVerdictChannels` walks panel members + fold for an `AnyJudge` slot.
185
+ checkVerdictChannels(v.judge, name, stage, "verify-verdict-channel-collision", report);
186
+ }
187
+
188
+ function checkRetryBounds(stage: StageDef, report: ReportFn): void {
189
+ if (stage.maxRetries === undefined) return;
190
+ if (stage.maxRetries < MIN_VALIDATION_RETRIES || stage.maxRetries > MAX_VALIDATION_RETRIES) {
191
+ report("max-retries-out-of-range", {
192
+ value: stage.maxRetries,
193
+ min: MIN_VALIDATION_RETRIES,
194
+ max: MAX_VALIDATION_RETRIES,
195
+ });
196
+ }
197
+ }
198
+
199
+ function checkTimeoutBounds(stage: StageDef, report: ReportFn): void {
200
+ if (stage.validateTimeoutMs === undefined) return;
201
+ if (
202
+ stage.validateTimeoutMs < MIN_VALIDATION_RETRY_TIMEOUT_MS ||
203
+ stage.validateTimeoutMs > MAX_VALIDATION_RETRY_TIMEOUT_MS
204
+ ) {
205
+ report("validate-timeout-out-of-range", {
206
+ value: stage.validateTimeoutMs,
207
+ min: MIN_VALIDATION_RETRY_TIMEOUT_MS,
208
+ max: MAX_VALIDATION_RETRY_TIMEOUT_MS,
209
+ });
210
+ }
211
+ }
212
+
213
+ function checkStageEnums(stage: StageDef, report: ReportFn): void {
214
+ if (stage.onInvalid !== undefined && !(ON_INVALID_VALUES as readonly string[]).includes(stage.onInvalid)) {
215
+ report("on-invalid-unknown", { value: stage.onInvalid, allowed: ON_INVALID_VALUES.join(", ") });
216
+ }
217
+ if (!(STAGE_KINDS as readonly string[]).includes(stage.kind)) {
218
+ report("stage-kind-unknown", { value: stage.kind, allowed: STAGE_KINDS.join(", ") });
219
+ }
220
+ if (!(SESSION_POLICIES as readonly string[]).includes(stage.sessionPolicy)) {
221
+ report("session-policy-unknown", { value: stage.sessionPolicy, allowed: SESSION_POLICIES.join(", ") });
222
+ }
223
+ if (stage.kind === "produces" && !stage.outcome && !stage.run) {
224
+ report("produces-without-outcome");
225
+ }
226
+ }
227
+
228
+ /**
229
+ * `prompt` is the raw-text dispatch — the third option alongside skill
230
+ * (`/skill:<name>`) and script `run`. Its invariants keep the dispatch
231
+ * discriminator unambiguous and the input model single:
232
+ *
233
+ * - mutually exclusive with an explicit `skill` (you're either invoking a
234
+ * skill or sending raw text — `skill` defaulting to the record key does
235
+ * NOT trip this, only an explicitly-set `skill`);
236
+ * - mutually exclusive with `fanout`/`iterate` loops (principled, not
237
+ * deferred: every unit's message comes from `units()`/`next()`, so a
238
+ * stage-level `prompt` would have no role). `assess` loops and `verify`
239
+ * COMPOSE: the stage's `prompt` is round/attempt 0's message and
240
+ * `feedForward` builds each retry's complete message (raw — no `/skill:`
241
+ * prefix to attach an arg to);
242
+ * - mutually exclusive with `reads` — a skill stage's `reads` auto-builds a
243
+ * labelled-flag arg, but a prompt stage's text is author-owned; rather than
244
+ * give `reads` two meanings, require the prompt to read `state.named`
245
+ * itself via its `PromptFn`;
246
+ * - a literal empty/whitespace string is a no-op dispatch → author error.
247
+ *
248
+ * (`prompt` + `run` is reported by checkScriptStageInvariants, mirroring
249
+ * fanout/iterate + run. `produces` + `prompt` with no `outcome` is already
250
+ * caught by the produces-requires-outcome rule — `prompt`, unlike `run`, is not
251
+ * carved out of it.)
252
+ *
253
+ * A `continue` prompt stage used as the workflow START gets a WARNING: a
254
+ * follow-up turn with no prior context to lean on is almost certainly an
255
+ * authoring mistake (the continue session would have nothing to continue).
256
+ */
257
+ function checkPromptInvariants(stage: StageDef, isStart: boolean, report: ReportFn): void {
258
+ if (stage.prompt === undefined) return;
259
+ // The narrowed PromptStage arm pins `reads` to `never` — exactly why this
260
+ // gate exists: a jiti-loaded literal can still ship the field. Probe the
261
+ // erased shape, not the arm.
262
+ const erased = stage as { skill?: unknown; reads?: readonly string[] };
263
+ if (erased.skill !== undefined) {
264
+ report("prompt-with-skill");
265
+ }
266
+ if (stage.loop && stage.loop.kind !== "assess") {
267
+ report("prompt-with-loop", { kind: stage.loop.kind });
268
+ }
269
+ if (erased.reads?.length) {
270
+ report("prompt-with-reads");
271
+ }
272
+ if (typeof stage.prompt === "string" && stage.prompt.trim() === "") {
273
+ report("prompt-empty");
274
+ }
275
+ if (stage.sessionPolicy === "continue" && isStart) {
276
+ report("prompt-continue-at-start");
277
+ }
278
+ }
279
+
280
+ /**
281
+ * `inheritsArtifacts: false` is the `terminal()` factory's mechanism — it
282
+ * tells the runner to bypass upstream-artifact inheritance for a
283
+ * side-effect stage. Setting it on a `produces` stage is meaningless: a
284
+ * `produces` stage emits its own outcome and never consumes the upstream
285
+ * primary artifact in `inputForStage` (the first stage always uses
286
+ * originalInput, and inheritance only affects the prompt arg). Surface
287
+ * the redundancy as a warning so users don't author "off" flags they
288
+ * think are doing something.
289
+ */
290
+ function checkInheritsArtifactsKind(stage: StageDef, report: ReportFn): void {
291
+ if (stage.inheritsArtifacts === false && stage.kind === "produces") {
292
+ report("inherits-artifacts-on-produces");
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Skillless script stages: presence of `stage.run` declares "the runner
298
+ * calls this TS function instead of dispatching a Pi skill." Four fields
299
+ * are categorically incompatible with that contract — fail loudly at
300
+ * load time so the runner branch can assume the invariant.
301
+ *
302
+ * Mutual-exclusion rules:
303
+ *
304
+ * - `skill` — the function IS the work; a skill body would never
305
+ * be dispatched.
306
+ * - `outcome` — the function returns the `Output` envelope directly;
307
+ * there is no transcript / tool-use stream for a
308
+ * collector to scan.
309
+ * - `loop` — a TS function can write its own loop; the runner's
310
+ * per-unit session machinery doesn't apply.
311
+ * - `sessionPolicy: "continue"` — there is no Pi session at all on a
312
+ * script stage; nothing to continue.
313
+ *
314
+ * Side-effect script stages with an `outputSchema` get a warning — the
315
+ * function returns `void`, so no data ever flows through the validator.
316
+ *
317
+ * The existing `produces` + `inheritsArtifacts: false` warning
318
+ * (`checkInheritsArtifactsKind`) fires uniformly for both skill and
319
+ * script variants — same author error, same message.
320
+ */
321
+ function checkScriptStageInvariants(stage: StageDef, report: ReportFn): void {
322
+ if (!stage.run) return;
323
+
324
+ if (stage.skill !== undefined) {
325
+ report("script-with-skill");
326
+ }
327
+ if (stage.outcome) {
328
+ report("script-with-outcome");
329
+ }
330
+ if (stage.loop) {
331
+ report("script-with-loop");
332
+ }
333
+ if (stage.prompt !== undefined) {
334
+ report("script-with-prompt");
335
+ }
336
+ if (stage.sessionPolicy === "continue") {
337
+ report("script-continue-session");
338
+ }
339
+ if (stage.kind === "side-effect" && stage.outputSchema) {
340
+ report("script-side-effect-output-schema");
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Every named channel some stage in this workflow can publish: top-level
346
+ * `produces` publishes (`resolvePublishName` — the runtime write rule), PLUS
347
+ * judge verdict channels from `loop` (assess) and `verify` — judge sessions
348
+ * run as `produces` and publish to `judge.outcome.name` (`judgeStageDef`). A
349
+ * PANEL slot publishes one channel per member verdict plus the folded verdict
350
+ * (`panelVerdictChannel`). The old produces-only scan missed verdict channels,
351
+ * so a downstream `reads: ["<verdict>"]` falsely errored at load while the
352
+ * runtime `ensureNamedReads` preflight would have passed.
353
+ *
354
+ * Computed ONCE by the orchestrator and threaded to both consumers
355
+ * (`checkReadsReferences`, `checkFanoutSource`).
356
+ */
357
+ export function publishedNamesOf(w: Workflow): Set<string> {
358
+ const published = new Set<string>();
359
+ for (const [name, stage] of Object.entries(w.stages)) {
360
+ if (stage.kind === "produces") published.add(resolvePublishName(stage, name));
361
+ const slot = judgeSlotOf(stage);
362
+ if (!slot) continue;
363
+ if (isPanel(slot)) {
364
+ // A panel publishes one channel per MEMBER verdict plus the folded
365
+ // verdict (`<stage>-panel` or the author's `outcome.name`).
366
+ for (const m of slot.members) if (m?.outcome?.name) published.add(m.outcome.name);
367
+ published.add(panelVerdictChannel(slot, name));
368
+ } else if (slot.outcome?.name) {
369
+ published.add(slot.outcome.name);
370
+ }
371
+ }
372
+ return published;
373
+ }
374
+
375
+ /**
376
+ * Every name in a stage's `reads:` must be filled by some `produces` stage
377
+ * in the workflow. The publish key is `stage.outcome?.name ?? <record-key>`
378
+ * — same rule the runner enforces at write time (see
379
+ * `resolvePublishName`). Reachability isn't checked here: validating that
380
+ * the producer can actually reach the consumer in the edge graph is a
381
+ * larger graph problem and the static check is intentionally narrow —
382
+ * it answers "does this name correspond to something in the workflow at
383
+ * all?", catching typos and renames; the runtime `ensureNamedReads`
384
+ * preflight handles the "haven't fired yet" case.
385
+ */
386
+ export function checkReadsReferences(w: Workflow, published: ReadonlySet<string>, r: IssueReporter): void {
387
+ for (const [name, stage] of Object.entries(w.stages)) {
388
+ if (!stage.reads?.length) continue;
389
+ const report = r.forStage(name);
390
+ for (const read of stage.reads) {
391
+ if (published.has(read)) continue;
392
+ report("reads-unpublished", { channel: read });
393
+ }
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Load-time loop-source check (control-flow as data). A stage whose `loop`
399
+ * declares a `source` channel (via `fanout()`/`iterate()`/`assess()`) must have
400
+ * that channel published by some `produces` stage in this workflow — otherwise
401
+ * the stage splits over a channel nothing fills. Same publisher model as
402
+ * `checkReadsReferences` (`stage.outcome?.name ?? <record-key>`).
403
+ *
404
+ * WARNS (never errors): `source` is an introspective hint, and a loop without
405
+ * `source` degrades silently — mirrors the edge-compat posture. When the source
406
+ * is already in the stage's `reads`, `checkReadsReferences` owns it (errors) —
407
+ * skip to avoid double-reporting. The additive value is the `iterate`/closure-
408
+ * sourced case, which declares no `reads:` and is otherwise unchecked.
409
+ */
410
+ const LOOP_VERB = { fanout: "fans out over", iterate: "iterates over", assess: "assesses over" } as const;
411
+
412
+ export function checkFanoutSource(w: Workflow, published: ReadonlySet<string>, r: IssueReporter): void {
413
+ for (const [name, stage] of Object.entries(w.stages)) {
414
+ const spec = loopSpecOf(stage.loop);
415
+ const source = spec?.source;
416
+ if (!source || published.has(source)) continue; // no source / satisfied → degrade
417
+ if (stage.reads?.includes(source)) continue; // checkReadsReferences owns this channel
418
+ r.forStage(name)("loop-source-unpublished", { verb: LOOP_VERB[spec.kind], source });
419
+ }
420
+ }
@@ -50,6 +50,74 @@ export const DEFAULT_VALIDATION_RETRY_TIMEOUT_MS = 5 * 60 * 1000;
50
50
  export const MAX_VALIDATION_RETRY_TIMEOUT_MS = 30 * 60 * 1000;
51
51
  export const MIN_VALIDATION_RETRY_TIMEOUT_MS = 1_000;
52
52
 
53
+ /**
54
+ * Thrown by `withTimeout` (internal-utils.ts) when the caller passes a
55
+ * `SchemaTimeoutError` instance as the message. Lets validation consumers
56
+ * distinguish a schema-evaluation timeout from inner-promise rejections via
57
+ * `instanceof` instead of string-identity comparison. Lives in the validation
58
+ * domain — it is part of the schema-validation contract, not a generic
59
+ * timeout utility.
60
+ */
61
+ export class SchemaTimeoutError extends Error {}
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Retry-policy loop
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /**
68
+ * Hooks for `runValidationRetryLoop`. `H` is the caller's halt payload — a
69
+ * tagged value that aborts the loop immediately (extraction's fatal arm; the
70
+ * script path's already-recorded failure marker). Throws are NOT caught:
71
+ * they propagate to the caller's own catch posture (the runner's single
72
+ * catch site for the script path; extraction wraps inside its hooks).
73
+ */
74
+ export interface RetryLoopHooks<T, H> {
75
+ /** Produce attempt `n` (0-based; 0 = the initial production). */
76
+ produce(attempt: number): Promise<{ ok: true; value: T } | { ok: false; halt: H }>;
77
+ /** Validate one produced value. */
78
+ validate(value: T): Promise<{ ok: true; result: ValidationResult } | { ok: false; halt: H }>;
79
+ /** Between a failed validation and the next produce. `attempt` is 1-based. */
80
+ onRetry(attempt: number, failures: SchemaValidationFailure[]): Promise<{ ok: true } | { ok: false; halt: H }>;
81
+ }
82
+
83
+ export type RetryLoopOutcome<T, H> =
84
+ | { kind: "ok"; value: T }
85
+ | { kind: "exhausted"; failures: SchemaValidationFailure[] }
86
+ | { kind: "halt"; halt: H };
87
+
88
+ /**
89
+ * THE produce → validate → retry policy loop, shared by the skill path
90
+ * (extraction.ts — re-prompts the agent between attempts) and the script
91
+ * path (script-stage.ts — re-invokes the function). One structure: produce,
92
+ * validate, and while invalid — stop on `haltOnInvalid` or a spent budget
93
+ * (`"exhausted"`), otherwise fire the retry hook and go again. Total
94
+ * productions are bounded by `maxRetries + 1`.
95
+ */
96
+ export async function runValidationRetryLoop<T, H>(
97
+ policy: { maxRetries: number; haltOnInvalid: boolean },
98
+ hooks: RetryLoopHooks<T, H>,
99
+ ): Promise<RetryLoopOutcome<T, H>> {
100
+ let attempt = 0;
101
+ let produced = await hooks.produce(attempt);
102
+ if (!produced.ok) return { kind: "halt", halt: produced.halt };
103
+ let validation = await hooks.validate(produced.value);
104
+ if (!validation.ok) return { kind: "halt", halt: validation.halt };
105
+
106
+ while (!validation.result.valid) {
107
+ if (policy.haltOnInvalid || attempt >= policy.maxRetries) {
108
+ return { kind: "exhausted", failures: validation.result.failures };
109
+ }
110
+ attempt++;
111
+ const retried = await hooks.onRetry(attempt, validation.result.failures);
112
+ if (!retried.ok) return { kind: "halt", halt: retried.halt };
113
+ produced = await hooks.produce(attempt);
114
+ if (!produced.ok) return { kind: "halt", halt: produced.halt };
115
+ validation = await hooks.validate(produced.value);
116
+ if (!validation.ok) return { kind: "halt", halt: validation.halt };
117
+ }
118
+ return { kind: "ok", value: produced.value };
119
+ }
120
+
53
121
  // ---------------------------------------------------------------------------
54
122
  // Validation
55
123
  // ---------------------------------------------------------------------------
@@ -59,7 +127,7 @@ export const MIN_VALIDATION_RETRY_TIMEOUT_MS = 1_000;
59
127
  * to return synchronously or as a Promise; this function mirrors that —
60
128
  * callers must `await` the result. Both seams that drive validation
61
129
  * (`retryUntilValid` in extraction.ts and `ensureInputValid` in
62
- * stage-lifecycle.ts) are async, so awaiting a sync value is free (one
130
+ * run-stage.ts) are async, so awaiting a sync value is free (one
63
131
  * microtask) and async schemas (I/O-backed checks, async-by-default libs
64
132
  * like ArkType) round-trip without a sync-only escape hatch.
65
133
  */