@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/load/merge.ts CHANGED
@@ -16,12 +16,12 @@
16
16
  import { existsSync, readdirSync } from "node:fs";
17
17
  import { join } from "node:path";
18
18
  import type { Workflow } from "../api.js";
19
+ import { formatError } from "../internal-utils.js";
19
20
  import type { ConfigLayer } from "../layers.js";
20
21
  import { cachedImport } from "./cache.js";
21
- import type { Issue } from "./index.js";
22
+ import type { Issue } from "./issues.js";
22
23
  import { type FileKind, normalizeDefaultExport, type ParsedConfig } from "./normalize.js";
23
24
  import type { OverlayPaths } from "./paths.js";
24
- import { formatError } from "./shape-guards.js";
25
25
 
26
26
  /**
27
27
  * Mutable bag of state threaded through `loadLayer` → `loadOverlayFile`
@@ -11,10 +11,9 @@
11
11
  * `default` that doesn't name an existing workflow records an error and
12
12
  * falls through to the next layer.
13
13
  *
14
- * Historic note: this used to fall back to a hard-coded `"mid"` sentinel,
15
- * which encoded an rpiv-pi-specific bias inside a skill-agnostic package.
16
- * Siblings that want to ship a preferred default set it via the
17
- * config-file envelope at their own load time.
14
+ * This package is skill-agnostic: there is no hard-coded default, so a
15
+ * `"mid"`-sentinel bias never leaks into it. Siblings that want to ship a
16
+ * preferred default set it via the config-file envelope at their own load time.
18
17
  */
19
18
 
20
19
  import type { ConfigLayer } from "../layers.js";
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Runtime shape guards + small formatting helpers used during default-export
3
3
  * normalisation. `isWorkflow` / `isEnvelope` narrow `unknown` default exports
