@juicesharp/rpiv-pi 2.9.0 → 2.10.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 (33) hide show
  1. package/extensions/rpiv-core/artifact-collector.ts +30 -7
  2. package/extensions/rpiv-core/built-in-workflows.ts +222 -70
  3. package/extensions/rpiv-core/built-ins/citations.ts +9 -0
  4. package/extensions/rpiv-core/built-ins/design.ts +64 -0
  5. package/extensions/rpiv-core/built-ins/elaboration.ts +53 -0
  6. package/extensions/rpiv-core/built-ins/gates.ts +282 -12
  7. package/extensions/rpiv-core/built-ins/grade-panel.ts +54 -26
  8. package/extensions/rpiv-core/built-ins/index.ts +20 -1
  9. package/extensions/rpiv-core/built-ins/markdown-fence.ts +26 -1
  10. package/extensions/rpiv-core/built-ins/plan-phases.ts +8 -0
  11. package/extensions/rpiv-core/built-ins/priors.ts +9 -2
  12. package/extensions/rpiv-core/built-ins/remediation.ts +60 -7
  13. package/extensions/rpiv-core/built-ins/scope-checks.ts +74 -11
  14. package/extensions/rpiv-core/built-ins/shared.ts +5 -3
  15. package/extensions/rpiv-core/built-ins/slice-checks.ts +164 -28
  16. package/extensions/rpiv-core/built-ins/slices.ts +44 -13
  17. package/extensions/rpiv-core/built-ins/verdict-collector.ts +207 -0
  18. package/extensions/rpiv-core/built-ins/verdict-outcome.ts +36 -0
  19. package/extensions/rpiv-core/lane-list.ts +10 -1
  20. package/extensions/rpiv-core/lane-progress.ts +1 -1
  21. package/extensions/rpiv-core/lane-usage.ts +1 -1
  22. package/extensions/rpiv-core/models-picker.ts +4 -3
  23. package/extensions/rpiv-core/run-lane-registry.ts +1 -2
  24. package/extensions/rpiv-core/sdk-workflow-host.ts +20 -4
  25. package/extensions/rpiv-core/session-hooks.ts +1 -1
  26. package/package.json +4 -3
  27. package/skills/_shared/stitch-elaborations.mjs +282 -21
  28. package/skills/acceptance/SKILL.md +3 -2
  29. package/skills/amend/SKILL.md +5 -5
  30. package/skills/design-slice/SKILL.md +5 -0
  31. package/skills/elaborate/SKILL.md +10 -3
  32. package/skills/grade/SKILL.md +13 -10
  33. package/skills/validate/SKILL.md +14 -0
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * models-picker — filterable select panel for /rpiv-models cascade pickers.
3
3
  *
4
- * Clone of the advisor's showFilterablePicker (advisor-ui.ts:65-115) at
5
- * Phase-1 zero-cross-imports contract enforcement. Promotion to a shared TUI
6
- * package (e.g. packages/rpiv-tui/) is queued as a follow-up.
4
+ * Local clone of the advisor's showFilterablePicker (advisor-ui.ts) — the
5
+ * zero-cross-imports contract forbids an rpiv-core → rpiv-advisor import.
6
+ * Promotion to a shared TUI package (e.g. packages/rpiv-tui/) is a candidate
7
+ * follow-up.
7
8
  */
8
9
 
