@juicesharp/rpiv-workflow 1.20.0 → 2.1.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 (111) hide show
  1. package/README.md +98 -545
  2. package/api.ts +1 -1
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +18 -0
  5. package/audit.ts +119 -164
  6. package/built-ins.ts +26 -6
  7. package/chain-state.ts +119 -68
  8. package/command-run.ts +35 -30
  9. package/command.ts +10 -4
  10. package/docs/embedding.md +341 -0
  11. package/docs/workflow-authoring.md +70 -16
  12. package/docs/workflow-basics.md +125 -10
  13. package/events.ts +44 -4
  14. package/execution-host.ts +75 -0
  15. package/host.ts +137 -82
  16. package/internal-utils.ts +89 -3
  17. package/internal.ts +1 -0
  18. package/judge.ts +23 -11
  19. package/load/alias.ts +3 -3
  20. package/load/index.ts +15 -1
  21. package/load/issues.ts +2 -2
  22. package/load/legacy.ts +2 -2
  23. package/load/resolve-default.ts +3 -4
  24. package/load/skill-contract-phase.ts +1 -1
  25. package/loop-constructors.ts +19 -618
  26. package/loop-def.ts +60 -15
  27. package/loop-kinds.ts +319 -62
  28. package/loop-parallel.ts +250 -0
  29. package/loop-waves.ts +99 -0
  30. package/loop.ts +106 -80
  31. package/loops/constructors.ts +334 -0
  32. package/loops/derivations.ts +65 -0
  33. package/loops/introspection.ts +184 -0
  34. package/loops/panel.ts +196 -0
  35. package/loops/verify.ts +99 -0
  36. package/messages.ts +58 -33
  37. package/outcomes/collectors/index.ts +1 -0
  38. package/outcomes/collectors/text-scan.ts +47 -0
  39. package/outcomes/collectors/transcript-path.ts +2 -15
  40. package/outcomes/collectors/union.ts +2 -1
  41. package/outcomes/collectors/url.ts +2 -14
  42. package/outcomes/collectors/workspace-diff.ts +1 -1
  43. package/outcomes/git-commit.ts +57 -6
  44. package/output-spec.ts +1 -1
  45. package/output.ts +59 -1
  46. package/package.json +19 -6
  47. package/preview.ts +18 -18
  48. package/registration.ts +11 -4
  49. package/routing-dsl.ts +53 -41
  50. package/routing.ts +46 -0
  51. package/runner/chain-advance.ts +30 -17
  52. package/runner/errors.ts +7 -30
  53. package/runner/failure.ts +67 -13
  54. package/runner/input-validation.ts +8 -5
  55. package/runner/preflight.ts +17 -21
  56. package/runner/resume-entry.ts +23 -3
  57. package/runner/resume-loop.ts +50 -29
  58. package/runner/resume.ts +96 -10
  59. package/runner/run-context.ts +20 -16
  60. package/runner/run-stage.ts +125 -91
  61. package/runner/runner.ts +163 -69
  62. package/runner/script-stage.ts +23 -29
  63. package/schema-compat.ts +1 -2
  64. package/semaphore.ts +55 -0
  65. package/sessions/extraction.ts +103 -60
  66. package/sessions/halt-routing.ts +195 -0
  67. package/sessions/index.ts +2 -2
  68. package/sessions/locate.ts +60 -9
  69. package/sessions/reattach.ts +28 -20
  70. package/sessions/sessions.ts +103 -191
  71. package/sessions/spawn.ts +132 -119
  72. package/sessions/success-persist.ts +89 -0
  73. package/skill-contracts/composition.ts +8 -10
  74. package/skill-contracts/harvest.ts +3 -2
  75. package/skill-contracts/registry.ts +1 -1
  76. package/stage-def.ts +115 -47
  77. package/stage-errors.ts +84 -0
  78. package/stage-identity.ts +56 -0
  79. package/startup.ts +1 -0
  80. package/state/paths.ts +11 -3
  81. package/state/raw.ts +2 -3
  82. package/state/resolve.ts +3 -3
  83. package/state/state.ts +26 -3
  84. package/state/writes.ts +1 -1
  85. package/types.ts +97 -43
  86. package/validate/contract-compat.ts +16 -11
  87. package/validate/graph.ts +10 -1
  88. package/validate/issue.ts +20 -6
  89. package/validate/stage-rules.ts +139 -60
  90. package/validate-output.ts +27 -20
  91. package/validate-workflow.ts +5 -3
  92. package/validation-bounds.ts +35 -0
  93. package/docs/cover.png +0 -0
  94. package/docs/cover.svg +0 -120
  95. package/load/cache.test.ts +0 -82
  96. package/load/shape-guards.test.ts +0 -77
  97. package/outcomes/collectors/directory-path.test.ts +0 -64
  98. package/outcomes/collectors/tool-call.test.ts +0 -112
  99. package/outcomes/collectors/transcript-path.test.ts +0 -70
  100. package/outcomes/collectors/union.test.ts +0 -113
  101. package/outcomes/collectors/url.test.ts +0 -67
  102. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  103. package/outcomes/git-commit.test.ts +0 -240
  104. package/outcomes/parsers/json-body.test.ts +0 -80
  105. package/runner/by-name.test.ts +0 -95
  106. package/runner/by-run-id.test.ts +0 -115
  107. package/runner/header-write-failure.test.ts +0 -64
  108. package/runner/resume-loop.test.ts +0 -1410
  109. package/runner/resume-session.test.ts +0 -400
  110. package/runner/resume.test.ts +0 -1805
  111. package/sessions/locate.test.ts +0 -77
