@juicesharp/rpiv-workflow 1.19.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
@@ -7,7 +7,9 @@ Complete reference for the `@juicesharp/rpiv-workflow` authoring DSL. A workflow
7
7
  - [defineWorkflow](#defineworkflow)
8
8
  - [Stage factories](#stage-factories)
9
9
  - [produces](#produces)
10
- - [iterate (sequential accumulation)](#iterate-sequential-accumulation)
10
+ - [Loops (fanout / iterate / assess)](#loops-fanout--iterate--assess)
11
+ - [Per-stage verification (verify)](#per-stage-verification-verify)
12
+ - [Adversarial verification (panel)](#adversarial-verification-panel)
11
13
  - [acts](#acts)
12
14
  - [terminal](#terminal)
13
15
  - [Script stages](#script-stages)
@@ -15,6 +17,7 @@ Complete reference for the `@juicesharp/rpiv-workflow` authoring DSL. A workflow
15
17
  - [Edge targets](#edge-targets)
16
18
  - [Conditional routing](#conditional-routing)
17
19
  - [gate](#gate)
20
+ - [match](#match)
18
21
  - [defineRoute](#defineroute)
19
22
  - [Predicate helpers](#predicate-helpers)
20
23
  - [Outcomes](#outcomes)
@@ -65,16 +68,11 @@ produces({
65
68
  outputSchema: typeboxSchema(Type.Object({ blockers_count: Type.Integer() })),
66
69
  })
67
70
 
68
- // With fanout (one Pi session per unit, all units known up front)
71
+ // With a loop (one Pi session per unit — see Loops below).
72
+ // `fanout()` / `iterate()` / `assess()` all build a `loop:` value.
69
73
  produces({
70
- outcome: myOutcome,
71
- fanout: myFanoutFn,
72
- })
73
-
74
- // With iterate (sequential, accumulating — see below)
75
- produces({
76
- outcome: myOutcome, // outcome MUST carry a `name`
77
- iterate: myIterateFn,
74
+ outcome: myOutcome, // outcome MUST carry a `name` for a collecting loop
75
+ loop: fanout({ units: myUnitsFn }),
78
76
  })
79
77
 
80
78
  // With validation retry
@@ -98,63 +96,291 @@ produces({
98
96
  | `onInvalid` | `"retry"` | `"retry"` (re-invoke up to `maxRetries`) or `"halt"` (fail fast). |
99
97
  | `maxRetries` | — | Max retries on schema rejection. |
100
98
  | `validateTimeoutMs` | — | Timeout for async schemas. |
101
- | `fanout` | none | `FanoutFn` — decomposes work into N units, one Pi session per unit. All units computed up front. |
102
- | `iterate` | none | `IterateFn` — sequential, accumulating units pulled one at a time, each seeing prior units' outputs. Requires `outcome.name`. See [iterate](#iterate-sequential-accumulation). |
99
+ | `loop` | none | `LoopDef` — opt-in unit loop authored via `fanout()` / `iterate()` / `assess()`. Expands the stage into one Pi session per unit through one driver. Mutually exclusive with `run`/`prompt` and `sessionPolicy: "continue"`. See [Loops](#loops-fanout--iterate--assess). |
103
100
  | `sessionPolicy` | `"fresh"` | `"fresh"` (new session) or `"continue"` (reuse prior session). |
104
101
 
105
- ### iterate (sequential accumulation)
102
+ ### Loops (fanout / iterate / assess)
103
+
104
+ A **loop** expands one stage into one Pi session per unit, all running the identical stage path with a distinct unit identity. You don't set the loop kind directly — you author a `loop:` value with one of three constructors. Each validates at construction (invalid shapes throw before the workflow ever loads) and fills the kind-specific defaults:
105
+
106
+ | Constructor | Generation | Stage kind | Use when |
107
+ |---|---|---|---|
108
+ | `fanout({ units })` | **push** — all units computed up front, blind to one another | any (`acts` for side-effects, `produces` to collect) | independent units (e.g. `implement` one pass per plan phase) |
109
+ | `iterate({ next })` | **pull** — one unit per call, fed the accumulated prefix | requires `produces` + named `outcome` | each unit must build on the last (e.g. `blueprint` per review phase) |
110
+ | `assess({ judge, done, feedForward })` | **producer → judge rounds** until the model says done | requires `produces` + named `outcome` | refine a single artifact until a model-judge approves it |
111
+
112
+ All three share the introspectable facet (`source`, `unit`) and the policy knobs (`max`, `onCap`, `result`) described under [the knobs](#the-loop-knobs) below.
106
113
 
107
- `iterate` is a field on a `produces` stage — the **sequential, accumulating** dual of `fanout`. Where `fanout` computes every unit up front and runs them blind to one another, `iterate` pulls one unit at a time: the runner calls your `IterateFn` per unit, feeding it the validated outputs of every prior unit in the same stage. Return the next unit, or `null`/`undefined` to terminate.
114
+ #### fanout (push — all units up front)
108
115
 
109
- Each unit runs the stage's `outcome` collector exactly like a one-shot `produces` pass — it validates against `outputSchema`, appends its `Output` to `state.named[outcome.name]`, and rolls the primary artifact forward. So a downstream stage (or a downstream `fanout`) can read every accumulated output straight from `state`.
116
+ `fanout()` computes the full unit list once, then runs each unit as its own session. On an **`acts`** stage the units are pure side-effects (one bare audit row each). On a **`produces`** stage each unit is *collecting* — it runs the full collect → validate → publish path and appends its `Output` to `state.named[outcome.name]`, so a collecting fanout **requires `outcome.name`**. An empty `units()` return falls through to the single-stage path (no loop).
110
117
 
111
118
  ```typescript
112
- import type { IterateFn } from "@juicesharp/rpiv-workflow";
113
-
114
- // One blueprint pass per review phase, each building on the plans already produced.
115
- const perPhase: IterateFn = ({ artifact, accumulated, index, cwd, state }) => {
116
- if (artifact?.handle.kind !== "fs") return null;
117
- const phases = readPhases(artifact.handle.path, cwd);
118
- if (index >= phases.length) return null; // terminator
119
- const prior = accumulated.flatMap((o) => o.artifacts).map((a) => pathOf(a));
120
- return {
121
- prompt: `${artifact.handle.path} Phase ${phases[index].n}` +
122
- (prior.length ? `\nPrior plans (build on them): ${prior.join(", ")}` : ""),
123
- label: `phase ${index + 1}/${phases.length}`,
124
- id: `phase-${phases[index].n}`, // stable audit key
125
- };
126
- };
119
+ import { acts, fanout, type Unit } from "@juicesharp/rpiv-workflow";
120
+
121
+ // rpiv-pi's FRONTMATTER_PHASE_FANOUT — one implement session per plan phase.
122
+ const FRONTMATTER_PHASE_FANOUT = fanout({
123
+ source: "plans", // the named channel units split FROM
124
+ unit: { by: "frontmatter-array", pattern: "phases" }, // opaque introspection hint
125
+ max: MAX_PHASES,
126
+ units: ({ state, cwd }) => {
127
+ const plan = latestFsArtifact(state, "plans");
128
+ if (plan?.handle.kind !== "fs") return []; // empty ⇒ single-stage fall-through
129
+ const promptPath = handleToString(plan.handle);
130
+ return planPhaseRecords(readArtifactFile(plan.handle.path, cwd)).map((r) => ({
131
+ prompt: `${promptPath} Phase ${r.n}: ${r.title}`.trimEnd(),
132
+ label: `phase ${r.index + 1}/${r.total}`, // human display tag
133
+ }));
134
+ },
135
+ });
127
136
 
128
- produces({ outcome: rpivBucketOutcome("plans"), iterate: perPhase })
137
+ // acts stage + fanout loop — side-effect units (no per-unit collector)
138
+ acts({ loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] })
129
139
  ```
130
140
 
131
- **`IterateContext` (what each call receives):**
141
+ A **`Unit`** is `{ prompt, label, id? }`: `prompt` is the body sent to the skill, `label` is the human display tag woven into the status line / per-unit toast / decorated audit row, and `id` is the stable audit identity (falls back to `label`). Set `id` when `label` may be reworded — the resume drift guard and post-hoc tooling join on `id ?? label`.
142
+
143
+ **`FanoutContext` (what `units()` receives):** `{ cwd, artifact, state }` — `artifact` is the primary inherited from upstream (undefined when the loop stage is the entry point); `state` is the read-only `RunState`. A thrown error halts the stage attributed to it.
144
+
145
+ #### iterate (pull — accumulating)
146
+
147
+ `iterate()` pulls one unit at a time: the runner calls your `IterateFn` per unit, feeding it the validated `Output`s of every prior unit in this generation. Return the next unit, or `null`/`undefined` to terminate. Every unit runs the stage's `outcome` collector exactly like a one-shot `produces` pass — so it **requires `kind: "produces"` + an `outcome` with a `name`**, and a downstream stage can read every accumulated output straight from `state.named[outcome.name]`.
148
+
149
+ ```typescript
150
+ import { iterate, produces } from "@juicesharp/rpiv-workflow";
151
+
152
+ // rpiv-pi's REVIEW_PHASE_ITERATE — one blueprint pass per review phase,
153
+ // each building on the plans the phases it depends on already produced.
154
+ const REVIEW_PHASE_ITERATE = iterate({
155
+ source: "architecture-reviews",
156
+ unit: { by: "frontmatter-array", pattern: "phases" },
157
+ max: MAX_PHASES,
158
+ next: ({ artifact, state, accumulated, cwd }) => {
159
+ const review = latestFsArtifact(state, "architecture-reviews") ?? artifact;
160
+ if (review?.handle.kind !== "fs") return null;
161
+ const phases = readPhases(review.handle.path, cwd);
162
+ const i = accumulated.length; // 0-based cursor (== index)
163
+ if (i >= phases.length) return null; // every phase planned ⇒ terminate
164
+ const prior = accumulated.flatMap((o) => o.artifacts).map((a) => handleToString(a.handle));
165
+ return {
166
+ prompt: `${handleToString(review.handle)} Implement Phase ${phases[i].n}: ${phases[i].title}` +
167
+ (prior.length ? `\nPrior phase plans (build on them): ${prior.join(", ")}` : ""),
168
+ label: `phase ${i + 1}/${phases.length}`,
169
+ id: `phase-${phases[i].n}`, // stable audit key
170
+ };
171
+ },
172
+ });
173
+
174
+ produces({ loop: REVIEW_PHASE_ITERATE })
175
+ ```
176
+
177
+ **`IterateContext` (what each `next()` call receives):**
132
178
 
133
179
  | Field | Meaning |
134
180
  |-------|---------|
135
181
  | `cwd` | Run working directory. |
136
182
  | `artifact` | Stage-entry primary, **FROZEN** across every unit (does NOT roll to the prior unit's output). Undefined when iterate is the entry stage. On a corrective back-edge re-entry the rolling primary may be a downstream doc — source your true input from `state.named` in that case. |
137
183
  | `state` | Read-only `RunState`. `state.named[outcome.name]` is the global accumulation channel. |
138
- | `accumulated` | This stage's already-completed units' validated `Output`s, in order. The primary accumulation channel. |
184
+ | `accumulated` | This generation's already-completed units' validated `Output`s, in order. |
139
185
  | `index` | 0-based index of the unit about to run (`== accumulated.length`). |
140
186
 
141
- **Invariants (enforced at load + preflight):**
187
+ A first-call `null` is a zero-unit no-op: nothing published, primary unchanged, chain advances (with a warning).
188
+
189
+ #### assess (producer → judge rounds, until done)
190
+
191
+ `assess()` runs the stage as a **model-judged until-done loop**: each round runs a producer session (this stage's skill + outcome) then a judge session (`opts.judge`). A sync `done(verdict)` predicate decides termination; `feedForward` carries the just-judged round into the next producer prompt. The producer is a collecting unit every round, so assess also **requires `kind: "produces"` + an `outcome` with a `name`**. Unlike fanout/iterate, the cap **soft-stops by default** (`onCap: "advance"`).
192
+
193
+ ```typescript
194
+ import { assess, judge, produces } from "@juicesharp/rpiv-workflow";
195
+
196
+ const BREAKDOWN_ASSESS = assess({
197
+ judge: judge({ skill: "grade-breakdown", outcome: verdictOutcome }),
198
+ done: (v) => (v.data as { done?: boolean }).done === true,
199
+ feedForward: ({ output, verdict }) =>
200
+ `Revise ${handleToString(output.artifacts[0]!.handle)} per the grader's feedback: ` +
201
+ `${(verdict.data as { feedback?: string }).feedback ?? ""}`,
202
+ max: 5, // round cap; defaults to 8 if omitted
203
+ });
204
+
205
+ produces({ loop: BREAKDOWN_ASSESS, outcome: rpivArtifactMdOutcome })
206
+ ```
207
+
208
+ **`FeedForwardContext` (what `feedForward()` receives):** `{ cwd, output, verdict, round, state }` — `output` is the producer output just judged, `verdict` is the judge's validated `Output` (carrying its feedback), `round` is the 0-based round index just judged.
209
+
210
+ ##### judge() — the model-judge concept
211
+
212
+ A `Judge` names a dispatchable grading session. Author it with `judge({ ... })`, which validates the shape at construction:
213
+
214
+ - **Dispatch is `skill` XOR `prompt`** (exactly one): `skill` dispatches `/skill:<skill> <producerHandle>` with the latest producer artifact auto-injected as the input handle; `prompt` sends raw text (the author embeds the handle/output themselves). Setting both is ambiguous; setting neither has nothing to dispatch — both throw.
215
+ - **`outcome` is required** — it validates the verdict and names its own dedicated `state.named` channel. That channel's `.name` MUST differ from the producer outcome's name (a workflow-level check, since it needs the producer's identity).
216
+ - **≥1-artifact constraint**: the judge's collector MUST materialize at least one artifact (e.g. a JSON verdict file whose parser yields `{ done, feedback }`). A judge session that collects zero artifacts is a **fatal halt** — no retry, no soft-stop.
217
+ - **Skill label for per-unit consumers**: a `skill` judge's units carry that skill name in `onUnitStart`/`onUnitEnd` and the JSONL rows; a `prompt` judge dispatches under the synthetic label **`<stageName>-judge`**. Per-unit listeners that key on the dispatched skill (e.g. rpiv-pi's `models.json` `skills.<name>` model-override rung) can target a prompt-judge by adding an entry under that synthetic name; with no entry, judge units run on the baseline model.
218
+
219
+ Keeping the termination predicate OFF `Judge` is what makes it reusable: both `assess()` and the per-stage `verify` field add their own `done(verdict)` predicate over the same opaque verdict `Output` (they share the `JudgedRepetition` vocabulary — `done` + `max`); [`panel()`](#adversarial-verification-panel) composes N judges into one verdict the same `done` reads. A panel therefore slots into any of them with zero per-site code.
220
+
221
+ #### The loop knobs
222
+
223
+ Every constructor accepts the shared introspectable facet and policy knobs:
224
+
225
+ | Knob | Default | Meaning |
226
+ |---|---|---|
227
+ | `source` | none | The named channel the units are split FROM (a `consumes` hint for lints and agents — the `checkFanoutSource` lint warns if no `produces` stage publishes it). |
228
+ | `unit` | none | `{ by, pattern? }` — how units are detected. Opaque convention; the framework never interprets it. |
229
+ | `max` | none (assess: 8) | Cardinality ceiling. Must be an integer **≥ 1** (throws at construction). Always clamped by the run-wide `maxIterations` (default 32, via `RunWorkflowOptions.maxIterations`). |
230
+ | `onCap` | fanout/iterate `"halt"` · assess `"advance"` | What happens at the effective cap (`min(max, run.maxIterations)`). `"halt"` — terminal failure (mirrors the backward-jump guard). `"advance"` — soft-stop: warn, land a `{type:"loop-cap"}` telemetry row, fire `onLoopCap`, keep the projected result, advance downstream. |
231
+ | `result` | fanout `"entry"` · iterate/assess `"last"` | What the loop leaves in `{state.output, state.primaryArtifact}` (the pair is governed as one). `"entry"` restores the pair captured at loop entry (reproduces routing-sees-upstream); `"last"` uses the last completed produce unit's pair (zero produce units degrades to entry). |
232
+
233
+ #### The resume contract (all loop kinds)
234
+
235
+ A unit source must be **deterministic w.r.t. the fold-replayed `RunState` at the unit boundary plus this generation's accumulated outputs**. On resume, the fold re-calls your `units()` / `next()` at every folded boundary and compares each recomputed unit against what the run recorded. If they diverge — a non-deterministic generator recomputed a different unit — resume **refuses** with a terminal failure rather than re-run the wrong units. Set a stable `id` on each unit so the join survives a reworded `label`. The same contract covers the model-judged predicates: `assess`'s and `verify`'s `done` / `feedForward` are recomputed on resume (never persisted), so each must be deterministic w.r.t. the verdict `Output`. Runs recorded before this redesign carry no `parent` field on their unit rows and cannot be resumed (`stage-gone` refusal — no migration).
236
+
237
+ #### Loop lifecycle hooks
238
+
239
+ Loops are observed through unit-generic lifecycle hooks (register via `registerLifecycle`). `onStageStart` still fires exactly once per loop stage; the loop hooks add per-loop and per-unit granularity:
240
+
241
+ | Hook | Payload | When |
242
+ |---|---|---|
243
+ | `onLoopStart(stage, info)` | `{ kind, units? }` — `units` only for fanout (push precomputes them) | after `onStageStart`, before unit 1's session |
244
+ | `onUnitStart(stage, unit)` | `UnitEvent` `{ role, index, unitId?, label, skill }` | before each unit's session opens — fired for **produce AND judge** units; the seam a model-override listener flips the model on (units run strictly sequentially, so the flip is race-free) |
245
+ | `onUnitEnd(stage, unit, output)` | `UnitEvent` + the unit's validated `Output` | after the unit's JSONL row lands (loop units never fire `onStageEnd`) |
246
+ | `onLoopCap(stage, info)` | `LoopCapInfo` `{ kind, count, max, policy }` | after an `onCap: "advance"` trip (after the `{type:"loop-cap"}` row append attempt) |
247
+
248
+ `UnitEvent.skill` is the unit's *dispatched* skill body — the parent stage's skill for produce units, the judge's own skill for judge units — so a model-override listener can resolve a per-unit model through the existing `models.json` cascade (`skills.<name>`) with no new configuration axes.
249
+
250
+ ### Per-stage verification (verify)
251
+
252
+ **verify** attaches a post-condition judge to a `produces` stage: after each attempt completes (collected, validated, persisted), the judge session grades the attempt's primary artifact and `done(verdict)` gates advancement — true → the chain advances with the attempt's producer pair; false → a fresh retry attempt (prompt arg built by `feedForward`) up to `max` attempts (default 1 = gate-only), then the workflow halts with "verification failed". A pass on the final attempt is a normal completion. Requires `kind: "produces"` + an `outcome` with a `name`; composes with `reads` and with `prompt` dispatch (attempt 0 sends the stage's resolved `prompt` raw; retries send `feedForward`'s output raw — for prompt dispatch it is the complete retry message, not a skill arg); mutually exclusive with `loop`, `run`, and `sessionPolicy: "continue"`. `verify` shares the `JudgedRepetition` field vocabulary with `assess` — `done` (the pass predicate), `max` (the attempt budget), and `feedForward` — one set of names for both judged-repetition shapes.
253
+
254
+ ```ts
255
+ import { judge, produces, verify } from "@juicesharp/rpiv-workflow";
256
+
257
+ // Gate-only: one attempt; a failing verdict halts the workflow.
258
+ const GATED = produces({
259
+ outcome: implOutcome, // publishes "impl"
260
+ verify: verify({
261
+ judge: judge({ skill: "review-gate", outcome: verdictOutcome }), // publishes "impl-verdict"
262
+ done: (v) => (v.data as { ok?: boolean }).ok === true,
263
+ }),
264
+ });
265
+
266
+ // Retry-with-feedback: up to 3 fresh attempts, each retried prompt carrying the verdict's feedback.
267
+ const RETRIED = produces({
268
+ outcome: implOutcome,
269
+ reads: ["design", "plan"], // composes — attempt prompts use the labelled-flag projection
270
+ verify: verify({
271
+ judge: judge({ skill: "review-gate", outcome: verdictOutcome }),
272
+ done: (v) => (v.data as { ok?: boolean }).ok === true,
273
+ feedForward: ({ verdict }) => `address: ${(verdict.data as { feedback?: string }).feedback}`,
274
+ max: 3, // requires feedForward when > 1
275
+ }),
276
+ });
277
+ ```
278
+
279
+ **Two budgets, two cost scales:** `verify.max` is the FULL-attempt budget — each attempt is a fresh session running the whole produce→validate→persist cycle. `stage.maxRetries` stays the orthogonal in-session schema-fix budget and remains live inside every attempt.
280
+
281
+ **Lifecycle (loop semantics):** a verified stage runs through the loop driver, so `onLoopStart` fires with `kind: "verify"`, each attempt/verdict fires `onUnitStart`/`onUnitEnd` (roles `"produce"`/`"verify"`), and the stage does NOT fire `onStageEnd` — observe units, not stage-end. A model-override listener resolves the judge's own skill through `onUnitStart`, exactly as for assess judges.
282
+
283
+ **Fallback routing instead of halting:** the verdict publishes durably to `state.named[judge.outcome.name]`, so a route can read it — no built-in fail→route policy exists (or is needed):
284
+
285
+ ```ts
286
+ edges: {
287
+ implement: defineRoute(
288
+ ["ship", "fallback"],
289
+ ({ state }) => ((state.named["impl-verdict"]?.at(-1)?.data as { ok?: boolean })?.ok ? "ship" : "fallback"),
290
+ { readsData: false },
291
+ ),
292
+ }
293
+ ```
294
+
295
+ **Resume:** crash after an attempt but before its verdict → resume re-runs just the verify; a recovered failing verdict re-computes `done` and continues the retry (or halts a gate-only verify); a recovered passing verdict fast-advances. `done` is recomputed, never persisted — it joins the loop determinism contract (deterministic w.r.t. the verdict `Output`).
296
+
297
+ ### Adversarial verification (panel)
298
+
299
+ A single judge agreeing with itself is not a check — that is self-preference bias. **`panel()`** turns one judge into N independent skeptics and reduces their verdicts to one decision with a **fold**. It is a `Judge`-shaped *value*, not a new site: it slots into any slot a `judge` does — `assess({ judge })` or `verify({ judge })` — with **zero per-site code**, because every judge site dispatches through one expander (`panelMembers`) and reads the fold opaquely via its existing `done` predicate. A plain `judge` is simply a panel of one.
300
+
301
+ ```ts
302
+ import { judge, majority, panel, produces, verify } from "@juicesharp/rpiv-workflow";
303
+ import type { PanelVerdict } from "@juicesharp/rpiv-workflow";
304
+
305
+ // Three independent skeptics — distinct lenses beat N copies (correctness, security, repro).
306
+ const REVIEW_PANEL = panel({
307
+ members: [
308
+ judge({ skill: "review-correctness", outcome: { name: "v-correctness", collector } }),
309
+ judge({ skill: "review-security", outcome: { name: "v-security", collector } }),
310
+ judge({ skill: "review-repro", outcome: { name: "v-repro", collector } }),
311
+ ],
312
+ // The per-member `pred` interprets each member's OWN verdict schema.
313
+ fold: majority((v) => (v.data as { ok?: boolean }).ok === true),
314
+ });
315
+
316
+ // Slots into a verify site. The site's `done` reads the FOLDED canonical verdict.
317
+ const VERIFIED = produces({
318
+ outcome: implOutcome, // publishes "impl"
319
+ verify: verify({
320
+ judge: REVIEW_PANEL, // fold publishes to "impl-panel"
321
+ done: (v) => (v.data as PanelVerdict).pass, // the strict-majority result
322
+ }),
323
+ });
324
+ ```
325
+
326
+ **Two predicates, not one redundancy.** The per-member `pred` (passed to `majority`/`all`/`any`) interprets *one member's* own verdict; the site's `done` (`assess`'s and `verify`'s termination predicate) interprets *the fold*. Members never need a shared verdict schema — only the `pred` knows each member's shape.
327
+
328
+ **`panel({ members, fold, outcome? })`:**
329
+
330
+ - `members` — a **non-empty** array of single `judge(...)` values. Each carries its own `outcome` whose `name` must be **mutually distinct** and **distinct from the producer's** (a load-time check). Members do **not** nest — `panel` of `panel` is rejected at construction (§ "Explicitly not building").
331
+ - `fold` — a function reducing the member verdicts to the panel's decision data. Either a **sugar** fold (`majority`/`all`/`any`, branded) or a **raw** `FoldFn`.
332
+ - `outcome` — present **only** on the custom (raw-fold) path; it names + validates the fold's channel.
142
333
 
143
- - Requires `kind: "produces"` and an `outcome` with a `name` (every unit publishes to the same named slot; the per-unit audit row is decorated, so a name is mandatory to keep the slot from splitting).
144
- - Mutually exclusive with `fanout` (push vs pull) and with `run` (script stages write their own loop).
145
- - Incompatible with `sessionPolicy: "continue"` (each unit needs an isolated session).
146
- - Generator `null` on the first call → zero-unit no-op: nothing published, primary unchanged, chain advances (with a warning).
147
- - A run-wide `maxIterations` cap (default 32, configurable via `RunWorkflowOptions.maxIterations`) backstops a generator that never returns `null` — the stage halts with a terminal failure.
334
+ #### Canonical ⊕ custom — a hard XOR
148
335
 
149
- **iterate vs fanout** — duals, not substitutes:
336
+ The fold output is a validated, publishable `Output` so a downstream route can branch on it. Two disjoint ways to obtain the `(schema, channel, fold)` triple:
150
337
 
151
- | | `fanout` | `iterate` |
338
+ | Path | `fold` | `outcome` | Schema / channel | Use |
339
+ |---|---|---|---|---|
340
+ | **Canonical** | sugar (`majority`/`all`/`any`) | **omitted** | built-in `PANEL_VERDICT`; channel `<stage>-panel` | zero-config disagreement routing |
341
+ | **Custom** | raw `FoldFn` | **required** | author's schema + name | mean / weighted / synthesize |
342
+
343
+ The XOR is enforced at construction (and re-checked at load for hand-rolled literals), so exactly one source names the verdict — never both, never neither:
344
+
345
+ ```
346
+ sugar fold + outcome present → construction error (sugar ⊕ outcome)
347
+ raw fold + outcome absent → construction error (raw ⊕ outcome)
348
+ ```
349
+
350
+ #### The canonical verdict — `PANEL_VERDICT`
351
+
352
+ Sugar folds emit this shape; disagreement is first-class because production routing keys on it:
353
+
354
+ ```ts
355
+ PANEL_VERDICT = {
356
+ pass: boolean, // the fold's decision (per the sugar rule below)
357
+ votes: { pass: number, fail: number }, // the split
358
+ agreement: number, // |majority| / N — the disagreement signal
359
+ tie: boolean, // an even split
360
+ }
361
+ ```
362
+
363
+ | Sugar fold | `pass` is true when | Meaning |
152
364
  |---|---|---|
153
- | Generation | push (once, all units) | pull (per unit, sees prior) |
154
- | Stage kind | any (often `acts`) | requires `produces` + named `outcome` |
155
- | Collector per unit | no (bare audit row) | yes (full produces path) |
156
- | Count known up front | yes | no (generator-terminated) |
157
- | Use when | independent side-effect units (e.g. `implement` per plan phase) | each unit must build on the last (e.g. `blueprint` per review phase) |
365
+ | `majority(pred)` | strict majority of members pass `pred` | even split is a tie ⇒ fail (see `tie`/`agreement`) |
366
+ | `all(pred)` | every member passes `pred` | unanimous — one fail vetoes |
367
+ | `any(pred)` | at least one member passes `pred` | veto / rescue — one pass carries it |
368
+
369
+ #### Where the fold publishes
370
+
371
+ The fold publishes **decision data**, not a file artifact. It lands on its own named channel — `<stage>-panel` (canonical) or your `outcome.name` (custom) — with `artifacts: []`, so it never claims the rolling primary. Each member *also* publishes its own verdict to its own `outcome.name` channel, so the full per-member trail is preserved. A downstream stage that wants to **read survivors** reads the producer/member artifacts; a route that wants the **decision** reads the fold channel (see [`match`](#match)'s `from`).
372
+
373
+ #### The four flows
374
+
375
+ - **Generate-and-filter** — `fanout` to generate candidates → a stage whose `verify` judge is a `panel(...)` → `match` on the published verdict to keep survivors.
376
+ - **Classify-and-route** — panel verdict → `match("decision", …)`.
377
+ - **Escalate-on-disagreement** (highest value) — route on `tie`/`agreement` to a human/escalation stage; falls out for free once the channel + disagreement signal exist.
378
+ - **Tournament** — unchanged; a future `iterate` over a bracket.
379
+
380
+ #### Caveats & resume
381
+
382
+ - **Sequential cost.** Pi is single-active-session, so members run one after another — a panel costs **N judge sessions per check**. Panels are slower, never incorrect. Parallelism is a roadmap item, not a property of the fold.
383
+ - **Resume parity.** Each member is its own durable audit row (member-index-bearing tag); the **folded verdict is never persisted** — it is recomputed from the member rows and republished at the same transition on resume, byte-identical to live. The fold must therefore be deterministic w.r.t. the member verdicts (it joins the loop determinism contract). A crash mid-panel re-runs only the pending member, then recomputes the fold.
158
384
 
159
385
  ### acts
160
386
 
@@ -169,8 +395,8 @@ acts()
169
395
  // With a different skill name
170
396
  acts({ skill: "implement" })
171
397
 
172
- // With fanout
173
- acts({ fanout: phaseFanout })
398
+ // With a loop (one side-effect session per unit — see Loops)
399
+ acts({ loop: fanout({ units: phaseUnits }) })
174
400
 
175
401
  // With outcome (e.g., git commit detection)
176
402
  acts({ outcome: gitCommitOutcome })
@@ -252,7 +478,7 @@ const notifySlack = terminal.script({
252
478
  ```
253
479
 
254
480
  **Constraints on script stages:**
255
- - Cannot declare `skill`, `outcome`, `fanout`, `iterate`, or `sessionPolicy: "continue"` — load-time validation rejects the combination.
481
+ - Cannot declare `skill`, `outcome`, `loop`, `prompt`, or `sessionPolicy: "continue"` — load-time validation rejects the combination. Script stages cannot loop — write a loop inside `run()` instead.
256
482
  - `produces.script` may declare `outputSchema`, `maxRetries`, `onInvalid`.
257
483
  - `acts.script` / `terminal.script` may declare `inputSchema`.
258
484
 
@@ -271,8 +497,8 @@ prefix, no implicit upstream-artifact arg appended. Use it for a focused,
271
497
  one-off instruction that doesn't warrant a whole skill.
272
498
 
273
499
  **Prefer the typed builders** `produces.prompt({ … })` / `acts.prompt({ … })`
274
- (mirroring `.script`). Their options structurally omit `skill`/`run`/`fanout`/
275
- `iterate`/`reads`, so an invalid combo fails to compile instead of only failing
500
+ (mirroring `.script`). Their options structurally omit `skill`/`run`/`loop`/
501
+ `reads`, so an invalid combo fails to compile instead of only failing
276
502
  load validation:
277
503
 
278
504
  ```typescript
@@ -310,9 +536,13 @@ stages: {
310
536
  ```
311
537
 
312
538
  **Constraints (load + preflight):**
313
- - Mutually exclusive with an explicit `skill`, with `run`, with `reads`, and —
314
- in v1 — with `fanout`/`iterate`. (Read `state.named` from the `PromptFn` itself
315
- instead of `reads`.)
539
+ - Mutually exclusive with an explicit `skill`, with `run`, with `reads`, and
540
+ with `fanout`/`iterate` loops (units own their prompts — every unit's message
541
+ comes from `units()`/`next()`, so a stage-level `prompt` would have no role).
542
+ Read `state.named` from the `PromptFn` itself instead of `reads`.
543
+ - Composes with `assess` loops and with `verify`: the stage's `prompt` is
544
+ round/attempt 0's message, and `feedForward` builds each retry's COMPLETE
545
+ message (sent raw — there is no skill to prefix an arg onto).
316
546
  - `produces` + `prompt` still requires an `outcome`. `side-effect` + `prompt` is
317
547
  a pure chat turn.
318
548
  - A prompt stage skips the skill-registry check (no skill to register) and the
@@ -347,6 +577,7 @@ A conditional edge is an **`EdgeFn`**: a `(ctx) => string` predicate carrying a
347
577
 
348
578
  - **`defineRoute(targets, fn)`** — general. Arbitrary TS body, explicit `targets`. Use for strings, enums, multiple fields, ranges — anything.
349
579
  - **`gate(field, branches)`** — terse convenience for one **numeric** field with threshold predicates; derives `.targets` from the branch keys. Not more powerful than `defineRoute`, just shorter for the numeric case.
580
+ - **`match(field, branches, opts?)`** — the string/boolean companion to `gate`: classify on a discrete (enum) field by strict `===`. Derives `.targets` from the branch keys; shorter than `defineRoute` for the enum case.
350
581
 
351
582
  ### gate (numeric field)
352
583
 
@@ -363,6 +594,33 @@ edges: {
363
594
  }
364
595
  ```
365
596
 
597
+ ### match (enum field)
598
+
599
+ `match(field, branches, opts?)` maps each target stage to the **discrete value** that routes to it. The field is compared by strict `===` in declaration order; first match wins. Where `gate` keys on a `Number(...)` threshold, `match` keys on a string/number/boolean equal — the enum classifier `gate` can't express.
600
+
601
+ ```typescript
602
+ import { match } from "@juicesharp/rpiv-workflow";
603
+
604
+ edges: {
605
+ triage: match("severity", { escalate: "p0", fix: "p1", backlog: "p2" }),
606
+ }
607
+ ```
608
+
609
+ **No-match is explicit, never silent.** With `opts.fallback` the unmatched value routes there; without one it terminates (`STOP`). Either way the no-match lands a routing-audit `note`.
610
+
611
+ **Routing on a panel's verdict** — `opts.from` reads the field from a named channel's latest output (`state.named[from].at(-1).data[field]`) instead of the stage's projected `output.data`. This is how `match` branches on a [panel](#adversarial-verification-panel)'s published fold (the fold lands on a channel, never on the stage's projected output):
612
+
613
+ ```typescript
614
+ // Escalate when the panel split, otherwise keep survivors.
615
+ edges: {
616
+ review: match("tie", { escalate: true }, { fallback: "keep", from: "review-panel" }),
617
+ }
618
+ ```
619
+
620
+ A channel-sourced route validates the *channel's* data, not the source stage's output, so it does **not** mark the source stage `READS_DATA`.
621
+
622
+ **Construction rules:** each enum value must map to exactly one stage (a duplicate value throws — ambiguous), and branch keys must not be integer-like (`"2"`) — JS hoists array-index keys ahead of declaration order, silently reordering priority. Built on `defineRoute`, so `.targets` (incl. the fallback) feeds the reachability BFS and `READS_DATA` auto-applies unless `from` sources a channel.
623
+
366
624
  ### defineRoute (strings, enums, multi-field)
367
625
 
368
626
  The body is plain TS, so there is no separate string/enum helper — compare the field directly. Every value the body can return must appear in `targets`, or the validator flags the edge. Auto-marks the route as reading `output.data` (the source stage needs an `outputSchema`); pass `{ readsData: false }` for a state-only route.
@@ -539,8 +797,8 @@ When to add schemas:
539
797
 
540
798
  ### Session-policy decision rules
541
799
 
542
- - **Default to `"fresh"`.** It is compatible with `fanout`, script stages, and keeps context bounded.
543
- - **Use `"continue"` only when Q3 demands reasoning that isn't capturable on disk or via a transcript marker.** `"continue"` is incompatible with `fanout` and script stages — load-time validation rejects the combination.
800
+ - **Default to `"fresh"`.** It is compatible with loops, script stages, and keeps context bounded.
801
+ - **Use `"continue"` only when Q3 demands reasoning that isn't capturable on disk or via a transcript marker.** `"continue"` is incompatible with loops and script stages — a stage cannot combine a loop with `sessionPolicy: "continue"` (each unit requires an isolated session), and load-time validation rejects the combination.
544
802
  - Every `"continue"` stage grows context monotonically. Long chains of continued sessions become expensive and fragile.
545
803
 
546
804
  ### Authoring protocol
@@ -600,6 +858,38 @@ When `reads:` is set the runner replaces the default prompt with a labelled-flag
600
858
 
601
859
  Multi-artifact stages get flag repetition: an upstream with two `fs` artifacts expands to `--plans <a> --plans <b>` so skill arg-parsers collect repeated flags into arrays the same way `argparse`/`clap`/shell utilities do.
602
860
 
861
+ ### Fan-in: reading every entry (`fanin` — fanout-and-synthesize)
862
+
863
+ A bare-string read resolves to the channel's **latest** entry (`array.at(-1)`). That is the wrong default for the fan-in half of *fanout-and-synthesize*: a `fanout` produces N per-unit `Output`s on one channel, and the synthesize stage's whole job is to **merge all N into one**. Latest-wins would hand it only the last unit.
864
+
865
+ Wrap a name in `fanin(name)` to read **every accumulated entry** of the channel, in run order:
866
+
867
+ ```typescript
868
+ import { acts, fanin, fanout, produces } from "@juicesharp/rpiv-workflow";
869
+
870
+ // fan-out: one collecting unit per plan phase → each appends to state.named["drafts"]
871
+ draft: produces({
872
+ outcome: draftOutcome, // outcome.name === "drafts"
873
+ loop: fanout({ source: "plans", unit: { by: "frontmatter-array", pattern: "phases" } }),
874
+ }),
875
+
876
+ // fan-in (the barrier): read ALL drafts, synthesize one result
877
+ synthesize: produces({
878
+ outcome: summaryOutcome,
879
+ reads: [fanin("drafts")], // every unit's artifacts, not just the last
880
+ }),
881
+ ```
882
+
883
+ The synthesize prompt flag-repeats across the whole channel (× each entry's artifacts):
884
+
885
+ ```
886
+ /skill:synthesize --drafts <unit1> --drafts <unit2> --drafts <unit3> …
887
+ ```
888
+
889
+ `fanin()` is the consumer-side mirror of `fanout()` — fan-out on the producer, fan-in on the consumer. It composes with non-fanout channels too (e.g. reading every `iterate` accumulation), and one `reads:` list may mix forms: `reads: [fanin("drafts"), "spec"]` reads all drafts but only the latest spec. The `reads:` element type is `string | { name; all? }`; `fanin(name)` builds `{ name, all: true }`.
890
+
891
+ A lint backs the idiom: a **bare-string** read of a channel that a `fanout` fills emits the `reads-latest-from-fanout` warning ("wrap it in `fanin(...)`"). It only warns — latest-only is legal — and `fanin()` reads are already opted in, so they're never flagged. `/wf` preview marks a fan-in consumer with `⇉ <names>`, mirroring the `panel(N, fold)` fan-in surfacing.
892
+
603
893
  ### The named-publish registry — `state.named`
604
894
 
605
895
  Every `produces` stage APPENDS its full `Output` envelope onto `state.named[key]` after each successful run. The key is computed once at write time:
@@ -613,7 +903,7 @@ Two layers, no override knob:
613
903
  - **Outcome carries a name.** Multiple stages wiring the same outcome converge — both stages append onto the same slot, latest-wins on read. This is how a workflow expresses "two stages both produce the canonical plan" without restating the name on each stage.
614
904
  - **Outcome has no name.** Stages publish under their record key. Downstream `reads: ["blueprint", "code-review"]` references stage record keys directly.
615
905
 
616
- Slots are **arrays** — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)`. Side-effect stages don't write to the registry. The slot is never cleared by `terminal()` either: it's an additive channel orthogonal to the rolling primary.
906
+ Slots are **arrays** — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)` (latest-wins), while a `fanin(name)` read consumes the whole slot (see [Fan-in](#fan-in-reading-every-entry-fanin--fanout-and-synthesize)). Side-effect stages don't write to the registry. The slot is never cleared by `terminal()` either: it's an additive channel orthogonal to the rolling primary.
617
907
 
618
908
  ### Validation + preflight
619
909
 
@@ -630,11 +920,11 @@ A fresh-session stage starts a clean Pi conversation. It only sees (1) the rolli
630
920
 
631
921
  | # | Mechanism | What downstream sees | Trade-off |
632
922
  |---|-----------|----------------------|-----------|
633
- | 1 | `sessionPolicy: "continue"` on the downstream stage | Full prior Pi conversation (messages + tool calls) | Incompatible with `fanout` and script stages. Context grows monotonically. |
923
+ | 1 | `sessionPolicy: "continue"` on the downstream stage | Full prior Pi conversation (messages + tool calls) | Incompatible with loops and script stages. Context grows monotonically. |
634
924
  | 2 | `workspaceDiffCollector` outcome on the upstream stage | Every file the stage touched, as `fs` artifacts | Free when the work IS files on disk. Captures *what*, not *why*. |
635
925
  | 3 | `transcriptPathCollector` outcome on the upstream stage | The last regex-matched chunk of assistant text, written to disk | Captures narrative knowledge. Needs the skill to emit a recognizable marker. |
636
926
  | 4 | Custom collector / parser (+ optional `outputSchema`) | Author-defined typed shape | Most precise; most authoring effort. Enables gate routing. |
637
- | 5 | `reads:` on the downstream stage referencing named-publish slots | Latest `Output` per declared name, woven into a labelled-flag prompt | Reaches further back than the rolling primary; survives intermediate produces stages overwriting the chain. See [Multi-input stages](#multi-input-stages). |
927
+ | 5 | `reads:` on the downstream stage referencing named-publish slots | Latest `Output` per declared name (or **all** entries via `fanin(name)`), woven into a labelled-flag prompt | Reaches further back than the rolling primary; survives intermediate produces stages overwriting the chain. `fanin()` is the fanout-and-synthesize barrier. See [Multi-input stages](#multi-input-stages). |
638
928
 
639
929
  **Picking between them — where does the knowledge live after the stage finishes?**
640
930
 
@@ -754,9 +1044,12 @@ Generated workflows must pass `validateWorkflow()` before writing. The validator
754
1044
  - `produces` stages have an `outcome`
755
1045
  - `gate` / data-reading `defineRoute` source stages have `outputSchema`
756
1046
  - Every `reads:` name is published by some `produces` stage in the workflow (publish key = `outcome.name ?? stage.<record-key>`)
757
- - Fanout is incompatible with `sessionPolicy: "continue"`
758
- - Iterate requires `kind: "produces"` + an `outcome` with a `name`; it is mutually exclusive with `fanout` and `run`, and incompatible with `sessionPolicy: "continue"`
759
- - Prompt stages cannot also set `skill`, `run`, `reads`, `fanout`, or `iterate`; a `produces` prompt stage still needs an `outcome`; an empty prompt string is rejected
760
- - Script stages cannot declare `skill`, `outcome`, `fanout`, `iterate`, `prompt`, or `sessionPolicy: "continue"`
1047
+ - A stage **cannot combine a loop with sessionPolicy "continue"** — each unit requires an isolated session
1048
+ - **A collecting loop requires an `outcome` with a `name`** so units publish to a stable named slot (iterate and assess always; a `fanout` when its stage `kind` is `produces`)
1049
+ - `iterate` / `assess` require `kind: "produces"` — each unit runs an outcome collector
1050
+ - `loop.max` must be an integer `>= 1` (the run-wide `maxIterations` caps the upper bound)
1051
+ - a judge's `outcome.name` must differ from the producer's publish name (`assess` and `verify`); `assess` composes with `reads` (the v1 restriction is lifted — round-0 producer args are derived by one authority and frozen by the resume fold at loop-generation open)
1052
+ - **prompt and fanout/iterate loops are mutually exclusive** — units own their prompts (`assess` loops and `verify` compose with prompt dispatch); prompt stages also cannot set `skill`, `run`, or `reads`; a `produces` prompt stage still needs an `outcome`; an empty prompt string is rejected
1053
+ - **Script stages cannot loop — write a loop inside run() instead**; they also cannot declare `skill`, `outcome`, `prompt`, or `sessionPolicy: "continue"`
761
1054
 
762
1055
  > **Important:** The `/wf` command blocks execution on any `severity: "error"` issue. Always validate before writing.