9
10
  import { DynamicBorder, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
@@ -88,8 +88,7 @@ export interface PendingInput {
88
88
  export const SINGLE_UNIT_KEY = -1;
89
89
 
90
90
  /**
91
- * One fan-out unit's switchable sub-lane. Bundles everything that used to
92
- * live as a single scalar on `LaneEntry` — the live child session, the terminal
91
+ * One fan-out unit's switchable sub-lane. Bundles the live child session, the terminal
93
92
  * snapshot (branch/cwd/tool-defs), the durable disk-fallback pointer, and the
94
93
  * deferred-input queue — so each concurrent unit owns its own slot keyed by its
95
94
  * declared fan-out `index`. Under fan-out a sibling's teardown can never clobber
@@ -159,8 +159,13 @@ export function withoutAmbientExtensions(base: LoadExtensionsResult): LoadExtens
159
159
  * the dir from cwd+runId and hands rpiv-pi the concrete path.
160
160
  */
161
161
  export interface SdkWorkflowHostDeps {
162
- /** The interactive ctx — observer (ui/sessionManager) + the hasUI source. */
163
- live: Pick<WorkflowHostContext, "ui" | "sessionManager" | "hasUI">;
162
+ /**
163
+ * The interactive ctx — observer (sessionManager reads) + the hasUI source.
164
+ * Deliberately NOT the toast channel: every `live` member is a pi getter that
165
+ * throws stale once the launcher session is replaced/disposed mid-run, so
166
+ * toasts route through the raw `uiContext` below instead (see `relayUi`).
167
+ */
168
+ live: Pick<WorkflowHostContext, "sessionManager" | "hasUI">;
164
169
  /** Borrowed at session_start (carries auth/OAuth state). */
165
170
  modelRegistry: ModelRegistry;
166
171
  /** The real launcher UI the deferring relay forwards to (captured at session_start). */
@@ -459,7 +464,9 @@ export class SdkWorkflowHost implements WorkflowHostContext {
459
464
  private adapt(session: AgentSession, depth: number, watchdog: BashWatchdog): WorkflowSessionContext {
460
465
  return {
461
466
  cwd: this.cwd,
462
- hasUI: this.deps.live.hasUI,
467
+ // Constructor snapshot, not a fresh `live.hasUI` getter read — adapt
468
+ // runs mid-run, when the launcher ctx may already be stale.
469
+ hasUI: this.hasUI,
463
470
  ui: this.relayUi(),
464
471
  maxConcurrency: this.maxConcurrency,
465
472
  // A child may itself fan out — each level increments the depth, bounded
@@ -513,9 +520,18 @@ export class SdkWorkflowHost implements WorkflowHostContext {
513
520
  : undefined;
514
521
  }
515
522
 
523
+ /**
524
+ * Toasts go through the session_start-captured RAW uiContext, never a
525
+ * guarded `live.ui` getter read: the stage machinery and audit paths notify
526
+ * mid-run — long after `/wf` returned — and pi invalidates every ctx getter
527
+ * of the old generation on launcher session replacement (/new, resume,
528
+ * /reload, auto-compaction). The raw object survives replacement and still
529
+ * points at the persistent TUI, so a floated run's progress/completion
530
+ * toasts can't throw the stale-ctx error out of the runner.
531
+ */
516
532
  private relayUi() {
517
533
  return {
518
- notify: (message: string, level?: "info" | "warning" | "error") => this.deps.live.ui.notify(message, level),
534
+ notify: (message: string, level?: "info" | "warning" | "error") => this.deps.uiContext.notify(message, level),
519
535
  };
520
536
  }
521
537
  }
@@ -2,7 +2,7 @@
2
2
  * Session lifecycle wiring for rpiv-core.
3
3
  *
4
4
  * Each handler body is a named helper; pi.on(...) lines are pure wiring.
5
- * Ordering and invariants preserved verbatim from the pre-refactor index.ts.
5
+ * Handler order is deliberate — preserve it.
6
6
  */
7
7
 
8
8
  import {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-pi",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "A skill-based development workflow for Pi Agent. 30 contract-carrying skills (discover → research → design → plan → implement → validate → code-review → commit, and more), the 15 named subagents they dispatch, and four built-in /wf workflows that chain them end to end in detached parallel runs.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -38,7 +38,8 @@
38
38
  "!docs/*.svg",
39
39
  "README.md",
40
40
  "LICENSE",
41
- "!**/*.test.ts"
41
+ "!**/*.test.ts",
42
+ "!extensions/rpiv-core/built-ins/__fixtures__/"
42
43
  ],
43
44
  "pi": {
44
45
  "image": "https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-pi/docs/cover.png",
@@ -50,7 +51,7 @@
50
51
  ]
51
52
  },
52
53
  "dependencies": {
53
- "@juicesharp/rpiv-config": "^2.9.0",
54
+ "@juicesharp/rpiv-config": "^2.10.0",
54
55
  "typebox": "^1.1.24"
55
56
  },
56
57
  "peerDependencies": {
@@ -15,16 +15,24 @@
15
15
  // implement-ready code; its frontmatter is stripped before splicing.
16
16
  //
17
17
  // Preserved verbatim: the plan's frontmatter (incl. `phase_count`) and the
18
- // preamble before the first phase (`## Synthesis Notes`, etc.). Phase boundaries
18
+ // preamble before the first phase (`## Synthesis Notes`, etc.). The trailing
19
+ // `## Whole-Plan Verification` section is preserved as well: an authored block
20
+ // is re-appended verbatim after the last phase (the swap of an elaborated last
21
+ // phase would otherwise drop it, heading to EOF); with no authored block but a
22
+ // Synthesis-Notes reference to one, a block is derived from the per-phase
23
+ // `Automated Verification:` items — never invented otherwise. Phase boundaries
19
24
  // are detected fence-aware (a `## ` inside a Find/Replace code block is NOT a
20
25
  // boundary) and each phase owns everything up to the next `## Phase N:` heading,
21
26
  // so the swap is idempotent — re-stitching can't accumulate duplicate per-phase
22
- // trailers (Success Criteria / Notes / Deferred). The heading count is unchanged
23
- // (1:1 swap), so the downstream `phase_count == '## Phase N:' headings`
27
+ // trailers (Success Criteria / Notes / Deferred). An elaboration is refused
28
+ // when a fence it opens never closes (the leak would swallow the next phase's
29
+ // heading) or when it carries other than one out-of-fence `## Phase N:`
30
+ // heading, and the stitched body is refused before writing if its heading
31
+ // count drifted, so the downstream `phase_count == '## Phase N:' headings`
24
32
  // derive-check stays valid.
25
33
  //
26
34
  // Always exits 0 on a normal run (a plan phase with no elaboration is left as-is
27
- // and reported — partial runs are allowed). Exits 1 only on a wiring/path error:
35
+ // and reported — partial runs are allowed). Exits 1 on a refused elaboration or a wiring/path error:
28
36
  // missing argument, missing plan, or zero elaboration docs found.
29
37
  import { execFileSync } from "node:child_process";
30
38
  import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -61,18 +69,235 @@ const elaborationsDir = resolve(dirname(planPath), "..", "elaborations");
61
69
  const FRONTMATTER_RE = /^---\n[\s\S]*?\n---\n/;
62
70
  const PHASE_HEADING_RE = /^## Phase (\d+):/;
63
71
 
72
+ // A fence-shaped line: optional leading whitespace then 3+ backticks or 3+
73
+ // tildes (the CommonMark fence delimiters). Deliberate mirror of the same-char
74
+ // twins packages/rpiv-pi/extensions/rpiv-core/built-ins/markdown-fence.ts and
75
+ // packages/rpiv-pi/extensions/rpiv-core/built-ins/reconcile-directives.mjs —
76
+ // importing them is impossible here: this script runs as a bare `node` CLI
77
+ // spawned by the workflow host
78
+ // (packages/rpiv-pi/extensions/rpiv-core/built-in-workflows.ts), with no
79
+ // loader that resolves package-root TypeScript. The close predicate below is
80
+ // deliberately LOOSER than those twins (length-only, NOT same-char): a
81
+ // backtick-opened fence closed by a bare `~~~` line is accepted. Closing that
82
+ // gap is a behavior change, not a cleanup — it would strand the walk inside
83
+ // the fence and swallow the next real `## Phase N:` heading, recreating the
84
+ // 8534cb3c failure class (boundaries missed by a mis-tracked fence walk).
85
+ const FENCE_LINE_RE = /^\s*(`{3,}|~{3,})/;
86
+
87
+ /** Advance the fence-walk state `{ inFence, fenceLen }` (mutated in place)
88
+ * across one line. Returns true for any fence-shaped line — an opener, a
89
+ * closer, or a fence line that does not close the open fence — so the caller
90
+ * can skip heading work and apply its own offset policy. The close test is
91
+ * length-only on purpose (see FENCE_LINE_RE above): the delimiter run must
92
+ * be at least as long as the opener's and alone on the line. */
93
+ const fenceStep = (state, line) => {
94
+ const fence = line.match(FENCE_LINE_RE);
95
+ if (!fence) return false;
96
+ const len = fence[1].length;
97
+ if (!state.inFence) {
98
+ state.inFence = true;
99
+ state.fenceLen = len;
100
+ } else if (len >= state.fenceLen && line.trim().length === len) {
101
+ state.inFence = false;
102
+ state.fenceLen = 0;
103
+ }
104
+ return true;
105
+ };
106
+
64
107
  /** Split a document into [frontmatter, body]; frontmatter ("" when absent) is kept verbatim. */
65
108
  const splitFrontmatter = (content) => {
66
109
  const m = content.match(FRONTMATTER_RE);
67
110
  return m ? [m[0], content.slice(m[0].length)] : ["", content];
68
111
  };
69
112
 
113
+ /** 1-based line of a fence opener that never closes, or undefined when balanced. */
114
+ const openFenceLine = (text) => {
115
+ const fenceState = { inFence: false, fenceLen: 0 };
116
+ let opened;
117
+ text.split("\n").forEach((line, i) => {
118
+ const was = fenceState.inFence;
119
+ if (fenceStep(fenceState, line) && !was) opened = i + 1;
120
+ });
121
+ return fenceState.inFence ? opened : undefined;
122
+ };
123
+
70
124
  /** Extract the `## Phase N:` section (heading to EOF) from an elaboration body. */
71
125
  const phaseSection = (body) => {
72
126
  const idx = body.search(/^## Phase \d+:/m);
73
127
  return idx === -1 ? null : body.slice(idx).trim();
74
128
  };
75
129
 
130
+ // --- Whole-Plan Verification ----------------------------------------------
131
+ //
132
+ // The trailing `## Whole-Plan Verification` section is owned by the stitch,
133
+ // not by any elaboration lane: swapping an elaborated last phase drops the
134
+ // whole original span (heading to EOF), which would silently drop the block
135
+ // that carries the whole-tree gates. Authored-first, never invented:
136
+ //
137
+ // 1. An AUTHORED block — a section in the ORIGINAL last-phase span whose
138
+ // first body line is not the derived provenance marker — is re-appended
139
+ // verbatim after the last rebuilt phase; the Synthesis Notes are never
140
+ // consulted when one exists (authored wins over a concurrent reference).
141
+ // 2. Only when nothing authored was extracted AND the preamble references a
142
+ // whole-plan verification block (the canonical phrase, fence-aware) is a
143
+ // block DERIVED from the final post-swap sections' per-phase
144
+ // `#### Automated Verification:` checkbox items: heading, provenance
145
+ // marker, one intro line, deduped items in plan order. A derived block
146
+ // found in the original span is a prior stitch's own emission — dropped
147
+ // and re-derived, never treated as authored.
148
+ // 3. Otherwise nothing is emitted.
149
+ //
150
+ // The append is guarded by one fence-aware scan of the post-strip composition:
151
+ // a block already present anywhere in the preamble or a kept section (a
152
+ // degenerate mid-document occurrence) suppresses it, so every output carries
153
+ // at most one section.
154
+
155
+ /** The whole-plan verification heading: column-0, canonical prefix,
156
+ * suffix-tolerant (`## Whole-Plan Verification (owned by validate)` is the
157
+ * same section). */
158
+ const WPV_HEADING_RE = /^## Whole-Plan Verification\b/;
159
+
160
+ /** The provenance marker emitted as a derived block's first body line — the
161
+ * byte-stable discriminator between authored content and a prior stitch's
162
+ * own derived emission. */
163
+ const DERIVED_MARKER =
164
+ "<!-- derived by stitch-elaborations from per-phase Automated Verification items; re-derived on every stitch -->";
165
+
166
+ /** The Synthesis-Notes promise probe: the canonical phrase only. A promise
167
+ * phrased solely as the skills' shorthand is deliberately not detected —
168
+ * widening the probe would fire the derived fallback on non-promises. */
169
+ const NOTES_REFERENCE_RE = /whole-plan verification/i;
170
+
171
+ /** The plan template's exact `#### Automated Verification:` heading —
172
+ * preserved verbatim by every elaborate lane's Success Criteria section. */
173
+ const AV_HEADING_RE = /^#### Automated Verification:$/;
174
+
175
+ /** The one intro line of a derived block. */
176
+ const WPV_INTRO =
177
+ "Collected from each phase's `Automated Verification:` blocks in plan order; run on the merged tree once every phase has landed.";
178
+
179
+ /** Call `fn(line)` for each line of `text` OUTSIDE fenced code blocks — the
180
+ * same fence rules as the phase-boundary walk, both consuming the shared
181
+ * `fenceStep` over the module-level `FENCE_LINE_RE` (an elaboration's fenced
182
+ * Find/Replace blocks may legitimately contain heading- and bullet-shaped
183
+ * lines). Shared on purpose: the scope-note lift's re-land will consume this
184
+ * same walk. */
185
+ const eachOutsideFence = (text, fn) => {
186
+ const fenceState = { inFence: false, fenceLen: 0 };
187
+ for (const line of text.split("\n")) {
188
+ if (fenceStep(fenceState, line)) continue;
189
+ if (!fenceState.inFence) fn(line);
190
+ }
191
+ };
192
+
193
+ /** Char offsets of column-0 `re`-matching lines OUTSIDE fenced code blocks —
194
+ * the main flow's own boundary-walk accumulation pattern (fence toggling via
195
+ * `fenceStep` over the module-level `FENCE_LINE_RE`, `+line.length+1`),
196
+ * factored out for reuse. The unconditional offset advance is load-bearing:
197
+ * the offsets feed `slice()` spans, so fence lines must advance the cursor
198
+ * like any other line. */
199
+ const headingOffsets = (text, re) => {
200
+ const offsets = [];
201
+ const fenceState = { inFence: false, fenceLen: 0 };
202
+ let offset = 0;
203
+ for (const line of text.split("\n")) {
204
+ if (!fenceStep(fenceState, line) && !fenceState.inFence && re.test(line)) offsets.push(offset);
205
+ offset += line.length + 1;
206
+ }
207
+ return offsets;
208
+ };
209
+
210
+ /** The whole-plan verification section of a phase span: from the first WPV
211
+ * heading to the next column-0 `## ` heading or end-of-span. `derived` is
212
+ * true when the block's first body line is exactly `DERIVED_MARKER` (a prior
213
+ * stitch's emission, not authored content). Null when the span carries no
214
+ * such section. */
215
+ const extractTrailingWpv = (span) => {
216
+ const at = headingOffsets(span, WPV_HEADING_RE)[0];
217
+ if (at === undefined) return null;
218
+ const end = headingOffsets(span, /^## /).find((o) => o > at) ?? span.length;
219
+ const text = span.slice(at, end).trimEnd();
220
+ let derived = false;
221
+ for (const line of text.split("\n").slice(1)) {
222
+ const content = line.trim();
223
+ if (content === "") continue;
224
+ derived = content === DERIVED_MARKER;
225
+ break;
226
+ }
227
+ return { offset: at, text, derived };
228
+ };
229
+
230
+ /** True when the preamble — kept verbatim, where the Synthesis Notes live —
231
+ * promises a whole-plan verification block via the canonical phrase,
232
+ * fence-aware. */
233
+ const notesReferenceWpv = (preamble) => {
234
+ let found = false;
235
+ eachOutsideFence(preamble, (line) => {
236
+ if (NOTES_REFERENCE_RE.test(line)) found = true;
237
+ });
238
+ return found;
239
+ };
240
+
241
+ /** Per-phase `#### Automated Verification:` checkbox lines from the FINAL
242
+ * post-swap sections: collected after the heading, stopping at the next
243
+ * heading of any level, fence-aware; deduped by exact trimmed-line equality,
244
+ * in plan order. */
245
+ const collectAvItems = (sections) => {
246
+ const items = [];
247
+ const seen = new Set();
248
+ for (const section of sections) {
249
+ let inAv = false;
250
+ eachOutsideFence(section, (line) => {
251
+ if (AV_HEADING_RE.test(line)) {
252
+ inAv = true;
253
+ return;
254
+ }
255
+ if (/^#{1,6}\s/.test(line)) {
256
+ inAv = false;
257
+ return;
258
+ }
259
+ if (!inAv) return;
260
+ const item = line.trim();
261
+ if (/^- \[[ x]\]/.test(item) && !seen.has(item)) {
262
+ seen.add(item);
263
+ items.push(item);
264
+ }
265
+ });
266
+ }
267
+ return items;
268
+ };
269
+
270
+ /** The canonical derived block: heading + provenance marker + one intro line
271
+ * + the collected item lines verbatim. */
272
+ const deriveWpvBlock = (items) =>
273
+ ["## Whole-Plan Verification", "", DERIVED_MARKER, WPV_INTRO, ...items].join("\n");
274
+
275
+ /** Resolve the whole-plan verification tail. Pure — mutates nothing; the
276
+ * strip of a kept-original last phase is expressed by the caller's `rebuilt`
277
+ * construction, and this orchestrator re-reads the ORIGINAL pre-swap body.
278
+ * `note` carries the fail-open reasons ("notes reference but no verification
279
+ * items", "block already present") for the summary. */
280
+ const wholePlanVerification = ({ preamble, starts, body, rebuilt }) => {
281
+ const last = starts.at(-1);
282
+ const extracted = last ? extractTrailingWpv(body.slice(last.offset)) : null;
283
+ let candidate;
284
+ let mode = "none";
285
+ if (extracted && !extracted.derived) {
286
+ candidate = extracted.text;
287
+ mode = "authored";
288
+ } else if (notesReferenceWpv(preamble)) {
289
+ const items = collectAvItems(rebuilt);
290
+ if (items.length === 0) return { text: null, mode: "none", note: "notes reference but no verification items" };
291
+ candidate = deriveWpvBlock(items);
292
+ mode = "derived";
293
+ } else {
294
+ return { text: null, mode: "none" };
295
+ }
296
+ const alreadyPresent = [preamble, ...rebuilt].some((part) => headingOffsets(part, WPV_HEADING_RE).length > 0);
297
+ if (alreadyPresent) return { text: null, mode: "none", note: "block already present" };
298
+ return { text: candidate, mode };
299
+ };
300
+
76
301
  // Collect elaborations: phase number -> spliced section text, keyed off the
77
302
  // `<planBase>__phase-<N>.md` filename so the pairing is independent of any
78
303
  // timestamp slug inside the doc.
@@ -82,9 +307,26 @@ if (existsSync(elaborationsDir)) {
82
307
  for (const name of readdirSync(elaborationsDir)) {
83
308
  const m = name.match(NAME_RE);
84
309
  if (!m) continue;
85
- const [, body] = splitFrontmatter(readFileSync(resolve(elaborationsDir, name), "utf-8"));
310
+ const raw = readFileSync(resolve(elaborationsDir, name), "utf-8");
311
+ const [, body] = splitFrontmatter(raw);
86
312
  const section = phaseSection(body);
87
- if (section) elaborations.set(Number.parseInt(m[1], 10), section);
313
+ if (!section) continue;
314
+ const open = openFenceLine(raw);
315
+ if (open !== undefined) {
316
+ console.error(
317
+ `stitch-elaborations: ${name} refused — the fence opened at line ${open} never closes ` +
318
+ "(a bare ``` inside a ``` block closes it; open and close the outer block with four backticks)",
319
+ );
320
+ process.exit(1);
321
+ }
322
+ const headings = headingOffsets(section, PHASE_HEADING_RE).length;
323
+ if (headings !== 1) {
324
+ console.error(
325
+ `stitch-elaborations: ${name} refused — ${headings} '## Phase N:' headings outside fences, expected exactly 1`,
326
+ );
327
+ process.exit(1);
328
+ }
329
+ elaborations.set(Number.parseInt(m[1], 10), section);
88
330
  }
89
331
  }
90
332
 
@@ -112,24 +354,18 @@ const [frontmatter, body] = splitFrontmatter(readFileSync(planPath, "utf-8"));
112
354
  // guard halted the run.)
113
355
  // Content before the first phase (Synthesis Notes, etc.) is the preamble, kept
114
356
  // verbatim. Content after the last phase is absorbed into that phase — the plan
115
- // format has no post-phase appendix; trailing matter belongs to the elaboration.
357
+ // format has no post-phase appendix; trailing matter belongs to the elaboration
358
+ // — EXCEPT the whole-plan verification section, which the stitch strips from
359
+ // the last phase and re-emits itself (see the whole-plan verification section
360
+ // above).
116
361
  const lines = body.split("\n");
117
362
  const starts = []; // { offset, n }
118
- let inFence = false;
119
- let fenceLen = 0;
363
+ // Fence state for the shared fenceStep walk — FENCE_LINE_RE is matched
364
+ // inside fenceStep, never inlined in any walker.
365
+ const fenceState = { inFence: false, fenceLen: 0 };
120
366
  let offset = 0;
121
367
  for (const line of lines) {
122
- const fence = line.match(/^\s*(`{3,}|~{3,})/);
123
- if (fence) {
124
- const len = fence[1].length;
125
- if (!inFence) {
126
- inFence = true;
127
- fenceLen = len;
128
- } else if (len >= fenceLen && line.trim().length === len) {
129
- inFence = false;
130
- fenceLen = 0;
131
- }
132
- } else if (!inFence) {
368
+ if (!fenceStep(fenceState, line) && !fenceState.inFence) {
133
369
  const m = line.match(PHASE_HEADING_RE);
134
370
  if (m) starts.push({ offset, n: Number.parseInt(m[1], 10) });
135
371
  }
@@ -138,6 +374,15 @@ for (const line of lines) {
138
374
 
139
375
  const preamble = starts.length ? body.slice(0, starts[0].offset) : body;
140
376
 
377
+ // Whole-plan verification extraction runs off the ORIGINAL last-phase span
378
+ // BEFORE the rebuilt map: a kept-original last phase is stripped at the
379
+ // extracted offset below (an elaborated one drops the whole span via the swap),
380
+ // and the emitter re-appends the resolved tail after the rebuilt sections —
381
+ // authored verbatim, derived when only the Synthesis Notes reference a block,
382
+ // never invented.
383
+ const lastStart = starts.at(-1);
384
+ const wpvExtracted = lastStart ? extractTrailingWpv(body.slice(lastStart.offset)) : null;
385
+
141
386
  let stitched = 0;
142
387
  const missing = [];
143
388
  const total = starts.length;
@@ -149,12 +394,28 @@ const rebuilt = starts.map(({ offset: start, n }, i) => {
149
394
  return replacement;
150
395
  }
151
396
  missing.push(n);
397
+ if (wpvExtracted && i === starts.length - 1) return original.slice(0, wpvExtracted.offset).trim();
152
398
  return original.trim();
153
399
  });
154
400
 
155
- const newBody = [preamble.trim(), ...rebuilt].filter((s) => s.length > 0).join("\n\n");
401
+ const wpv = wholePlanVerification({ preamble, starts, body, rebuilt });
402
+
403
+ // The WPV tail joins the body as a peer top-level element, NOT as part of
404
+ // `rebuilt` — it is no phase's section content, and folding it into one would
405
+ // feed the block's own AV-shaped checkbox lines back into the next derivation.
406
+ const newBody = [preamble.trim(), ...rebuilt, ...(wpv.text ? [wpv.text] : [])]
407
+ .filter((s) => s.length > 0)
408
+ .join("\n\n");
409
+ const after = headingOffsets(newBody, PHASE_HEADING_RE).length;
410
+ if (after !== starts.length) {
411
+ console.error(
412
+ `stitch-elaborations: refusing to write ${basename(planPath)} — '## Phase N:' headings would drift from ${starts.length} to ${after}`,
413
+ );
414
+ process.exit(1);
415
+ }
156
416
  writeFileSync(planPath, `${frontmatter.trimEnd()}\n\n${newBody}\n`);
157
417
 
158
418
  let summary = `stitch-elaborations: stitched ${stitched}/${total} phases into ${basename(planPath)}`;
159
419
  if (missing.length) summary += ` — no elaboration for phase(s) ${missing.sort((a, b) => a - b).join(", ")}`;
420
+ summary += ` — whole-plan verification: ${wpv.mode}${wpv.note ? ` (${wpv.note})` : ""}`;
160
421
  console.log(summary);
@@ -71,7 +71,7 @@ An acceptance item is one **observable outcome** the goal asks for — behavior
71
71
 
72
72
  Evidence, per item — exactly one of:
73
73
 
74
- - `command` + `expect` — a **read-only, self-contained, repo-root-relative** command expected to exit 0 once the outcome holds (a test invocation, a grep invariant, a `tsc --noEmit`, a file-existence check), with `expect` naming the observable in one line. Ground it in the research/tree so paths and script names are real. It is **future-tense**: it may (and usually will) fail on today's tree — validate runs it after implement.
74
+ - `command` + `expect` — a **read-only, self-contained, repo-root-relative** command expected to exit 0 once the outcome holds (a test invocation, a grep invariant, a `tsc --noEmit`, a file-existence check), with `expect` naming the observable in one line. Ground it in the research/tree so paths and script names are real. It is **future-tense**: it may (and usually will) fail on today's tree — validate runs it after implement. Two limits: the command measures the **outcome itself, never a record of it** (a doc cell, a checkbox, or a table row that says "done" is not evidence the thing happened), and its pass condition must be **reachable by the implementing lanes alone** — a check that can only go green after a person, a paired device, or a network has acted is not a command.
75
75
  - `manual` — a one-line human procedure, ONLY when no read-only command can measure the outcome (visual appearance, real-terminal behavior). Prefer a command whenever one exists; a `manual` item is homework validate can record but not discharge.
76
76
 
77
77
  ## Flow
@@ -82,7 +82,7 @@ Evidence, per item — exactly one of:
82
82
 
83
83
  1. **Read.** The goal FULLY — it is the sole source of items. The research doc FULLY when given — it is the sole *grounding* for evidence commands (test layouts, script names, conventions). Spot-check any path a command will cite against the real tree.
84
84
  2. **Enumerate.** Walk the goal sentence by sentence and extract every explicit ask and explicit constraint as an item (`a1`, `a2`, … in goal order). Ambiguity is resolved toward the goal's own words — restate, don't interpret. Do NOT consult the research for what belongs in the set: a research doc that narrowed the brief must not narrow the inventory.
85
- 3. **Attach evidence.** For each item, derive the strongest read-only command the tree supports and one `expect` line; fall back to `manual` only when nothing runnable can measure it. Never write a command that mutates the tree, reaches the network, or depends on state outside the repo.
85
+ 3. **Attach evidence.** For each item, derive the strongest read-only command the tree supports and one `expect` line; fall back to `manual` only when nothing runnable can measure it. Never write a command that mutates the tree, reaches the network, or depends on state outside the repo. Before keeping a command, ask: *could validate's sandbox make this exit 0 with no human in the loop?* If its pass depends on another item's `manual` procedure having been performed, the command is a proxy for that item — drop it; the manual item already carries the ask.
86
86
  4. **Write** the inventory in one pass to `.rpiv/artifacts/acceptance/<slug>_<description>.md` (`<description>` a brief kebab-case task summary), `status: ready` directly. Then print the path and `acceptance written: {N} item(s), {M} executable`.
87
87
 
88
88
  Use this template:
@@ -118,6 +118,7 @@ Derived from the verbatim goal ({goal path}). Items enumerate the goal's explici
118
118
  - **Items from the goal ALONE.** Research grounds evidence, never membership — the whole point of this stage is a standard the later narrowing cannot rewrite. If the goal names an ask the research argues against, the item still exists; the PLAN defers it legibly.
119
119
  - **The inventory is frozen.** No downstream stage re-emits on the acceptance channel; deferral happens in the plan (visibly, per item id), never by editing this artifact.
120
120
  - **Read-only, self-contained commands.** Validate runs them as written after implement — a command that mutates the tree or depends on external state corrupts the very measurement it exists to make.
121
+ - **One observation, one item.** A human-only outcome appears once, as `manual`. Never re-encode its completion as a sibling `command` over its record: validate would gate on a check nothing in the pipeline can satisfy, and the run would stop at the last stage with every machine-verifiable item green.
121
122
  - **Future-tense evidence.** Do not run the commands here and do not weaken one because it fails today — failing today is the expected state of a check on unbuilt work.
122
123
  - **Non-interactive.** No `ask_user_question`, no subagents. Resolve ambiguity toward the goal's own words; the grade panel adjudicates a genuinely contestable reading.
123
124
  - **NEVER edit source files.** This skill produces an inventory document only.
@@ -36,17 +36,17 @@ The first tab-separated field is `<iso>` (use as `last_updated`).
36
36
  ## Steps
37
37
 
38
38
  1. **Read the artifact fully** (no limit/offset) and **read every verdict JSON**.
39
- 2. **Select the failing findings.** Group verdicts by `dimension`; for each dimension keep the **latest** (by `graded_at`) — verdicts accumulate across amend loops, so an older failing verdict may already be superseded. From the latest-per-dimension set, take those with `pass: false`, **and also any carrying a non-empty `risk_duty_demotions` array** (a field the workflow stamps after grading — even when the verdict's own `pass` is `true`, a demoted risk ruling records the demotion there). If none fail and none carry a demotion, the artifact already passes: re-emit it unchanged (only bump `last_updated`) and report — the panel will confirm.
40
- 3. **Apply each failing verdict's `feedback`/`findings` surgically.** Use each finding's `where` to locate the exact spot and change only that. Honor `feedback` as the instruction set. Where a finding requires checking the codebase (a `correctness` or `pattern-following` fix), Read/Grep the cited `file:line` to ground the edit — but never edit code, only the artifact. A **completeness-class** finding (the artifact under-covers the brief) is repaired from the lineage sources — `--goal`, `--research`, `--subplans` — by reading the authoritative source there and folding the missing point in; never reconstruct the missing content from verdict prose or guess it from a directory listing.
41
- 4. **Confirm coverage** — every failing finding maps to an edit you made. Do not introduce changes no finding asked for.
39
+ 2. **Select the failing findings.** Group verdicts by `dimension`; for each dimension keep the **latest** (by `graded_at`) — verdicts accumulate across amend loops, so an older failing verdict may already be superseded. From the latest-per-dimension set, take those with `pass: false`, **and also any carrying a non-empty `risk_duty_demotions` array** (a field the workflow stamps after grading — even when the verdict's own `pass` is `true`, a demoted risk ruling records the demotion there). **Additionally, from each PASSING dimension's latest verdict, select any finding that asserts a deterministic failure-as-written** — the emitted code or edit fails typecheck/compile as written, a cited file or symbol does not exist, an edit anchor does not match its target. Left in place, such a finding is a landmine: a later round's grader will rate it blocking and it then costs a whole extra grade-fix lap. Select only that class from passing verdicts — every other finding on a passing verdict stays out of scope. If this selects nothing, the artifact already passes: re-emit it unchanged (only bump `last_updated`) and report — the panel will confirm.
40
+ 3. **Apply each selected verdict's `feedback`/`findings` surgically** (for a passing verdict, only its selected failure-as-written findings — its `feedback` is not an instruction set). Use each finding's `where` to locate the exact spot and change only that. Honor `feedback` as the instruction set. Where a finding requires checking the codebase (a `correctness` or `pattern-following` fix), Read/Grep the cited `file:line` to ground the edit — but never edit code, only the artifact. A **completeness-class** finding (the artifact under-covers the brief) is repaired from the lineage sources — `--goal`, `--research`, `--subplans` — by reading the authoritative source there and folding the missing point in; never reconstruct the missing content from verdict prose or guess it from a directory listing.
41
+ 4. **Confirm coverage** — every selected finding maps to an edit you made. Do not introduce changes no finding asked for.
42
42
  5. **Re-emit the artifact to the SAME path** (Edit in place; Write only if a structural rewrite of a section is unavoidable). Preserve everything outside the cited findings, keep `status: ready`, and update `last_updated: <iso>` in the frontmatter. Same path ⇒ the artifact's channel updates latest-wins for re-judging.
43
43
  6. **Print the artifact path**, then a one-line summary: `amended for <dimensions>: <k> findings addressed`.
44
44
 
45
45
  ## Hard rules
46
46
 
47
- - **A `risk_duty_demotions` demotion is grader-side — re-emit unchanged.** A verdict carrying a non-empty `risk_duty_demotions` array records a risk ruling the panel marked `pass: true` that a duty demoted: the evidence citation format (a mechanics claim with no adjacent `file:line`) or the ruling's missing `procedure`+`owner` (a verify-at-implement deferral). The plan carries **no defect** for it — the demoted ruling was `pass: true`, and the defect lives in grader-emit fields (the citation shape or the ruling's procedure/owner), not the plan body. So amend re-emits the artifact unchanged (only bump `last_updated`), exactly the "none fail" branch; it does **NOT** manufacture `risks:` edits for the demotion and does **NOT** invoke the two resolve moves of the failed-ruling hard rule below (which govern only `pass: false` rulings). The re-grade — with the evidence-duty prompt — addresses the citation format; the demotion is a signal to select the verdict, not a plan defect to fix.
47
+ - **A `risk_duty_demotions` demotion is grader-side — re-emit unchanged.** A verdict carrying a non-empty `risk_duty_demotions` array records a risk ruling the panel marked `pass: true` that a duty demoted: the evidence citation format (a mechanics claim with no adjacent `file:line`) or the ruling's missing `procedure`+`owner` (a verify-at-implement deferral). The plan carries **no defect** for it — the demoted ruling was `pass: true`, and the defect lives in grader-emit fields (the citation shape or the ruling's procedure/owner), not the plan body. So amend re-emits the artifact unchanged (only bump `last_updated`), exactly the "selects nothing" branch; it does **NOT** manufacture `risks:` edits for the demotion and does **NOT** invoke the two resolve moves of the failed-ruling hard rule below (which govern only `pass: false` rulings). The re-grade — with the evidence-duty prompt — addresses the citation format; the demotion is a signal to select the verdict, not a plan defect to fix.
48
48
  - **Resolve a failed risk ruling, don't re-assert it.** When a grade/validate panel ruled a plan risk flag `fail`, amend may close it ONLY one of two ways: (a) **resolve-verified-against-code** — ground the mechanism against the cited `file:line` in the real code and fix the plan's `claim` to match verified reality (then re-grade confirms it); or (b) **attach `verify-at-implement`** — edit the risk flag to add a concrete `procedure` (named command/test) + `owner` phase that will discharge it. Never re-emit the risk as a bare, still-unverified mechanism assertion — the gate demotes an un-evidenced mechanics pass and rejects a procedure-less deferral, so a bare re-assertion just re-fails.
49
- - **Surgical, not wholesale.** Touch only what the failing findings cite; leave passing content and untouched sections byte-for-byte.
49
+ - **Surgical, not wholesale.** Touch only what the selected findings cite; leave passing content and untouched sections byte-for-byte.
50
50
  - **Fix the artifact, never the repo.** Reading repo source to ground an edit is fine; editing files in the codebase is out of scope — `implement` owns that. **Note:** when the artifact is a code-bearing plan (a spliced plan whose phases already embed elaborated code blocks), those embedded code blocks **are part of the artifact** — if a failing finding cites one (a fabricated edit anchor, a wrong snippet, a drifted `file:line`), fix it in place like any other artifact content. The boundary is the repo working tree, not the plan's own fenced code.
51
51
  - **Re-emit in place.** Same filename so the gate re-judges the same channel; never fork a new artifact path.
52
52
  - **No subagents. No self-review. No `ask_user_question`.** Apply the verdicts and re-emit; the grade panel is the validation.
@@ -15,6 +15,10 @@ contract:
15
15
  properties:
16
16
  status:
17
17
  enum: [in-progress, in-review, ready]
18
+ # Derived from the path + frontmatter by the build workflow's design parser, never authored:
19
+ # `matches` iff the basename's `_slice-<N>_` token equals `slice_n`.
20
+ filename_slice:
21
+ enum: [matches]
18
22
  consumes:
19
23
  meta:
20
24
  artifactKind: [slices, design]
@@ -110,6 +114,7 @@ tags: [design, slice]
110
114
  ## Hard rules
111
115
 
112
116
  - **One slice only.** Never design or touch work that the slice map assigns to a different slice.
117
+ - **The path carries the slice.** The basename's `_slice-<N>_` segment is mandatory and must equal `slice_n` — the workflow resolves which slice a design belongs to from both, and a title that happens to look like an ID (`LV-2`, `DT-1`) never substitutes for it.
113
118
  - **Code shape, not implementation.** Interfaces, file map, decisions — `implement` writes the actual code later.
114
119
  - **No discovery/analysis subagents. No self-review.** Read the files the slice names; decide; write. Ask only to clear a genuine blocking fork.
115
120
  - **Build against decided upstream contracts.** When `--upstream` designs are provided, consume their `## Key Interfaces` as fixed — never redesign a dependency's contract. If a contract you depend on is undecided (parked in the upstream's `## Notes / Deferred`), escalate (Step 5), don't guess.
@@ -15,6 +15,11 @@ contract:
15
15
  properties:
16
16
  status:
17
17
  enum: [in-progress, in-review, ready]
18
+ # Derived from the body by the build workflow's elaboration parser, never authored.
19
+ fence_walk:
20
+ enum: [balanced]
21
+ phase_headings:
22
+ enum: [1]
18
23
  consumes:
19
24
  meta:
20
25
  artifactKind: [plan]
@@ -47,7 +52,7 @@ Copy values verbatim. `<iso>` is the first tab-separated field (use as `date`);
47
52
 
48
53
  ## Steps
49
54
 
50
- 1. **Read the plan fully** (no limit/offset). Note its `## Synthesis Notes` (the reconciled seams — conflict resolutions, shared locals, integration order) and locate the `## Phase N:` section you own: its `### Changes` (the files/symbols to touch) and its `### Success Criteria`. Skim the **other** phases' sections too — to know what they own and what interfaces they expose — but never implement them.
55
+ 1. **Read the plan fully** (no limit/offset). Note its `## Synthesis Notes` (the reconciled seams — conflict resolutions, shared locals, integration order) and locate the `## Phase N:` section you own: its `### Changes` (the files/symbols to touch) and its `### Success Criteria`. Skim the **other** phases' sections too — to know what they own and what interfaces they expose — but never implement them. The plan's trailing `## Whole-Plan Verification` block (when present) is not part of any phase's section — no phase owns it.
51
56
  2. **Ground in the live code.** For every file the phase's `### Changes` names, Read/Grep the cited `path:line` in the **current** tree. The plan may have been written against a slightly older state — anchor the code you write to what is actually there now (signatures, imports, surrounding style). Files owned by a **sibling phase** are the exception: never Read, Grep, or wait for them on disk — sibling lanes create them concurrently, so they may not exist yet, and an ENOENT on a sibling-owned path is expected, never a retry. Their interfaces come from the plan's Synthesis Notes and the sibling's phase section (Step 3).
52
57
  3. **Write the code for this phase only.** For each file in the phase's Changes, emit a concrete, paste-ready code block: the full function/section to add, or the exact edit (enough that `implement` applies it without guessing). Match the surrounding code's conventions. Where the phase depends on a sibling phase's symbol, reference it by the shape the plan/Synthesis Notes already fixed — do not redefine it.
53
58
  4. **Carry the success criteria.** Preserve the phase's `### Success Criteria` (Automated + Manual), tightening a check only if your code makes it more concrete. Do not drop or weaken a criterion.
@@ -71,7 +76,7 @@ Path: `.rpiv/artifacts/elaborations/<plan-basename>__phase-<N>.md`, where `<plan
71
76
 
72
77
  The body **must** contain exactly one `## Phase <N>: <title>` section — verbatim heading text matching the plan (same `N`, same title). The `stitch-elaborations` script swaps the plan's `## Phase N:` section for this one, so the heading is the splice anchor: do not rename it or change `N`.
73
78
 
74
- ```markdown
79
+ ````markdown
75
80
  ---
76
81
  date: <iso>
77
82
  author: <author>
@@ -110,14 +115,16 @@ tags: [elaboration]
110
115
 
111
116
  ## Notes / Deferred
112
117
  <only if a blocker forced an assumption — otherwise omit this section>
113
- ```
118
+ ````
114
119
 
115
120
  ## Hard rules
116
121
 
117
122
  - **One phase only.** Never write code for a file another phase owns; reference its interfaces by the shape `synthesize` already fixed.
123
+ - **Never carry the plan's trailing `## Whole-Plan Verification` block into your elaboration doc.** No phase owns it; the stitch strips it from the last phase's span and re-emits it itself (authored verbatim, or derived from the AV items) — a lane that spliced it back in would duplicate the block.
118
124
  - **Implement-ready code, grounded in the current tree.** Read the cited files first; emit code blocks, not prose hand-waving ("handle appropriately", "etc.").
119
125
  - **Repo-root-relative citations, from what you read.** Every `file:line` your elaboration emits — in prose or in code comments — uses the **repo-root-relative** path (`packages/billing/src/invoice.ts:NN`), never a subdirectory-relative form (`src/invoice.ts:NN`) or a bare basename, and comes from a file you actually read; if you're unsure of the line, cite the path alone and omit the `:line`.
120
126
  - **Body is exactly one `## Phase N: <title>` section** with the verbatim heading — the deterministic splice folds it back by phase number. Don't rename the heading or change `N`.
127
+ - **A fence that wraps other fences is longer than them.** A block whose content itself contains ``` lines — an embedded markdown or guidance file, a doc edit with examples — opens and closes with four backticks (````). A bare ``` inside a ``` block closes it, the leaked fence swallows the next phase's heading at the splice, and the stitch refuses the elaboration.
121
128
  - **Write the doc, not the code.** You only write your elaboration artifact; reading the codebase to ground the code is required, editing it is out of scope — `implement` applies the code later, after the splice. The Self-check step's tree mutation is the ONE exception: a transient, reverted probe that applies drafted blocks to verify them, then reverts byte-identical — it never leaves the edit for `implement` (the elaboration doc carries the code; the tree returns clean).
122
129
  - **Byte-identical self-check revert (the sole parallel-safety contract).** The Self-check `git restore <tracked> + rm -f <new>` MUST return the tree to a `git status --porcelain` byte-identical pre-probe snapshot; any residue is a blocking error and the unit emits nothing. Under the parallel phase fanout a sibling unit's in-flight edit can surface as cross-file check noise — attribute ONLY errors in YOUR write-set and revert past the rest.
123
130
  - **Per-phase write-scope.** Each unit applies and reverts ONLY the files its phase's `### Changes` names — the same write-scope discipline `implement`'s single-phase mode follows. Never probe, edit, or revert a file another phase owns. A declared production file's co-located test twin (e.g. `x.ts` → `x.test.ts`) is inside the phase's write-scope automatically — the scope floor and the implement DAG both twin-expand `files:` — so a mechanical twin follow-up (mock arity, call-site signature) needs no scope-addition note; only a NON-twin file outside the phase's `files:` is a scope change worth flagging.