@juicesharp/rpiv-workflow 1.20.0 → 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 (106) hide show
  1. package/api.ts +1 -1
  2. package/audit-ctx.ts +103 -0
  3. package/audit-rows.ts +18 -0
  4. package/audit.ts +119 -164
  5. package/built-ins.ts +26 -6
  6. package/chain-state.ts +119 -68
  7. package/command-run.ts +35 -30
  8. package/command.ts +10 -4
  9. package/docs/workflow-authoring.md +34 -2
  10. package/events.ts +44 -4
  11. package/execution-host.ts +75 -0
  12. package/host.ts +137 -82
  13. package/internal-utils.ts +89 -3
  14. package/internal.ts +1 -0
  15. package/judge.ts +23 -11
  16. package/load/alias.ts +3 -3
  17. package/load/index.ts +15 -1
  18. package/load/issues.ts +2 -2
  19. package/load/legacy.ts +2 -2
  20. package/load/resolve-default.ts +3 -4
  21. package/load/skill-contract-phase.ts +1 -1
  22. package/loop-constructors.ts +19 -618
  23. package/loop-def.ts +60 -15
  24. package/loop-kinds.ts +319 -62
  25. package/loop-parallel.ts +250 -0
  26. package/loop-waves.ts +99 -0
  27. package/loop.ts +106 -80
  28. package/loops/constructors.ts +334 -0
  29. package/loops/derivations.ts +65 -0
  30. package/loops/introspection.ts +184 -0
  31. package/loops/panel.ts +196 -0
  32. package/loops/verify.ts +99 -0
  33. package/messages.ts +58 -33
  34. package/outcomes/collectors/index.ts +1 -0
  35. package/outcomes/collectors/text-scan.ts +47 -0
  36. package/outcomes/collectors/transcript-path.ts +2 -15
  37. package/outcomes/collectors/union.ts +2 -1
  38. package/outcomes/collectors/url.ts +2 -14
  39. package/outcomes/collectors/workspace-diff.ts +1 -1
  40. package/outcomes/git-commit.ts +57 -6
  41. package/output-spec.ts +1 -1
  42. package/output.ts +59 -1
  43. package/package.json +16 -6
  44. package/preview.ts +18 -18
  45. package/registration.ts +11 -4
  46. package/routing-dsl.ts +53 -41
  47. package/routing.ts +46 -0
  48. package/runner/chain-advance.ts +30 -17
  49. package/runner/errors.ts +7 -30
  50. package/runner/failure.ts +67 -13
  51. package/runner/input-validation.ts +8 -5
  52. package/runner/preflight.ts +17 -21
  53. package/runner/resume-entry.ts +23 -3
  54. package/runner/resume-loop.ts +50 -29
  55. package/runner/resume.ts +96 -10
  56. package/runner/run-context.ts +20 -16
  57. package/runner/run-stage.ts +125 -91
  58. package/runner/runner.ts +163 -69
  59. package/runner/script-stage.ts +23 -29
  60. package/schema-compat.ts +1 -2
  61. package/semaphore.ts +55 -0
  62. package/sessions/extraction.ts +103 -60
  63. package/sessions/halt-routing.ts +195 -0
  64. package/sessions/index.ts +2 -2
  65. package/sessions/locate.ts +60 -9
  66. package/sessions/reattach.ts +28 -20
  67. package/sessions/sessions.ts +103 -191
  68. package/sessions/spawn.ts +132 -119
  69. package/sessions/success-persist.ts +89 -0
  70. package/skill-contracts/composition.ts +8 -10
  71. package/skill-contracts/harvest.ts +3 -2
  72. package/skill-contracts/registry.ts +1 -1
  73. package/stage-def.ts +115 -47
  74. package/stage-errors.ts +84 -0
  75. package/stage-identity.ts +56 -0
  76. package/startup.ts +1 -0
  77. package/state/paths.ts +11 -3
  78. package/state/raw.ts +2 -3
  79. package/state/resolve.ts +3 -3
  80. package/state/state.ts +26 -3
  81. package/state/writes.ts +1 -1
  82. package/types.ts +97 -43
  83. package/validate/contract-compat.ts +16 -11
  84. package/validate/graph.ts +10 -1
  85. package/validate/issue.ts +20 -6
  86. package/validate/stage-rules.ts +139 -60
  87. package/validate-output.ts +27 -20
  88. package/validate-workflow.ts +5 -3
  89. package/validation-bounds.ts +35 -0
  90. package/load/cache.test.ts +0 -82
  91. package/load/shape-guards.test.ts +0 -77
  92. package/outcomes/collectors/directory-path.test.ts +0 -64
  93. package/outcomes/collectors/tool-call.test.ts +0 -112
  94. package/outcomes/collectors/transcript-path.test.ts +0 -70
  95. package/outcomes/collectors/union.test.ts +0 -113
  96. package/outcomes/collectors/url.test.ts +0 -67
  97. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  98. package/outcomes/git-commit.test.ts +0 -240
  99. package/outcomes/parsers/json-body.test.ts +0 -80
  100. package/runner/by-name.test.ts +0 -95
  101. package/runner/by-run-id.test.ts +0 -115
  102. package/runner/header-write-failure.test.ts +0 -64
  103. package/runner/resume-loop.test.ts +0 -1410
  104. package/runner/resume-session.test.ts +0 -400
  105. package/runner/resume.test.ts +0 -1805
  106. package/sessions/locate.test.ts +0 -77