@@ -32,15 +32,27 @@ import { execFileAsync, GIT_EXEC_TIMEOUT_MS } from "./exec.js";
32
32
 
33
33
  /**
34
34
  * Output data shape produced by `gitCommitParser` — co-located with the
35
- * outcome that emits it, as is the `GitCommitOutput` narrowing alias below
36
- * (G6: the core envelope module never enumerates a concrete outcome).
35
+ * outcome that emits it, as is the `GitCommitOutput` narrowing alias below.
37
36
  */
37
+ /** One commit the stage produced, journaled so earlier-phase commits stay visible. */
38
+ export interface GitCommitRecord {
39
+ sha: string;
40
+ subject: string;
41
+ }
42
+
38
43
  export interface GitCommitData {
39
44
  sha: string;
40
45
  prevSha: string;
41
46
  subject: string;
42
47
  filesChanged: number;
43
48
  noOp?: boolean;
49
+ /**
50
+ * EVERY commit in `prevSha..sha`, oldest-first — not just the head. A stage
51
+ * that lands several commits (an incremental implement pass) journaled only
52
+ * the head sha + an aggregate file count, leaving the earlier commits
53
+ * invisible in the trail; this preserves each one. Absent on a no-op.
54
+ */
55
+ commits?: readonly GitCommitRecord[];
44
56
  }
45
57
 
46
58
  /** Tagged-union narrowing alias: `output.kind === "git-commit"` ⇒ `data: GitCommitData`. */
@@ -65,6 +77,12 @@ export interface GitCommitArtifactMeta {
65
77
  noOp: boolean;
66
78
  subject: string;
67
79
  filesChanged: number;
80
+ /**
81
+ * Every commit in `baselineSha..headSha`, oldest-first, interrogated at
82
+ * collect time while the SHAs still resolve. Optional so a pre-existing
83
+ * (pre-`commits`) meta still passes `isGitCommitMeta`; empty/absent on a no-op.
84
+ */
85
+ commits?: readonly GitCommitRecord[];
68
86
  }
69
87
 
70
88
  /** Run a git command from `cwd`, returning trimmed stdout. */
@@ -125,11 +143,12 @@ export const gitCommitCollector: ArtifactCollector<GitHeadSnapshot | undefined>
125
143
  return ok(noOpMeta(baselineSha, headSha));
126
144
  }
