@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.
- package/README.md +81 -8
- package/api.ts +18 -703
- package/audit-rows.ts +136 -0
- package/audit.ts +139 -126
- package/built-ins.ts +20 -45
- package/chain-state.ts +169 -0
- package/command-run.ts +31 -3
- package/command.ts +116 -20
- package/docs/workflow-authoring.md +322 -61
- package/{lifecycle.ts → events.ts} +119 -35
- package/host.ts +30 -0
- package/index.ts +25 -81
- package/internal-utils.ts +92 -78
- package/internal.ts +21 -1
- package/judge.ts +229 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +16 -109
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/shape-guards.test.ts +4 -1
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +623 -0
- package/loop-def.ts +240 -0
- package/loop-kinds.ts +493 -0
- package/loop.ts +304 -0
- package/messages.ts +225 -157
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/tool-call.test.ts +3 -1
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +2 -3
- package/outcomes/collectors/union.test.ts +54 -0
- package/outcomes/collectors/union.ts +28 -9
- package/outcomes/collectors/url.ts +7 -0
- package/outcomes/collectors/workspace-diff.test.ts +13 -0
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.test.ts +76 -30
- package/outcomes/git-commit.ts +139 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +40 -20
- package/package.json +13 -7
- package/predicates.ts +11 -8
- package/preview.ts +77 -17
- package/registration.ts +109 -35
- package/routing-dsl.ts +310 -0
- package/routing.ts +2 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +59 -44
- package/runner/errors.ts +33 -0
- package/runner/failure.ts +109 -0
- package/runner/header-write-failure.test.ts +64 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +11 -21
- package/runner/preflight.ts +173 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +101 -0
- package/runner/resume-loop.test.ts +1410 -0
- package/runner/resume-loop.ts +110 -0
- package/runner/resume-session.test.ts +400 -0
- package/runner/resume.test.ts +881 -206
- package/runner/resume.ts +281 -261
- package/runner/run-context.ts +161 -0
- package/runner/run-stage.ts +456 -0
- package/runner/runner.ts +59 -400
- package/runner/script-stage.ts +103 -105
- package/schema-compat.ts +13 -1
- package/sessions/extraction.ts +53 -31
- package/sessions/index.ts +3 -1
- package/sessions/locate.test.ts +77 -0
- package/sessions/locate.ts +90 -0
- package/sessions/reattach.ts +63 -0
- package/sessions/sessions.ts +130 -127
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +88 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +2 -3
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +527 -0
- package/startup.ts +3 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +12 -0
- package/state/raw.ts +78 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +112 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +202 -44
- package/validate/contract-compat.ts +193 -0
- package/validate/graph.ts +125 -0
- package/validate/issue.ts +314 -0
- package/validate/stage-rules.ts +420 -0
- package/validate-output.ts +69 -1
- package/validate-workflow.ts +55 -759
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- 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
|
-
- [
|
|
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
|
|
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:
|
|
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
|
-
| `
|
|
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
|
-
###
|
|
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
|
-
|
|
114
|
+
#### fanout (push — all units up front)
|
|
108
115
|
|
|
109
|
-
|
|
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
|
|
113
|
-
|
|
114
|
-
//
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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
|
+
});
|
|
136
|
+
|
|
137
|
+
// acts stage + fanout loop — side-effect units (no per-unit collector)
|
|
138
|
+
acts({ loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] })
|
|
139
|
+
```
|
|
140
|
+
|
|
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`.
|
|
127
142
|
|
|
128
|
-
|
|
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 })
|
|
129
175
|
```
|
|
130
176
|
|
|
131
|
-
**`IterateContext` (what each call receives):**
|
|
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
|
|
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
|
-
|
|
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? })`:**
|
|
142
329
|
|
|
143
|
-
-
|
|
144
|
-
-
|
|
145
|
-
-
|
|
146
|
-
|
|
147
|
-
|
|
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.
|
|
333
|
+
|
|
334
|
+
#### Canonical ⊕ custom — a hard XOR
|
|
335
|
+
|
|
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:
|
|
337
|
+
|
|
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
|
+
```
|
|
148
349
|
|
|
149
|
-
|
|
350
|
+
#### The canonical verdict — `PANEL_VERDICT`
|
|
150
351
|
|
|
151
|
-
|
|
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
|
-
|
|
|
154
|
-
|
|
|
155
|
-
|
|
|
156
|
-
|
|
157
|
-
|
|
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
|
|
173
|
-
acts({ fanout:
|
|
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`, `
|
|
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`/`
|
|
275
|
-
`
|
|
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
|
-
|
|
315
|
-
|
|
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
|
|
543
|
-
- **Use `"continue"` only when Q3 demands reasoning that isn't capturable on disk or via a transcript marker.** `"continue"` is incompatible with
|
|
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
|
|
@@ -630,7 +888,7 @@ A fresh-session stage starts a clean Pi conversation. It only sees (1) the rolli
|
|
|
630
888
|
|
|
631
889
|
| # | Mechanism | What downstream sees | Trade-off |
|
|
632
890
|
|---|-----------|----------------------|-----------|
|
|
633
|
-
| 1 | `sessionPolicy: "continue"` on the downstream stage | Full prior Pi conversation (messages + tool calls) | Incompatible with
|
|
891
|
+
| 1 | `sessionPolicy: "continue"` on the downstream stage | Full prior Pi conversation (messages + tool calls) | Incompatible with loops and script stages. Context grows monotonically. |
|
|
634
892
|
| 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
893
|
| 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
894
|
| 4 | Custom collector / parser (+ optional `outputSchema`) | Author-defined typed shape | Most precise; most authoring effort. Enables gate routing. |
|
|
@@ -754,9 +1012,12 @@ Generated workflows must pass `validateWorkflow()` before writing. The validator
|
|
|
754
1012
|
- `produces` stages have an `outcome`
|
|
755
1013
|
- `gate` / data-reading `defineRoute` source stages have `outputSchema`
|
|
756
1014
|
- Every `reads:` name is published by some `produces` stage in the workflow (publish key = `outcome.name ?? stage.<record-key>`)
|
|
757
|
-
-
|
|
758
|
-
-
|
|
759
|
-
-
|
|
760
|
-
-
|
|
1015
|
+
- A stage **cannot combine a loop with sessionPolicy "continue"** — each unit requires an isolated session
|
|
1016
|
+
- **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`)
|
|
1017
|
+
- `iterate` / `assess` require `kind: "produces"` — each unit runs an outcome collector
|
|
1018
|
+
- `loop.max` must be an integer `>= 1` (the run-wide `maxIterations` caps the upper bound)
|
|
1019
|
+
- 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)
|
|
1020
|
+
- **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
|
|
1021
|
+
- **Script stages cannot loop — write a loop inside run() instead**; they also cannot declare `skill`, `outcome`, `prompt`, or `sessionPolicy: "continue"`
|
|
761
1022
|
|
|
762
1023
|
> **Important:** The `/wf` command blocks execution on any `severity: "error"` issue. Always validate before writing.
|