@juicesharp/rpiv-workflow 2.3.0 → 2.4.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/docs/embedding.md CHANGED
@@ -150,7 +150,7 @@ const result = await runWorkflow(ctx, { // ctx: WorkflowHostContext
150
150
  | `input` | `string` | required — passed to the start stage as its argument |
151
151
  | `host` | `WorkflowHost` | none; used for the skill-registration preflight snapshot |
152
152
  | `maxIterations` | `number` | `32` — run-wide cap on loop units of every kind |
153
- | `maxBackwardJumps` | `number` | `2` per destination stage |
153
+ | `maxBackwardJumps` | `number` | `3` per destination stage |
154
154
  | `trigger` | `RunTrigger` | `{ kind: "programmatic" }` |
155
155
  | `lifecycle` | `LifecycleListeners` | none |
156
156
  | `signal` | `AbortSignal` | none |
@@ -195,7 +195,7 @@ Two backstops bound every run regardless of what a workflow declares:
195
195
  | Cap | Default | Effect |
196
196
  | --- | --- | --- |
197
197
  | `maxIterations` | `32` | Run-wide ceiling on loop units of every kind. The effective loop cap is `min(loop.max, run.maxIterations)` |
198
- | Backward-jump budget | `2` per destination stage | At most 3 executions of any one stage across decision-edge loop-backs |
198
+ | Backward-jump budget | `3` per destination stage | At most 4 executions of any one stage across decision-edge loop-backs |
199
199
 
200
200
  ## Trusting overlay files
201
201
 
package/loop-kinds.ts CHANGED
@@ -607,85 +607,8 @@ const assessStrategy: SequentialStrategy = {
607
607
  // carries no marker, so live and resume can't disagree about flavoring.
608
608
  async pull(e, cursor, cap, run) {
609
609
  const loop = e.loop as AssessLoop;
610
- const isVerify = e.def.verify !== undefined;
611
- if (cursor.phase === "judge") {
612
- const lp = lastProduceOf(cursor, e.name); // a judge step always follows a completed produce
613
- // Expand the judge slot to its members and dispatch the member the
614
- // panel sub-state points at. A single judge is the panel of one
615
- // (`memberIndex` undefined, member 0 the only member), so its transition
616
- // is byte-identical to today; a panel walks member 0..N-1 across
617
- // successive judge-phase pulls, `advanceCursor` bumping
618
- // `cursor.panel.memberIndex` between them.
619
- const memberIndex = isPanel(loop.judge) ? (cursor.panel?.memberIndex ?? 0) : undefined;
620
- const judge = panelMembers(loop.judge)[memberIndex ?? 0]!;
621
- const judgeSkill = judge.skill ?? (isVerify ? `${e.name}-verify` : `${e.name}-judge`);
622
- let prompt: string;
623
- if (judge.skill !== undefined) {
624
- // produces-validation guarantees the producer emitted an artifact —
625
- // a miss is the same corrupted-cursor class as a missing produce.
626
- if (!lp.artifact) {
627
- const msg = MSG_LOOP_CURSOR_CORRUPT(e.name, "judge skill dispatch found no produced artifact");
628
- throw invariantPreflight(e.name, msg);
629
- }
630
- prompt = `/skill:${judge.skill} ${handleToString(lp.artifact.handle)}`;
631
- } else {
632
- prompt = await resolveJudgePrompt(judge.prompt!, {
633
- cwd: run.cwd,
634
- output: lp.output,
635
- entryArtifact: e.entryArtifact,
636
- state: run.state,
637
- round: cursor.index,
638
- });
639
- }
640
- const label = judgeUnitLabel(cursor.index, isVerify, memberIndex);
641
- return {
642
- kind: "unit",
643
- role: isVerify ? "verify" : "judge",
644
- tag: label,
645
- // Panel member rows carry an `id` so they are identity-bearing for the
646
- // resume join (`unitId` = the `#{memberIndex}` tag); a single judge keeps
647
- // identity `(role, round)` with no `id`, exactly as before.
648
- id: memberIndex === undefined ? undefined : label,
649
- label,
650
- skill: judgeSkill,
651
- prompt,
652
- def: judgeStageDef(judge),
653
- };
654
- }
655
-
656
- // produce — done wins over cap (one code path for live + resume fast-advance)
657
- if (cursor.lastVerdict !== undefined && loop.done(cursor.lastVerdict)) return { kind: "complete" };
658
- if (cursor.index >= cap) return { kind: "cap", count: cursor.index };
659
- // Producer dispatch is skill XOR prompt (the judge arm's posture). For
660
- // prompt dispatch the message is sent raw: round 0 resolves the stage's own
661
- // `prompt` at dispatch time (re-resolved on resume — the PromptFn joins the
662
- // loop determinism contract), and retry rounds send feedForward's output as
663
- // the COMPLETE message (there is no skill to prefix an arg onto).
664
- const isPrompt = e.def.prompt !== undefined;
665
- // `lastVerdict` is only set by a completed judge, which also bumps `index` —
666
- // so `index - 1 ≥ 0` whenever feedForward runs (round 0 takes entryArgs).
667
- const arg =
668
- cursor.lastVerdict !== undefined
669
- ? loop.feedForward({
670
- cwd: run.cwd,
671
- output: lastProduceOf(cursor, e.name).output,
672
- verdict: cursor.lastVerdict,
673
- round: cursor.index - 1,
674
- state: run.state,
675
- })
676
- : isPrompt
677
- ? await resolveStagePrompt(e.def.prompt!, run.cwd, run.state)
678
- : e.entryArgs;
679
- const label = isVerify ? `a${cursor.index}·attempt` : `r${cursor.index}·produce`;
680
- return {
681
- kind: "unit",
682
- role: "produce",
683
- tag: label,
684
- label,
685
- skill: e.skill,
686
- prompt: isPrompt ? arg : `/skill:${e.skill} ${arg}`,
687
- def: e.def,
688
- };
610
+ if (cursor.phase === "judge") return dispatchPanelMember(loop, cursor, e, run);
611
+ return dispatchProduce(loop, cursor, e, cap, run);
689
612
  },
690
613
  // The kind-agnostic (role, unitIndex) arithmetic already matched in the
691
614
  // caller. Full-check extras:
@@ -720,6 +643,126 @@ const assessStrategy: SequentialStrategy = {
720
643
  },
721
644
  };
722
645
 
646
+ /**
647
+ * The produce phase's termination check — a set `lastVerdict` that the loop's
648
+ * `done` predicate accepts. Named so the done-wins-over-cap ordering in
649
+ * `dispatchProduce` reads as intent.
650
+ */
651
+ const isDone = (loop: AssessLoop, cursor: LoopCursor): boolean =>
652
+ cursor.lastVerdict !== undefined && loop.done(cursor.lastVerdict);
653
+
654
+ /**
655
+ * Judge/verify phase dispatch — the panel-member arm of `assessStrategy.pull`.
656
+ * Expand the judge slot to its members and dispatch the member the panel
657
+ * sub-state points at. A single judge is the panel of one (`memberIndex`
658
+ * undefined, member 0 the only member), so its transition is byte-identical to
659
+ * today; a panel walks member 0..N-1 across successive judge-phase pulls,
660
+ * `advanceCursor` bumping `cursor.panel.memberIndex` between them.
661
+ */
662
+ async function dispatchPanelMember(
663
+ loop: AssessLoop,
664
+ cursor: LoopCursor,
665
+ e: LoopEntry,
666
+ run: RunContext,
667
+ ): Promise<NextStep> {
668
+ const isVerify = e.def.verify !== undefined;
669
+ const lp = lastProduceOf(cursor, e.name); // a judge step always follows a completed produce
670
+ const memberIndex = isPanel(loop.judge) ? (cursor.panel?.memberIndex ?? 0) : undefined;
671
+ const judge = panelMembers(loop.judge)[memberIndex ?? 0]!;
672
+ const judgeSkill = judge.skill ?? (isVerify ? `${e.name}-verify` : `${e.name}-judge`);
673
+ let prompt: string;
674
+ if (judge.skill !== undefined) {
675
+ // produces-validation guarantees the producer emitted an artifact —
676
+ // a miss is the same corrupted-cursor class as a missing produce.
677
+ if (!lp.artifact) {
678
+ const msg = MSG_LOOP_CURSOR_CORRUPT(e.name, "judge skill dispatch found no produced artifact");
679
+ throw invariantPreflight(e.name, msg);
680
+ }
681
+ prompt = `/skill:${judge.skill} ${handleToString(lp.artifact.handle)}`;
682
+ } else {
683
+ prompt = await resolveJudgePrompt(judge.prompt!, {
684
+ cwd: run.cwd,
685
+ output: lp.output,
686
+ entryArtifact: e.entryArtifact,
687
+ state: run.state,
688
+ round: cursor.index,
689
+ });
690
+ }
691
+ const label = judgeUnitLabel(cursor.index, isVerify, memberIndex);
692
+ return {
693
+ kind: "unit",
694
+ role: isVerify ? "verify" : "judge",
695
+ tag: label,
696
+ // Panel member rows carry an `id` so they are identity-bearing for the
697
+ // resume join (`unitId` = the `#{memberIndex}` tag); a single judge keeps
698
+ // identity `(role, round)` with no `id`, exactly as before.
699
+ id: memberIndex === undefined ? undefined : label,
700
+ label,
701
+ skill: judgeSkill,
702
+ prompt,
703
+ def: judgeStageDef(judge),
704
+ };
705
+ }
706
+
707
+ /**
708
+ * Produce phase dispatch — the producer arm of `assessStrategy.pull`. Done wins
709
+ * over cap (one code path for live + resume fast-advance). Producer dispatch is
710
+ * skill XOR prompt (the judge arm's posture). For prompt dispatch the message is
711
+ * sent raw: round 0 resolves the stage's own `prompt` at dispatch time
712
+ * (re-resolved on resume — the PromptFn joins the loop determinism contract),
713
+ * and retry rounds send feedForward's output as the COMPLETE message (there is no
714
+ * skill to prefix an arg onto).
715
+ */
716
+ async function dispatchProduce(
717
+ loop: AssessLoop,
718
+ cursor: LoopCursor,
719
+ e: LoopEntry,
720
+ cap: number,
721
+ run: RunContext,
722
+ ): Promise<NextStep> {
723
+ if (isDone(loop, cursor)) return { kind: "complete" };
724
+ if (cursor.index >= cap) return { kind: "cap", count: cursor.index };
725
+ const isPrompt = e.def.prompt !== undefined;
726
+ const arg = await resolveProduceArg(loop, cursor, e, run);
727
+ const isVerify = e.def.verify !== undefined;
728
+ const label = isVerify ? `a${cursor.index}·attempt` : `r${cursor.index}·produce`;
729
+ return {
730
+ kind: "unit",
731
+ role: "produce",
732
+ tag: label,
733
+ label,
734
+ skill: e.skill,
735
+ prompt: isPrompt ? arg : `/skill:${e.skill} ${arg}`,
736
+ def: e.def,
737
+ };
738
+ }
739
+
740
+ /**
741
+ * The producer's next-round arg — the three-way verdict/retry/init resolution:
742
+ * a retry round (a completed judge set `lastVerdict`) runs `feedForward`; round 0
743
+ * of a prompt stage resolves the stage's own `prompt`; round 0 of a skill stage
744
+ * takes the loop's entryArgs. `lastVerdict` is only set by a completed judge,
745
+ * which also bumps `index` — so `index - 1 ≥ 0` whenever feedForward runs
746
+ * (round 0 takes entryArgs). The async wrap preserves the await asymmetry:
747
+ * `feedForward` is a sync `(ctx) => string` (its bare `return` is wrapped by
748
+ * this async helper into a resolved promise), while `resolveStagePrompt` is
749
+ * `Promise<string>` and is awaited.
750
+ */
751
+ async function resolveProduceArg(loop: AssessLoop, cursor: LoopCursor, e: LoopEntry, run: RunContext): Promise<string> {
752
+ const isPrompt = e.def.prompt !== undefined;
753
+ return cursor.lastVerdict !== undefined
754
+ ? loop.feedForward({
755
+ cwd: run.cwd,
756
+ output: lastProduceOf(cursor, e.name).output,
757
+ verdict: cursor.lastVerdict,
758
+ round: cursor.index - 1,
759
+ state: run.state,
760
+ })
761
+ : isPrompt
762
+ ? await resolveStagePrompt(e.def.prompt!, run.cwd, run.state)
763
+ : e.entryArgs;
764
+ }
765
+
723
766
  /**
724
767
  * One strategy per kind — the `Record` shape turns "added a `LoopDef` arm,
725
768
  * forgot the strategy" into a compile error. Keyed value types are preserved
package/loop.ts CHANGED
@@ -36,11 +36,11 @@
36
36
  * no-op (pinned behavior).
37
37
  */
38
38
 
39
- import type { LoopDef } from "./api.js";
39
+ import type { AssessLoop, LoopDef } from "./api.js";
40
40
  import { applyCompletedStage } from "./chain-state.js";
41
41
  import { lifecycleCtxFor, skillStageRef } from "./events.js";
42
42
  import { nowIso } from "./internal-utils.js";
43
- import { isPanel } from "./judge.js";
43
+ import { type AnyJudge, isPanel, type PanelJudge } from "./judge.js";
44
44
  import { panelVerdictChannel, panelVerdictDef } from "./loop-constructors.js";
45
45
  import {
46
46
  advanceCursor,
@@ -88,6 +88,23 @@ export async function announceLoopStart(
88
88
  const isPristine = (cursor: LoopCursor): boolean =>
89
89
  cursor.index === 0 && cursor.accumulated.length === 0 && cursor.slots === undefined;
90
90
 
91
+ /** Narrows `loop` to AssessLoop — the one bearing a `judge` field; the first
92
+ * publishPanelVerdict guard routes through this so `loop.judge` type-checks
93
+ * without a cast. */
94
+ const isAssessLoop = (loop: LoopDef): loop is AssessLoop => loop.kind === "assess";
95
+
96
+ /** The panel-closing transition — fires exactly once per round: the LAST member's
97
+ * judge advance clears `cursor.panel` and flips to `produce` with the folded
98
+ * verdict already on `lastVerdict`. The positive conjunction of the De Morgan
99
+ * dual of the original guard. */
100
+ const isPanelClosingTransition = (judge: AnyJudge, cursor: LoopCursor): judge is PanelJudge =>
101
+ isPanel(judge) && cursor.panel === undefined && cursor.phase === "produce";
102
+
103
+ /** A live empty pull (iterate) loop — no units ran this invocation and none
104
+ * accumulated — the one shape that earns the zero-unit warning. */
105
+ const isZeroUnitPullLoop = (cursor: LoopCursor, loop: LoopDef): boolean =>
106
+ cursor.ranThisInvocation === 0 && cursor.accumulated.length === 0 && loop.kind === "iterate";
107
+
91
108
  /** Run (or resume) one loop generation. The caller fired onStageStart/onLoopStart. */
92
109
  export async function runLoop(
93
110
  hostCtx: WorkflowHostContext,
@@ -248,9 +265,9 @@ export function publishPanelVerdict(
248
265
  cursor: LoopCursor,
249
266
  state: RunContext["state"],
250
267
  ): void {
251
- if (loop.kind !== "assess") return; // narrows `loop` to AssessLoop — no cast needed below
268
+ if (!isAssessLoop(loop)) return;
252
269
  const judge = loop.judge;
253
- if (!isPanel(judge) || cursor.panel !== undefined || cursor.phase !== "produce") return;
270
+ if (!isPanelClosingTransition(judge, cursor)) return;
254
271
  if (cursor.lastVerdict === undefined) return; // defensive — the fold always set it
255
272
  applyCompletedStage(
256
273
  state,
@@ -303,7 +320,7 @@ async function finishLoop(
303
320
  deps: LoopDeps,
304
321
  ): Promise<void> {
305
322
  projectResult(e.loop, e.entryPair, cursor, run.state);
306
- if (cursor.ranThisInvocation === 0 && cursor.accumulated.length === 0 && e.loop.kind === "iterate") {
323
+ if (isZeroUnitPullLoop(cursor, e.loop)) {
307
324
  hostCtx.ui.notify(MSG_LOOP_ZERO_UNITS(e.skill), "warning");
308
325
  }
309
326
  await deps.advanceAfter(hostCtx, e.name, e.stageIdx, run);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -111,7 +111,7 @@
111
111
  ]
112
112
  },
113
113
  "dependencies": {
114
- "@juicesharp/rpiv-config": "^2.3.0",
114
+ "@juicesharp/rpiv-config": "^2.4.0",
115
115
  "jiti": "^2.7.0",
116
116
  "typebox": "^1.1.24"
117
117
  },
@@ -11,7 +11,7 @@
11
11
  * spelled as a module cycle.
12
12
  */
13
13
 
14
- import { takeRouteNote } from "../api.js";
14
+ import { type EdgeTarget, takeRouteNote } from "../api.js";
15
15
  import { auditCtxFor, failedArgs, recordFatalFailure } from "../audit.js";
16
16
  import { resolveSkill } from "../chain-state.js";
17
17
  import { lifecycleCtxFor, skillStageRef } from "../events.js";
@@ -65,19 +65,10 @@ export async function advanceChain(
65
65
  const fromRef = skillStageRef(currentName, idx + 1, skill);
66
66
 
67
67
  if (result.kind === "stop") {
68
- // A decision edge stopping the chain is audited like any forward pick,
69
- // and a stop carrying a ROUTE_NOTE is `match`'s no-fallback termination:
70
- // the gate found no branch for the value it read (typically a failed
71
- // verdict on a pass-only gate). That run is BLOCKED awaiting
72
- // intervention, not complete — record a terminal failure row so the
73
- // trail and the lane show a stopped run instead of a silent ✓. A
74
- // noteless decision stop (a custom edge deliberately returning STOP)
75
- // and the ordinary end-of-chain stop remain completions.
76
- const edge = run.workflow.edges[currentName];
77
- const note = wasDecision && typeof edge === "function" ? takeRouteNote(edge) : undefined;
68
+ const note = stopRouteNote(wasDecision, run.workflow.edges[currentName]);
78
69
  if (wasDecision) auditRoutingDecision(hostCtx, run, idx, currentName, "stop", note);
79
70
  await run.lifecycle.fire(hostCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
80
- if (note !== undefined) {
71
+ if (isBlockedGateStop(note)) {
81
72
  return haltChain(hostCtx, run, currentName, skill, failedArgs(FAIL_GATE_STOP(currentName, note)));
82
73
  }
83
74
  return finalizeWorkflow(hostCtx, run);
@@ -210,3 +201,28 @@ async function haltOnRoutingError(
210
201
  );
211
202
  return "halted";
212
203
  }
204
+
205
+ /**
206
+ * Read the ROUTE_NOTE a decision EdgeFn attached to its most recent pick,
207
+ * or undefined when the stop did not come from a decision edge function.
208
+ *
209
+ * Returns the note VALUE, not a boolean — `takeRouteNote` reads the
210
+ * `ROUTE_NOTE` symbol once then clears it (read-and-clear), so a boolean
211
+ * variant called twice would see undefined on the second read. The single
212
+ * returned note is threaded to both the audit row and the halt-vs-finalize
213
+ * decision. Non-decision stops and declarative edges (string / STOP) carry
214
+ * no note.
215
+ */
216
+ const stopRouteNote = (wasDecision: boolean, edge: EdgeTarget): string | undefined =>
217
+ wasDecision && typeof edge === "function" ? takeRouteNote(edge) : undefined;
218
+
219
+ /**
220
+ * A decision stop carrying a ROUTE_NOTE is `match`'s no-fallback
221
+ * termination: the gate found no branch for the value it read (typically
222
+ * a failed verdict on a pass-only gate). That run is BLOCKED awaiting
223
+ * intervention, not complete — halt via `haltChain` so the trail and the
224
+ * lane show a stopped run instead of a silent ✓. A noteless decision stop
225
+ * (a custom edge deliberately returning STOP) and the ordinary
226
+ * end-of-chain stop remain completions.
227
+ */
228
+ const isBlockedGateStop = (note: string | undefined): note is string => note !== undefined;
@@ -122,22 +122,25 @@ function ensureSkillRegistered(stage: ResolvedStage, run: RunContext): void {
122
122
  * The start node consumes the user's brief; subsequent stages MUST inherit
123
123
  * an upstream artifactPath. Falling back to originalInput past the start
124
124
  * would silently hand a downstream skill the raw feature description.
125
- *
126
- * Three opt-outs skip the check:
127
- * - `inheritsArtifacts: false` (authored via `terminal()`) — stage consumes
128
- * `originalInput` by design.
129
- * - `reads: [...]` — stage builds its prompt from the named-publish
130
- * registry instead of the rolling primary slot; `ensureNamedReads`
131
- * enforces its own coverage rule.
132
- * - prompt dispatch — the stage builds its own text and never consumes the
133
- * rolling primary as an arg (a continue chat turn typically leans on
134
- * session context, not a handle).
135
125
  */
126
+
127
+ /** The start node consumes the user's brief; it has no upstream artifact to inherit. */
128
+ const isStartStage = (stage: ResolvedStage, run: RunContext): boolean => stage.name === run.workflow.start;
129
+
130
+ /** Authored via `terminal()`: the stage consumes `originalInput` by design. */
131
+ const optsOutOfArtifactInheritance = (stage: ResolvedStage): boolean => stage.def.inheritsArtifacts === false;
132
+
133
+ /** Builds its prompt from the named-publish registry, not the rolling primary slot. */
134
+ const readsNamedChannels = (stage: ResolvedStage): boolean => !!stage.def.reads?.length;
135
+
136
+ /** Prompt dispatch builds its own text and never takes the rolling primary as an arg. */
137
+ const isPromptDispatch = (stage: ResolvedStage): boolean => stage.dispatch === "prompt";
138
+
136
139
  function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
137
- if (stage.name === run.workflow.start) return;
138
- if (stage.def.inheritsArtifacts === false) return;
139
- if (stage.def.reads?.length) return;
140
- if (stage.dispatch === "prompt") return;
140
+ if (isStartStage(stage, run)) return;
141
+ if (optsOutOfArtifactInheritance(stage)) return;
142
+ if (readsNamedChannels(stage)) return;
143
+ if (isPromptDispatch(stage)) return;
141
144
  if (currentPrimaryArtifact(run.state)) return;
142
145
  const f = FAIL_MISSING_ARTIFACT(stage.skill, stage.stageNumber);
143
146
  throw haltPreflight(stage.skill, f);