package/state/state.ts CHANGED
@@ -29,6 +29,15 @@ import type { RunTrigger } from "../triggers.js";
29
29
  // Row shapes
30
30
  // ---------------------------------------------------------------------------
31
31
 
32
+ /**
33
+ * On-disk status stamped on every `WorkflowStage` row. `"skipped"` is the
34
+ * FROZEN on-disk marker for a user-cancellation: the canonical in-memory name
35
+ * is `RunTermination.status: "cancelled"` (../types.ts), and the sole writer of
36
+ * a `"skipped"` row is `recordCancellation` (../audit.ts). The split is
37
+ * deliberate — the row value is a versioned on-disk contract (see
38
+ * `STATE_SCHEMA_VERSION`), so it keeps its long-standing spelling even though
39
+ * the in-memory outcome reads "cancelled". Literal unchanged.
40
+ */
32
41
  export type StageStatus = "completed" | "failed" | "skipped" | "aborted";
33
42
 
34
43
  /**
@@ -114,6 +123,15 @@ export interface WorkflowStage {
114
123
  role?: UnitRole;
115
124
  unitId?: string;
116
125
  unitIndex?: number;
126
+ /**
127
+ * Marks a NON-terminal collect-all fanout unit halt (`recordUnitHalt`):
128
+ * the unit failed but the run survives and a `failedOutput` sentinel fills its
129
+ * declared slot. Distinguishes a SOFT halt from a hard `recordTerminalFailure`
130
+ * row (byte-identical otherwise) so the resume fold rebuilds the
131
+ * sentinel by `unitIndex` rather than re-dispatching the unit. Absent on every
132
+ * other row (`undefined` is dropped by `JSON.stringify`).
133
+ */
134
+ collected?: true;
117
135
  }
118
136
 
119
137
  /**
@@ -137,10 +155,15 @@ export interface LoopCapRow {
137
155
  * `reconstructState` refuses headers carrying any other version
138
156
  * (`reason: "version-mismatch"`) instead of silently mis-replaying.
139
157
  *
140
- * BACK-COMPAT RULE: an absent `v` is version 1 — files written before the
141
- * field existed resume normally. Tested in `runner/resume.test.ts`.
158
+ * v2 = parallel-fanout trails: completion rows are placed by `unitIndex` (not
159
+ * trail order), and a `collected:true` failed row's `errMsg` rebuilds a
160
+ * `failedOutput` sentinel. A v1 trail (sequential fold) — and an absent
161
+ * `v`, which resolves to 1 — is rejected by `reconstructState`'s header version
162
+ * gate with `version-mismatch` ("start a fresh run"): there is no in-place
163
+ * migration (sole consumer rpiv-pi; no back-compat). Tested in
164
+ * `runner/resume.test.ts`.
142
165
  */
143
- export const STATE_SCHEMA_VERSION = 1;
166
+ export const STATE_SCHEMA_VERSION = 2;
144
167
 