127
145
  try {
128
- const [subject, filesChanged] = await Promise.all([
146
+ const [subject, filesChanged, commits] = await Promise.all([
129
147
  git(ctx.cwd, "log", "-1", "--format=%s", headSha),
130
148
  countFilesChanged(ctx.cwd, baselineSha, headSha),
149
+ listCommits(ctx.cwd, baselineSha, headSha),
131
150
  ]);
132
- return ok({ baselineSha, headSha, baselineMissing: false, noOp: false, subject, filesChanged });
151
+ return ok({ baselineSha, headSha, baselineMissing: false, noOp: false, subject, filesChanged, commits });
133
152
  } catch (e) {
134
153
  // A commit LANDED but its interrogation failed — fabricating noOp
135
154
  // would route `gate` on invented data; halt with the real cause.
@@ -170,6 +189,21 @@ async function countFilesChanged(cwd: string, baselineSha: string, headSha: stri
170
189
  return match ? parseInt(match[1]!, 10) : 0;
171
190
  }
172
191
 
192
+ /**
193
+ * Enumerate every commit in `baselineSha..headSha`, oldest-first — the full
194
+ * list a multi-commit stage produced, so the trail reflects each commit and not
195
+ * just the head. `%x1f` (unit separator) delimits sha↔subject so a subject
196
+ * containing spaces or tabs never mis-splits.
197
+ */
198
+ async function listCommits(cwd: string, baselineSha: string, headSha: string): Promise<GitCommitRecord[]> {
199
+ const raw = await git(cwd, "log", "--reverse", "--format=%H%x1f%s", `${baselineSha}..${headSha}`);
200
+ if (!raw) return [];
201
+ return raw.split("\n").flatMap((line) => {
202
+ const [sha, subject] = line.split("\x1f");
203
+ return sha ? [{ sha, subject: subject ?? "" }] : [];
204
+ });
205
+ }
206
+
173
207
  // ---------------------------------------------------------------------------
174
208
  // Parser — PURE projection of the collected meta into typed GitCommitData
175
209
  // ---------------------------------------------------------------------------
@@ -183,10 +217,19 @@ function isGitCommitMeta(meta: unknown): meta is GitCommitArtifactMeta {
183
217
  typeof m.baselineMissing === "boolean" &&
184
218
  typeof m.noOp === "boolean" &&
185
219
  typeof m.subject === "string" &&
186
- typeof m.filesChanged === "number"
220
+ typeof m.filesChanged === "number" &&
221
+ // Optional (back-compat): a pre-`commits` meta omits it; when present it
222
+ // must be a well-formed record list.
223
+ (m.commits === undefined || (Array.isArray(m.commits) && m.commits.every(isGitCommitRecord)))
187
224
  );
188
225
  }
189
226
 
227
+ /** Structural guard for one journaled commit record. */
228
+ function isGitCommitRecord(r: unknown): r is GitCommitRecord {
229
+ const c = r as Partial<GitCommitRecord> | undefined;
230
+ return typeof c?.sha === "string" && typeof c.subject === "string";
231
+ }
232
+
190
233
  /**
191
234
  * Pure: validates the artifact's `meta` shape (fatal on mismatch — a blind
192
235
  * cast here would coerce a foreign collector's artifact into fabricated
@@ -208,7 +251,15 @@ export const gitCommitParser: ArtifactParser<GitHeadSnapshot | undefined, "git-c
208
251
  }
209
252
  const data: GitCommitData = meta.noOp
210
253
  ? { sha: meta.headSha, prevSha: meta.baselineSha, subject: "", filesChanged: 0, noOp: true }
211
- : { sha: meta.headSha, prevSha: meta.baselineSha, subject: meta.subject, filesChanged: meta.filesChanged };
254
+ : {
255
+ sha: meta.headSha,
256
+ prevSha: meta.baselineSha,
257
+ subject: meta.subject,
258
+ filesChanged: meta.filesChanged,
259
+ // Project the per-commit journal through only when the collector
260
+ // recorded it — a pre-`commits` meta stays byte-identical.
261
+ ...(meta.commits ? { commits: meta.commits } : {}),
262
+ };
212
263
  return { kind: "ok", payload: { kind: "git-commit", data } };
213
264
  },
214
265
  };
package/output-spec.ts CHANGED
@@ -64,7 +64,7 @@ export interface CollectCtx<Snapshot = unknown> extends SnapshotCtx {
64
64
  * `kind: "fatal"` — collector cannot satisfy its contract;
65
65
  * runner halts with the carried message.
66
66
  *
67
- * THE "NOTHING FOUND" CONVENTION (T10) — what a collector returns when it
67
+ * THE "NOTHING FOUND" CONVENTION — what a collector returns when it
68
68
  * comes up empty depends on WHY it's empty, and the two must never be
69
69
  * conflated:
70
70
  *
package/output.ts CHANGED
@@ -51,7 +51,7 @@ export interface Output<K extends string = string, D = unknown> {
51
51
  // Tagged-union narrowing convenience for consumers. Only the two
52
52
  // framework-native kinds live here; outcome-specific aliases live with
53
53
  // their producing outcome (`GitCommitOutput` → outcomes/git-commit.ts) so
54
- // the core envelope module never enumerates concrete plugins (G6).
54
+ // the core envelope module never enumerates concrete plugins.
55
55
  // ---------------------------------------------------------------------------
56
56
 
57
57
  export type ArtifactsOutput = Output<"artifacts", readonly Artifact[]>;
@@ -116,3 +116,61 @@ export function finalizeOutput<K extends string, D>(
116
116
  meta,
117
117
  };
118
118
  }
119
+
120
+ /**
121
+ * The single construction home for an `OutputMeta` literal. The five former
122
+ * assembly sites (`sessions/extraction.ts:wrapOutput`, `sessions/sessions.ts:
123
+ * outputMetaFor`, `loop-parallel.ts:unitOutputMeta`, the `runner/script-stage.ts`
124
+ * produce hook, and the `runner/resume.ts` soft-halt sentinel) all route through
125
+ * this — so a structural divergence between the live path's minted meta and the
126
+ * resume fold's rebuilt sentinel is unrepresentable (modeled on the `audit.ts`
127
+ * `terminalArgsOf` flat-pairing authority).
128
+ *
129
+ * `ts` is a PARAMETER, not an injected `nowIso()`: live call sites pass
130
+ * `nowIso()`; the resume fold replays the persisted `row.ts`. That is what lets
131
+ * the two paths share one constructor — resume stays byte-identical to the row
132
+ * the live path wrote.
133
+ *
134
+ * `skill` is conditionally spread (not defaulted) so a call site that omits it
135
+ * (script-stage rows, and any resume row whose `skill` is absent) produces an
136
+ * object with NO `skill` key — preserving the script-row "no skill field"
137
+ * contract (`JSON.stringify` drops `undefined`, so this must stay a key
138
+ * omission, not `{ skill: undefined }`).
139
+ */
140
+ export function outputMeta(args: {
141
+ stage: string;
142
+ skill?: string;
143
+ stageNumber: number;
144
+ ts: string;
145
+ runId: string;
146
+ }): OutputMeta {
147
+ return {
148
+ stage: args.stage,
149
+ ...(args.skill !== undefined ? { skill: args.skill } : {}),
150
+ stageNumber: args.stageNumber,
151
+ ts: args.ts,
152
+ runId: args.runId,
153
+ };
154
+ }
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // Failed-unit sentinel (collect-all fanout)
158
+ // ---------------------------------------------------------------------------
159
+
160
+ /** The data shape of a failed-unit sentinel — collect-all fanout places one of
161
+ * these in a unit's declared slot when the unit halts (the run survives). */
162
+ export const FAILED_OUTPUT_KIND = "failed";
163
+ export type FailedOutput = Output<"failed", { reason: string }>;
164
+
165
+ /**
166
+ * A failed unit's contribution to a collect-all fanout. A real `Output` with NO
167
+ * artifacts, so: `applyCompletedStage` leaves the rolling primary alone; the
168
+ * `fanin` reader contributes no args for it (the `.filter(Boolean)` convention
169
+ * needs no widening); `advanceCursor` advances the index without making it the
170
+ * "last" produce; and the resume fold replays it like any produce row.
171
+ */
172
+ export function failedOutput(meta: OutputMeta, reason: string): FailedOutput {
173
+ return finalizeOutput({ kind: FAILED_OUTPUT_KIND, artifacts: [], data: { reason } }, meta);
174
+ }
175
+
176
+ export const isFailedOutput = (o: Output): o is FailedOutput => o.kind === FAILED_OUTPUT_KIND;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "1.20.0",
3
+ "version": "2.1.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",
@@ -35,15 +35,20 @@
35
35
  "internal.ts",
36
36
  "api.ts",
37
37
  "stage-def.ts",
38
+ "stage-identity.ts",
39
+ "stage-errors.ts",
38
40
  "loop-def.ts",
39
41
  "routing-dsl.ts",
40
42
  "audit.ts",
43
+ "audit-ctx.ts",
41
44
  "audit-rows.ts",
42
45
  "built-ins.ts",
43
46
  "chain-state.ts",
44
47
  "command.ts",
45
48
  "command-run.ts",
49
+ "execution-host.ts",
46
50
  "loop-constructors.ts",
51
+ "loops/",
47
52
  "extension.ts",
48
53
  "registration.ts",
49
54
  "handle.ts",
@@ -56,6 +61,8 @@
56
61
  "events.ts",
57
62
  "loop.ts",
58
63
  "loop-kinds.ts",
64
+ "loop-parallel.ts",
65
+ "loop-waves.ts",
59
66
  "load/",
60
67
  "output.ts",
61
68
  "messages.ts",
@@ -67,6 +74,7 @@
67
74
  "skill-contracts/",
68
75
  "routing.ts",
69
76
  "runner/",
77
+ "semaphore.ts",
70
78
  "startup.ts",
71
79
  "sessions/",
72
80
  "state/",
@@ -75,12 +83,17 @@
75
83
  "typebox-adapter.ts",
76
84
  "types.ts",
77
85
  "validate-output.ts",
86
+ "validation-bounds.ts",
78
87
  "validate-workflow.ts",
79
88
  "validate/",
80
89
  "docs-protocol.ts",
81
90
  "docs/",
91
+ "!docs/*.png",
92
+ "!docs/*.jpg",
93
+ "!docs/*.svg",
82
94
  "README.md",
83
- "LICENSE"
95
+ "LICENSE",
96
+ "!**/*.test.ts"
84
97
  ],
85
98
  "exports": {
86
99
  ".": "./index.ts",
@@ -95,12 +108,12 @@
95
108
  ]
96
109
  },