4
- * to the structural shapes `normalizeDefaultExport` accepts; `describe` /
5
- * `formatError` synthesize human-readable strings for load-issue messages.
4
+ * to the structural shapes `normalizeDefaultExport` accepts; `describe`
5
+ * synthesizes human-readable strings for load-issue messages. (`formatError`
6
+ * lives in `../internal-utils.ts` — it's package-wide, not loader-specific.)
6
7
  */
7
8
 
8
9
  import type { Workflow } from "../api.js";
@@ -42,7 +43,3 @@ export function describe(v: unknown): string {
42
43
  if (Array.isArray(v)) return "an array";
43
44
  return typeof v;
44
45
  }
45
-
46
- export function formatError(e: unknown): string {
47
- return e instanceof Error ? e.message : String(e);
48
- }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The loader's skill-contract phase — everything between "workflows are
3
+ * merged + aliased" and "validation runs": flush the lazy contract
4
+ * providers, surface their recorded failures and cross-owner collisions,
5
+ * build the effective registry (declared ⊕ harvested), and invoke the
6
+ * registered outcome derivers against per-load stage copies.
7
+ *
8
+ * Extracted from `loadWorkflows` so the orchestrator reads as a
9
+ * sequence of phases. Every issue this phase emits is attributed to
10
+ * `"framework"` — these are failures of provider/deriver machinery, not of
11
+ * any config file.
12
+ */
13
+
14
+ import { formatError } from "../internal-utils.js";
15
+ import type { SkillContractMap } from "../skill-contract.js";
16
+ import {
17
+ buildEffectiveContracts,
18
+ drainSkillContractCollisions,
19
+ drainSkillContractProviderErrors,
20
+ flushSkillContractProviders,
21
+ getBucketKindMappings,
22
+ getOutcomeDerivers,
23
+ } from "../skill-contracts/index.js";
24
+ import type { LoadAccumulator } from "./merge.js";
25
+
26
+ /**
27
+ * Run the phase against the merged accumulator. Mutates `acc` (issues +
28
+ * per-load stage copies when derivers will run) and returns the effective
29
+ * contract registry the validation loop and the runner consume.
30
+ *
31
+ * Must run BEFORE the validation loop: `checkEdgeSchemaCompat` needs the
32
+ * registry, and derivers must have wired `outcome`s before the
33
+ * produces-without-outcome rule fires.
34
+ */
35
+ export async function applySkillContractPhase(acc: LoadAccumulator): Promise<SkillContractMap> {
36
+ // Flush lazy contract providers before reading the registry. Each provider
37
+ // throw was RECORDED (not propagated) — drain and surface as issues so the
38
+ // loader keeps its never-throws contract without swallowing the failure.
39
+ await flushSkillContractProviders();
40
+ for (const err of drainSkillContractProviderErrors()) {
41
+ acc.issues.push({
42
+ kind: "load",
43
+ layer: "framework",
44
+ message: `skill-contract provider failed: ${formatError(err)}`,
45
+ severity: "warning",
46
+ });
47
+ }
48
+ // Cross-owner contract collisions — last-writer still wins, but the
49
+ // divergence is no longer silent.
50
+ for (const message of drainSkillContractCollisions()) {
51
+ acc.issues.push({ kind: "load", layer: "framework", message, severity: "warning" });
52
+ }
53
+
54
+ // Effective registry: a NEW map (harvested gap-fill first, declared
55
+ // overriding per skill) — never mutates the shared global registry.
56
+ const skillContracts = buildEffectiveContracts([...acc.workflowMap.values()]);
57
+
58
+ // Deriver mutations (`stage.outcome = ...`) must land on PER-LOAD copies,
59
+ // never on shared sources: built-ins live in a process-global registry and
60
+ // unchanged overlay files come back BY REFERENCE from the mtime cache, so an
61
+ // in-place mutation would pin this load's derived outcome onto every future
62
+ // load — the deriver's `if (stage.outcome) continue` idempotency guard would
63
+ // then skip re-derivation even after a contract change. Shallow-copy each
64
+ // workflow's stage records first (same `{...stage}` copy `aliasSkills` uses).
65
+ if (getOutcomeDerivers().length > 0) {
66
+ for (const [name, w] of acc.workflowMap) {
67
+ acc.workflowMap.set(name, {
68
+ ...w,
69
+ stages: Object.fromEntries(Object.entries(w.stages).map(([k, s]) => [k, { ...s }])),
70
+ });
71
+ }
72
+ }
73
+ for (const deriver of getOutcomeDerivers()) {
74
+ try {
75
+ deriver(
76
+ acc.workflowMap.values(),
77
+ skillContracts,
78
+ (message, severity) => {
79
+ acc.issues.push({ kind: "load", layer: "framework", severity, message });
80
+ },
81
+ getBucketKindMappings(),
82
+ );
83
+ } catch (err) {
84
+ acc.issues.push({
85
+ kind: "load",
86
+ layer: "framework",
87
+ severity: "error",
88
+ message: `outcome deriver failed: ${formatError(err)}`,
89
+ });
90
+ }
91
+ }
92
+
93
+ return skillContracts;
94
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Loop constructors + introspection — split into the `loops/` modules behind
3
+ * this preserving re-export barrel. The monolith that lived here was
4
+ * decomposed into five disjoint facets:
5
+ * - `loops/constructors.ts` — `fanout()` / `iterate()` / `assess()` + the
6
+ * `LOOP_DEFAULTS` / `VERIFY_LOOP_DEFAULTS` identity tables they consult;
7
+ * - `loops/verify.ts` — `verify()` + the `synthesizeVerifyLoop` desugar;
8
+ * - `loops/panel.ts` — `panel()` + the canonical fold vocabulary;
9
+ * - `loops/introspection.ts` — `describeFlow()` + the `loopSpecOf` projections;
10
+ * - `loops/derivations.ts` — `effectiveLoopOf` / `freezesEntryArgsOf` /
11
+ * `judgeSlotOf` / `forEachJudgeChannel` (the per-stage consults).
12
+ *
13
+ * This file keeps the original import path (`./loop-constructors.js`) so the
14
+ * existing consumers (9 production + 8 test importers, plus `registration.ts`)
15
+ * resolve unchanged — a pure re-export surface, no logic. Skill-agnostic and
16
+ * runner-free — safe on `registration`.
17
+ */
18
+
19
+ export type { UnitSelector } from "./api.js";
20
+ export * from "./loops/constructors.js";
21
+ export * from "./loops/derivations.js";
22
+ export * from "./loops/introspection.js";
23
+ export * from "./loops/panel.js";
24
+ export * from "./loops/verify.js";
package/loop-def.ts ADDED
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Loop vocabulary — the data shapes behind `StageDef.loop` and
3
+ * `StageDef.verify`, AS TYPES. Constructors live in loop-constructors.ts
4
+ * (`fanout()` / `iterate()` / `assess()` / `verify()`); the per-kind runtime
5
+ * strategy table lives in loop-kinds.ts. Split out of api.ts so the
6
+ * loop concept has one home instead of accreting into the stage module.
7
+ *
8
+ * Leaf-ish: imports only types from judge/output/handle.
9
+ */
10
+
11
+ import type { Artifact } from "./handle.js";
12
+ import type { AnyJudge } from "./judge.js";
13
+ import type { Output, RunView } from "./output.js";
14
+
15
+ /**
16
+ * One unit of loop work — the single unit type for all three loop kinds.
17
+ * `prompt` is the body sent to the skill; `label` is the human display tag
18
+ * woven into the status line, the per-unit toast, and the decorated row
19
+ * display; `id` is the stable audit identity written to the row's `unitId`
20
+ * field (falls back to `label`). Post-hoc tooling and the resume drift guard
21
+ * join on `id ?? label` — set `id` when `label` may be reworded.
22
+ */
23
+ export interface Unit {
24
+ prompt: string;
25
+ label: string;
26
+ id?: string;
27
+ /**
28
+ * Fanout only — the `id ?? label` identities of the units this unit depends
29
+ * on. The wave scheduler topologically orders dispatch over these directed
30
+ * edges: a unit dispatches only after every unit it lists here has completed
31
+ * (its slot filled). Absent/empty ⇒ a root (wave 0). A reference that matches
32
+ * no unit's `id ?? label`, or any cycle, halts the stage at the live entry
33
+ * (`validateUnitDeps`). Ignored by the sequential kinds (iterate/assess
34
+ * consume the prior unit, so ordering is implicit).
35
+ */
36
+ deps?: readonly string[];
37
+ }
38
+
39
+ /**
40
+ * Push-model unit source: all units computed up front, each run blind to the
41
+ * others. Empty return ⇒ no loop (fall through to the single-stage path).
42
+ * Throws ⇒ stage halts, attributed to this stage (a thrown
43
+ * `StagePreflightError` keeps its own attribution — the `haltPreflight`
44
+ * consumer contract).
45
+ */
46
+ export type FanoutFn = (ctx: FanoutContext) => readonly Unit[] | Promise<readonly Unit[]>;
47
+
48
+ export interface FanoutContext {
49
+ cwd: string;
50
+ /** Primary artifact inherited from upstream (undefined when the loop stage is the entry point). */
51
+ artifact: Artifact | undefined;
52
+ state: RunView;
53
+ }
54
+
55
+ /**
56
+ * Pull-model unit source: invoked once per unit, each call receiving the
57
+ * validated `Output`s of every prior unit in this generation. Return the next
58
+ * unit, or `null`/`undefined` to terminate the loop.
59
+ *
60
+ * RESUME CONTRACT (all loop kinds): the unit source must be deterministic
61
+ * w.r.t. the fold-replayed `RunState` at the unit boundary + this
62
+ * generation's accumulated outputs. The resume fold re-calls it at every
63
+ * folded boundary and refuses on drift.
64
+ */
65
+ export type IterateFn = (ctx: IterateContext) => Unit | null | Promise<Unit | null>;
66
+
67
+ export interface IterateContext {
68
+ cwd: string;
69
+ /** Stage-entry primary, FROZEN across every unit (never rolls forward). */
70
+ artifact: Artifact | undefined;
71
+ state: RunView;
72
+ /** Validated Outputs of this generation's completed units, in order. */
73
+ accumulated: readonly Output[];
74
+ /** 0-based index of the unit about to run (== accumulated.length). */
75
+ index: number;
76
+ }
77
+
78
+ /** Context handed to `AssessLoop.feedForward` and `VerifySpec.feedForward`. */
79
+ export interface FeedForwardContext {
80
+ cwd: string;
81
+ /** Producer output just judged. */
82
+ output: Output;
83
+ /** Judge verdict (incl. feedback). */
84
+ verdict: Output;
85
+ /** 0-based round index of the round just judged (== the attempt index for verify). */
86
+ round: number;
87
+ state: RunView;
88
+ }
89
+
90
+ /**
91
+ * The shared "repeat under a model judge" vocabulary — ONE set of field names
92
+ * for the two judged-repetition shapes (`AssessLoop` rounds, `VerifySpec`
93
+ * attempts). The runtime already admits they're one concept (verify desugars
94
+ * to a degenerate assess loop); this base keeps their vocabularies from
95
+ * drifting again (`pass`/`done`, `maxAttempts`/`max` were two spellings of
96
+ * the same two knobs).
97
+ */
98
+ export interface JudgedRepetition {
99
+ /**
100
+ * The judge SLOT — a single `Judge` or an N-member `PanelJudge` (a single
101
+ * judge is the panel of one). Widened to `AnyJudge` so `assess`/`verify`
102
+ * compose a panel with zero per-site code; the runtime expands it through
103
+ * `panelMembers` at the one judge-dispatch site.
104
+ */
105
+ judge: AnyJudge;
106
+ /**
107
+ * Sync TS reading the model-made verdict. `true` → the repetition stops
108
+ * and the chain advances with the last producer pair. RESUME CONTRACT:
109
+ * recomputed on resume (never persisted) — must be deterministic w.r.t.
110
+ * the verdict `Output`. A `true` on the final round/attempt is a normal
111
+ * completion (the predicate wins over the cap).
112
+ */
113
+ done: (verdict: Output) => boolean;
114
+ /**
115
+ * Builds the next round/attempt's prompt arg from the just-judged
116
+ * producer output + verdict. On a prompt-dispatch stage the returned
117
+ * string is the COMPLETE retry message (sent raw — there is no skill to
118
+ * prefix an arg onto).
119
+ */
120
+ feedForward?: (ctx: FeedForwardContext) => string;
121
+ /** Repetition cap. Integer >= 1; clamped by `run.maxIterations` at runtime. */
122
+ max?: number;
123
+ }
124
+
125
+ /**
126
+ * Per-stage post-condition judge — the data shape behind `StageDef.verify`.
127
+ * After each attempt of the stage completes (collected, validated, persisted),
128
+ * the judge session grades the attempt's primary artifact; `done(verdict)`
129
+ * true → verified, the chain advances with the attempt's producer pair;
130
+ * false → a fresh retry attempt (prompt arg built by `feedForward`) up to
131
+ * `max` attempts, then a terminal "verification failed" halt. Author via the
132
+ * `verify()` constructor (loop-constructors.ts), which validates at construction;
133
+ * load-time validation re-checks hand-rolled literals through the same
134
+ * `verifyShapeIssues` rule source.
135
+ *
136
+ * Field semantics on top of the shared `JudgedRepetition` vocabulary:
137
+ * - `done` — the pass predicate (`true` = verified).
138
+ * - `max` — total attempt budget; each attempt is a FRESH session running
139
+ * the full produce→validate→persist cycle. Orthogonal to
140
+ * `stage.maxRetries` (the cheap in-session schema-fix budget, which stays
141
+ * live inside every attempt). Default 1 (gate-only).
142
+ * - `feedForward` — REQUIRED when `max > 1` (without it the retried prompt
143
+ * would be byte-identical to the original and the model would have no
144
+ * signal about why it failed); never called when `max` is 1.
145
+ *
146
+ * Runtime: the runner desugars the field into a degenerate assess loop run by
147
+ * the ONE loop driver. The desugar's gate-only defaults (`max`, `onCap`,
148
+ * `result`) are spelled ONCE in `VERIFY_LOOP_DEFAULTS` (loop-constructors.ts) —
149
+ * the named peer to `LOOP_DEFAULTS` (verify is not a `LoopDef["kind"]`) —
150
+ * and consulted by `synthesizeVerifyLoop`. Attempts and verdicts land as unit
151
+ * rows (`role: "produce"` / `role: "verify"`, `unitIndex` = 0-based attempt);
152
+ * the verdict publishes durably to `state.named[judge.outcome.name]` (so
153
+ * declarative fallback routing over `EdgeContext.state.named` works); and
154
+ * `projectResult` restores the last attempt's producer pair before the chain
155
+ * advances — downstream stages never inherit the verdict.
156
+ */
157
+ export type VerifySpec = JudgedRepetition;
158
+
159
+ /**
160
+ * Role a unit row/event carries. Every main-work unit — fanout unit, iterate
161
+ * unit, assess producer, verify attempt — is `"produce"`; assess judge
162
+ * sub-steps are `"judge"`; verify verdict sub-steps are `"verify"`. The
163
+ * `result: "last"` projection and the resume fold's apply rule key on this.
164
+ */
165
+ export type UnitRole = "produce" | "judge" | "verify";
166
+
167
+ /**
168
+ * What happens when a loop hits its effective cap (`min(max, run.maxIterations)`):
169
+ * `"halt"` — terminal failure (mirrors the backward-jump guard);
170
+ * `"advance"` — soft-stop: warn, land a `{type:"loop-cap"}` telemetry row,
171
+ * fire `onLoopCap`, keep the projected result, advance downstream.
172
+ */
173
+ export type CapPolicy = "halt" | "advance";
174
+
175
+ /**
176
+ * What the loop leaves in `{state.output, state.primaryArtifact}` — the PAIR
177
+ * is governed as one (routing + downstream prompts read both):
178
+ * `"entry"` — restore the pair captured at loop entry;
179
+ * `"last"` — the last completed `role: "produce"` unit's pair (zero produce
180
+ * units degrades to entry).
181
+ * The per-kind default (`entry` for fanout, `last` for iterate/assess) is
182
+ * spelled ONCE in `LOOP_DEFAULTS` (loop-constructors.ts) and consulted by each
183
+ * constructor via `firstDefined` — see that table rather than re-stating the
184
+ * per-kind literal here. Applied at ONE point — loop advance — by the live
185
+ * driver and the resume fold's generation close identically. Mid-loop
186
+ * transient rolls are accepted.
187
+ */
188
+ export type ResultProjection = "entry" | "last";
189
+
190
+ /**
191
+ * How a stage's work is split into units, AS DATA. The framework never
192
+ * interprets `by`/`pattern` — they're introspection hints for agents and the
193
+ * `checkFanoutSource` lint.
194
+ */
195
+ export interface UnitSelector {
196
+ by: string;
197
+ pattern?: string;
198
+ meta?: Record<string, unknown>;
199
+ }
200
+
201
+ /** Introspectable data common to all three loop kinds. */
202
+ interface LoopCommon {
203
+ /** The named channel the units are split FROM (a `consumes` signal). */
204
+ source?: string;
205
+ /** How units are detected (opaque convention). */
206
+ unit?: UnitSelector;
207
+ /** Cardinality ceiling; clamped by `run.maxIterations` at runtime. */
208
+ max?: number;
209
+ onCap: CapPolicy;
210
+ result: ResultProjection;
211
+ }
212
+
213
+ /** Parallel-shaped push loop — units run in bounded parallel (maxConcurrency). */
214
+ export interface FanoutLoop extends LoopCommon {
215
+ kind: "fanout";
216
+ units: FanoutFn;
217
+ /** Per-fanout concurrency ceiling. Caps in-flight units to
218
+ * `min(concurrency, host maxConcurrency)`; `1` SERIALIZES the loop — the safe
219
+ * model for a stage that mutates SHARED state (e.g. `implement` applying a plan
220
+ * to one working tree, where parallel phases race on a shared file and a
221
+ * dependent phase can run before its prerequisite has landed). Absent ⇒ the host
222
+ * cap governs. Must be an integer ≥ 1 (validated at construction + load). */
223
+ concurrency?: number;
224
+ /** Opt out of collect-all: any unit failure halts the run. Default (absent) ⇒
225
+ * collect-all. Under parallel dispatch, the first failing unit halts the
226
+ * run terminally AND cancels in-flight siblings via the per-generation
227
+ * `genAbort` controller: the worker that records the terminal failure fires
228
+ * `genAbort.abort()`, which `session.abort()`s every still-running sibling and
229
+ * drains queued units from the semaphore. Cancelled siblings leave unfilled
230
+ * slots (no row written), so a terminally-failed run that is later resumed
231
+ * re-dispatches them. `genAbort` is also driven by run-level abort (Ctrl-C /
232
+ * `run.signal`), so the same machinery serves both. */
233
+ failFast?: boolean;
234
+ /**
235
+ * When set, the dispatcher injects each completed dependency's published
236
+ * artifact path into the dependent unit's prompt as `${depArtifactFlag} <path>`
237
+ * (one per direct `Unit.deps` entry whose slot is filled with a non-failed
238
+ * output). Pairs with `Unit.deps`: deps order the waves, this flag hands the
239
+ * dependent the upstream artifact to read (build `design` sets `"--upstream"`
240
+ * so a dependent slice reads its dependency's decided Key Interfaces). A
241
+ * failed/sentinel dep slot is skipped — the dependent designs blind for that
242
+ * dep, exactly as today. Engine-generic: the flag string is data; the engine
243
+ * knows nothing of the consuming skill. Validated non-empty at construction +
244
+ * load.
245
+ */
246
+ depArtifactFlag?: string;
247
+ }
248
+
249
+ /** Sequential accumulating pull loop. */
250
+ export interface IterateLoop extends LoopCommon {
251
+ kind: "iterate";
252
+ next: IterateFn;
253
+ }
254
+
255
+ /**
256
+ * Model-judged until-done loop: producer→judge rounds. Shares the
257
+ * `JudgedRepetition` vocabulary with `VerifySpec`; here `max` (the round cap)
258
+ * and `feedForward` are REQUIRED — the `assess()` constructor defaults `max`
259
+ * to 8 and rejects a missing `feedForward`.
260
+ */
261
+ export interface AssessLoop extends LoopCommon, JudgedRepetition {
262
+ kind: "assess";
263
+ /** Round cap — REQUIRED here (the `assess()` constructor defaults it to 8). */
264
+ max: number;
265
+ /** Builds the next producer prompt arg from the just-judged round's pair. */
266
+ feedForward: (ctx: FeedForwardContext) => string;
267
+ }
268
+
269
+ /**
270
+ * The single loop field's value — a DATA object with function-valued fields,
271
+ * introspectable by construction (project with `loopSpecOf`). Author via the
272
+ * `fanout()` / `iterate()` / `assess()` constructors (loop-constructors.ts), which
273
+ * validate at construction and fill kind-specific defaults.
274
+ */
275
+ export type LoopDef = FanoutLoop | IterateLoop | AssessLoop;
276
+
277
+ /**
278
+ * Runtime enumeration of `LoopDef["kind"]` — exported from where `LoopDef`
279
+ * lives so the validator (kind whitelist) and the per-kind strategy table
280
+ * (loop-kinds.ts) consume one list. The `satisfies` pin rejects a stray
281
+ * member; completeness is enforced by the strategy table's
282
+ * `Record<LoopDef["kind"], …>` shape (a new union arm fails compilation
283
+ * there first).
284
+ */
285
+ export const LOOP_KINDS = ["fanout", "iterate", "assess"] as const satisfies readonly LoopDef["kind"][];