145
168
  /** First line of the JSONL file. */
146
169
  export interface WorkflowHeader {
package/state/writes.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * or checksums touch this file only. This is NOT a full storage-backend
6
6
  * seam: `reads.ts`, `raw.ts`, and `names.ts` hit `node:fs` directly, so
7
7
  * swapping the backend means touching all of `state/` (a `RunStore` port
8
- * is a known possible follow-up, deliberately deferred — M13).
8
+ * is a known possible follow-up, deliberately deferred).
9
9
  *
10
10
  * writeHeader — boolean; the runner refuses the run start on failure.
11
11
  * appendStage — boolean; allocator gates monotonic counters on it.
package/types.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Runtime types. Three nouns flow through the workflow runtime:
3
3
  *
4
4
  * - `RunContext` — per-run carry (cwd, runId, workflow, state, visited,
5
- * continueHost, registeredSkills, maxBackwardJumps). Read by every
5
+ * registeredSkills, resolveModel, maxBackwardJumps). Read by every
6
6
  * layer; mutated only by the runner.
7
7
  * - `RunState` — mutable bookkeeping (output, counters, telemetry,
8
8
  * termination). Read by every layer; mutated through the chain-state
@@ -26,14 +26,20 @@
26
26
  import type { StageDef, Workflow } from "./api.js";
27
27
  import type { LifecycleDispatcher, LifecycleListeners } from "./events.js";
28
28
  import type { Artifact } from "./handle.js";
29
- import type { WorkflowHost, WorkflowHostContext } from "./host.js";
29
+ import type { ModelSelection, WorkflowHost, WorkflowHostContext } from "./host.js";
30
30
  import type { Output } from "./output.js";
31
31
  import type { SkillContractMap } from "./skill-contract.js";
32
+ import type { SessionRef } from "./state/index.js";
32
33
  import type { RunTrigger } from "./triggers.js";
33
34
 
34
35
  // Re-export the host port so runtime layers can pull `RunContext`,
35
- // `RunState`, and the threaded ctx from this single runtime-types module.
36
- export type { WorkflowHostContext } from "./host.js";
36
+ // `RunState`, and the threaded ctx + model type from this single
37
+ // runtime-types module.
38
+ export type {
39
+ ModelSelection,
40
+ WorkflowHostContext,
41
+ WorkflowSessionContext,
42
+ } from "./host.js";
37
43
 
38
44
  /** Mutable per-run bookkeeping threaded through the chain by reference. */
