@juicesharp/rpiv-pi 2.6.4 → 2.7.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 (31) hide show
  1. package/extensions/rpiv-core/agents.ts +10 -13
  2. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  3. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  4. package/extensions/rpiv-core/built-in-workflows.ts +228 -3497
  5. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  6. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  7. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  8. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  9. package/extensions/rpiv-core/built-ins/index.ts +46 -0
  10. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  11. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  12. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  13. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  14. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  15. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  16. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  17. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  18. package/extensions/rpiv-core/constants.ts +5 -1
  19. package/extensions/rpiv-core/lane-console.ts +9 -2
  20. package/extensions/rpiv-core/lane-list.ts +10 -1
  21. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  22. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  23. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  24. package/package.json +2 -2
  25. package/skills/elaborate/SKILL.md +1 -1
  26. package/skills/implement/SKILL.md +1 -0
  27. package/skills/plan/SKILL.md +3 -1
  28. package/skills/remediate/SKILL.md +1 -0
  29. package/skills/synthesize/SKILL.md +1 -0
  30. package/skills/validate/SKILL.md +25 -19
  31. package/skills/validate/templates/validation.md +1 -1
@@ -0,0 +1,420 @@
1
+ /**
2
+ * The two deterministic slice-map floors: the slice structure check
3
+ * (acyclicity, coverage conservation, citation backing) and the subplan
4
+ * cluster-coverage check between the cluster fanout and the root merge.
5
+ */
6
+ import { basename } from "node:path";
7
+ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import { handleToString, type Output, type RunView, type ScriptContext } from "@juicesharp/rpiv-workflow/registration";
9
+ import { verifyCitations } from "./citations.js";
10
+ import { latestVerdictPerDimension } from "./gates.js";
11
+ import { fencedSpans } from "./markdown-fence.js";
12
+ import {
13
+ haltPreflight,
14
+ latestFsArtifact,
15
+ type PhaseRecord,
16
+ readArtifactFile,
17
+ type StructureFinding,
18
+ writeStructureVerdict,
19
+ } from "./shared.js";
20
+ import {
21
+ clusterSliceDag,
22
+ DESIGN_SLICE_RE,
23
+ designPathsBySlice,
24
+ sliceCoverageUnits,
25
+ sliceCovers,
26
+ sliceDepCycle,
27
+ sliceRecords,
28
+ } from "./slices.js";
29
+
30
+ /** A dispatched sub-plan basename with its `_cluster-<k>` ordinal resolved. */
31
+ type DispatchedCluster = { path: string; k: number };
32
+
33
+ /**
34
+ * A citation string occurs LIVE in the slice-map text — outside fenced spans
35
+ * and not as half of an `old→new` refresh-note pair. A re-slice's revision
36
+ * note legitimately QUOTES the citations it refreshed (contract: only as
37
+ * arrow pairs or inside a fence — see the slice skill's re-slice mode);
38
+ * treating a quoted old citation as still-live would forfeit every documented
39
+ * refresh's discharge, and treating a quoted new one as present would credit
40
+ * a fix that never touched the live `Draws on` lines.
41
+ */
42
+ const citeOccursLive = (body: string, spans: readonly [number, number][], cite: string): boolean => {
43
+ for (let i = body.indexOf(cite); i !== -1; i = body.indexOf(cite, i + 1)) {
44
+ if (spans.some(([s, e]) => i >= s && i < e)) continue;
45
+ if (body.startsWith("→", i + cite.length)) continue;
46
+ if (body.endsWith("→", i)) continue;
47
+ return true;
48
+ }
49
+ return false;
50
+ };
51
+
52
+ /**
53
+ * One cite-remedy finding is satisfied by the slice-map text: the demanded
54
+ * seed's path occurs live — line suffixes are stripped before matching,
55
+ * because the fix may cite a corrected range and the citation floor
56
+ * (`verifyCitations`) verifies whatever range it actually wrote. `Draws on`
57
+ * and `Out of scope` both satisfy the remedy, so a live occurrence anywhere
58
+ * in the map is the contract. (The former REFRESH mode — a `stale` drifted
59
+ * line number to replace — was removed with anchor-precision grading: a
60
+ * drifted line number is no longer a finding, so nothing demands a refresh.)
61
+ *
62
+ * A finding without a concrete string `requires` is unverifiable ⇒ not satisfied.
63
+ */
64
+ const citeFindingSatisfied = (
65
+ mapBody: string,
66
+ spans: readonly [number, number][],
67
+ f: { requires?: unknown },
68
+ ): boolean =>
69
+ typeof f.requires === "string" &&
70
+ f.requires.length > 0 &&
71
+ citeOccursLive(mapBody, spans, f.requires.replace(/:\d[-\d,:]*$/, ""));
72
+
73
+ /**
74
+ * Structural fingerprint of one slice-map round: the `slices` + `coverage`
75
+ * frontmatter it published on the `slices` channel — no file re-read.
76
+ * `undefined` when the round carried no `slices` data; a caller must treat
77
+ * that as "cannot compare", never as "unchanged".
78
+ */
79
+ const sliceShape = (round: Output | undefined): string | undefined => {
80
+ const d = round?.data as { slices?: unknown; coverage?: unknown } | undefined;
81
+ return d?.slices === undefined ? undefined : JSON.stringify({ slices: d.slices, coverage: d.coverage ?? null });
82
+ };
83
+
84
+ /** The verdict fields the cite-only discharge consults. */
85
+ type CiteRemedyVerdict = {
86
+ pass?: boolean;
87
+ remedy?: string;
88
+ findings?: readonly { requires?: unknown }[];
89
+ };
90
+
91
+ /**
92
+ * Deterministic discharge of a CITE-ONLY `design-readiness` fail — the middle
93
+ * case between "carry a passing verdict" (impossible on the slice gate: its
94
+ * lone dimension failed) and "buy a full re-grade panel" (wasteful when the
95
+ * grader already named the exact citations to add or refresh). A fix that
96
+ * also restructured forfeits the discharge and takes the normal re-grade.
97
+ */
98
+ const citeRemedyDischarged = (state: RunView, mapBody: string): boolean => {
99
+ const verdict = latestVerdictPerDimension(state.named["slice-verdicts"]).get("design-readiness");
100
+ const v = verdict?.data as CiteRemedyVerdict | undefined;
101
+ if (v?.pass !== false || v.remedy !== "cite") return false;
102
+ // A fix must have LANDED since the verdict — discharging the judged map
103
+ // unchanged would contradict the grader, who read it and found the cites
104
+ // wrong. Basename inequality cannot witness the fix (a re-slice may
105
+ // legitimately edit the map in place); publication order can: the latest
106
+ // `slices` round must postdate the verdict.
107
+ const entries = state.named.slices ?? [];
108
+ const verdictTs = verdict?.meta?.ts;
109
+ const currentTs = entries.at(-1)?.meta?.ts;
110
+ if (typeof verdictTs !== "string" || typeof currentTs !== "string" || currentTs <= verdictTs) return false;
111
+ const findings = Array.isArray(v.findings) ? v.findings : [];
112
+ if (findings.length === 0) return false;
113
+ const spans = fencedSpans(mapBody);
114
+ if (!findings.every((f) => f != null && citeFindingSatisfied(mapBody, spans, f))) return false;
115
+ // Shape must match the round the grader judged — located by publication
116
+ // order, not filename, for the same in-place reason.
117
+ const judged = [...entries].reverse().find((s) => typeof s.meta?.ts === "string" && s.meta.ts <= verdictTs);
118
+ const judgedShape = sliceShape(judged);
119
+ return judgedShape !== undefined && judgedShape === sliceShape(entries.at(-1));
120
+ };
121
+
122
+ /**
123
+ * Deterministic Phase-1 slice-check — the un-gameable floor beneath the LLM
124
+ * `design-readiness` panel. It enforces the invariants a prose grader cannot
125
+ * reliably hold because it grades the slicer's own self-description:
126
+ * • acyclicity — the `deps` DAG must be cycle-free.
127
+ * • coverage conservation — every coverage unit FROZEN at the first cut
128
+ * (`state.named.slices[0]`) must still be claimed by ≥1 slice's `covers`,
129
+ * so a reslice can only redistribute the brief, never simplify by dropping
130
+ * scope. Anchored to the FIRST cut (not the latest map) so a reslice cannot
131
+ * disable the check by deleting the `coverage:` array — the frozen set is
132
+ * read from round 0.
133
+ * • citation backing — every `file:line` the slice map cites (its `Draws on:`
134
+ * footing, refracted up from research) must resolve against the tree. An
135
+ * unbacked citation is fabricated precision that would otherwise starve or
136
+ * mislead the design pass; the deterministic floor stops it here.
137
+ * Emits one combined `{ dimension: "structure" }` verdict onto the
138
+ * `slice-check` channel AND writes it to an fs artifact so the reslice arm's
139
+ * `reads: [fanin("slice-check")]` projection carries the FINDINGS (not just the
140
+ * pass/fail) into `slice-fix` — the way `amend` receives `--code-verdicts`. The
141
+ * gate route folds the channel `data` with the LLM verdicts.
142
+ * Deterministic ⇒ idempotent across reslice rounds (no flicker, resume-safe): the
143
+ * verdict basename is keyed on the slice-map basename, so a re-run OVERWRITES its
144
+ * own slot rather than duplicating it.
145
+ */
146
+ const sliceStructureCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
147
+ const latest = latestFsArtifact(state, "slices");
148
+ if (latest?.handle.kind !== "fs") {
149
+ throw haltPreflight(
150
+ "slice-check",
151
+ "slice-check: no slice map to check",
152
+ "slice-check: no fs artifact on the 'slices' channel — slice must run before the structure check",
153
+ );
154
+ }
155
+ const mapBody = readArtifactFile(latest.handle.path, cwd);
156
+ const records = sliceRecords(mapBody, "slice-check", latest.handle.path);
157
+ const findings: { detail: string; where: string }[] = [];
158
+
159
+ const cycle = sliceDepCycle(records);
160
+ if (cycle.length > 0) {
161
+ const loop = [...cycle, cycle[0]].join("→");
162
+ findings.push({
163
+ detail: `Dependency cycle ${loop} — slices in a cycle cannot be designed independently. Break it: merge the cycle into one slice, or invert one edge so a shared contract has a single owning slice.`,
164
+ where: `deps: ${cycle.map((n) => `Slice ${n}`).join(", ")}`,
165
+ });
166
+ }
167
+
168
+ // Coverage conservation, anchored to the FROZEN units of the first cut.
169
+ const firstFs = state.named.slices?.[0]?.artifacts.find((a) => a.handle.kind === "fs");
170
+ const frozen = firstFs?.handle.kind === "fs" ? sliceCoverageUnits(readArtifactFile(firstFs.handle.path, cwd)) : [];
171
+ if (frozen.length > 0) {
172
+ const covered = new Set(records.flatMap((r) => sliceCovers(r.entry)));
173
+ const dropped = frozen.filter((u) => !covered.has(u.id));
174
+ if (dropped.length > 0) {
175
+ findings.push({
176
+ detail: `Coverage regression — ${dropped.length} brief unit(s) frozen at the first cut are no longer claimed by any slice's 'covers': ${dropped.map((u) => `${u.id} (${u.brief})`).join("; ")}. A reslice must redistribute every unit across slices, never drop one. Re-add the dropped unit(s) to an owning slice's 'covers'.`,
177
+ where: `coverage: ${dropped.map((u) => u.id).join(", ")}`,
178
+ });
179
+ }
180
+ }
181
+
182
+ // Citation backing — every file:line the map cites must resolve.
183
+ findings.push(...verifyCitations(mapBody, cwd));
184
+
185
+ // Stamp the cite-only discharge ONLY on a green floor: structure clean +
186
+ // citation backing verified + demanded seeds present + shape unchanged is
187
+ // exactly what a fresh design-readiness pass on this map would re-establish,
188
+ // so the `sliceGatePasses` skip stays provably equivalent to "re-grade, then pass".
189
+ const discharge =
190
+ findings.length === 0 && citeRemedyDischarged(state, mapBody)
191
+ ? { citeDischarged: basename(latest.handle.path) }
192
+ : undefined;
193
+ return writeStructureVerdict("slice-check", latest.handle, findings, cwd, discharge);
194
+ };
195
+
196
+ /**
197
+ * `_<k>` cluster ordinal a partial sub-plan carries in its basename
198
+ * (`<slug>_cluster-<k>.md`), emitted by `synthesize`'s partial mode from the
199
+ * `--cluster <k>` the fanout threads on every cluster unit. The token a
200
+ * `subplan-check` reconciliation keys dispatched sub-plans on. Anchored to the
201
+ * basename TAIL (extension optional — extensionless agent writes happen, see
202
+ * the implement-scope floor precedent) so a name carrying several `_cluster-`
203
+ * tokens binds the trailing one deterministically, not the first match.
204
+ */
205
+ const CLUSTER_TOKEN_RE = /_cluster-(\d+)(?:\.\w+)?$/;
206
+
207
+ /** The pre-filter cluster count the fanout received — the count
208
+ * `subplanCoverageCheck` reconciles dispatched ordinals against. Delegates to
209
+ * `clusterSliceDag`. */
210
+ const expectedClusterCount = (records: readonly PhaseRecord[]): number => clusterSliceDag(records).length;
211
+
212
+ /** Slice numbers that have NO design artifact on the `designs` channel — the gap
213
+ * the missing-design preflight halts on (a slice with no design is unrepairable
214
+ * by re-dispatch). */
215
+ const designCoverageGap = (sliceNumbers: Set<number>, designBySlice: Map<number, string>): number[] =>
216
+ [...sliceNumbers].filter((n) => !designBySlice.has(n)).sort((a, b) => a - b);
217
+
218
+ /** Collect every dispatched sub-plan's `_cluster-<k>` ordinal from the `subplans`
219
+ * channel. The `subplans` slot is a produces-fanout channel: `placeFanoutOutput`
220
+ * pre-sizes it to the round's unit total and overwrites each unit's own index, so
221
+ * with a stable unit set iterating it reflects the latest output per unit — a
222
+ * re-dispatch's fresh artifacts re-evaluate cleanly. (A unit that FAILS on
223
+ * re-dispatch leaves its prior-round output at its index; that stale entry
224
+ * re-reads as current here.) Returns the resolved ordinals AND a `tokenless`
225
+ * finding per basename that carries no `_cluster-<k>` token (the root merge
226
+ * cannot attribute a tokenless sub-plan to a slice-DAG cluster). */
227
+ const dispatchedClusterOrdinals = (
228
+ state: RunView,
229
+ ): { dispatched: DispatchedCluster[]; tokenless: StructureFinding[] } => {
230
+ const dispatched: DispatchedCluster[] = [];
231
+ const tokenless: StructureFinding[] = [];
232
+ for (const out of state.named.subplans ?? []) {
233
+ for (const a of out.artifacts) {
234
+ if (a.handle.kind !== "fs") continue;
235
+ const name = basename(a.handle.path);
236
+ const m = CLUSTER_TOKEN_RE.exec(name);
237
+ if (!m) {
238
+ tokenless.push({
239
+ detail: `Tokenless sub-plan basename ${name} — it carries no '_cluster-<k>' ordinal, so the root merge cannot attribute it to a slice-DAG cluster. The cluster fanout threads '--cluster <k>' on every unit; a tokenless name means 'synthesize' dropped the flag. Re-dispatch the cluster with its '--cluster <k>' honored in the output filename.`,
240
+ where: name,
241
+ });
242
+ continue;
243
+ }
244
+ dispatched.push({ path: handleToString(a.handle), k: Number(m[1]) });
245
+ }
246
+ }
247
+ return { dispatched, tokenless };
248
+ };
249
+
250
+ /** A finding per `_cluster-<k>` ordinal claimed by MORE THAN ONE dispatched
251
+ * sub-plan — a clobber (not a legitimate re-emit: within one round every unit
252
+ * index is a distinct artifact because the channel is replaced each round, so a
253
+ * shared `<k>` is the lost-cluster collision itself). */
254
+ const clobberedOrdinals = (dispatched: readonly DispatchedCluster[]): StructureFinding[] => {
255
+ const pathsByK = new Map<number, string[]>();
256
+ for (const d of dispatched) {
257
+ const arr = pathsByK.get(d.k);
258
+ if (arr) arr.push(d.path);
259
+ else pathsByK.set(d.k, [d.path]);
260
+ }
261
+ const findings: StructureFinding[] = [];
262
+ for (const [k, paths] of pathsByK) {
263
+ if (paths.length > 1) {
264
+ findings.push({
265
+ detail: `Duplicate/clobbered cluster-${k} — ${paths.length} dispatched sub-plans claim the same '_cluster-${k}' ordinal (${paths.map((p) => basename(p)).join(", ")}). Two clusters collided on one filename token, so the root merge would fold one cluster's content over the other and lose a slice-DAG component. Re-dispatch with each cluster's '--cluster <k>' distinct.`,
266
+ where: `cluster-${k}`,
267
+ });
268
+ }
269
+ }
270
+ return findings;
271
+ };
272
+
273
+ /** sources-coverage — every slice's design must appear in SOME sub-plan's
274
+ * `sources:`. Reads the covered-slice set off each sub-plan's parsed `sources:`
275
+ * (designs follow the `_slice-<N>` convention) and reconciles it against the full
276
+ * slice map. A sub-plan whose frontmatter does not PARSE gets its own
277
+ * re-dispatchable finding naming the FILE (never a terminal halt — the same
278
+ * stray-colon class `artifact-collector` degrades on); when ANY sub-plan is
279
+ * unparseable, the per-slice reconciliation DEFERS (an unreadable sub-plan's
280
+ * coverage is unknowable; blaming its slices would misdirect the repair). */
281
+ const sourcesCoverageGaps = (state: RunView, cwd: string, sliceNumbers: Set<number>): StructureFinding[] => {
282
+ const findings: StructureFinding[] = [];
283
+ const coveredSlices = new Set<number>();
284
+ let unparseable = false;
285
+ for (const out of state.named.subplans ?? []) {
286
+ for (const a of out.artifacts) {
287
+ if (a.handle.kind !== "fs") continue;
288
+ let frontmatter: unknown;
289
+ try {
290
+ ({ frontmatter } = parseFrontmatter(readArtifactFile(handleToString(a.handle), cwd)));
291
+ } catch {
292
+ unparseable = true;
293
+ findings.push({
294
+ detail: `Unparseable frontmatter in sub-plan ${basename(a.handle.path)} — its YAML frontmatter does not parse (typically a bare ': ' inside an unquoted scalar), so its 'sources:' coverage cannot be read. Re-dispatch the cluster and re-write the sub-plan with parseable frontmatter listing every '--designs' path in 'sources:'.`,
295
+ where: basename(a.handle.path),
296
+ });
297
+ continue;
298
+ }
299
+ const fm = frontmatter && typeof frontmatter === "object" ? (frontmatter as Record<string, unknown>) : {};
300
+ const sources = fm.sources;
301
+ if (!Array.isArray(sources)) continue;
302
+ for (const s of sources) {
303
+ if (typeof s !== "string") continue;
304
+ const sm = DESIGN_SLICE_RE.exec(s);
305
+ if (sm) coveredSlices.add(Number(sm[1]));
306
+ }
307
+ }
308
+ }
309
+ if (!unparseable) {
310
+ for (const n of [...sliceNumbers].sort((a, b) => a - b)) {
311
+ if (!coveredSlices.has(n)) {
312
+ findings.push({
313
+ detail: `Slice ${n} design absent from every sub-plan's 'sources:' — the cluster fanout threads each '--designs <path>' and 'synthesize' echoes them into 'sources:'; a slice whose design no sub-plan lists is one the root merge would silently drop. List every '--designs' path in its sub-plan's 'sources:'.`,
314
+ where: `sources: slice ${n}`,
315
+ });
316
+ }
317
+ }
318
+ }
319
+ return findings;
320
+ };
321
+
322
+ /**
323
+ * Deterministic subplan cluster-coverage floor — the structural backstop between
324
+ * the cluster fanout and the root merge. After `subplan` fans each slice-DAG
325
+ * cluster out to a partial sub-plan, this reconciles what was DISPATCHED against
326
+ * what the slice map PROMISED, before the root `plan` merge fans them in:
327
+ * • cluster-count conservation — the PRE-FILTER cluster count
328
+ * (`clusterSliceDag(sliceRecords(latest slices)).length`) must equal the
329
+ * number of distinct `_cluster-<k>` ordinals the fanout emitted. A re-dispatch
330
+ * that re-clobbered an ordinal (the pre-fix clobber bug — two clusters
331
+ * sharing `<k>`, or a tokenless basename) collapses the distinct count,
332
+ * surfacing as a missing cluster here.
333
+ * • token conformance — every dispatched sub-plan basename MUST carry a
334
+ * `_cluster-<k>` token; a tokenless name means `synthesize` dropped the
335
+ * `--cluster <k>` flag and the merge can't attribute it to a cluster.
336
+ * • duplicate/clobbered ordinal — two dispatched sub-plans sharing the same
337
+ * `<k>` (a clobber, not a legitimate re-emit: `placeFanoutOutput` overwrites
338
+ * each unit's own index in the channel slot, so within one round every unit
339
+ * index is a distinct artifact — a shared `<k>` is a real collision, the
340
+ * lost-cluster bug itself).
341
+ * • sources-coverage — every slice's design must appear in SOME sub-plan's
342
+ * `sources:` (the fanout threads each `--designs <path>` and `synthesize`
343
+ * echoes them into `sources:`). Designs follow the `_slice-<N>` convention, so
344
+ * the covered slice set is read off `sources:` and reconciled against the full
345
+ * slice map; a slice whose design no sub-plan lists is a slice the merge would
346
+ * silently drop. A sub-plan whose frontmatter does not PARSE gets its own
347
+ * re-dispatchable finding naming the FILE (never a `FAIL_SCRIPT_THREW` halt —
348
+ * the same stray-colon class `artifact-collector` degrades on), and the
349
+ * per-slice reconciliation defers until every sub-plan parses, so a parse
350
+ * failure is never mis-blamed on the slices it happened to cover.
351
+ * Preflight: a slice with NO design on the `designs` channel halts LOUD before
352
+ * any reconciliation — the fanout drops (or under-feeds) its cluster pre-dispatch
353
+ * (`if (!designs.length) return undefined`), so re-dispatching `subplan` re-drops
354
+ * it every round until `maxBackwardJumps` exhausts with a diagnostic naming the
355
+ * refused re-entry instead of the cause. The missing design is upstream
356
+ * (`slice-design`/`design-review`) and unreachable from this loop's backward
357
+ * edge; halting here names the actual defect and spends no jump budget.
358
+ * Emits `severity: pass ? "none" : "high"` (load-bearing — the route routes via
359
+ * `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently passes a
360
+ * `pass:false` verdict rated `low`/`none`; a lost cluster MUST rate `high` or it
361
+ * ships). Deliberately NOT the `match("verdict", …)` STOP idiom
362
+ * `implementScopeCheck` uses — a lost cluster IS repairable by re-dispatch, so the
363
+ * floor routes the backward edge to `subplan`, bounded by `maxBackwardJumps`.
364
+ * Deterministic ⇒ idempotent across re-dispatch rounds: the verdict basename is
365
+ * keyed on the slice-map basename, so a re-run OVERWRITES its own slot.
366
+ */
367
+ const subplanCoverageCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
368
+ const latestSliceMap = latestFsArtifact(state, "slices");
369
+ if (latestSliceMap?.handle.kind !== "fs") {
370
+ throw haltPreflight(
371
+ "subplan-check",
372
+ "subplan-check: no slice map to reconcile against",
373
+ "subplan-check: no fs artifact on the 'slices' channel — slice must run before the subplan coverage check",
374
+ );
375
+ }
376
+ const mapBody = readArtifactFile(latestSliceMap.handle.path, cwd);
377
+ const records = sliceRecords(mapBody, "subplan-check", latestSliceMap.handle.path);
378
+ // PRE-FILTER expected clusters — the count the fanout RECEIVED, not the
379
+ // post-drop dispatched count. The fanout drops a zero-design cluster
380
+ // (`if (!designs.length) return undefined` in SYNTH_CLUSTER_FANOUT's units);
381
+ // design-review catches those upstream, so a healthy run lands here with
382
+ // pre-filter == dispatched — an invariant the missing-design preflight below
383
+ // enforces loudly rather than assumes.
384
+ const expectedK = expectedClusterCount(records);
385
+ const sliceNumbers = new Set(records.map((r) => r.n));
386
+
387
+ // A slice with no design cannot be repaired by the backward edge: the fanout
388
+ // drops a zero-design cluster pre-dispatch, so every `subplan` re-dispatch
389
+ // reproduces the identical gap until maxBackwardJumps exhausts blaming the
390
+ // re-entry. Halt loud at the floor instead, naming the upstream cause.
391
+ const designBySlice = designPathsBySlice(state);
392
+ const undesigned = designCoverageGap(sliceNumbers, designBySlice);
393
+ if (undesigned.length > 0) {
394
+ throw haltPreflight(
395
+ "subplan-check",
396
+ `subplan-check: slice(s) ${undesigned.join(", ")} have no design on the 'designs' channel`,
397
+ `subplan-check: slice(s) ${undesigned.join(", ")} in the slice map have no design artifact on the 'designs' channel, so the cluster fanout dropped (or under-fed) their cluster(s) before dispatch. Re-dispatching 'subplan' cannot repair this — no sub-plan can list a design that was never produced. The missing design(s) come from upstream ('slice-design' emits, 'design-review' re-emits the accepted docs); investigate why they never reached the 'designs' channel.`,
398
+ );
399
+ }
400
+
401
+ const { dispatched, tokenless } = dispatchedClusterOrdinals(state);
402
+ const findings: StructureFinding[] = [...tokenless];
403
+ findings.push(...clobberedOrdinals(dispatched));
404
+
405
+ // Cluster-count conservation — distinct dispatched ordinals vs the pre-filter
406
+ // expected count. A clobber or a never-dispatched cluster both surface here.
407
+ const dispatchedK = new Set(dispatched.map((d) => d.k)).size;
408
+ if (dispatchedK < expectedK) {
409
+ findings.push({
410
+ detail: `Missing cluster coverage — the slice map promised ${expectedK} slice-DAG cluster(s) but the fanout dispatched ${dispatchedK} distinct '_cluster-<k>' sub-plan(s). A cluster went undispatched (or two collided on one ordinal — see any duplicate finding above); its slices would be absent from the merged plan. Re-dispatch the missing cluster(s).`,
411
+ where: `clusters (expected ${expectedK}, dispatched ${dispatchedK})`,
412
+ });
413
+ }
414
+
415
+ findings.push(...sourcesCoverageGaps(state, cwd, sliceNumbers));
416
+
417
+ return writeStructureVerdict("subplan-check", latestSliceMap.handle, findings, cwd);
418
+ };
419
+
420
+ export { sliceStructureCheck, subplanCoverageCheck };