@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.
Files changed (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
@@ -0,0 +1,623 @@
1
+ /**
2
+ * Loop constructors + introspection — control flow as data, completed.
3
+ *
4
+ * `fanout()` / `iterate()` / `assess()` build the `LoopDef` a stage carries on
5
+ * its single `loop` field; `verify()` builds the `VerifySpec` a stage carries
6
+ * on its `verify` field. Unlike the retired spec-attaching builders (which
7
+ * ATTACHED a `.spec` to a bare function), the LoopDef IS data with
8
+ * function-valued fields — the spec is the source of truth in the
9
+ * constructor, so introspection can never lag a new loop kind. `loopSpecOf`
10
+ * projects the pure-data facet.
11
+ *
12
+ * Constructors validate at construction (the `defineRoute` pattern): a bad
13
+ * `max`, an invalid judge shape, or a non-function `done`/`feedForward`
14
+ * throws immediately at authoring time. Load-time validation re-checks the
15
+ * same rules defensively for hand-rolled literals (jiti erases TS types).
16
+ *
17
+ * Skill-agnostic: the unit detectors (`units`/`next`) are consumer-supplied;
18
+ * rpiv-workflow ships no conventions. Runner-free — safe on `registration`.
19
+ */
20
+
21
+ import { type Static, Type } from "typebox";
22
+ import type {
23
+ AssessLoop,
24
+ CapPolicy,
25
+ EdgeFn,
26
+ FanoutFn,
27
+ FanoutLoop,
28
+ FeedForwardContext,
29
+ IterateFn,
30
+ IterateLoop,
31
+ LoopDef,
32
+ ResultProjection,
33
+ StageDef,
34
+ UnitSelector,
35
+ VerifySpec,
36
+ Workflow,
37
+ } from "./api.js";
38
+ import { STOP } from "./api.js";
39
+ import {
40
+ type AnyJudge,
41
+ brandCanonicalFold,
42
+ type CanonicalFoldName,
43
+ canonicalFoldName,
44
+ type FoldFn,
45
+ isPanel,
46
+ type Judge,
47
+ judgeShapeIssues,
48
+ marksCanonicalFold,
49
+ type NamedOutcome,
50
+ type PanelJudge,
51
+ panelMembers,
52
+ } from "./judge.js";
53
+ import { noopCollector } from "./outcomes/index.js";
54
+ import type { Output } from "./output.js";
55
+
56
+ // `UnitSelector` moved to api.ts (it lives with the loop vocabulary now);
57
+ // re-exported here so existing consumers' import path is unchanged.
58
+ export type { UnitSelector } from "./api.js";
59
+
60
+ // ===========================================================================
61
+ // Introspection — per-stage control-flow + edge shape
62
+ // ===========================================================================
63
+
64
+ /**
65
+ * Per-stage control-flow + edge shape, read entirely from attached data — no
66
+ * probing. The control-flow analogue of `legalNextSkills`: what an
67
+ * analyzing/suggesting agent consumes to render or reason about a flow's
68
+ * structure. `control.mode` now covers assess (previously read as "single").
69
+ */
70
+ export interface StageShape {
71
+ stage: string;
72
+ skill?: string;
73
+ control: { mode: "single" | LoopDef["kind"]; spec?: LoopSpec };
74
+ /**
75
+ * Present iff the stage carries a `verify` post-condition. `control.mode`
76
+ * stays `"single"` for verify stages — verify is a stage property in the
77
+ * introspection model, not a loop kind (the desugar is a runtime concern).
78
+ * A `panel()` post-condition projects a `PanelJudgeSpec` here (still + `max`).
79
+ */
80
+ verify?: AnyJudgeSpec & { max: number };
81
+ edge: { mode: "linear" | "route" | "terminal"; targets?: readonly string[] };
82
+ }
83
+
84
+ /** Describe a workflow's structure stage-by-stage from attached metadata alone. */
85
+ export function describeFlow(w: Workflow): StageShape[] {
86
+ return Object.entries(w.stages).map(([name, stage]) => {
87
+ const control: StageShape["control"] = stage.loop
88
+ ? { mode: stage.loop.kind, spec: loopSpecOf(stage.loop) }
89
+ : { mode: "single" };
90
+
91
+ const target = w.edges[name];
92
+ let edge: StageShape["edge"];
93
+ if (target === undefined || target === STOP) {
94
+ edge = { mode: "terminal" };
95
+ } else if (typeof target === "string") {
96
+ edge = { mode: "linear", targets: [target] };
97
+ } else {
98
+ edge = { mode: "route", targets: (target as EdgeFn).targets };
99
+ }
100
+
101
+ return {
102
+ stage: name,
103
+ skill: stage.skill,
104
+ control,
105
+ ...(stage.verify ? { verify: { ...judgeSlotSpecOf(stage.verify.judge), max: stage.verify.max ?? 1 } } : {}),
106
+ edge,
107
+ };
108
+ });
109
+ }
110
+
111
+ // ===========================================================================
112
+ // Loop constructors — fanout() / iterate() / assess() build StageDef.loop
113
+ // ===========================================================================
114
+
115
+ /** Default round cap when an `assess()` call omits `max`. Clamped by `run.maxIterations`. */
116
+ export const DEFAULT_ASSESS_MAX = 8;
117
+
118
+ /** Options shared by all three constructors — the introspectable facet + policy knobs. */
119
+ interface LoopOptionsBase {
120
+ /** The named channel the units are split FROM (a `consumes` hint for lints/agents). */
121
+ source?: string;
122
+ /** How units are detected (opaque convention — e.g. `{ by: "frontmatter-array", pattern: "phases" }`). */
123
+ unit?: UnitSelector;
124
+ /** Cardinality ceiling. Must be an integer >= 1 (throws at construction). */
125
+ max?: number;
126
+ /** Cap policy override. Defaults: fanout/iterate → "halt", assess → "advance". */
127
+ onCap?: CapPolicy;
128
+ /** Result projection override. Defaults: fanout → "entry", iterate/assess → "last". */
129
+ result?: ResultProjection;
130
+ }
131
+
132
+ export interface FanoutOptions extends LoopOptionsBase {
133
+ /** Push-model unit source — all units computed up front. */
134
+ units: FanoutFn;
135
+ }
136
+
137
+ export interface IterateOptions extends LoopOptionsBase {
138
+ /** Pull-model unit source — one unit per call, fed the accumulated prefix. */
139
+ next: IterateFn;
140
+ }
141
+
142
+ export interface AssessOptions extends LoopOptionsBase {
143
+ /** The judge SLOT — a single `Judge` or an N-member `panel()` (a single judge is the panel of one). */
144
+ judge: AnyJudge;
145
+ /** Sync TS reading the model-made verdict. `true` → loop stops, producer output is the result. */
146
+ done: (verdict: Output) => boolean;
147
+ /** Builds the next producer prompt arg from the just-judged round's output + verdict. */
148
+ feedForward: (ctx: FeedForwardContext) => string;
149
+ }
150
+
151
+ /**
152
+ * Push loop: all units precomputed, each unit its own session. On a
153
+ * `produces` stage units COLLECT (full collect→validate→publish per unit;
154
+ * `outcome.name` required); on an `acts` stage units are side-effects.
155
+ * Empty `units()` return ⇒ single-stage fall-through.
156
+ */
157
+ export function fanout(opts: FanoutOptions): FanoutLoop {
158
+ return {
159
+ kind: "fanout",
160
+ units: opts.units,
161
+ source: opts.source,
162
+ unit: opts.unit,
163
+ max: checkedMax("fanout", opts.max),
164
+ onCap: opts.onCap ?? "halt",
165
+ result: opts.result ?? "entry",
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Pull loop: sequential, accumulating — each `next()` call sees the prior
171
+ * units' validated Outputs. Requires `kind: "produces"` + `outcome.name`
172
+ * (workflow-level, checked at load). First-call `null` ⇒ zero-unit no-op.
173
+ */
174
+ export function iterate(opts: IterateOptions): IterateLoop {
175
+ return {
176
+ kind: "iterate",
177
+ next: opts.next,
178
+ source: opts.source,
179
+ unit: opts.unit,
180
+ max: checkedMax("iterate", opts.max),
181
+ onCap: opts.onCap ?? "halt",
182
+ result: opts.result ?? "last",
183
+ };
184
+ }
185
+
186
+ /**
187
+ * Model-judged until-done loop: each round runs a producer session (this
188
+ * stage's skill/outcome) then a judge session (`opts.judge`). `done(verdict)`
189
+ * decides termination; `feedForward` carries the verdict into the next
190
+ * producer round. The cap soft-stops by default (`onCap: "advance"`).
191
+ * Requires `kind: "produces"` + `outcome.name` (workflow-level, checked at
192
+ * load) — every round runs the produces collector, so the producer needs a
193
+ * stable named slot like any other collecting loop.
194
+ */
195
+ export function assess(opts: AssessOptions): AssessLoop {
196
+ // The judge slot is an `AnyJudge`: route a panel through `panelShapeIssues`,
197
+ // a single judge through `judgeShapeIssues` (same rule sources the load gate
198
+ // re-checks for hand-rolled literals).
199
+ const issues = isPanel(opts.judge) ? panelShapeIssues(opts.judge) : judgeShapeIssues(opts.judge);
200
+ if (issues.length > 0) throw new Error(`assess(): ${issues[0]}`);
201
+ if (typeof opts.done !== "function") {
202
+ throw new Error("assess(): `done` must be a function deciding termination from the verdict");
203
+ }
204
+ if (typeof opts.feedForward !== "function") {
205
+ throw new Error("assess(): `feedForward` must be a function building the next producer arg");
206
+ }
207
+ return {
208
+ kind: "assess",
209
+ judge: opts.judge,
210
+ done: opts.done,
211
+ feedForward: opts.feedForward,
212
+ source: opts.source,
213
+ unit: opts.unit,
214
+ max: checkedMax("assess", opts.max) ?? DEFAULT_ASSESS_MAX,
215
+ onCap: opts.onCap ?? "advance",
216
+ result: opts.result ?? "last",
217
+ };
218
+ }
219
+
220
+ /**
221
+ * Per-stage post-condition judge: after each attempt of the stage completes,
222
+ * `judge` grades it and `done(verdict)` gates advancement — true → advance
223
+ * with the attempt's producer pair; false → fresh retry attempt (prompt arg
224
+ * from `feedForward`) up to `max` attempts (default 1 = gate-only), then a
225
+ * terminal "verification failed" halt. Requires `kind: "produces"` + an
226
+ * `outcome` with a `name` (workflow-level, checked at load). Composes with
227
+ * `reads` and with `prompt` dispatch (attempt 0 sends the stage's resolved
228
+ * prompt; retries send `feedForward`'s output raw); mutually exclusive with
229
+ * `loop`/`run`/continue.
230
+ *
231
+ * The runner desugars the spec into a degenerate assess loop
232
+ * (`synthesizeVerifyLoop`) run by the ONE driver — verify rides the tested
233
+ * pair-restore / per-attempt-snapshot / resume machinery rather than forking it.
234
+ */
235
+ export function verify(spec: VerifySpec): VerifySpec {
236
+ const issues = verifyShapeIssues(spec);
237
+ if (issues.length > 0) throw new Error(`verify(): ${issues[0]}`);
238
+ return spec;
239
+ }
240
+
241
+ /**
242
+ * Single rule source for the verify shape. Returns human-readable violations
243
+ * (empty array = valid). `verify()` throws on the first; `validateWorkflow`
244
+ * maps each to a load issue for hand-rolled literals that bypassed the
245
+ * factory (jiti-loaded configs erase TS types). Same pattern as
246
+ * `judgeShapeIssues` / `judge()`.
247
+ */
248
+ export function verifyShapeIssues(candidate: unknown): string[] {
249
+ if (!candidate || typeof candidate !== "object") return ["a verify object is required"];
250
+ const v = candidate as Partial<VerifySpec>;
251
+ // The judge slot is an `AnyJudge` — route a panel through `panelShapeIssues`,
252
+ // a single judge through `judgeShapeIssues` (one rule source per shape).
253
+ const judgeIssues = v.judge && isPanel(v.judge) ? panelShapeIssues(v.judge) : judgeShapeIssues(v.judge);
254
+ const issues: string[] = [...judgeIssues];
255
+ if (typeof v.done !== "function") {
256
+ issues.push("verify requires `done` to be a function deciding pass/fail from the verdict");
257
+ }
258
+ if (v.max !== undefined && (!Number.isInteger(v.max) || v.max < 1)) {
259
+ issues.push(`verify.max: ${v.max} — must be an integer >= 1 (run.maxIterations caps the upper bound)`);
260
+ }
261
+ if (v.feedForward !== undefined && typeof v.feedForward !== "function") {
262
+ issues.push("verify `feedForward` must be a function building the next attempt's prompt arg");
263
+ }
264
+ if ((v.max ?? 1) > 1 && v.feedForward === undefined) {
265
+ issues.push(
266
+ "verify.max > 1 requires `feedForward` — without it the retried prompt would be byte-identical to the original",
267
+ );
268
+ }
269
+ return issues;
270
+ }
271
+
272
+ /**
273
+ * Unreachable by construction: the driver's cap check precedes the
274
+ * feedForward call (loop.ts pullNext), so a gate-only verify (`max` 1, the
275
+ * only shape allowed to omit `feedForward`) caps before a second attempt
276
+ * could ever ask for an arg. A throw here means that invariant broke
277
+ * — fail loudly (propagates to the runner's single catch) rather than
278
+ * silently dispatching an empty-arg prompt.
279
+ */
280
+ const NEVER_FEED_FORWARD = (): string => {
281
+ throw new Error("verify: feedForward invoked on a gate-only verify (max 1) — driver invariant violated");
282
+ };
283
+
284
+ /**
285
+ * The desugar: a `VerifySpec` as a degenerate assess loop — the shared
286
+ * `JudgedRepetition` fields flow straight through (`max` defaulted to 1 for
287
+ * the gate-only shape); the cap policy is always `"halt"`
288
+ * (a failing final verdict = "verification failed"; `done` wins over the cap
289
+ * so a pass on the final attempt is a normal completion), and `result:
290
+ * "last"` restores the last attempt's producer pair at loop advance.
291
+ * Allocates per call — callers cache (LoopEntry live; OpenGeneration on the
292
+ * fold), and nothing compares loop identity.
293
+ *
294
+ * NOT re-exported from registration.ts — runtime plumbing, not authoring
295
+ * surface (precedent: `judgeStageDef`).
296
+ */
297
+ export function synthesizeVerifyLoop(v: VerifySpec): AssessLoop {
298
+ return {
299
+ kind: "assess",
300
+ judge: v.judge,
301
+ done: v.done,
302
+ feedForward: v.feedForward ?? NEVER_FEED_FORWARD,
303
+ max: v.max ?? 1,
304
+ onCap: "halt",
305
+ result: "last",
306
+ };
307
+ }
308
+
309
+ // ===========================================================================
310
+ // Panel — N independent judges + a vote fold (the adversarial generalization
311
+ // of a single judge). Construction + the canonical verdict surface live here;
312
+ // execution (cursor sub-state, member dispatch, fold-close publish) lands in
313
+ // later phases behind the one `panelMembers` expander.
314
+ // ===========================================================================
315
+
316
+ /**
317
+ * The canonical fold output shape — what `majority`/`all`/`any` emit and what
318
+ * a downstream `defineRoute`/`gate`/`match` branches on. `agreement` (|majority|
319
+ * / N) is the first-class disagreement signal; `tie` flags an even split. A
320
+ * custom (raw) fold publishes the author's own schema instead (the §4 XOR).
321
+ */
322
+ export const PANEL_VERDICT = Type.Object({
323
+ pass: Type.Boolean(),
324
+ votes: Type.Object({ pass: Type.Integer(), fail: Type.Integer() }),
325
+ agreement: Type.Number(),
326
+ tie: Type.Boolean(),
327
+ });
328
+
329
+ /** Static type of the canonical {@link PANEL_VERDICT} fold output. */
330
+ export type PanelVerdict = Static<typeof PANEL_VERDICT>;
331
+
332
+ /**
333
+ * Built-in named outcome the CANONICAL path publishes under — the default a
334
+ * sugar panel resolves to (`judge.outcome ?? PANEL_VERDICT_OUTCOME`, wired in
335
+ * the panel-close publish phase). Its `name` is a fallback: the live publish
336
+ * overrides it with the per-stage `<stage>-panel` channel, so distinct panel
337
+ * stages never collide. The collector is a no-op — the fold output is
338
+ * manufactured from the member verdicts (data, not a collected artifact), so
339
+ * nothing is ever collected on this outcome.
340
+ */
341
+ export const PANEL_VERDICT_OUTCOME: NamedOutcome = {
342
+ name: "panel-verdict",
343
+ collector: noopCollector,
344
+ };
345
+
346
+ /**
347
+ * Tally the members' per-member `pred` results into the canonical verdict
348
+ * shape. `votes`/`agreement`/`tie` are fold-independent (they describe the
349
+ * split); only `pass` differs per sugar fold, supplied by `passWhen`.
350
+ */
351
+ function tally(
352
+ verdicts: readonly Output[],
353
+ pred: (v: Output) => boolean,
354
+ passWhen: (pass: number, fail: number) => boolean,
355
+ ): PanelVerdict {
356
+ const n = verdicts.length;
357
+ const pass = verdicts.reduce((c, v) => c + (pred(v) ? 1 : 0), 0);
358
+ const fail = n - pass;
359
+ return {
360
+ pass: passWhen(pass, fail),
361
+ votes: { pass, fail },
362
+ agreement: n === 0 ? 0 : Math.max(pass, fail) / n,
363
+ tie: pass === fail,
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Sugar fold — the panel passes iff a STRICT majority of members pass `pred`
369
+ * (an even split is a tie ⇒ fail, surfaced via `tie`/`agreement`). The
370
+ * per-member `pred` interprets each member's OWN verdict schema (no convention
371
+ * on members); the fold's output is the canonical {@link PANEL_VERDICT}. Branded
372
+ * canonical, so pairing it with an explicit `outcome` is a construction error.
373
+ */
374
+ export function majority(pred: (v: Output) => boolean): FoldFn {
375
+ return brandCanonicalFold("majority", (verdicts) => tally(verdicts, pred, (pass, fail) => pass > fail));
376
+ }
377
+
378
+ /** Sugar fold — unanimous: the panel passes iff EVERY member passes `pred` (one fail vetoes). */
379
+ export function all(pred: (v: Output) => boolean): FoldFn {
380
+ return brandCanonicalFold("all", (verdicts) => tally(verdicts, pred, (pass, fail) => pass > 0 && fail === 0));
381
+ }
382
+
383
+ /** Sugar fold — veto/rescue: the panel passes iff ANY member passes `pred` (one pass carries it). */
384
+ export function any(pred: (v: Output) => boolean): FoldFn {
385
+ return brandCanonicalFold("any", (verdicts) => tally(verdicts, pred, (pass) => pass > 0));
386
+ }
387
+
388
+ /**
389
+ * Single rule source for the panel shape — mirrors `judgeShapeIssues` /
390
+ * `verifyShapeIssues`. Returns human-readable violations (empty = valid);
391
+ * `panel()` throws on the first, `validateWorkflow` maps each to a load issue
392
+ * for hand-rolled literals. Takes `unknown` ON PURPOSE: typed call sites are
393
+ * already guarded by the `PanelJudge` type, so everything reaching here is an
394
+ * untyped jiti-loaded literal.
395
+ *
396
+ * Enforces: a non-empty `members` array, each member a VALID single judge with
397
+ * NO nesting (§9 — `members` is `Judge[]`), a function `fold`, and the §4 XOR
398
+ * (canonical sugar ⊕ `outcome` — exactly one names the verdict schema/channel).
399
+ */
400
+ export function panelShapeIssues(candidate: unknown): string[] {
401
+ if (!candidate || typeof candidate !== "object") return ["a panel object is required"];
402
+ const p = candidate as { members?: unknown; fold?: unknown; outcome?: { name?: unknown } };
403
+ const issues: string[] = [];
404
+
405
+ if (!Array.isArray(p.members) || p.members.length === 0) {
406
+ issues.push("panel.members must be a non-empty array of judges");
407
+ } else {
408
+ for (const m of p.members) {
409
+ if (m && typeof m === "object" && (m as PanelJudge).kind === "panel") {
410
+ issues.push("panel.members may not nest another panel — members are single judges (skill or prompt)");
411
+ continue;
412
+ }
413
+ for (const issue of judgeShapeIssues(m)) issues.push(`panel member: ${issue}`);
414
+ }
415
+ }
416
+
417
+ const foldIsFn = typeof p.fold === "function";
418
+ if (!foldIsFn) {
419
+ issues.push("panel.fold must be a function reducing the member verdicts to the panel's decision");
420
+ }
421
+
422
+ // The §4 XOR — a sugar fold OWNS the canonical verdict (no `outcome`); a raw
423
+ // fold REQUIRES an `outcome` to name + validate its channel. Never both.
424
+ const isSugar = foldIsFn && marksCanonicalFold(p.fold as FoldFn);
425
+ const hasOutcome = p.outcome !== undefined;
426
+ if (isSugar && hasOutcome) {
427
+ issues.push(
428
+ "a canonical fold (majority/all/any) publishes the built-in PANEL_VERDICT — drop `outcome` (sugar ⊕ outcome)",
429
+ );
430
+ }
431
+ if (foldIsFn && !isSugar && !hasOutcome) {
432
+ issues.push("a custom (raw) fold requires an `outcome` naming + validating its verdict channel (raw ⊕ outcome)");
433
+ }
434
+ if (hasOutcome && !p.outcome?.name) {
435
+ issues.push("panel.outcome must carry a `name` so the folded verdict publishes to its own named channel");
436
+ }
437
+
438
+ return issues;
439
+ }
440
+
441
+ /** Authoring input for {@link panel} — the `PanelJudge` minus the injected `kind` discriminator. */
442
+ export interface PanelSpec {
443
+ members: readonly Judge[];
444
+ fold: FoldFn;
445
+ outcome?: NamedOutcome;
446
+ }
447
+
448
+ /**
449
+ * Promote a panel literal to a validated `PanelJudge` — injects the
450
+ * `kind: "panel"` discriminator and throws on the first shape issue, so a
451
+ * `panel(...)`-authored value is correct by construction (cf. `judge()` /
452
+ * `defineRoute`). The judge SITES already accept it through the widened
453
+ * `AnyJudge` slot; their member dispatch + fold-close publish arrive in the
454
+ * execution phases, so `assess`/`verify` don't yet route a panel here.
455
+ */
456
+ export function panel(spec: PanelSpec): PanelJudge {
457
+ const candidate: PanelJudge = { kind: "panel", ...spec };
458
+ const issues = panelShapeIssues(candidate);
459
+ if (issues.length > 0) throw new Error(`panel(): ${issues[0]}`);
460
+ return candidate;
461
+ }
462
+
463
+ /**
464
+ * The channel a panel's FOLDED verdict publishes to — the author's
465
+ * `outcome.name` on the custom path, or the `<stage>-panel` convention on the
466
+ * canonical path (sugar fold, no `outcome`). ONE definition so the load gate
467
+ * (`validateWorkflow`) and the panel-close publish (later phases) can never
468
+ * drift on the name. Member verdicts publish to their OWN `outcome.name`
469
+ * channels; this is only the fold's slot.
470
+ */
471
+ export function panelVerdictChannel(p: PanelJudge, stageName: string): string {
472
+ return p.outcome?.name ?? `${stageName}-panel`;
473
+ }
474
+
475
+ /**
476
+ * Synthetic `produces` def the panel-close publish lands the FOLDED verdict
477
+ * under — the twin of `judgeStageDef` (which a single MEMBER runs on). The
478
+ * publish channel is resolved ONCE through {@link panelVerdictChannel} and baked
479
+ * into `outcome.name`, so the canonical path's per-stage `<stage>-panel` channel
480
+ * OVERRIDES `PANEL_VERDICT_OUTCOME`'s fallback name (distinct panel stages never
481
+ * collide) and the custom path keeps the author's own `outcome`. The folded
482
+ * Output carries no artifact, so `applyCompletedStage` leaves the rolling primary
483
+ * untouched and only appends to the named channel. ONE construction site —
484
+ * the live publish (`loop.ts`) and the resume fold (`runner/resume.ts`) share it,
485
+ * so the two paths can never drift on the def or the channel.
486
+ */
487
+ export function panelVerdictDef(p: PanelJudge, stageName: string): StageDef {
488
+ const base = p.outcome ?? PANEL_VERDICT_OUTCOME;
489
+ return { kind: "produces", outcome: { ...base, name: panelVerdictChannel(p, stageName) }, sessionPolicy: "fresh" };
490
+ }
491
+
492
+ /**
493
+ * THE loop-or-verify consult — the one derivation of "does this stage run
494
+ * through the loop driver, and with what spec." Consulted by `tryLoop`
495
+ * (live), the resume fold's generation open, and `resumeLoopStage`, so the
496
+ * three can never disagree about a verify stage's loop shape.
497
+ */
498
+ export function effectiveLoopOf(def: StageDef): LoopDef | undefined {
499
+ if (def.loop) return def.loop;
500
+ return def.verify ? synthesizeVerifyLoop(def.verify) : undefined;
501
+ }
502
+
503
+ /**
504
+ * THE judge-of-stage derivation — an assess loop's judge or the verify
505
+ * post-condition's, whichever the stage carries (they're mutually exclusive
506
+ * by load validation). Twin of `effectiveLoopOf` for the judge facet, so the
507
+ * validator's judge-dependent rules key off one expression.
508
+ */
509
+ export function judgeOf(stage: StageDef): Judge | undefined {
510
+ const slot = judgeSlotOf(stage);
511
+ // Panel widening (Phase 1): collapse the `AnyJudge` slot to its member-0
512
+ // view so the single-`Judge` consumers not yet panel-aware (introspection,
513
+ // contract-compat) keep their signature. For a single judge this is an
514
+ // identity; panel-aware sites use `judgeSlotOf` to see the whole panel.
515
+ return slot ? panelMembers(slot)[0] : undefined;
516
+ }
517
+
518
+ /**
519
+ * THE judge-SLOT-of-stage derivation — the RAW `AnyJudge` (a single `Judge` or
520
+ * an N-member `PanelJudge`) a stage carries, before any member collapse. Twin
521
+ * of `judgeOf`, which returns its member-0 view; panel-aware sites (the load
522
+ * gate's channel rules, `publishedNamesOf`) read the whole slot through this.
523
+ */
524
+ export function judgeSlotOf(stage: StageDef): AnyJudge | undefined {
525
+ return stage.loop?.kind === "assess" ? stage.loop.judge : stage.verify?.judge;
526
+ }
527
+
528
+ /** `max < 1` would cap at unit 0 and silently produce nothing — reject at construction. */
529
+ function checkedMax(ctor: string, max: number | undefined): number | undefined {
530
+ if (max === undefined) return undefined;
531
+ if (!Number.isInteger(max) || max < 1) {
532
+ throw new Error(`${ctor}(): max must be an integer >= 1 (got ${max})`);
533
+ }
534
+ return max;
535
+ }
536
+
537
+ // ===========================================================================
538
+ // Introspection — one channel for all loop kinds
539
+ // ===========================================================================
540
+
541
+ /**
542
+ * Pure-data projection of a LoopDef — what `describeFlow`, `preview`, and the
543
+ * `checkFanoutSource` lint consume. `judge` summarises the dispatch without
544
+ * exposing functions: `prompt: true` means a prompt judge (the text/closure
545
+ * itself stays opaque).
546
+ */
547
+ /** Pure-data judge summary — `prompt: true` means a prompt judge (the text/closure stays opaque). */
548
+ export interface JudgeSpec {
549
+ skill?: string;
550
+ prompt: boolean;
551
+ outcome: string;
552
+ }
553
+
554
+ /**
555
+ * Pure-data summary of an N-member panel — the introspection twin of
556
+ * `PanelJudge`. `panel` carries one `JudgeSpec` per member; `fold` is the sugar
557
+ * name (`majority`/`all`/`any`) for a canonical fold, `"custom"` for a raw
558
+ * author fold; `outcome` is the custom verdict channel, or `""` when the panel
559
+ * uses the canonical `<stage>-panel` default. Discriminated from `JudgeSpec` by
560
+ * the presence of `panel`.
561
+ */
562
+ export interface PanelJudgeSpec {
563
+ panel: JudgeSpec[];
564
+ fold: CanonicalFoldName | "custom";
565
+ outcome: string;
566
+ }
567
+
568
+ /** Pure-data summary of a judge SLOT — a single judge or a panel (the introspection twin of `AnyJudge`). */
569
+ export type AnyJudgeSpec = JudgeSpec | PanelJudgeSpec;
570
+
571
+ /**
572
+ * Project the introspectable facet off a Judge — shared by `loopSpecOf` and the
573
+ * `StageShape.verify` projection so the two can't drift. Defensive on `outcome`:
574
+ * `validateWorkflow`'s lints run this over UNVALIDATED configs (a malformed
575
+ * member can lack `outcome` entirely), so a projection must never throw.
576
+ */
577
+ export function judgeSpecOf(judge: Judge): JudgeSpec {
578
+ return { skill: judge.skill, prompt: judge.prompt !== undefined, outcome: judge.outcome?.name ?? "" };
579
+ }
580
+
581
+ /**
582
+ * Project the introspectable facet off a panel — member summaries + fold flavor
583
+ * + verdict channel. Defensive (like `judgeSpecOf`): a hand-rolled panel reaching
584
+ * a load-time lint may carry a non-array `members` or non-function `fold`.
585
+ */
586
+ export function panelSpecOf(p: PanelJudge): PanelJudgeSpec {
587
+ const members = Array.isArray(p.members) ? p.members : [];
588
+ return {
589
+ panel: members.map(judgeSpecOf),
590
+ fold: typeof p.fold === "function" ? (canonicalFoldName(p.fold) ?? "custom") : "custom",
591
+ outcome: p.outcome?.name ?? "",
592
+ };
593
+ }
594
+
595
+ /** Project the introspectable facet off a judge SLOT — a panel through `panelSpecOf`, a single judge through `judgeSpecOf`. */
596
+ export function judgeSlotSpecOf(slot: AnyJudge): AnyJudgeSpec {
597
+ return isPanel(slot) ? panelSpecOf(slot) : judgeSpecOf(slot);
598
+ }
599
+
600
+ export interface LoopSpec {
601
+ kind: LoopDef["kind"];
602
+ source?: string;
603
+ unit?: UnitSelector;
604
+ max?: number;
605
+ onCap: CapPolicy;
606
+ result: ResultProjection;
607
+ judge?: AnyJudgeSpec;
608
+ }
609
+
610
+ /** Project the introspectable facet off a stage's loop, or undefined for non-loop stages. */
611
+ export function loopSpecOf(loop: LoopDef | undefined): LoopSpec | undefined {
612
+ if (!loop) return undefined;
613
+ const base: LoopSpec = {
614
+ kind: loop.kind,
615
+ source: loop.source,
616
+ unit: loop.unit,
617
+ max: loop.max,
618
+ onCap: loop.onCap,
619
+ result: loop.result,
620
+ };
621
+ if (loop.kind === "assess") base.judge = judgeSlotSpecOf(loop.judge);
622
+ return base;
623
+ }