39
45
  export interface RunState {
@@ -75,9 +81,27 @@ export interface RunState {
75
81
  stagesCompleted: number;
76
82
  /** Most recently allocated stageNumber. Advances on every recordStage call. */
77
83
  lastAllocatedStageNumber: number;
84
+ /**
85
+ * The `SessionRef` of the most recently completed SINGLE stage — what a
86
+ * downstream `sessionPolicy: "continue"` stage forks from (its predecessor's
87
+ * persisted child session). Rolls forward like `output`: set on every
88
+ * single-stage success (`recordStageSuccess`) and reconstructed by the resume
89
+ * fold from the last completed single-stage row. Loop UNITS never touch it
90
+ * (they take the unit branch of `recordStageSuccess` and fold via
91
+ * `foldUnitRow`), so a `continue` right after a loop forks the last single
92
+ * stage — the loop was a fan-out excursion with no single session to continue.
93
+ * Undefined at run start or when the predecessor persisted no session (an
94
+ * in-memory host); either degrades a `continue` stage to a fresh dispatch.
95
+ */
96
+ lastSession?: SessionRef;
78
97
 
79
98
  // ── Telemetry (post-hoc only; not consulted by chain advancement) ──
80
99
  telemetry: {
100
+ /**
101
+ * Run-wide cumulative count of backward jumps (decision-edge routes to
102
+ * an already-visited stage). Never reset. The halt decision reads the
103
+ * per-destination `RunContext.revisits` ledger, not this total.
104
+ */
81
105
  backwardJumps: number;
82
106
  /**
83
107
  * Routing rows whose JSONL append failed mid-run. The chain advanced
@@ -103,8 +127,9 @@ export interface RunState {
103
127
  /**
104
128
  * How the run ended — `"running"` until the single end-of-run write via
105
129
  * `terminate()` (audit.ts), the ONLY sanctioned mutator. Discriminated so
106
- * every outcome is representable (cancellation used to be smuggled
107
- * through the error string) and so a halt site can't set half the shape.
130
+ * every outcome is representable — cancellation is its own status, not
131
+ * smuggled through the error string — and so a halt site can't set half
132
+ * the shape.
108
133
  */
109
134
  termination: RunTermination;
110
135
  }
@@ -119,7 +144,10 @@ export interface RunState {
119
144
  * - `"failed"` — a stage/preflight/routing halt; `error` carries the cause.
120
145
  * - `"aborted"` — cooperative cancellation via `RunWorkflowOptions.signal`,
121
146
  * or the model aborted the stage.
122
- * - `"cancelled"` — the user dismissed the live session mid-stage.
147
+ * - `"cancelled"` — the user dismissed the live session mid-stage. Recorded
148
+ * on disk as the legacy FROZEN `StageStatus: "skipped"` (state/state.ts),
149
+ * written solely by `recordCancellation` (audit.ts); the canonical name
150
+ * (`"cancelled"`) and the frozen row value (`"skipped"`) differ by design.
123
151
  */
124
152
  export type RunTermination =
125
153
  | { status: "running"; error?: undefined }
@@ -141,9 +169,9 @@ export interface RunWorkflowOptions {
141
169
  workflow: Workflow;
142
170
  /** Passed to the start stage as its argument. */
143
171
  input: string;
144
- /** Required for "continue"-policy stages (host.sendUserMessage). */
172
+ /** Registry-level host — enumerated once for the skill-registration snapshot. */
145
173
  host?: WorkflowHost;
146
- /** Defaults to MAX_BACKWARD_JUMPS. */
174
+ /** Per-destination decision-edge re-entry cap. Defaults to MAX_BACKWARD_JUMPS. */
147
175
  maxBackwardJumps?: number;
148
176
  /** Run-wide safety cap on loop units (all kinds). Defaults to MAX_ITERATIONS. */
149
177
  maxIterations?: number;
@@ -170,6 +198,12 @@ export interface RunWorkflowOptions {
170
198
  * mid-stage.
171
199
  */
172
200
  signal?: AbortSignal;
201
+ /**
202
+ * Per-stage model-override resolver, injected by the embedder. Threaded onto
203
+ * `RunContext.resolveModel` → every `StageSession.model`; the host applies it
204
+ * at child-session creation. Undefined ⇒ host default for every stage.
205
+ */
206
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
173
207
  /**
174
208
  * Human-readable alias for this run. Stored in the JSONL header and the
175
209
  * sidecar names.json index. Rejected if already in use — the error
@@ -185,8 +219,8 @@ export interface RunWorkflowResult {
185
219
  * this to `readLastStage` / `listArtifacts` / future inspect-past-run
186
220
  * helpers without recomputing the slug.
187
221
  *
188
- * Undefined ONLY for pre-flight rejections (start stage not declared,
189
- * continue-policy stages without pi) where no JSONL file was created.
222
+ * Undefined ONLY for pre-flight rejections (e.g. start stage not declared,
223
+ * name collision) where no JSONL file was created.
190
224
  */
191
225
  runId?: string;
192
226
  stagesCompleted: number;
@@ -237,20 +271,30 @@ export interface RunContext {
237
271
  runId: string;
238
272
  workflow: Workflow;
239
273
  /**
240
- * Upper bound for stage status display — count of stages reachable from
274
+ * Upper bound for stage-progress display — count of stages reachable from
241
275
  * `workflow.start`, computed once at run start. The actual stage count
242
- * is path-dependent (a predicate edge may short-circuit), so this is
243
- * the denominator users see; the numerator is the live stage index.
276
+ * is path-dependent (a predicate edge may short-circuit), so this is the
277
+ * denominator surfaced through the lifecycle `LifecycleContext.totalStages`
278
+ * (e.g. the lane-dock `visited/totalStages` progress bar); the numerator is
279
+ * the live stage index.
244
280
  */
245
281
  totalStages: number;
246
282
  state: RunState;
247
283
  /**
248
- * Stage names already executed in this run. The backward-jump guard
249
- * increments `state.telemetry.backwardJumps` on every re-entry; revise →
250
- * implement loops legitimately revisit stages, but unbounded loops trip
251
- * the cap.
284
+ * Stage names already executed in this run. A decision edge resolving to
285
+ * a visited stage is a backward jump; revise → implement loops
286
+ * legitimately revisit stages, but unbounded loops trip the cap.
252
287
  */
253
288
  visited: Set<string>;
289
+ /**
290
+ * Decision-edge re-entry count per destination stage — the backward-jump
291
+ * guard's ledger. Each stage may be re-entered at most `maxBackwardJumps`
292
+ * times; counting per destination (not as a shared streak) keeps the
293
+ * retry budget invariant to how many decision edges a fix cycle crosses
294
+ * per iteration, and gives unrelated loops independent budgets by
295
+ * construction.
296
+ */
297
+ revisits: Map<string, number>;
254
298
  /**
255
299
  * Set of bare skill names registered with Pi at workflow start (e.g.
256
300
  * "research", "blueprint" — the `skill:` prefix is stripped). Snapshot
@@ -281,24 +325,12 @@ export interface RunContext {
281
325
  */
282
326
  skillContracts?: SkillContractMap;
283
327
  /**
284
- * Pi `ExtensionAPI` handle, retained as the FALLBACK send-path for
285
- * continue-policy stages — used only when the live inner ctx lacks
286
- * `sendUserMessage` (i.e. the workflow's first stage is continue and
287
- * the runtime is still on the outer command ctx). Everywhere else,
288
- * `CONTINUE_HANDLER` prefers `ctx.sendUserMessage` because Pi marks
289
- * this handle stale after the first `ctx.newSession()`. Touching it
290
- * for anything other than the fallback path will throw "extension
291
- * ctx is stale" on every workflow whose first stage is fresh.
292
- *
293
- * Read-only registry needs go through `registeredSkills` (snapshotted
294
- * at workflow start). Continue-policy presence checks
295
- * (`enforceSessionInvariants`) still gate on this field so the
296
- * fallback path has a working host when the start-stage path needs it.
297
- *
298
- * Naming: deliberately NOT called `host`. Future code-readers see the
299
- * field name and know the constraint without reading the JSDoc.
328
+ * Resolve a per-stage model override, injected by the embedder (rpiv-pi maps
329
+ * each `{ stage, skill }` to its model/effort override). The runner threads
330
+ * the result onto every `StageSession.model`; the host applies it at child
331
+ * creation (NOT via global mutation). Undefined ⇒ host default.
300
332
  */
301
- continueHost?: WorkflowHost;
333
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
302
334
  maxBackwardJumps: number;
303
335
  /**
304
336
  * Run-wide safety cap on loop units — clamps the effective cap of EVERY
@@ -401,13 +433,36 @@ export interface StageSession extends SessionContext {
401
433
  /** Pre-stage snapshot value (undefined if the stage's `outcome` has no `snapshot`). */
402
434
  snapshot: unknown;
403
435
  /**
404
- * Pi `ExtensionAPI` handle reserved for the continue-policy handler
405
- * (`spawn.ts`). Required iff `stage.sessionPolicy === "continue"`.
406
- * Same constraint as `RunContext.continueHost`: stale after any prior
407
- * `ctx.newSession()`, so the runner MUST NOT read it for registry
408
- * inspection. See `RunContext.continueHost` JSDoc.
436
+ * Resolved per-unit model override (from `RunContext.resolveModel`), applied
437
+ * by the host at child-session creation — NOT via global mutation. Undefined
438
+ * ⇒ host default.
439
+ */
440
+ model?: ModelSelection;
441
+ /**
442
+ * Per-child cooperative-abort signal. Threaded from `RunContext.signal` (the
443
+ * fanout dispatcher narrows it to a per-generation controller) so
444
+ * an aborted run interrupts an in-flight child, not just the between-stage
445
+ * seam.
446
+ */
447
+ signal?: AbortSignal;
448
+ /**
449
+ * When true (a collect-all fanout unit), a unit failure soft-halts THIS unit
450
+ * (non-terminal failed-output sentinel handed to `onSuccess`) instead of
451
+ * terminating the whole run. Set by `buildUnitSession` for non-fail-fast
452
+ * fanout; the soft-halt routing lives in `postStage`.
453
+ */
454
+ collectAll?: boolean;
455
+ /**
456
+ * The per-unit lane key for rpiv-pi's lane dock/viewer — set ONLY for fan-out
457
+ * units (`e.loop.kind === "fanout"`), to the unit's declared `index`. Undefined for
458
+ * sequential loop units (iterate/assess) and single stages, which collapse onto the
459
+ * host's reserved single-unit slot so the lane (parent) row keeps showing the one
460
+ * live session. Distinct from `unit.index` (the audit identity threaded for every
461
+ * loop unit): this field exists purely so the host can decide which spawns become
462
+ * individually-addressable concurrent sub-lanes. `openChild` threads it into
463
+ * `spawnChild`'s `unitIndex`; inert on a non-lane host.
409
464
  */
410
- continueHost?: WorkflowHost;
465
+ laneUnitIndex?: number;
411
466
  /** Only set for continue stages — branch slice offset. */
412
467
  branchOffset?: number;
413
468
  /**
@@ -422,8 +477,7 @@ export interface StageSession extends SessionContext {
422
477
  /**
423
478
  * Receives the stage's VALIDATED Output envelope (not just
424
479
  * `artifacts[0]`) — loop continuations thread it into `accumulated` /
425
- * `feedForward` directly, removing the `run.state.output!` back-read
426
- * pattern the old drivers carried.
480
+ * `feedForward` directly, with no `run.state.output!` back-read.
427
481
  *
428
482
  * Return type is `Promise<unknown>` (not `void`) so the chain walk's
429
483
  * `ChainOutcome`-returning continuations plug in directly; the session
@@ -12,7 +12,7 @@
12
12
  * - linear `data` + `status` → RUNTIME (`ensureContractInputValid`).
13
13
  * - produces self-check → PRODUCE-TIME (`extraction.ts:effectiveOutputSchema`).
14
14
  *
15
- * Per-stage schema fallback (DECIDED, D4): when a stage carries no contract,
15
+ * Per-stage schema fallback (DECIDED): when a stage carries no contract,
16
16
  * `checkEdgeSchemaCompat` falls back to the stage's own
17
17
  * `outputSchema`/`inputSchema`. That fallback lives HERE, not in harvest:
18
18
  * harvest derives per-SKILL contracts from dispatching stages only
@@ -22,11 +22,12 @@
22
22
  */
23
23
 
24
24
  import { marksReadsData, STOP, type Workflow } from "../api.js";
25
- import { isDispatchingStage, resolvePublishName, resolveSkill } from "../chain-state.js";
26
25
  import { extractJsonSchema } from "../json-schema.js";
27
- import { judgeOf } from "../loop-constructors.js";
26
+ import { forEachJudgeChannel } from "../loop-constructors.js";
28
27
  import type { ProducesSpec, SkillContractMap } from "../skill-contract.js";
29
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";
30
31
  import type { IssueReporter } from "./issue.js";
31
32
 
32
33
  /**
@@ -74,7 +75,7 @@ export function checkPredicateSchemas(
74
75
  * (registry-sourced, falling back to the stage's own output/input schema — see
75
76
  * the module header for why the fallback lives here). Warns on a definite
76
77
  * mismatch; degrades on predicate/STOP edges and opaque schemas via the shared
77
- * `compareDataChannel` core (same engine `canCompose` consults — D4).
78
+ * `compareDataChannel` core (same engine `canCompose` consults).
78
79
  *
79
80
  * Edge-local is correct here — the rolling primary flows along edges. The
80
81
  * many-to-one NAMED (`reads`) channel is handled by `checkReadsChannelCompat`.
@@ -150,12 +151,15 @@ export function checkReadsChannelCompat(
150
151
  const produces = skillContracts.get(resolveSkill(stage, name))?.produces;
151
152
  if (produces) indexPublisher(resolvePublishName(stage, name), name, produces);
152
153
  }
153
- // A skill judge is a publisher of its verdict channel; unsigned judges degrade.
154
- const judge = judgeOf(stage);
155
- if (judge?.skill && judge.outcome?.name) {
156
- const produces = skillContracts.get(judge.skill)?.produces;
157
- if (produces) indexPublisher(judge.outcome.name, name, produces);
158
- }
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
+ });
159
163
  }
160
164
 
161
165
  for (const [consumerName, consumer] of Object.entries(w.stages)) {
@@ -167,7 +171,8 @@ export function checkReadsChannelCompat(
167
171
  : undefined;
168
172
  if (!consumes?.reads) continue; // unsigned consumer — degrade
169
173
  const report = r.forStage(consumerName);
170
- for (const channel of consumer.reads) {
174
+ for (const rawRead of consumer.reads) {
175
+ const channel = readName(rawRead);
171
176
  const publishers = publishersByChannel.get(channel);
172
177
  if (!publishers) continue; // "no publisher at all" is checkReadsReferences's job
173
178
  for (const { stage: producerName, produces } of publishers) {
package/validate/graph.ts CHANGED
@@ -9,6 +9,12 @@
9
9
  * the orchestrator gates `checkReachability` on that code's presence (a BFS
10
10
  * over unenumerable edges would emit "unreachable" cascades whose root cause
11
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.
12
18
  */
13
19
 
14
20
  import { type EdgeTarget, STOP, type Workflow } from "../api.js";
@@ -54,7 +60,10 @@ export function checkEdgeTargets(w: Workflow, r: IssueReporter): void {
54
60
  }
55
61
  }
56
62
 
57
- /** Stages with no outgoing edge are implicit terminals — usually a missing connection. */
63
+ /**
64
+ * Stages with no outgoing edge are implicit terminals — usually a missing
65
+ * connection. ("terminal" = graph-sink sense; see the module header.)
66
+ */
58
67
  export function checkMissingEdges(w: Workflow, r: IssueReporter): void {
59
68
  for (const name of Object.keys(w.stages)) {
60
69
  if (!(name in w.edges)) {
package/validate/issue.ts CHANGED
@@ -7,8 +7,7 @@
7
7
  * never drift between two emissions of the same rule) and its message
8
8
  * template. Checks report `(code, params)` through an `IssueReporter`; the
9
9
  * reporter renders the prose once, here. Consumers filter/assert on `code`
10
- * — never on message text (the message-regex control flow this replaces was
11
- * finding C5).
10
+ * — never on message text.
12
11
  *
13
12
  * Messages NEVER embed the stage name — `stage` is carried structurally on
14
13
  * the issue and display renderers compose the attribution
@@ -113,6 +112,16 @@ export const ISSUE_DEFS = {
113
112
  "error",
114
113
  (p) => `loop.max: ${p.max} — must be an integer >= 1 (run.maxIterations caps the upper bound)`,
115
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
+ ),
116
125
  "loop-requires-produces": def<{ kind: string }>(
117
126
  "error",
118
127
  (p) => `${p.kind} requires kind "produces" — each unit runs an outcome collector`,
@@ -224,6 +233,12 @@ export const ISSUE_DEFS = {
224
233
  (p) =>
225
234
  `reads "${p.channel}" but no produces stage in this workflow publishes it (check outcome.name or stage record key)`,
226
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
+ ),
227
242
 
228
243
  // --- contract / schema compatibility --------------------------------------
229
244
  "route-reads-unvalidated-data": def(
@@ -283,10 +298,9 @@ type ReportArgs<C extends ValidationIssueCode> = keyof ValidationIssueParamsOf<C
283
298
  export type ReportFn = <C extends ValidationIssueCode>(code: C, ...args: ReportArgs<C>) => void;
284
299
 
285
300
  /**
286
- * Issue reporter bound to one workflow + one sink — replaces the
287
- * `(w, name, stage, issues)` four-tuple every check used to thread. Checks
288
- * hold either the workflow-level `report` or a `forStage(name)` binding;
289
- * construction (severity lookup + render) happens in exactly one place.
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.
290
304
  */
291
305
  export interface IssueReporter {
292
306
  /** Workflow-level issue (no stage attribution). */