97
110
  "dependencies": {
98
- "@juicesharp/rpiv-config": "^1.20.0",
99
- "jiti": "^2.7.0"
111
+ "@juicesharp/rpiv-config": "^2.1.0",
112
+ "jiti": "^2.7.0",
113
+ "typebox": "^1.1.24"
100
114
  },
101
115
  "peerDependencies": {
102
116
  "@earendil-works/pi-coding-agent": "*",
103
- "@standard-schema/spec": "*",
104
- "typebox": "*"
117
+ "@standard-schema/spec": "*"
105
118
  }
106
119
  }
package/preview.ts CHANGED
@@ -132,6 +132,8 @@ function formatStageRow(
132
132
  if (stage.outputSchema) decorations.push("out-schema");
133
133
  if (shape.control.mode !== "single") decorations.push(loopTag(shape.control));
134
134
  if (shape.verify) decorations.push(verifyTag(shape.verify));
135
+ const fanin = faninTag(shape);
136
+ if (fanin) decorations.push(fanin);
135
137
 
136
138
  const displayName = shape.skill && shape.skill !== stageName ? `${stageName} (skill: ${shape.skill})` : stageName;
137
139
  const arrow = formatEdge(shape.edge, edgeDeclared);
@@ -141,10 +143,8 @@ function formatStageRow(
141
143
  }
142
144
 
143
145
  /**
144
- * Single tag per stage encoding the outcome shape. Custom outcomes
145
- * report `custom` (+`snapshot` when the collector declares a snapshot
146
- * hook, +`parser` when a parser is wired). Stages without an outcome
147
- * fall through to the framework default: `side-effect` for
146
+ * Single tag per stage encoding the outcome shape. Stages without an
147
+ * outcome fall through to the framework default: `side-effect` for
148
148
  * side-effect stages (the only kind that has a default); `???` for
149
149
  * `produces` (load-time validation rejects this — the tag is for
150
150
  * defensive rendering only).
@@ -162,9 +162,7 @@ function outcomeTag(stage: StageDef): string {
162
162
  /**
163
163
  * Decoration for a loop stage. Assess keeps its exact pre-redesign strings
164
164
  * (`assess(judge: skill:<name>)·max=N`, `assess(judge: prompt)·max=N` — the
165
- * constructor always sets `max`, defaulting to 8). Fanout/iterate gain tags
166
- * for the first time: `fanout·max=32`, `iterate·max=32`, or the bare kind
167
- * when no cap is declared (the run-wide maxIterations still backstops).
165
+ * constructor always sets `max`, defaulting to 8).
168
166
  */
169
167
  function loopTag(control: StageShape["control"]): string {
170
168
  const spec = control.spec;
@@ -176,22 +174,19 @@ function loopTag(control: StageShape["control"]): string {
176
174
  return spec.max !== undefined ? `${spec.kind}·max=${spec.max}` : spec.kind;
177
175
  }
178
176
 
179
- /**
180
- * Render a judge SLOT for a stage tag: `skill:<name>` / `prompt` for a single
181
- * judge, or `panel(<N>, <fold>)` for an N-member panel (`fold` is the sugar
182
- * name or `custom`) — the fan-in surfaces at a glance.
183
- */
177
+ /** Judge-slot label: skill/prompt/panel. */
184
178
  function judgeSlotTag(spec: AnyJudgeSpec): string {
185
179
  if ("panel" in spec) return `panel(${spec.panel.length}, ${spec.fold})`;
186
180
  return spec.skill ? `skill:${spec.skill}` : "prompt";
187
181
  }
188
182
 
189
- /**
190
- * Decoration for a verify-bearing stage: `verify(skill:<name>)` /
191
- * `verify(prompt)` / `verify(panel(N, fold))`, with the attempt budget appended
192
- * when retrying (`·attempts=N`); a gate-only verify (the default, max 1) stays
193
- * compact.
194
- */
183
+ /** Fan-in decoration for `fanin()` all-reads: `⇉ <names>`. */
184
+ function faninTag(shape: StageShape): string | undefined {
185
+ const allReads = shape.reads?.filter((r) => r.all).map((r) => r.name);
186
+ return allReads?.length ? `⇉ ${allReads.join(",")}` : undefined;
187
+ }
188
+
189
+ /** Verify decoration: `verify(<judge>)` + `·attempts=N` when retrying. */
195
190
  function verifyTag(v: NonNullable<StageShape["verify"]>): string {
196
191
  const attempts = v.max > 1 ? `·attempts=${v.max}` : "";
197
192
  return `verify(${judgeSlotTag(v)})${attempts}`;
@@ -203,6 +198,11 @@ function verifyTag(v: NonNullable<StageShape["verify"]>): string {
203
198
  * explicit `STOP` into one `terminal` mode; the declared-or-not distinction
204
199
  * is a one-key lookup the caller supplies (it matters to authors — the
205
200
  * validator warns on the undeclared form).
201
+ *
202
+ * The "terminal" rendered below is the GRAPH-SINK sense (a stage with no
203
+ * outgoing edge OR an explicit `STOP`) — NOT the `terminal()` stage factory
204
+ * (stage-def.ts) and NOT a "terminal failure" run outcome (audit.ts). See the
205
+ * glossary on `stage-def.ts`'s `terminal` export.
206
206
  */
207
207
  function formatEdge(edge: StageShape["edge"], declared: boolean): string | undefined {
208
208
  if (edge.mode === "terminal") return declared ? STOP : "(terminal — no edge declared)";
package/registration.ts CHANGED
@@ -22,6 +22,7 @@ export {
22
22
  type FanoutFn,
23
23
  type FanoutLoop,
24
24
  type FeedForwardContext,
25
+ fanin,
25
26
  gate,
26
27
  type IterateContext,
27
28
  type IterateFn,
@@ -49,6 +50,7 @@ export {
49
50
  STOP,
50
51
  type StageDef,
51
52
  type StageKind,
53
+ type StageRead,
52
54
  type StageSchema,
53
55
  terminal,
54
56
  type Unit,
@@ -80,7 +82,12 @@ export {
80
82
  opaque,
81
83
  url,
82
84
  } from "./handle.js";
83
- export type { WorkflowHost, WorkflowHostContext, WorkflowSessionContext } from "./host.js";
85
+ export type {
86
+ ModelSelection,
87
+ WorkflowHost,
88
+ WorkflowHostContext,
89
+ WorkflowSessionContext,
90
+ } from "./host.js";
84
91
  // Only the contract data types are public — they're referenced by kept public
85
92
  // signatures (`JsonSchemaCapable` ← `typeboxSchema`, `JsonSchemaObject` ←
86
93
  // `ConsumesSpec`/`ProducesSpec.data`, `SchemaCompatResult` ← `canCompose`). The
@@ -214,9 +221,9 @@ export {
214
221
  } from "./state/index.js";
215
222
  export { DEFAULT_TRIGGER, type RunTrigger } from "./triggers.js";
216
223
  export { typeboxSchema } from "./typebox-adapter.js";
217
- // `RunState` is deliberately NOT here — it became runner-private when user
218
- // contexts switched to the deep-readonly `RunView` (T3). Test fixtures that
219
- // must construct one import it from `@juicesharp/rpiv-workflow/internal`.
224
+ // `RunState` is deliberately NOT here — it is runner-private; user contexts
225
+ // use the deep-readonly `RunView`. Test fixtures that must construct one
226
+ // import it from `@juicesharp/rpiv-workflow/internal`.
220
227
  export type { RunTermination } from "./types.js";
221
228
  export { type SchemaValidationFailure, validateOutputData } from "./validate-output.js";
222
229
  export {
package/routing-dsl.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * EXECUTION lives in routing.ts — this module is authoring-surface only.
7
7
  */
8
8
 
9
+ import { markSymbol, readSymbol, requireNonEmptyString, throwInvalid } from "./internal-utils.js";
9
10
  import type { Output, RunView } from "./output.js";
10
11
  import type { NumericPredicate } from "./predicates.js";
11
12
 
@@ -67,12 +68,13 @@ export const READS_DATA: unique symbol = Symbol.for("rpiv.workflow.readsData");
67
68
  * declare an `outputSchema` — data-reading routes need a validated output
68
69
  * shape; state-only routes don't.
69
70
  *
70
- * Centralises the double-cast required to symbol-key into a function object
71
- * so consumers don't sprinkle `as unknown as Record<symbol, …>` at every
72
- * read site.
71
+ * Delegates the symbol-keyed read to `readSymbol` (`internal-utils.ts`) — the
72
+ * single home for the function-object symbol-access cast — so consumers read
73
+ * intent, not mechanics. The `READS_DATA`/`ROUTE_NOTE`/`CANONICAL_FOLD` family
74
+ * all route through the same `readSymbol`/`markSymbol` pair.
73
75
  */
74
76
  export function marksReadsData(fn: EdgeFn): boolean {
75
- return Boolean((fn as unknown as Record<symbol, boolean>)[READS_DATA]);
77
+ return Boolean(readSymbol<boolean>(fn, READS_DATA));
76
78
  }
77
79
 
78
80
  /** Options for `defineRoute`. */
@@ -104,7 +106,7 @@ export interface DefineRouteOptions {
104
106
  */
105
107
  export function defineRoute(targets: readonly string[], fn: EdgePredicate, opts?: DefineRouteOptions): EdgeFn {
106
108
  if (targets.length === 0) {
107
- throw new Error("defineRoute: targets must declare at least one possible return value");
109
+ throwInvalid("defineRoute", "targets must declare at least one possible return value");
108
110
  }
109
111
  // Fresh delegating wrapper — NEVER mutate the caller's function. Reusing
110
112
  // one predicate across two defineRoute calls must not alias their targets
@@ -112,7 +114,7 @@ export function defineRoute(targets: readonly string[], fn: EdgePredicate, opts?
112
114
  // must not inherit a marker a prior call attached.
113
115
  const wrapped: EdgeFn = (ctx) => fn(ctx);
114
116
  wrapped.targets = [...targets];
115
- if (opts?.readsData !== false) (wrapped as unknown as Record<symbol, boolean>)[READS_DATA] = true;
117
+ if (opts?.readsData !== false) markSymbol(wrapped, READS_DATA, true);
116
118
  return wrapped;
117
119
  }
118
120
 
@@ -134,9 +136,8 @@ export const ROUTE_NOTE: unique symbol = Symbol.for("rpiv.workflow.routeNote");
134
136
  * Returns undefined when the edge recorded nothing (the common case).
135
137
  */
136
138
  export function takeRouteNote(fn: EdgeFn): string | undefined {
137
- const slot = fn as unknown as Record<symbol, string | undefined>;
138
- const note = slot[ROUTE_NOTE];
139
- if (note !== undefined) slot[ROUTE_NOTE] = undefined;
139
+ const note = readSymbol<string>(fn, ROUTE_NOTE);
140
+ if (note !== undefined) markSymbol(fn, ROUTE_NOTE, undefined);
140
141
  return note;
141
142
  }
142
143
 
@@ -147,6 +148,27 @@ export function takeRouteNote(fn: EdgeFn): string | undefined {
147
148
  */
148
149
  const INTEGER_LIKE_KEY = /^\d+$/;
149
150
 
151
+ /**
152
+ * Shared branch-key guards for `gate`/`match`: at least one branch must be
153
+ * declared, and no key may be integer-like (`"2"`) — JS hoists array-index keys
154
+ * ahead of declaration order, silently reordering match priority. `factory`
155
+ * names the throwing builder; `renameHint` is the builder-specific tail of the
156
+ * integer-key message (gate offers `otherwise`, match does not).
157
+ */
158
+ function validateBranchKeys(factory: "gate" | "match", branchTargets: string[], renameHint: string): void {
159
+ if (branchTargets.length === 0) {
160
+ throwInvalid(factory, "branches must declare at least one possible return value");
161
+ }
162
+ for (const key of branchTargets) {
163
+ if (INTEGER_LIKE_KEY.test(key)) {
164
+ throwInvalid(
165
+ factory,
166
+ `branch key "${key}" is integer-like — JS reorders such keys ahead of declaration order, silently changing match priority. ${renameHint}`,
167
+ );
168
+ }
169
+ }
170
+ }
171
+
150
172
  /**
151
173
  * Conditional routing keyed on a numeric field in `output.data`. Each
152
174
  * branch's predicate is evaluated against `Number(output.data[field])` in
@@ -173,28 +195,19 @@ const INTEGER_LIKE_KEY = /^\d+$/;
173
195
  */
174
196
  export function gate(field: string, branches: Record<string, NumericPredicate>, otherwise: string): EdgeFn {
175
197
  const branchTargets = Object.keys(branches);
176
- if (branchTargets.length === 0) {
177
- throw new Error("gate: branches must declare at least one possible return value");
178
- }
179
- if (typeof otherwise !== "string" || otherwise.length === 0) {
180
- throw new Error("gate: an explicit `otherwise` branch is required — the no-match fallback must be deliberate");
181
- }
182
- for (const key of branchTargets) {
183
- if (INTEGER_LIKE_KEY.test(key)) {
184
- throw new Error(
185
- `gate: branch key "${key}" is integer-like — JS reorders such keys ahead of declaration order, ` +
186
- `silently changing match priority. Rename the stage or route to it via \`otherwise\`.`,
187
- );
188
- }
189
- }
198
+ validateBranchKeys("gate", branchTargets, "Rename the stage or route to it via `otherwise`.");
199
+ requireNonEmptyString(
200
+ otherwise,
201
+ "gate",
202
+ "an explicit `otherwise` branch is required — the no-match fallback must be deliberate",
203
+ );
190
204
  const targets = [...new Set([...branchTargets, otherwise])];
191
205
  const route: EdgeFn = defineRoute(targets, ({ output }) => {
192
206
  const value = Number((output?.data as Record<string, unknown> | undefined)?.[field]);
193
207
  for (const target of branchTargets) {
194
208
  if (branches[target]!(value)) return target;
195
209
  }
196
- (route as unknown as Record<symbol, string>)[ROUTE_NOTE] =
197
- `gate("${field}"): no branch matched value ${value} — fell back to "${otherwise}"`;
210
+ markSymbol(route, ROUTE_NOTE, `gate("${field}"): no branch matched value ${value} — fell back to "${otherwise}"`);
198
211
  return otherwise;
199
212
  });
200
213
  return route;
@@ -209,7 +222,7 @@ export interface MatchOptions {
209
222
  * Stage to route to when no branch value matches. Optional: when omitted, an
210
223
  * unmatched value TERMINATES the chain (`STOP`). Either way the no-match is a
211
224
  * visible event — the routing-audit row carries a `note`. Provide a fallback
212
- * to keep the run going on an unexpected value (the roadmap-P4 `triage` shape).
225
+ * to keep the run going on an unexpected value (the `triage` shape).
213
226
  */
214
227
  fallback?: string;
215
228
  /**
@@ -252,25 +265,17 @@ export interface MatchOptions {
252
265
  */
253
266
  export function match(field: string, branches: Record<string, MatchValue>, opts?: MatchOptions): EdgeFn {
254
267
  const branchTargets = Object.keys(branches);
255
- if (branchTargets.length === 0) {
256
- throw new Error("match: branches must declare at least one possible return value");
257
- }
268
+ validateBranchKeys("match", branchTargets, "Rename the stage.");
258
269
  const claimedBy = new Map<string, string>();
259
270
  for (const key of branchTargets) {
260
- if (INTEGER_LIKE_KEY.test(key)) {
261
- throw new Error(
262
- `match: branch key "${key}" is integer-like — JS reorders such keys ahead of declaration order, ` +
263
- `silently changing match priority. Rename the stage.`,
264
- );
265
- }
266
271
  // Type-tag the value so 0/"0"/false stay distinct when deduping.
267
272
  const value = branches[key]!;
268
273
  const valueKey = `${typeof value}:${String(value)}`;
269
274
  const prior = claimedBy.get(valueKey);
270
275
  if (prior !== undefined) {
271
- throw new Error(
272
- `match: value ${JSON.stringify(value)} is claimed by both "${prior}" and "${key}" — ` +
273
- `each enum value must map to exactly one stage`,
276
+ throwInvalid(
277
+ "match",
278
+ `value ${JSON.stringify(value)} is claimed by both "${prior}" and "${key}" — each enum value must map to exactly one stage`,
274
279
  );
275
280
  }
276
281
  claimedBy.set(valueKey, key);
@@ -278,7 +283,7 @@ export function match(field: string, branches: Record<string, MatchValue>, opts?
278
283
 
279
284
  const fallback = opts?.fallback;
280
285
  if (fallback !== undefined && (typeof fallback !== "string" || fallback.length === 0)) {
281
- throw new Error("match: `fallback`, when provided, must be a non-empty stage name");
286
+ requireNonEmptyString(fallback, "match", "`fallback`, when provided, must be a non-empty stage name");
282
287
  }
283
288
  const noMatch = fallback ?? STOP;
284
289
  const targets = [...new Set([...branchTargets, noMatch])];
@@ -287,6 +292,10 @@ export function match(field: string, branches: Record<string, MatchValue>, opts?
287
292
  const route: EdgeFn = defineRoute(
288
293
  targets,
289
294
  ({ output, state }) => {
295
+ // `.at(-1)` on a PRE-SIZED produces-fanout channel could read a
296
+ // pending (`undefined`) or failed-sentinel tail. Safe by ordering: routes
297
+ // fire at `finishLoop`, AFTER `foldFanoutCompletion` has filled every
298
+ // settled slot, so the channel is never observed half-filled here.
290
299
  const source =
291
300
  from !== undefined
292
301
  ? (state.named[from]?.at(-1)?.data as Record<string, unknown> | undefined)
@@ -295,10 +304,13 @@ export function match(field: string, branches: Record<string, MatchValue>, opts?
295
304
  for (const target of branchTargets) {
296
305
  if (raw === branches[target]) return target;
297
306
  }
298
- (route as unknown as Record<symbol, string>)[ROUTE_NOTE] =
307
+ markSymbol(
308
+ route,
309
+ ROUTE_NOTE,
299
310
  `match("${field}"): value ${JSON.stringify(raw ?? null)} matched no branch — ${
300
311
  fallback ? `fell back to "${fallback}"` : `terminated (no fallback)`
301
- }`;
312
+ }`,
313
+ );
302
314
  return noMatch;
303
315
  },
304
316
  // A channel-sourced match validates the CHANNEL's data, not the source
package/routing.ts CHANGED
@@ -8,6 +8,12 @@
8
8
  * routing layer detected a violation (an `EdgeFn` body threw, or an
9
9
  * `EdgeFn` returned an undeclared target).
10
10
  *
11
+ * `{ kind: "stop" }` (and "terminal stages" above/below) is the GRAPH-SINK
12
+ * sense — a stage with no outgoing edge OR an explicit `STOP`. Unrelated to
13
+ * the `terminal()` stage factory (stage-def.ts) and to "terminal failure"
14
+ * run-outcome prose (audit.ts). See the glossary on `stage-def.ts`'s
15
+ * `terminal` export. The `kind: "stop"` literal is untouched.
16
+ *
11
17
  * Errors are returned, not thrown. The caller (runner) switches on
12
18
  * `kind` and routes `"err"` through `recordTerminalFailure` — same as
13
19
  * any other halt site.
@@ -51,6 +57,46 @@ export function edgeIsDecision(workflow: Workflow, current: string): boolean {
51
57
  return typeof workflow.edges[current] === "function";
52
58
  }
53
59
 
60
+ /**
61
+ * The not-taken targets of a DECISION edge that are pure RECOVERY arms — a
62
+ * stage whose own out-edge is a STRING edge pointing at an already-visited
63
+ * stage, i.e. taking it would loop BACK into covered territory rather than make
64
+ * forward progress.
65
+ *
66
+ * Used by the progress bridge (`rpiv-pi` lane-progress): when a gate takes its
67
+ * pass arm, the failure arm (build's `slice-fix` / `plan-fix` / `code-fix`) is bypassed for good
68
+ * on this path, so it counts toward "distinct nodes covered" — the bar reaches
69
+ * full WHILE the terminal stage runs instead of freezing one-below until the
70
+ * `onWorkflowEnd` snap. Surfaced as the `onRoute` lifecycle event's `bypassed`
71
+ * argument.
72
+ *
73
+ * Deliberately narrow: a not-taken target is credited ONLY when its successor
74
+ * is a string edge to an already-visited stage. A FORWARD arm (its successor
75
+ * not yet visited) is merely deferred, not bypassed — crediting it would push
76
+ * the numerator AHEAD of the stages actually reached. An arm with a gate/
77
+ * terminal out-edge is left uncredited (conservative; never over-counts).
78
+ *
79
+ * Returns distinct names; `chosen`, `STOP`, and already-visited arms are
80
+ * excluded, so the credited set never inflates the numerator past the reachable
81
+ * total.
82
+ */
83
+ export function bypassedRecoveryArms(
84
+ workflow: Workflow,
85
+ from: string,
86
+ chosen: string,
87
+ visited: ReadonlySet<string>,
88
+ ): string[] {
89
+ const edge = workflow.edges[from];
90
+ if (typeof edge !== "function" || !Array.isArray(edge.targets)) return [];
91
+ const out: string[] = [];
92
+ for (const t of edge.targets) {
93
+ if (t === chosen || t === STOP || visited.has(t)) continue;
94
+ const succ = workflow.edges[t]; // one-hop loop-back test
95
+ if (typeof succ === "string" && visited.has(succ)) out.push(t);
96
+ }
97
+ return out;
98
+ }
99
+
54
100
  // ---------------------------------------------------------------------------
55
101
  // Internals
56
102
  // ---------------------------------------------------------------------------