@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
package/README.md
CHANGED
|
@@ -21,6 +21,8 @@ This package serves four overlapping audiences. Find yours, then jump to the mat
|
|
|
21
21
|
- **I'm bundling workflows inside my own Pi extension.** → [Programmatic registration](#programmatic-registration).
|
|
22
22
|
- **I'm embedding the runtime in a non-Pi host.** → [Host boundary](#host-boundary) + [`runWorkflow`](#programmatic-runner).
|
|
23
23
|
|
|
24
|
+
Whatever the lane, the [Glossary](#glossary) at the bottom pins one name per concept.
|
|
25
|
+
|
|
24
26
|
## Install
|
|
25
27
|
|
|
26
28
|
```sh
|
|
@@ -97,6 +99,8 @@ The key is the **skill** name (`stage.skill ?? <stage key>`), not the stage id.
|
|
|
97
99
|
|
|
98
100
|
A workflow is a typed graph: named entry point, a `stages` record, and an `edges` table that maps each stage to another stage name, the sentinel `"stop"`, or a predicate function that chooses at runtime.
|
|
99
101
|
|
|
102
|
+
> **Typing model.** Inter-stage data typing is **runtime-contract-based**: `outputSchema` / `inputSchema` (Standard Schema v1) validate `output.data` when stages run, and skill contracts adjudicate composition at load time. The `StageDef<TIn, TOut>` type parameters are local inference helpers for a single factory call — they are erased at the `Workflow.stages` boundary (every stage collapses to `StageDef`), so they do **not** propagate types across edges. Don't lean on them for cross-stage safety; lean on schemas and contracts. A typed builder API that carries types through the graph is on the roadmap, not in this release.
|
|
103
|
+
|
|
100
104
|
Three factories for the two stage kinds:
|
|
101
105
|
|
|
102
106
|
- `produces(overrides?)` — `kind: "produces"`. The skill writes a file the next stage reads. Halts the chain if the path doesn't appear in the transcript. Without a Pi session, use [`produces.script`](#script-stages-no-pi-session).
|
|
@@ -120,20 +124,73 @@ Names address `state.named`, an accumulating registry every `produces` stage app
|
|
|
120
124
|
|
|
121
125
|
Slots are arrays — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)`. Load-time validation rejects `reads:` references whose name no produces stage publishes; the `ensureNamedReads` preflight halts at runtime when a name's slot is empty (the producer hasn't fired yet on this path).
|
|
122
126
|
|
|
123
|
-
Conditional routing uses `gate(field, branches)` with the bundled predicate helpers (`gt` / `gte` / `lt` / `lte` / `eq`):
|
|
127
|
+
Conditional routing uses `gate(field, branches, otherwise)` with the bundled predicate helpers (`gt` / `gte` / `lt` / `lte` / `eq`):
|
|
124
128
|
|
|
125
129
|
```ts
|
|
126
130
|
import { gate, gt, eq } from "@juicesharp/rpiv-workflow";
|
|
127
|
-
edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) }) }
|
|
131
|
+
edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) }, "commit") }
|
|
128
132
|
```
|
|
129
133
|
|
|
130
|
-
Branches are evaluated against `Number(output.data[field])` in declaration order; the first matching predicate wins,
|
|
134
|
+
Branches are evaluated against `Number(output.data[field])` in declaration order; the first matching predicate wins. When no predicate matches (including a missing or non-numeric field, which coerces to `NaN`), the explicit `otherwise` branch is taken and the run's routing-audit row carries a note saying the fallback fired — silent fallthrough is not a thing. Branch keys must not be integer-like (`"2"`): JS object literals reorder such keys ahead of declaration order, so `gate` rejects them at construction.
|
|
131
135
|
|
|
132
136
|
`gate` is the numeric convenience only. String/enum, multi-field, or computed routing uses `defineRoute(targets, fn, opts?)` — the body is plain TS (e.g. `output.data.verdict === "approve" ? "commit" : "revise"`), so there's no separate string helper. By default `opts.readsData` is `true` (reads `output.data`, requires the source stage to declare an `outputSchema`); pass `{ readsData: false }` for a route that consults only `state` / `output.meta`.
|
|
133
137
|
|
|
138
|
+
### Model-judged loops — `assess`
|
|
139
|
+
|
|
140
|
+
`assess` is the third loop primitive, alongside `fanout` (breadth) and `iterate` (TS-judged depth). It's a **depth loop whose termination is decided by a separate model judge** — for when "are we done yet?" needs a model to read the work, not a synchronous TS predicate. Set it on a `produces()` stage.
|
|
141
|
+
|
|
142
|
+
Each round runs **two** sessions:
|
|
143
|
+
|
|
144
|
+
1. a **producer** — this stage's skill/outcome, emitting the work artifact;
|
|
145
|
+
2. a **judge** — a separate session emitting a validated verdict `{ done, feedback }`.
|
|
146
|
+
|
|
147
|
+
If `judge.done(verdict)` is `true`, the loop stops and the **producer** output (never the verdict) is the stage result. Otherwise `feedForward` builds the next producer prompt from the verdict's feedback, and the loop continues.
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { produces, directoryPathCollector, jsonBodyParser } from "@juicesharp/rpiv-workflow";
|
|
151
|
+
|
|
152
|
+
// The judge's verdict outcome. The collector MUST materialize ≥1 artifact —
|
|
153
|
+
// here a JSON file the parser reads into { done, feedback }. (See the
|
|
154
|
+
// ≥1-artifact constraint below.) Its `name` is its OWN channel, distinct
|
|
155
|
+
// from the producer outcome's name.
|
|
156
|
+
const verdictSpec = {
|
|
157
|
+
name: "verdicts",
|
|
158
|
+
collector: directoryPathCollector({ dir: ".rpiv/artifacts/verdicts", ext: "json" }),
|
|
159
|
+
parser: jsonBodyParser, // output.data = { done: boolean, feedback?: string }
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
breakdown: produces({
|
|
163
|
+
outcome: taskListOutcome, // producer outcome (the task list)
|
|
164
|
+
assess: {
|
|
165
|
+
judge: {
|
|
166
|
+
skill: "grade-breakdown", // skill judge — producer handle auto-injected
|
|
167
|
+
outcome: verdictSpec,
|
|
168
|
+
done: (v) => Boolean(v.data.done), // sync TS reading the model-made verdict
|
|
169
|
+
},
|
|
170
|
+
feedForward: ({ verdict }) => `Decompose further. Notes: ${verdict.data.feedback}`,
|
|
171
|
+
max: 8, // default 8, clamped by run.maxIterations
|
|
172
|
+
},
|
|
173
|
+
}),
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
**Skill vs. prompt judge.** Exactly one of `judge.skill` / `judge.prompt` is the dispatch discriminator (validated at load — both or neither is an error):
|
|
177
|
+
|
|
178
|
+
- **Skill judge** (`judge.skill` set): dispatched as `/skill:<judge.skill> <producerHandle>` — the latest producer artifact's handle is auto-injected as the input, exactly like any skill stage. `judge.prompt` is optional.
|
|
179
|
+
- **Prompt judge** (`judge.skill` absent): the resolved `judge.prompt` text is sent verbatim, so `judge.prompt` is **required** — the author embeds the producer handle/output (and the frozen `entryArtifact`, if wanted) into the prompt themselves, since a dispatched session delivers only the prompt text.
|
|
180
|
+
|
|
181
|
+
**≥1-artifact judge constraint.** The judge runs as a `produces`-kind session, so `enforceCompletionContract` makes a judge whose collector returns **zero** artifacts a **fatal halt** — no retry, no soft-stop. A judge that replies "not done" inline without writing anything *kills the run*. Always have the judge materialize its verdict (e.g. write a JSON file the collector enumerates and the parser reads), as `verdictSpec` does above.
|
|
182
|
+
|
|
183
|
+
**Soft-stop at `max`.** When the round cap is hit without `done`, the loop **soft-stops**: it emits a warning, keeps the **last producer output** as the stage result, and advances downstream. No terminal failure, no new error code. `max` defaults to 8 and is clamped by `run.maxIterations`.
|
|
184
|
+
|
|
185
|
+
**Judge sessions use framework defaults.** The judge runs on a synthetic `produces` def, so it does **not** inherit the parent stage's `onInvalid` / `maxRetries` / `outputSchema` / `validateTimeoutMs` — those apply to the **producer** sessions only; the judge gets framework defaults. (A skill judge still picks up its own declared skill-contract.) The producer and judge publish into **distinct** `state.named` channels (producer's `outcome.name` vs. `judge.outcome.name`), so verdicts never collide with producer outputs.
|
|
186
|
+
|
|
187
|
+
**Determinism contract (for resume).** Like `iterate`, `feedForward` and `judge.done` must be **deterministic** w.r.t. their inputs. Each round persists two audit rows (`r{n}·produce`, `r{n}·judge`); the judge's verdict is recorded specifically so resume **trusts** it rather than re-grading a non-deterministic model. On resume only the pending sub-step re-runs; a boundary guard catches drift in `feedForward` / `judge.done` and fails terminally rather than re-running wrong work.
|
|
188
|
+
|
|
189
|
+
`assess` is mutually exclusive with `fanout` / `iterate` / `run` / `prompt` / `reads`, requires `kind: "produces"`, and rejects `sessionPolicy: "continue"` (all enforced at load).
|
|
190
|
+
|
|
134
191
|
## Script stages (no Pi session)
|
|
135
192
|
|
|
136
|
-
Some stages don't need an LLM — they merge two upstream artifacts, bump a version field, or fire a post-run notification. The `.script` accessor on each factory runs a pure TS function in place of a Pi skill body. No `/skill:<name>` dispatch, no session, no transcript scan: the function gets a `ScriptContext` (`cwd`, `input` — upstream `Output` envelope, `state` — `
|
|
193
|
+
Some stages don't need an LLM — they merge two upstream artifacts, bump a version field, or fire a post-run notification. The `.script` accessor on each factory runs a pure TS function in place of a Pi skill body. No `/skill:<name>` dispatch, no session, no transcript scan: the function gets a `ScriptContext` (`cwd`, `input` — upstream `Output` envelope, `state` — the deep-readonly `RunView`) and either returns the new envelope (`produces.script`) or returns `void` (`acts.script` / `terminal.script`).
|
|
137
194
|
|
|
138
195
|
Stages with `.run` set CANNOT also declare `skill`, `outcome`, `fanout`, or `sessionPolicy: "continue"` — load-time validation rejects the combination. `produces.script` may declare `outputSchema` + `maxRetries` + `onInvalid` (same retry semantics as skill stages); `acts.script` / `terminal.script` may declare `inputSchema` for the upstream-data contract.
|
|
139
196
|
|
|
@@ -359,9 +416,9 @@ const result = await runWorkflow(ctx, {
|
|
|
359
416
|
});
|
|
360
417
|
```
|
|
361
418
|
|
|
362
|
-
Every callback receives a `LifecycleContext` with `runId`, `workflow`, `totalStages`, the `trigger` metadata, and a `
|
|
419
|
+
Every callback receives a `LifecycleContext` with `runId`, `workflow`, `totalStages`, the `trigger` metadata, and a deep-readonly `RunView` snapshot of the run's data channels. Events fire AFTER their JSONL row lands on disk, so a listener that calls `readLastStage(cwd, ctx.runId)` is guaranteed to see the just-recorded row. Callbacks may be async — the runner awaits them before advancing, giving back-pressure for free. Throws are caught + surfaced through `ctx.ui.notify(..., "warning")`; they never halt the run.
|
|
363
420
|
|
|
364
|
-
Available callbacks: `onWorkflowStart`, `onStageStart`, `onStageEnd`, `onStageRetry`, `onStageError`, `onRoute`, `
|
|
421
|
+
Available callbacks: `onWorkflowStart`, `onStageStart`, `onStageEnd`, `onStageRetry`, `onStageError`, `onRoute`, `onLoopStart`, `onUnitStart`, `onUnitEnd`, `onLoopCap`, `onWorkflowEnd`. See the `LifecycleListeners` JSDoc for the per-event payload.
|
|
365
422
|
|
|
366
423
|
### Trigger
|
|
367
424
|
|
|
@@ -378,10 +435,10 @@ type RunTrigger =
|
|
|
378
435
|
|
|
379
436
|
## Outcomes — collectors and parsers
|
|
380
437
|
|
|
381
|
-
Each `produces` stage wires an `OutputSpec` that tells the runtime three things:
|
|
438
|
+
Each `produces` stage wires an `Outcome` (formerly `OutputSpec` — the old name remains as a deprecated alias for one release) that tells the runtime three things:
|
|
382
439
|
|
|
383
440
|
```ts
|
|
384
|
-
interface
|
|
441
|
+
interface Outcome<Snapshot, Kind, Data> {
|
|
385
442
|
name?: string; // CATEGORISE — the publish slot in state.named (optional)
|
|
386
443
|
collector: ArtifactCollector<Snapshot>; // ENUMERATE — what did the stage produce?
|
|
387
444
|
parser?: ArtifactParser<Snapshot, Kind, Data>; // INTERPRET — what's the typed data channel?
|
|
@@ -508,3 +565,19 @@ export default defineWorkflow({
|
|
|
508
565
|
The contract is identical — author an async `~standard.validate` and the runner awaits it. A schema whose Promise never settles is bounded by the stage's `validateTimeoutMs` (default 5 min); a rejected Promise surfaces as a clean stage halt, attributed to the stage, with the same error class as a shape-failure halt. No opt-in flag, no parallel code path.
|
|
509
566
|
|
|
510
567
|
> Keep validation separate from the collector + parser. The collector's job is "what did the agent produce?" (enumerate); the parser's job is "parse it into typed data" (shape). The validator's job is "is the result correct?" (check + verify). With async validators available you don't have to push I/O verification into a custom collector/parser — keep them pure and put correctness checks on `outputSchema`.
|
|
568
|
+
|
|
569
|
+
## Glossary
|
|
570
|
+
|
|
571
|
+
One canonical name per concept. Where two words exist for the same thing, the split is deliberate: one is the **authoring surface** (what you type in a workflow file), the other is the **data vocabulary** (what lands in rows, envelopes, and types).
|
|
572
|
+
|
|
573
|
+
| Term | Meaning |
|
|
574
|
+
|------|---------|
|
|
575
|
+
| **Workflow** | The typed graph: a name, a `start` stage, a `stages` record, an `edges` table. Built with `defineWorkflow`, loaded from config layers or registered programmatically. |
|
|
576
|
+
| **Stage** | One node of the graph — a unit of dispatch (skill session, prompt, or script). Two kinds: `"produces"` and `"side-effect"`. |
|
|
577
|
+
| **Kind vs. factory** | `kind` is the persisted data discriminator (`"produces"` \| `"side-effect"`); the factories are authoring verbs: `produces()` → `"produces"`, `acts()` → `"side-effect"`, `terminal()` → `"side-effect"` + `inheritsArtifacts: false`. `acts` is a verb because it reads naturally in a stage record (`commit: acts()`); `"side-effect"` is descriptive because it reads naturally in rows and output envelopes. `terminal` is **not** a third kind — it's `acts` plus an artifact-isolation flag. |
|
|
578
|
+
| **Run** | One execution of a workflow: a `runId`, an append-only JSONL run file (the system of record for resume), and the in-memory state the runner threads. |
|
|
579
|
+
| **Chain** | The path a run walks through the graph — stage activations following `edges` from `start` until `"stop"` or a halt. Loops add generations *within* one chain position. |
|
|
580
|
+
| **Output** | The envelope one stage activation hands downstream: `{ kind, data, meta, artifacts }` (`Output<K, D>`, `output.ts`). What predicates, routes, downstream prompts, and the audit log see. |
|
|
581
|
+
| **Outcome** | The producer-side declaration of *how* a stage's Output gets built from a session: `{ collector, parser? }` (`Outcome`, `output-spec.ts`). The collector enumerates artifacts; the parser interprets them into `data`. |
|
|
582
|
+
| **Verdict** | A judge's Output (`type Verdict = Output`). In `assess` / `verify` loops the judge emits a verdict that `done` reads; verdicts are recorded for resume but never become the stage result. |
|
|
583
|
+
| **Contract** | A skill contract — what a skill `consumes` / `produces`. Declared by the skill's owner or harvested from stage declarations; adjudicated at load time (`canCompose`, the validator) to check composition. |
|