@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
package/loops/panel.ts ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Panel — N independent judges + a vote fold (the adversarial generalization
3
+ * of a single judge). Construction + the canonical verdict surface live here;
4
+ * execution (cursor sub-state, member dispatch, fold-close publish) lands in the
5
+ * runner behind the one `panelMembers` expander.
6
+ */
7
+
8
+ import { type Static, Type } from "typebox";
9
+ import type { StageDef } from "../api.js";
10
+ import {
11
+ assertShape,
12
+ brandCanonicalFold,
13
+ type FoldFn,
14
+ type Judge,
15
+ judgeShapeIssues,
16
+ marksCanonicalFold,
17
+ type NamedOutcome,
18
+ type PanelJudge,
19
+ } from "../judge.js";
20
+ import { noopCollector } from "../outcomes/index.js";
21
+ import type { Output } from "../output.js";
22
+
23
+ /**
24
+ * The canonical fold output shape — what `majority`/`all`/`any` emit and what
25
+ * a downstream `defineRoute`/`gate`/`match` branches on. `agreement` (|majority|
26
+ * / N) is the first-class disagreement signal; `tie` flags an even split. A
27
+ * custom (raw) fold publishes the author's own schema instead (the XOR rule).
28
+ */
29
+ export const PANEL_VERDICT = Type.Object({
30
+ pass: Type.Boolean(),
31
+ votes: Type.Object({ pass: Type.Integer(), fail: Type.Integer() }),
32
+ agreement: Type.Number(),
33
+ tie: Type.Boolean(),
34
+ });
35
+
36
+ /** Static type of the canonical {@link PANEL_VERDICT} fold output. */
37
+ export type PanelVerdict = Static<typeof PANEL_VERDICT>;
38
+
39
+ /**
40
+ * Built-in named outcome the CANONICAL path publishes under — the default a
41
+ * sugar panel resolves to (`judge.outcome ?? PANEL_VERDICT_OUTCOME`, wired in
42
+ * the panel-close publish phase). Its `name` is a fallback: the live publish
43
+ * overrides it with the per-stage `<stage>-panel` channel, so distinct panel
44
+ * stages never collide. The collector is a no-op — the fold output is
45
+ * manufactured from the member verdicts (data, not a collected artifact), so
46
+ * nothing is ever collected on this outcome.
47
+ */
48
+ export const PANEL_VERDICT_OUTCOME: NamedOutcome = {
49
+ name: "panel-verdict",
50
+ collector: noopCollector,
51
+ };
52
+
53
+ /**
54
+ * Tally the members' per-member `pred` results into the canonical verdict
55
+ * shape. `votes`/`agreement`/`tie` are fold-independent (they describe the
56
+ * split); only `pass` differs per sugar fold, supplied by `passWhen`.
57
+ */
58
+ function tally(
59
+ verdicts: readonly Output[],
60
+ pred: (v: Output) => boolean,
61
+ passWhen: (pass: number, fail: number) => boolean,
62
+ ): PanelVerdict {
63
+ const n = verdicts.length;
64
+ const pass = verdicts.reduce((c, v) => c + (pred(v) ? 1 : 0), 0);
65
+ const fail = n - pass;
66
+ return {
67
+ pass: passWhen(pass, fail),
68
+ votes: { pass, fail },
69
+ agreement: n === 0 ? 0 : Math.max(pass, fail) / n,
70
+ tie: pass === fail,
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Sugar fold — the panel passes iff a STRICT majority of members pass `pred`
76
+ * (an even split is a tie ⇒ fail, surfaced via `tie`/`agreement`). The
77
+ * per-member `pred` interprets each member's OWN verdict schema (no convention
78
+ * on members); the fold's output is the canonical {@link PANEL_VERDICT}. Branded
79
+ * canonical, so pairing it with an explicit `outcome` is a construction error.
80
+ */
81
+ export function majority(pred: (v: Output) => boolean): FoldFn {
82
+ return brandCanonicalFold("majority", (verdicts) => tally(verdicts, pred, (pass, fail) => pass > fail));
83
+ }
84
+
85
+ /** Sugar fold — unanimous: the panel passes iff EVERY member passes `pred` (one fail vetoes). */
86
+ export function all(pred: (v: Output) => boolean): FoldFn {
87
+ return brandCanonicalFold("all", (verdicts) => tally(verdicts, pred, (pass, fail) => pass > 0 && fail === 0));
88
+ }
89
+
90
+ /** Sugar fold — veto/rescue: the panel passes iff ANY member passes `pred` (one pass carries it). */
91
+ export function any(pred: (v: Output) => boolean): FoldFn {
92
+ return brandCanonicalFold("any", (verdicts) => tally(verdicts, pred, (pass) => pass > 0));
93
+ }
94
+
95
+ /**
96
+ * Single rule source for the panel shape — mirrors `judgeShapeIssues` /
97
+ * `verifyShapeIssues`. Returns human-readable violations (empty = valid);
98
+ * `panel()` throws on the first, `validateWorkflow` maps each to a load issue
99
+ * for hand-rolled literals. Takes `unknown` ON PURPOSE: typed call sites are
100
+ * already guarded by the `PanelJudge` type, so everything reaching here is an
101
+ * untyped jiti-loaded literal.
102
+ *
103
+ * Enforces: a non-empty `members` array, each member a VALID single judge with
104
+ * NO nesting (`members` is `Judge[]`), a function `fold`, and the XOR rule
105
+ * (canonical sugar ⊕ `outcome` — exactly one names the verdict schema/channel).
106
+ */
107
+ export function panelShapeIssues(candidate: unknown): string[] {
108
+ if (!candidate || typeof candidate !== "object") return ["a panel object is required"];
109
+ const p = candidate as { members?: unknown; fold?: unknown; outcome?: { name?: unknown } };
110
+ const issues: string[] = [];
111
+
112
+ if (!Array.isArray(p.members) || p.members.length === 0) {
113
+ issues.push("panel.members must be a non-empty array of judges");
114
+ } else {
115
+ for (const m of p.members) {
116
+ if (m && typeof m === "object" && (m as PanelJudge).kind === "panel") {
117
+ issues.push("panel.members may not nest another panel — members are single judges (skill or prompt)");
118
+ continue;
119
+ }
120
+ for (const issue of judgeShapeIssues(m)) issues.push(`panel member: ${issue}`);
121
+ }
122
+ }
123
+
124
+ const foldIsFn = typeof p.fold === "function";
125
+ if (!foldIsFn) {
126
+ issues.push("panel.fold must be a function reducing the member verdicts to the panel's decision");
127
+ }
128
+
129
+ // The XOR rule — a sugar fold OWNS the canonical verdict (no `outcome`); a raw
130
+ // fold REQUIRES an `outcome` to name + validate its channel. Never both.
131
+ const isSugar = foldIsFn && marksCanonicalFold(p.fold as FoldFn);
132
+ const hasOutcome = p.outcome !== undefined;
133
+ if (isSugar && hasOutcome) {
134
+ issues.push(
135
+ "a canonical fold (majority/all/any) publishes the built-in PANEL_VERDICT — drop `outcome` (sugar ⊕ outcome)",
136
+ );
137
+ }
138
+ if (foldIsFn && !isSugar && !hasOutcome) {
139
+ issues.push("a custom (raw) fold requires an `outcome` naming + validating its verdict channel (raw ⊕ outcome)");
140
+ }
141
+ if (hasOutcome && !p.outcome?.name) {
142
+ issues.push("panel.outcome must carry a `name` so the folded verdict publishes to its own named channel");
143
+ }
144
+
145
+ return issues;
146
+ }
147
+
148
+ /** Authoring input for {@link panel} — the `PanelJudge` minus the injected `kind` discriminator. */
149
+ export interface PanelSpec {
150
+ members: readonly Judge[];
151
+ fold: FoldFn;
152
+ outcome?: NamedOutcome;
153
+ }
154
+
155
+ /**
156
+ * Promote a panel literal to a validated `PanelJudge` — injects the
157
+ * `kind: "panel"` discriminator and throws on the first shape issue, so a
158
+ * `panel(...)`-authored value is correct by construction (cf. `judge()` /
159
+ * `defineRoute`). The judge SITES already accept it through the widened
160
+ * `AnyJudge` slot; their member dispatch + fold-close publish arrive in the
161
+ * execution phases, so `assess`/`verify` don't yet route a panel here.
162
+ */
163
+ export function panel(spec: PanelSpec): PanelJudge {
164
+ const candidate: PanelJudge = { kind: "panel", ...spec };
165
+ assertShape("panel", panelShapeIssues(candidate));
166
+ return candidate;
167
+ }
168
+
169
+ /**
170
+ * The channel a panel's FOLDED verdict publishes to — the author's
171
+ * `outcome.name` on the custom path, or the `<stage>-panel` convention on the
172
+ * canonical path (sugar fold, no `outcome`). ONE definition so the load gate
173
+ * (`validateWorkflow`) and the panel-close publish (later phases) can never
174
+ * drift on the name. Member verdicts publish to their OWN `outcome.name`
175
+ * channels; this is only the fold's slot.
176
+ */
177
+ export function panelVerdictChannel(p: PanelJudge, stageName: string): string {
178
+ return p.outcome?.name ?? `${stageName}-panel`;
179
+ }
180
+
181
+ /**
182
+ * Synthetic `produces` def the panel-close publish lands the FOLDED verdict
183
+ * under — the twin of `judgeStageDef` (which a single MEMBER runs on). The
184
+ * publish channel is resolved ONCE through {@link panelVerdictChannel} and baked
185
+ * into `outcome.name`, so the canonical path's per-stage `<stage>-panel` channel
186
+ * OVERRIDES `PANEL_VERDICT_OUTCOME`'s fallback name (distinct panel stages never
187
+ * collide) and the custom path keeps the author's own `outcome`. The folded
188
+ * Output carries no artifact, so `applyCompletedStage` leaves the rolling primary
189
+ * untouched and only appends to the named channel. ONE construction site —
190
+ * the live publish (`loop.ts`) and the resume fold (`runner/resume.ts`) share it,
191
+ * so the two paths can never drift on the def or the channel.
192
+ */
193
+ export function panelVerdictDef(p: PanelJudge, stageName: string): StageDef {
194
+ const base = p.outcome ?? PANEL_VERDICT_OUTCOME;
195
+ return { kind: "produces", outcome: { ...base, name: panelVerdictChannel(p, stageName) }, sessionPolicy: "fresh" };
196
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Verify — the per-stage post-condition desugared to a degenerate assess loop.
3
+ * `verify()` builds the `VerifySpec` a stage carries on its `verify` field;
4
+ * `synthesizeVerifyLoop` is the desugar the runner consults (via
5
+ * `effectiveLoopOf`). Runner-free — safe on `registration`.
6
+ */
7
+
8
+ import type { AssessLoop, VerifySpec } from "../api.js";
9
+ import { assertShape } from "../judge.js";
10
+ import { judgeSlotShapeIssues, VERIFY_LOOP_DEFAULTS } from "./constructors.js";
11
+
12
+ /**
13
+ * Per-stage post-condition judge: after each attempt of the stage completes,
14
+ * `judge` grades it and `done(verdict)` gates advancement — true → advance
15
+ * with the attempt's producer pair; false → fresh retry attempt (prompt arg
16
+ * from `feedForward`) up to `max` attempts (default 1 = gate-only), then a
17
+ * terminal "verification failed" halt. Requires `kind: "produces"` + an
18
+ * `outcome` with a `name` (workflow-level, checked at load). Composes with
19
+ * `reads` and with `prompt` dispatch (attempt 0 sends the stage's resolved
20
+ * prompt; retries send `feedForward`'s output raw); mutually exclusive with
21
+ * `loop`/`run`/continue.
22
+ *
23
+ * The runner desugars the spec into a degenerate assess loop
24
+ * (`synthesizeVerifyLoop`) run by the ONE driver — verify rides the tested
25
+ * pair-restore / per-attempt-snapshot / resume machinery rather than forking it.
26
+ */
27
+ export function verify(spec: VerifySpec): VerifySpec {
28
+ assertShape("verify", verifyShapeIssues(spec));
29
+ return spec;
30
+ }
31
+
32
+ /**
33
+ * Single rule source for the verify shape. Returns human-readable violations
34
+ * (empty array = valid). `verify()` throws on the first; `validateWorkflow`
35
+ * maps each to a load issue for hand-rolled literals that bypassed the
36
+ * factory (jiti-loaded configs erase TS types). Same pattern as
37
+ * `judgeShapeIssues` / `judge()`.
38
+ */
39
+ export function verifyShapeIssues(candidate: unknown): string[] {
40
+ if (!candidate || typeof candidate !== "object") return ["a verify object is required"];
41
+ const v = candidate as Partial<VerifySpec>;
42
+ // The judge slot is an `AnyJudge` — route the panel-vs-single shape dispatch
43
+ // through the shared `judgeSlotShapeIssues` (one rule source per shape).
44
+ const judgeIssues = judgeSlotShapeIssues(v.judge);
45
+ const issues: string[] = [...judgeIssues];
46
+ if (typeof v.done !== "function") {
47
+ issues.push("verify requires `done` to be a function deciding pass/fail from the verdict");
48
+ }
49
+ if (v.max !== undefined && (!Number.isInteger(v.max) || v.max < 1)) {
50
+ issues.push(`verify.max: ${v.max} — must be an integer >= 1 (run.maxIterations caps the upper bound)`);
51
+ }
52
+ if (v.feedForward !== undefined && typeof v.feedForward !== "function") {
53
+ issues.push("verify `feedForward` must be a function building the next attempt's prompt arg");
54
+ }
55
+ if ((v.max ?? 1) > 1 && v.feedForward === undefined) {
56
+ issues.push(
57
+ "verify.max > 1 requires `feedForward` — without it the retried prompt would be byte-identical to the original",
58
+ );
59
+ }
60
+ return issues;
61
+ }
62
+
63
+ /**
64
+ * Unreachable by construction: the driver's cap check precedes the
65
+ * feedForward call (loop.ts pullNext), so a gate-only verify (`max` 1, the
66
+ * only shape allowed to omit `feedForward`) caps before a second attempt
67
+ * could ever ask for an arg. A throw here means that invariant broke
68
+ * — fail loudly (propagates to the runner's single catch) rather than
69
+ * silently dispatching an empty-arg prompt.
70
+ */
71
+ const NEVER_FEED_FORWARD = (): string => {
72
+ throw new Error("verify: feedForward invoked on a gate-only verify (max 1) — driver invariant violated");
73
+ };
74
+
75
+ /**
76
+ * The desugar: a `VerifySpec` as a degenerate assess loop — the shared
77
+ * `JudgedRepetition` fields flow straight through (`max` defaulted to 1 for
78
+ * the gate-only shape); the cap policy is always `"halt"`
79
+ * (a failing final verdict = "verification failed"; `done` wins over the cap
80
+ * so a pass on the final attempt is a normal completion), and `result:
81
+ * "last"` restores the last attempt's producer pair at loop advance.
82
+ * Allocates per call — callers cache (LoopEntry live; OpenGeneration on the
83
+ * fold), and nothing compares loop identity.
84
+ *
85
+ * NOT re-exported from registration.ts — runtime plumbing, not authoring
86
+ * surface (precedent: `judgeStageDef`).
87
+ */
88
+ export function synthesizeVerifyLoop(v: VerifySpec): AssessLoop {
89
+ const d = VERIFY_LOOP_DEFAULTS;
90
+ return {
91
+ kind: "assess",
92
+ judge: v.judge,
93
+ done: v.done,
94
+ feedForward: v.feedForward ?? NEVER_FEED_FORWARD,
95
+ max: v.max ?? d.max,
96
+ onCap: d.onCap,
97
+ result: d.result,
98
+ };
99
+ }