@juicesharp/rpiv-pi 2.2.0 → 2.3.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.
@@ -16,8 +16,7 @@
16
16
 
17
17
  import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
18
18
 
19
- import type { LaneUsage } from "./lane-usage.js";
20
- import { toLaneUsage } from "./lane-usage.js";
19
+ import { addLaneUsage, type LaneUsage, toLaneUsage } from "./lane-usage.js";
21
20
  import { emitQuestionAsked, emitQuestionResolved } from "./question-lifecycle.js";
22
21
 
23
22
  /** Lane status taxonomy — mirrors rpiv-workflow's RunTermination.status (types.ts:145-149). */
@@ -182,6 +181,14 @@ export interface LaneEntry {
182
181
  * generation only; the final generation's snapshots survive retirement.
183
182
  */
184
183
  readonly units: Map<number, UnitLane>;
184
+ /** Per-stage orchestrator token usage, keyed by stage name in execution (insertion)
185
+ * order. Folded by `foldStageUsage` at each stage transition (BEFORE `clearUnitLanes`
186
+ * empties `units`), so a completed stage's tokens survive even though its units are
187
+ * gone. The CURRENT running stage's tokens are NOT yet folded — they read live off
188
+ * `units` at render time (`renderStageBreakdown`). Survives resume reactivation
189
+ * (`recordRun` clears `units`, not this). Never mixed with subagent tokens
190
+ * (`subagent-usage.ts`) — unified only at render time. */
191
+ readonly stageUsage: Map<string, LaneUsage>;
185
192
  /** Live stage progress; undefined until the first onStageStart. */
186
193
  progress: LaneProgress | undefined;
187
194
  /**
@@ -191,6 +198,17 @@ export interface LaneEntry {
191
198
  * full. Absent for a `completed` run (no error) and while still running.
192
199
  */
193
200
  error?: string;
201
+ /**
202
+ * Primary artifact path at run termination — `RunWorkflowResult.lastArtifact`
203
+ * captured at `retireRun` (the runner's terminal `onWorkflowEnd`), so a completed
204
+ * lane row can surface `→ .rpiv/artifacts/<bucket>/<file>.md` as a trailing
205
+ * segment. Undefined for a side-effect-only run (no `produces` stage emitted a
206
+ * primary artifact) and for aborted/failed runs (the terminal writers pass ≤3
207
+ * args). Cleared on resume (`recordRun` reactivation) so a resumed run never
208
+ * leaks the prior run's path — mirroring the `error`/`progress`/`needsInputSince`
209
+ * clears.
210
+ */
211
+ lastArtifact?: string;
194
212
  /**
195
213
  * When this lane first started waiting on a deferred foreground question
196
214
  * — `Date.now()` stamped on the FIRST enqueue that finds the clock
@@ -298,6 +316,7 @@ export function recordRun(runId: string, name: string, meta?: { workflow?: strin
298
316
  }
299
317
  existing.units.clear(); // drop the prior run's per-unit sessions + terminal snapshots
300
318
  existing.error = undefined; // clear the prior run's terminal failure reason
319
+ existing.lastArtifact = undefined; // clear the prior run's primary artifact path
301
320
  existing.progress = undefined; // clear stale stage progress
302
321
  existing.needsInputSince = undefined; // clear any stale needs-input clock
303
322
  } else {
@@ -308,6 +327,7 @@ export function recordRun(runId: string, name: string, meta?: { workflow?: strin
308
327
  input: meta?.input,
309
328
  status: "running",
310
329
  units: new Map<number, UnitLane>(),
330
+ stageUsage: new Map<string, LaneUsage>(),
311
331
  progress: undefined,
312
332
  });
313
333
  }
@@ -393,7 +413,12 @@ function captureSnapshotInto(unit: UnitLane, session: LaneSession): void {
393
413
  }
394
414
  }
395
415
 
396
- export function retireRun(runId: string, status: Exclude<LaneStatus, "running">, error?: string): void {
416
+ export function retireRun(
417
+ runId: string,
418
+ status: Exclude<LaneStatus, "running">,
419
+ error?: string,
420
+ lastArtifact?: string,
421
+ ): void {
397
422
  const entry = state().lanes.get(runId);
398
423
  if (!entry) return;
399
424
  // Idempotent: FIRST retire wins. A lane can be retired by more than one path —
@@ -407,6 +432,7 @@ export function retireRun(runId: string, status: Exclude<LaneStatus, "running">,
407
432
  if (entry.status !== "running") return;
408
433
  entry.status = status;
409
434
  if (error !== undefined) entry.error = error; // terminal failure reason
435
+ if (lastArtifact !== undefined) entry.lastArtifact = lastArtifact; // primary artifact path (completed runs)
410
436
  // Capture units with a parked question BEFORE the settle loop clears pendingInput,
411
437
  // so each affected unit is addressable for a `cleared` emit after notify().
412
438
  const cleared: number[] = [];
@@ -438,11 +464,35 @@ export function retireRun(runId: string, status: Exclude<LaneStatus, "running">,
438
464
  * (with `currentSession` already gone), the snapshot is already in place. Best-effort:
439
465
  * a missing/evicted lane is a no-op. Does NOT notify — the paired `setCurrentSession`
440
466
  * that immediately follows in the host does.
467
+ *
468
+ * Capture-side fold-at-overwrite: a sequential multi-child stage parks EVERY child
469
+ * on the SAME `SINGLE_UNIT_KEY` slot, so `captureSnapshotInto`'s `finalUsage =`
470
+ * overwrite would evict each OUTGOING child's tokens before the stage-end
471
+ * `foldStageUsage` can count them (losing all but the last). Fold the unit's
472
+ * already-parked `finalUsage` (the outgoing child) into the CURRENT stage bucket
473
+ * BEFORE the overwrite; the overwrite then EVICTS it from the slot, so
474
+ * `foldStageUsage` cannot re-count it. Capture-time (children 1..N-1) and stage-end
475
+ * (surviving last child N) touch disjoint sets → fold-exactly-once, no double-count.
476
+ * Fail-soft by composition: no parked `finalUsage` (first capture / a failed
477
+ * getUsage) skips the fold, and `addStageUsage`'s own guard drops an unset
478
+ * stageName (pre-first-stage capture). Usage-only — `finalBranch`/`finalCwd`/
479
+ * `finalToolDefs` stay last-writer-wins across the overwrite.
480
+ *
481
+ * The fold is gated on a LIVE lane (`status === "running"`): the dock's optimistic
482
+ * `x` cancel calls `retireRun` BEFORE this teardown capture, and retire's own
483
+ * snapshot parks the SAME still-live child's usage onto the slot — so the parked
484
+ * value here is a same-child re-capture, not an outgoing sibling. Folding it would
485
+ * count the child twice (once in the bucket, once via the retained unit at render).
486
+ * Post-retirement the overwrite-only path is exactly right.
441
487
  */
442
488
  export function captureFinalSnapshot(runId: string, index: number, session: LaneSession): void {
443
489
  const entry = state().lanes.get(runId);
444
490
  if (!entry) return;
445
- captureSnapshotInto(upsertUnit(entry, index), session);
491
+ const unit = upsertUnit(entry, index);
492
+ if (unit.finalUsage && entry.status === "running") {
493
+ addStageUsage(runId, entry.progress?.stageName, unit.finalUsage);
494
+ }
495
+ captureSnapshotInto(unit, session);
446
496
  }
447
497
 
448
498
  /**
@@ -565,6 +615,32 @@ export function clearUnitLanes(runId: string): void {
565
615
  for (const idx of cleared) emitQuestionResolved(runId, idx, "cleared");
566
616
  }
567
617
 
618
+ /** Pairwise-accumulate one stage's usage into the `stageUsage` bucket for `runId` +
619
+ * `stageName` via `addLaneUsage` (so a re-folded stage SUMS, never overwrites). No-op
620
+ * on undefined usage / missing lane / undefined stageName — a pre-first-stage fold, or a
621
+ * lane with no live progress, records nothing. Does NOT notify (the paired
622
+ * `clearUnitLanes`/`setLaneProgress` that follows in the bridge does). */
623
+ export function addStageUsage(runId: string, stageName: string | undefined, usage: LaneUsage | undefined): void {
624
+ if (usage === undefined || stageName === undefined) return;
625
+ const entry = state().lanes.get(runId);
626
+ if (!entry) return;
627
+ const existing = entry.stageUsage.get(stageName);
628
+ entry.stageUsage.set(stageName, existing ? addLaneUsage(existing, usage)! : usage);
629
+ }
630
+
631
+ /** Fold the CURRENT stage's per-unit orchestrator tokens into its `stageUsage` bucket.
632
+ * Reads the OUTGOING stage name off `progress.stageName` (the bridge calls this BEFORE
633
+ * `setLaneProgress` flips to the next name and BEFORE `clearUnitLanes` empties `units`),
634
+ * then folds each unit's effective `unitUsage` (teardown snapshot else live child) into
635
+ * that stage's bucket via `addStageUsage`. No-op when the stage name is unset or `units`
636
+ * is empty. Does NOT notify — the paired `clearUnitLanes`/`setLaneProgress` does. */
637
+ export function foldStageUsage(runId: string): void {
638
+ const lane = state().lanes.get(runId);
639
+ const stageName = lane?.progress?.stageName;
640
+ if (!lane || stageName === undefined || lane.units.size === 0) return;
641
+ for (const unit of lane.units.values()) addStageUsage(runId, stageName, unitUsage(unit));
642
+ }
643
+
568
644
  /** Seed the CURRENT fan-out generation's unit sub-rows as PENDING (bridge `onLoopStart`
569
645
  * for a fanout): each declared unit's sub-lane is created FRESH with `status: "pending"`
570
646
  * keyed by its declared array `index`, so the dock fans out the generation the instant
@@ -37,7 +37,9 @@ import type { Model } from "@earendil-works/pi-ai";
37
37
  import {
38
38
  type AgentSession,
39
39
  createAgentSession,
40
+ createEventBus,
40
41
  DefaultResourceLoader,
42
+ type EventBus,
41
43
  type Extension,
42
44
  type ExtensionUIContext,
43
45
  getAgentDir,
@@ -53,7 +55,14 @@ import { armBashWatchdog, type BashWatchdog } from "./bash-timeout.js";
53
55
  import { createLaneRelayUiContext } from "./lane-relay-ui.js";
54
56
  import { createLaneSessionView } from "./lane-streaming.js";
55
57
  import { harvestToolDefs } from "./lane-tool-defs.js";
56
- import { captureFinalSnapshot, SINGLE_UNIT_KEY, setCurrentSession, setLaneSessionFile } from "./run-lane-registry.js";
58
+ import {
59
+ captureFinalSnapshot,
60
+ getLane,
61
+ SINGLE_UNIT_KEY,
62
+ setCurrentSession,
63
+ setLaneSessionFile,
64
+ } from "./run-lane-registry.js";
65
+ import { recordSubagentCompletion } from "./subagent-usage.js";
57
66
 
58
67
  /**
59
68
  * Launcher-only "ambient observer" extensions: they register session-lifecycle
@@ -265,7 +274,8 @@ export class SdkWorkflowHost implements WorkflowHostContext {
265
274
  throw new FanoutDepthExceededError(depth, MAX_FANOUT_DEPTH);
266
275
  }
267
276
 
268
- const resourceLoader = await this.buildChildResourceLoader();
277
+ const childEventBus = createEventBus();
278
+ const resourceLoader = await this.buildChildResourceLoader(childEventBus);
269
279
  const { session } = await createAgentSession({
270
280
  cwd: this.cwd,
271
281
  // Borrow ONLY the registry; authStorage is still defaulted per child
@@ -310,6 +320,23 @@ export class SdkWorkflowHost implements WorkflowHostContext {
310
320
  // aborts this child and records a reason `adapt` surfaces via `toolTimeout`, so the
311
321
  // runner soft-halts the unit instead of letting a runaway command strand the gate.
312
322
  const watchdog = armBashWatchdog(session);
323
+ // Subagent token capture: pi-subagents runs each subagent under its own
324
+ // `SessionManager.inMemory(...)` session, so its tokens NEVER reach the
325
+ // orchestrator child's `getSessionStats()`. It emits `subagents:completed` —
326
+ // or `subagents:failed` for error/stopped/aborted agents, SAME payload shape
327
+ // (carrying `{ tokens: { input, output, total } }`) — on the child's OWN
328
+ // eventBus (the one threaded into the resource loader above → `api.events`),
329
+ // so subscribing here attributes each terminal event to this run + the
330
+ // registry's current `progress.stageName` with zero cross-talk between
331
+ // concurrent children. BOTH channels are captured: a subagent that burns
332
+ // tokens and then errors still spent them. Best-effort capture: a
333
+ // missing/malformed `tokens` is a no-op (handled in
334
+ // `recordSubagentCompletion`). Disposed in the finally below so a torn-down
335
+ // child's bus emits no longer mutate the accumulator.
336
+ const recordSubagentTokens = (data: unknown) =>
337
+ recordSubagentCompletion(this.deps.runId, getLane(this.deps.runId)?.progress?.stageName, data);
338
+ const offSubagents = childEventBus.on("subagents:completed", recordSubagentTokens);
339
+ const offSubagentsFailed = childEventBus.on("subagents:failed", recordSubagentTokens);
313
340
  try {
314
341
  // Every child binds the DEFERRING relay: a floated run's stage queues +
315
342
  // badges its questionnaire instead of grabbing the (possibly hidden) real UI;
@@ -323,6 +350,8 @@ export class SdkWorkflowHost implements WorkflowHostContext {
323
350
  return await options.withSession(this.adapt(session, depth, watchdog));
324
351
  } finally {
325
352
  watchdog.dispose(); // unsubscribe + clear pending timers before the session tears down.
353
+ offSubagents(); // stop capturing subagent terminal events for this torn-down child's bus…
354
+ offSubagentsFailed(); // …on BOTH channels (completed + failed).
326
355
  options.signal?.removeEventListener("abort", onAbort);
327
356
  // Each unit owns its own registry key, so a sibling's teardown can NEVER clobber
328
357
  // another's entry — the `currentSession === laneView` slot-owner guard (the
@@ -352,13 +381,20 @@ export class SdkWorkflowHost implements WorkflowHostContext {
352
381
  * `LoadExtensionsResult` carries a shared `runtime`, so reusing one loader
353
382
  * across concurrent children would cross-wire their extension runtimes.
354
383
  */
355
- private async buildChildResourceLoader(): Promise<DefaultResourceLoader> {
384
+ private async buildChildResourceLoader(eventBus: EventBus): Promise<DefaultResourceLoader> {
356
385
  const agentDir = getAgentDir();
357
386
  const resourceLoader = new DefaultResourceLoader({
358
387
  cwd: this.cwd,
359
388
  agentDir,
360
389
  settingsManager: SettingsManager.create(this.cwd, agentDir),
361
390
  extensionsOverride: withoutAmbientExtensions,
391
+ // A PER-CHILD eventBus: the resource loader stores this (`this.eventBus`),
392
+ // hands it to every loaded extension factory (`loadExtensionFromFactory(…, eventBus)`
393
+ // → `createExtensionAPI(…, eventBus)` → `api.events = eventBus`), so a child's
394
+ // extensions — including pi-subagents — `pi.events.emit`/`on` against THIS bus.
395
+ // Subscribing on it below attributes each `subagents:completed` to this child's
396
+ // run + current stage with zero cross-talk between concurrent fan-out children.
397
+ eventBus,
362
398
  });
363
399
  await resourceLoader.reload();
364
400
  return resourceLoader;
@@ -0,0 +1,147 @@
1
+ /**
2
+ * subagent-usage — the process-global accumulator of subagent token usage,
3
+ * keyed `runId → stageName → LaneUsage`.
4
+ *
5
+ * Subagents (pi-subagents) each run under their own `SessionManager.inMemory(...)`
6
+ * session, so their tokens NEVER reach the orchestrator child's
7
+ * `AgentSession.getSessionStats()` (the lane tally's source). The only structured
8
+ * source of subagent tokens is the terminal EventBus event pi-subagents emits —
9
+ * `subagents:completed`, or `subagents:failed` for error/stopped/aborted agents,
10
+ * both carrying the same `{ …, tokens: { input, output, total } }` payload shape.
11
+ * The host subscribes to BOTH: a subagent that burns tokens and then dies still
12
+ * spent them.
13
+ *
14
+ * `sdk-workflow-host.ts` wires a PER-CHILD eventBus into each child's
15
+ * `DefaultResourceLoader({ eventBus })`, so the bus an extension sees as `pi.events`
16
+ * is the one the host created for that child — every loaded extension factory is
17
+ * handed that same bus (`createExtensionAPI(…, eventBus)` → `api.events = eventBus`).
18
+ * Subscribing on the child's own bus attributes each completion to the host's
19
+ * `runId` + the registry's current `progress.stageName` with zero cross-talk between
20
+ * concurrent fan-out children (no "single active run" assumption).
21
+ *
22
+ * Token-source partitioning (cross-phase invariant): subagent tokens live HERE,
23
+ * per-stage orchestrator tokens live on `LaneEntry.stageUsage`. They are
24
+ * NEVER mixed in storage — unified only at render time (`laneUsageTotal` /
25
+ * `renderStageBreakdown` / the lane roll-in). Folding orchestrator tokens in here
26
+ * would double-count.
27
+ *
28
+ * `cacheRead` is forced to `0` (pi-subagents deliberately excludes it — each turn's
29
+ * cacheRead is the cumulative cached prefix re-read, so summing counts the prefix N
30
+ * times; pi-subagents issue #38). `cacheWrite` is recovered as `max(0, total − input
31
+ * − output)` since the payload omits it. A missing/malformed `tokens` is a no-op.
32
+ *
33
+ * Mirrors `run-lane-registry.ts`'s process-global slot discipline: a
34
+ * `globalThis[Symbol.for("@juicesharp/rpiv-pi:subagentUsage")]` slot (NOT a
35
+ * module-level variable) so every re-loaded rpiv-pi instance shares ONE accumulator.
36
+ * `__resetSubagentUsage` clears it in place (slot identity preserved) and is wired
37
+ * into `test/setup.ts` beforeEach.
38
+ */
39
+
40
+ import { addLaneUsage, type LaneUsage } from "./lane-usage.js";
41
+
42
+ /** A minimal structural view of a `subagents:completed` payload, used only for
43
+ * defensive narrowing. Typed loose so the module imports no pi-subagents type. */
44
+ interface SubagentCompletedPayload {
45
+ tokens?: {
46
+ input?: unknown;
47
+ output?: unknown;
48
+ total?: unknown;
49
+ };
50
+ }
51
+
52
+ const isFiniteNumber = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
53
+
54
+ interface SubagentState {
55
+ /** runId → (stageName → accumulated LaneUsage). The outer key is the host run;
56
+ * the inner key is the registry's `progress.stageName` at completion time. */
57
+ readonly runs: Map<string, Map<string, LaneUsage>>;
58
+ }
59
+
60
+ const SUBAGENT_SLOT = Symbol.for("@juicesharp/rpiv-pi:subagentUsage");
61
+
62
+ /** Read the single process-global subagent accumulator, lazily creating it. */
63
+ function state(): SubagentState {
64
+ const g = globalThis as Record<symbol, unknown>;
65
+ let s = g[SUBAGENT_SLOT] as SubagentState | undefined;
66
+ if (s === undefined) {
67
+ s = { runs: new Map<string, Map<string, LaneUsage>>() };
68
+ g[SUBAGENT_SLOT] = s;
69
+ }
70
+ return s;
71
+ }
72
+
73
+ /**
74
+ * Narrow a raw `subagents:completed` payload into a `LaneUsage` defensively:
75
+ * `cacheRead = 0` (pi-subagents excludes it — issue #38), `cacheWrite = max(0,
76
+ * total − input − output)` (the payload omits it), `total` taken from the source.
77
+ * A missing/malformed `tokens` (or non-finite fields) returns `undefined` — the
78
+ * caller treats that as a no-op (never throws, never records a NaN).
79
+ */
80
+ function narrowSubagentTokens(payload: unknown): LaneUsage | undefined {
81
+ if (typeof payload !== "object" || payload === null) return undefined;
82
+ const t = (payload as SubagentCompletedPayload).tokens;
83
+ if (typeof t !== "object" || t === null) return undefined;
84
+ const input = t.input;
85
+ const output = t.output;
86
+ const total = t.total;
87
+ if (!isFiniteNumber(input) || !isFiniteNumber(output) || !isFiniteNumber(total)) return undefined;
88
+ const cacheWrite = Math.max(0, total - input - output);
89
+ return { input, output, cacheRead: 0, cacheWrite, total };
90
+ }
91
+
92
+ /**
93
+ * Record one subagent terminal event's tokens (`subagents:completed` OR
94
+ * `subagents:failed` — same payload shape) against a run + stage. Synchronous RMW
95
+ * is race-free under concurrent children (Node single-threaded `on` callbacks).
96
+ * A `undefined` stageName records nothing (the host can't attribute a completion
97
+ * before the first `onStageStart`); a missing/malformed `tokens` payload is a
98
+ * no-op. Subsequent completions for the SAME run+stage are pairwise-accumulated
99
+ * via `addLaneUsage` so a multi-subagent stage sums rather than overwrites.
100
+ */
101
+ export function recordSubagentCompletion(runId: string, stageName: string | undefined, payload: unknown): void {
102
+ if (stageName === undefined) return;
103
+ const usage = narrowSubagentTokens(payload);
104
+ if (!usage) return;
105
+ const { runs } = state();
106
+ let stages = runs.get(runId);
107
+ if (!stages) {
108
+ stages = new Map<string, LaneUsage>();
109
+ runs.set(runId, stages);
110
+ }
111
+ const existing = stages.get(stageName);
112
+ // Both `existing` and `usage` are defined here (usage guarded above; existing by
113
+ // the truthy branch), so addLaneUsage's contract ("undefined only when BOTH absent")
114
+ // guarantees a defined result — the assertion is contract-backed, not speculative.
115
+ stages.set(stageName, existing ? addLaneUsage(existing, usage)! : usage);
116
+ }
117
+
118
+ /**
119
+ * The summed subagent usage for an entire run, across every stage that recorded a
120
+ * completion. Returns `undefined` when no completion was ever recorded for the run
121
+ * (so a run with no subagents renders byte-identical to before this module existed).
122
+ */
123
+ export function getSubagentUsageForRun(runId: string): LaneUsage | undefined {
124
+ const stages = state().runs.get(runId);
125
+ if (!stages || stages.size === 0) return undefined;
126
+ let acc: LaneUsage | undefined;
127
+ for (const usage of stages.values()) acc = acc ? addLaneUsage(acc, usage) : usage;
128
+ return acc;
129
+ }
130
+
131
+ /**
132
+ * The accumulated subagent usage for ONE stage of a run, or `undefined` when no
133
+ * completion was ever recorded for that run+stage. Mirrors `getSubagentUsageForRun`
134
+ * but scoped to a single stage — consumed by `renderStageBreakdown` so a
135
+ * stage's subagent contribution folds into its per-stage tally alongside its
136
+ * orchestrator tokens.
137
+ */
138
+ export function getSubagentUsageForStage(runId: string, stageName: string): LaneUsage | undefined {
139
+ return state().runs.get(runId)?.get(stageName);
140
+ }
141
+
142
+ /** Test reset — wired into `test/setup.ts` beforeEach. Clears every run/stage map
143
+ * IN PLACE so the process-global slot identity is preserved across resets. */
144
+ export function __resetSubagentUsage(): void {
145
+ const s = state();
146
+ s.runs.clear();
147
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-pi",
3
- "version": "2.2.0",
4
- "description": "A skill-based development workflow for Pi Agent. 27 contract-carrying skills (discover → research → design → plan → implement → validate → code-review → commit, and more), the 15 named subagents they dispatch, and five built-in /wf workflows that chain them end to end in detached parallel runs.",
3
+ "version": "2.3.0",
4
+ "description": "A skill-based development workflow for Pi Agent. 27 contract-carrying skills (discover → research → design → plan → implement → validate → code-review → commit, and more), the 15 named subagents they dispatch, and three built-in /wf workflows that chain them end to end in detached parallel runs.",
5
5
  "keywords": [
6
6
  "pi-package",
7
7
  "pi-extension",
@@ -49,7 +49,7 @@
49
49
  ]
50
50
  },
51
51
  "dependencies": {
52
- "@juicesharp/rpiv-config": "^2.2.0",
52
+ "@juicesharp/rpiv-config": "^2.3.0",
53
53
  "typebox": "^1.1.24"
54
54
  },
55
55
  "peerDependencies": {
@@ -374,7 +374,7 @@ Use the `ask_user_question` tool to confirm. Question: "Slice {N/M}: {slice name
374
374
 
375
375
  **Write-scope rule (per-phase, mandatory before parallel implement):** every command in a phase's `#### Automated Verification:` block must be **write-scoped to that phase's own `files:` set** — running it must not modify anything outside the phase's `files:`. Phases run concurrently under build's parallel implement lane, so a command that rewrites the wider tree corrupts a sibling phase's in-flight edit; narrow any formatter or auto-fixer to the phase's paths (take the project's command vocabulary from its guidance `# Commands` table — where the table gives only an unscoped form, narrow it to the phase's paths rather than substituting a different tool). Read-only repo-wide commands (a type check, a non-fixing lint, a scoped test selection) are permitted. Whole-repo build/test verification belongs to the plan's final whole-plan block, owned by `validate` — never to a phase.
376
376
 
377
- **Exit-0 contract (the `reconcile` stage re-runs AV lines verbatim):** after implement, `reconcile` re-executes the FIRST backtick span of every `- [ ]` line in `#### Automated Verification:` via `execFileSync` — arg-array (no shell: no `|`/`&&`/redirection), stdin ignored, exit 0 the ONLY pass signal. Prose around the span never executes, and a non-zero exit halts the run with no fix arm. So every AV line must be ONE self-contained command that exits 0 exactly when the criterion holds: name the target file INSIDE the span (never "over `<file>`" in prose — the command then greps an empty stdin and always fails); never assert absence ("returns nothing" — grep exits 1 on no match, so that line can ONLY fail; restate it to exit 0 on success, e.g. a `node -e` probe that inverts the check, or move it to `#### Manual Verification:`); never rely on prose expected counts ("returns `4`" — fold the assertion into the command itself); never point a formatter at paths outside its configured scope (Biome on a doc-only phase's `.md` exits non-zero with "No files were processed"). The `plan-cite-check`/`code-cite-check` floor lints these shapes and routes violations into a plan-fix round; anything it cannot catch statically still kills the run at `reconcile`.
377
+ **Who runs AV lines:** `implement` runs each phase's own `#### Automated Verification:` commands in its shell and flips the checkboxes; `validate` re-runs them agent-side over the whole finished plan. Both are agents with a real shell and judgment — no deterministic harness re-executes these lines. Still prefer ONE self-contained command per line that exits 0 when the criterion holds, with the target path inside the backtick span; prose around the span is context for the agent, not executed syntax. Remember AV lines are written before sibling phases land: a check asserting another phase's rename target or source may be true at phase time and false on the final tree — scope each line to what YOUR phase owns.
378
378
 
379
379
  5. Update the Plan History section: `- Phase N: {name} — approved as generated`
380
380
  6. Decrement frontmatter `unresolved_phase_count` by 1
@@ -234,5 +234,5 @@ These reinforce the critical rules from the steps above — listed here so they
234
234
  - ALWAYS terminate on depth signal, not bucket-fill (Step 5)
235
235
  - ALWAYS synthesize from the interview log, never from memory of the conversation (Step 6)
236
236
  - NEVER skip the developer-facing interview — it's the entire point of this skill
237
- - NEVER ask a final "looks good / want to adjust" rubber-stamp question (anti-pattern per `a93e591`)
237
+ - NEVER ask a final "looks good / want to adjust" rubber-stamp question (anti-pattern per prior regressions)
238
238
  - NEVER dispatch agents before Step 2's `intent` question is answered
@@ -2,7 +2,7 @@
2
2
  name: elaborate
3
3
  description: Write implement-ready code into ONE phase of a synthesized plan — read the whole plan plus the real code the phase touches, then emit a code-bearing replacement for that single `## Phase N:` section to .rpiv/artifacts/elaborations/. Single-pass, no subagents, no self-review, no questions. Dispatched once per phase by an elaborate fanout after synthesize; the per-phase elaborations are folded back into the plan by the deterministic `stitch-elaborations` script, and the grade panel judges the stitched plan. Use as a fanout unit, not standalone.
4
4
  argument-hint: "<plan-path> Phase N: <title>"
5
- allowed-tools: Read, Edit, Write, Grep, Glob, Bash(git restore *), Bash(git checkout *), Bash(git status*), Bash(rm *), Bash(npx tsc *), Bash(npm run check:files *), Bash(npx biome check *), Bash(node *)
5
+ allowed-tools: Read, Edit, Write, Grep, Glob, Bash
6
6
  shell-timeout: 10
7
7
  disable-model-invocation: true
8
8
  contract:
@@ -52,16 +52,16 @@ Copy values verbatim. `<iso>` is the first tab-separated field (use as `date`);
52
52
  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
53
  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.
54
54
  5. **Resolve ambiguity yourself.** Decide from the plan, the Synthesis Notes, and the real code. This skill is **non-interactive** — if a genuine blocker can't be settled from those inputs, make the most defensible call, record it under `## Notes / Deferred`, and let the grade panel catch a bad call. Do **not** ask the user (N lanes run concurrently).
55
- 6. **Self-check (probe → revert → guard).** Before emitting, verify the drafted code blocks actually apply and typecheck at their REAL placement — declaration-order / `const`-TDZ (TS2448/2454) and contract-routing defects only surface when a block lands at its true anchor, not an idealized layout. Define **write-scope** = the set of repo-root-relative paths the phase's `### Changes` names (the files below this step's emitted `#### \`...\`` headings); the whole self-check applies and reverts ONLY those paths so the `FRONTMATTER_PHASE_FANOUT` parallelism (`packages/rpiv-pi/extensions/rpiv-core/built-in-workflows.ts:229`) is preserved — never touch a sibling phase's files. The cycle is exactly:
55
+ 6. **Self-check (probe → revert → guard).** Before emitting, verify the drafted code blocks actually apply and pass the project's checks at their REAL placement — declaration-order / initialization-order and integration defects only surface when a block lands at its true anchor, not an idealized layout. Define **write-scope** = the set of repo-root-relative paths the phase's `### Changes` names (the files below this step's emitted `#### \`...\`` headings); the whole self-check applies and reverts ONLY those paths — sibling phase lanes run concurrently in the same working tree, so touching a file another phase owns corrupts its in-flight edit. The cycle is exactly:
56
56
  - **Snapshot.** Capture `git status --porcelain` BEFORE the probe (the byte-identical revert target).
57
- - **Probe.** Apply each drafted code block via `Edit` at its REAL anchor position in the current file (not a speculative layout). New files named by the phase (`validate-workflow-invariant.mjs`/`.test.ts`) are written for the probe.
58
- - **Verify, in order, attributing only write-scope errors:**
59
- 1. `npx tsc --noEmit -p tsconfig.base.json` — a read-only repo-wide typecheck; attribute ONLY errors whose file path is in `write-scope` (sibling units' in-flight edits surface as cross-file noise — `c2r1` — and are NOT yours to act on; revert past them). Re-derive and fix drafted blocks from the attributed errors until clean.
60
- 2. `npm run check:files -- <write-scope files>` — scoped Biome (`--write --error-on-warnings`); may rewrite ONLY the write-scope paths it is given.
61
- 3. ONLY when `packages/rpiv-pi/extensions/rpiv-core/built-in-workflows.ts` is in `write-scope`: `node "${SKILL_DIR}/_helpers/validate-workflow-invariant.mjs"` — re-derives the live built-in workflows + contracts and surfaces any `route-reads-unvalidated-data` (or other) validation issue before emit.
57
+ - **Probe.** Apply each drafted code block via `Edit` at its REAL anchor position in the current file (not a speculative layout). New files named by the phase are written for the probe.
58
+ - **Verify, in order, attributing only write-scope errors.** Take the command vocabulary from the project's guidance `# Commands` table — never substitute a tool the project does not use:
59
+ 1. The project's **read-only whole-tree check** (type check, compile, or build — e.g. a no-emit typecheck, `cargo check`, `go build ./...`): attribute ONLY errors whose file path is in `write-scope` (sibling units' in-flight edits surface as cross-file noise and are NOT yours to act on; revert past them). Re-derive and fix drafted blocks from the attributed errors until clean. If the project records no such command, skip — the apply-at-anchor probe still validates placement.
60
+ 2. The project's **path-scoped auto-fix lint/format command** (the scoped form from the `# Commands` table), passed ONLY the write-scope paths — it may rewrite only those. Never run an unscoped auto-fixer: it rewrites sibling phases' in-flight edits.
61
+ 3. Any **project-specific invariant check** the guidance names for files in your write-scope (some projects register extra validators for load-bearing files) — run it as recorded there.
62
62
  - **Revert.** `git restore <tracked write-scope files>` (undo in-place `Edit`s) and `rm -f <newly-created files>` (undo new-file `Write`s) so the tree returns to its pre-probe state. The mutation is a TRANSIENT, reverted probe — the emitted elaboration doc is the only lasting output (`implement` applies the code later, after the splice).
63
63
  - **Guard.** `git status --porcelain` MUST equal the pre-probe snapshot byte-for-byte when you emit. ANY residue (a missed revert, an untracked file, a mode change) is a BLOCKING error: fail the elaboration, emit nothing, and surface the residue.
64
- - **Fix → re-emit.** From the attributed errors, fix the drafted code blocks in the elaboration; re-probe is optional, but emit ONLY blocks that passed (every block must have cleared its scoped `tsc` + `check:files`, and the workflow-invariant helper when applicable). A clean phase (no defect, no `built-in-workflows.ts`) still emits unchanged — the self-check is a no-op pass that reverts byte-identical.
64
+ - **Fix → re-emit.** From the attributed errors, fix the drafted code blocks in the elaboration; re-probe is optional, but emit ONLY blocks that passed every applicable check above. A clean phase still emits unchanged — the self-check is a no-op pass that reverts byte-identical.
65
65
  7. **Write the elaboration doc** (below), `status: ready`. Its filename pairs to the plan so the splice can fold it back deterministically — see Output document.
66
66
  8. **Print the path**, then a one-line summary: `Phase N elaborated: <k> files, <m> code blocks`.
67
67
 
@@ -90,15 +90,15 @@ tags: [elaboration]
90
90
 
91
91
  ### Changes
92
92
 
93
- #### `path/to/file.ts`
93
+ #### `path/to/file.ext`
94
94
  <one line: what and why>
95
- ```ts
95
+ ```<lang>
96
96
  <implement-ready code — the function/section to add, or the exact edit, grounded in the current file>
97
97
  ```
98
98
 
99
- #### `path/to/other.ts`
99
+ #### `path/to/other.ext`
100
100
  <one line>
101
- ```ts
101
+ ```<lang>
102
102
  <code>
103
103
  ```
104
104
 
@@ -119,6 +119,6 @@ tags: [elaboration]
119
119
  - **Repo-root-relative, verifiable citations.** 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 must be verifiable at the current revision: cite what you actually read; if you can't verify a line number, cite the path alone and omit the `:line`. Your elaboration is spliced into the plan and passes the deterministic `code-cite-check` floor — one unbacked or ambiguous citation fails the gate and buys the whole run a code-fix loop.
120
120
  - **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`.
121
121
  - **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
- - **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 `FRONTMATTER_PHASE_FANOUT` (`packages/rpiv-pi/extensions/rpiv-core/built-in-workflows.ts:229`) a sibling unit's in-flight edit can surface as cross-file `tsc` noise — attribute ONLY errors in YOUR write-set and revert past the rest.
123
- - **Per-phase write-scope.** Each unit applies and reverts ONLY the files its phase's `### Changes` names — the `packages/rpiv-pi/skills/implement/SKILL.md:77` discipline this slice adopts. Never probe, edit, or revert a file another phase owns.
122
+ - **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
+ - **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.
124
124
  - **No subagents. No self-review. No `ask_user_question`.** Decide, record any deferral in Notes, write — the grade panel is the validation.
@@ -73,7 +73,7 @@ You grade ONE artifact against ONE quality dimension and emit a verdict JSON. Yo
73
73
  Two duties tighten what a `pass` means, and the gate enforces both (an un-grounded `pass` is demoted as if it were `fail`):
74
74
 
75
75
  - **Echo the flag's duty fields verbatim.** Copy `claim_type`, `disposition`, `procedure`, and `owner` from the plan's `risks:` entry into your ruling UNCHANGED. The duty itself is imposed by the plan's `risks:` frontmatter — the gate cross-references it by flag `id`, so dropping or mistyping `claim_type`/`disposition` in your ruling waives NOTHING: a mechanics `pass` is still demoted unless the ruling carries a `file:line` `evidence`, and a verify-at-implement `pass` is still demoted unless the ruling carries a concrete `procedure` and a numeric `owner`. Echo the fields anyway — the ruling stays self-describing for the audit trail and for `validate`, which runs the deferred `procedure` against the shipped code.
76
- - **Mechanics evidence duty (`claim_type: mechanics`).** A mechanics risk ruled `pass` MUST cite the `file:line` you actually checked in the ruling's `evidence` (e.g. `"packages/x/y.ts:42 — the helper returns early on undefined"`). A mechanics `pass` with no `evidence`, or whose `evidence` is not `file:line`-shaped, is demoted to `fail` — the gate refuses a confident-but-ungrounded mechanism assertion (the a777 honest-lazy class). **The adjacency rule — what "`file:line`-shaped" means:** the gate validates `evidence` with a regex (`FILE_LINE_CITATION_RE`) that requires at least one site as a dotted file path with its line number IMMEDIATELY adjacent as `path.ext:NN` (colon-number directly after the extension, no space, e.g. `packages/x/y.ts:1168`); the check is `.match() !== null`, so ONE adjacent `path.ext:NN` anywhere in the string satisfies the duty. Make the FIRST cited site that full adjacent `path.ext:NN`; subsequent refs to other sites in the SAME string may then be abbreviated bare `:NN` (you have already grounded the file) — a compliant multi-site evidence string is `"packages/x/y.ts:85 (countHeadingsOutsideFences); further sites :1173, :1568 — all four consumers reproduce the continue-skip semantics"`, where the `:85` is adjacent to `packages/x/y.ts` and the abbreviated `:1173`/`:1568` that follow are fine. The 553b drift named a real file but attached no adjacent `:NN` to ANY site, so the duty's line never landed — give at least the first site its own adjacent `path.ext:NN`. Three shapes each NAME a real line yet fail the adjacency rule and demote the ruling (none carries an adjacent `path.ext:NN`): `symbol :NN` — a bare symbol (no dotted extension) with a space before the colon, e.g. `handleToString :34`; a bare `(:NN/:NN/:NN)` list where every ref is bare and the path (if named at all) sits separately in the sentence, e.g. `(:85/:1173/:1568)`; and a path token with no adjacent `:NN` at all, e.g. `built-in-workflows.ts — verified…`. Rule `fail` outright if the mechanism does not hold.
76
+ - **Mechanics evidence duty (`claim_type: mechanics`).** A mechanics risk ruled `pass` MUST cite the `file:line` you actually checked in the ruling's `evidence` (e.g. `"packages/x/y.ts:42 — the helper returns early on undefined"`). A mechanics `pass` with no `evidence`, or whose `evidence` is not `file:line`-shaped, is demoted to `fail` — the gate refuses a confident-but-ungrounded mechanism assertion (the honest-lazy class: a confident pass that never opened a file). **The adjacency rule — what "`file:line`-shaped" means:** the gate validates `evidence` with a regex (`FILE_LINE_CITATION_RE`) that requires at least one site as a dotted file path with its line number IMMEDIATELY adjacent as `path.ext:NN` (colon-number directly after the extension, no space, e.g. `packages/x/y.ts:1168`); the check is `.match() !== null`, so ONE adjacent `path.ext:NN` anywhere in the string satisfies the duty. Make the FIRST cited site that full adjacent `path.ext:NN`; subsequent refs to other sites in the SAME string may then be abbreviated bare `:NN` (you have already grounded the file) — a compliant multi-site evidence string is `"packages/x/y.ts:85 (countHeadingsOutsideFences); further sites :1173, :1568 — all four consumers reproduce the continue-skip semantics"`, where the `:85` is adjacent to `packages/x/y.ts` and the abbreviated `:1173`/`:1568` that follow are fine. A recurring drift shape names a real file but attaches no adjacent `:NN` to ANY site, so the duty's line never lands — give at least the first site its own adjacent `path.ext:NN`. Three shapes each NAME a real line yet fail the adjacency rule and demote the ruling (none carries an adjacent `path.ext:NN`): `symbol :NN` — a bare symbol (no dotted extension) with a space before the colon, e.g. `handleToString :34`; a bare `(:NN/:NN/:NN)` list where every ref is bare and the path (if named at all) sits separately in the sentence, e.g. `(:85/:1173/:1568)`; and a path token with no adjacent `:NN` at all, e.g. `built-in-workflows.ts — verified…`. Rule `fail` outright if the mechanism does not hold.
77
77
  - **Verify-at-implement rule (`disposition: verify-at-implement`).** You may defer a risk to the owner phase instead of ruling it finally here. Rule `pass` ONLY when the flag carries a concrete `procedure` (the named command/test the owner phase runs) AND a numeric `owner` phase AND you judge that phase actually carries that step; otherwise rule `fail` (a bare "verify later" with no procedure does not defer — it fails). When you defer, echo `procedure` and `owner` verbatim so `validate` can run the procedure against the shipped code.
78
78
 
79
79
  Emit these as a `risk_rulings: [{ id, pass, evidence?, claim_type?, disposition?, procedure?, owner? }]` array in your verdict — one ruling per declared flag, none omitted. `evidence` is REQUIRED on a mechanics `pass` (and must be `file:line`-shaped); `claim_type`/`disposition`/`procedure`/`owner` are echoed whenever the plan flag carries them.
@@ -104,7 +104,7 @@ Grade against the row matching `--dimension`. "Pass bar" is the line; meet it
104
104
  | Dimension | What it checks | Where to look | Pass bar |
105
105
  |---|---|---|---|
106
106
  | `completeness` | The artifact covers the whole brief — no unresolved `TODO`/`TBD`/`?`/"unknown"/"figure out later" markers; every area it names is addressed; open questions are resolved or explicitly deferred with a reason. **When `--goal` is given, the brief IS the goal file**: every explicit ask and constraint in it is addressed or explicitly deferred with a reason — a requirement present in the goal but absent from the artifact is a blocking gap. | The artifact's own content, cross-checked against `--goal` when given. | No blocking gap — nothing a downstream stage would need is left undefined, and no explicit `--goal` ask is silently dropped. |
107
- | `correctness` | Claims match reality — `file:line` references resolve and say what the artifact claims; described current behavior matches the actual code; no internal contradictions. When `--goal` is given, no claim or decision contradicts an explicit constraint stated in it. | **Spot-check the live codebase**: resolve a sample of the artifact's references with Read/Grep; check decisions against `--goal` when given. | No false claim found in the sample; references resolve; no explicit `--goal` constraint contradicted. |
107
+ | `correctness` | Claims match reality — cited files and symbols exist and the code does what the artifact claims; described current behavior matches the actual code; no internal contradictions. When `--goal` is given, no claim or decision contradicts an explicit constraint stated in it. | **Spot-check the live codebase**: resolve a sample of the artifact's references with Read/Grep — by file + named symbol, NOT by exact line number (line numbers are navigation hints); check decisions against `--goal` when given. | No false claim found in the sample; cited files/symbols exist; no explicit `--goal` constraint contradicted. |
108
108
  | `actionability` | A competent implementer could execute it without guessing — concrete steps, named files/symbols, explicit success criteria; no hand-waving ("somehow", "handle appropriately", "etc."). | The artifact's own content. | Every section/slice is executable as written. |
109
109
  | `architecture-fit` | The approach fits the existing architecture and the constraints surfaced in `--context` — respects module boundaries, dependency direction, established layering; introduces no boundary violation. | The artifact **and** `--context`, cross-checked against real module boundaries via Grep/Read. | No architectural conflict with the codebase or the research's constraints. |
110
110
  | `pattern-following` | Mirrors the codebase's dominant conventions (naming, error handling, file layout, test style) instead of inventing new ones where a precedent exists; any divergence is justified. | **Spot-check** comparable existing code via Grep/Read for the local convention. | Aligns with the dominant local pattern, or names a reason to diverge. |
@@ -115,9 +115,10 @@ Grade against the row matching `--dimension`. "Pass bar" is the line; meet it
115
115
  1. **Parse + validate flags.** Bail per the Input rules above if malformed.
116
116
  2. **Read fully** (no limit/offset): `--artifact`, and `--context` / `--goal` / `--prior` if given (skip `--goal` unless your dimension is `completeness` or `correctness`).
117
117
  3. **Select the single rubric row** for `--dimension`. Ignore every problem outside it.
118
- 4. **Evaluate.** For `correctness` / `architecture-fit` / `pattern-following` / `design-readiness`, spot-check against the real codebase — resolve references, compare conventions, check boundaries, expand each slice's true touch + dependency fan-out from its cited seeds to gauge whether the footing is bounded AND complete, and check each shared contract has a single owning slice. For `completeness` / `actionability`, judge the artifact's own content. **On `correctness`, also rule every plan-authored risk flag** (see "Plan-authored risk flags" above) — verify each `risks:` claim against the code and record a `risk_rulings` entry. **With `--prior`, also adjudicate every prior finding** (see "Prior-round adjudication" above) — verify each against artifact + code and record a `finding_rulings` entry. Collect findings — each is `{ detail, where }` (`where` = `path:line` or a section heading; for slice dimensions, cite the offending `## Slice N`). Where a `design-readiness` finding fires, the `feedback` must name the exact re-cut (which slice to split and along which seam, which under-cited grounding to add, or which overlap to separate) so the re-slice can act on it.
119
- 5. **Decide** `pass` (against the pass bar), `score` (0–100), `severity` (`none` | `low` | `medium` | `high` = the worst finding), and `feedback`. **`severity` is gate-load-bearing: the workflow treats any verdict whose worst finding is `low`/`none` as passing, even on `pass: false`, and only a `medium`+ finding blocks the gate.** So set `severity` to honestly reflect blocking weight — `low`/`none` for a cosmetic nit (a line-number off by one or two, a stylistic phrasing, a naming quibble that doesn't change behavior), `medium`+ for a finding a downstream stage genuinely cannot proceed past (a reference that won't resolve, a missing step, an executable edit that would fail as written, a boundary violation), **or for a claim about behavior you verified is false that sits in text the implementer copies verbatim (a code block, JSDoc, or comment) — behavior that happens to be correct anyway does not make it a nit; the shipped false claim is itself the defect**. Do **not** mark a real blocker `low` to be lenient, and do **not** mark a cosmetic nit `medium`+ to force a re-run — the gate reads `severity`, so mis-rating it either ships a defect or stalls the loop. **Every string you emit (`feedback` and each `findings[].detail` / `where`) MUST be JSON-safe: a single line, no literal newlines or tabs, no backticks or code fences, double-quotes escaped as `\"`. Put `path:line` citations in `findings[].where` — never paste code snippets into `feedback`.**
118
+ 4. **Evaluate.** For `correctness` / `architecture-fit` / `pattern-following` / `design-readiness`, spot-check against the real codebase — resolve references, compare conventions, check boundaries, expand each slice's true touch + dependency fan-out from its cited seeds to gauge whether the footing is bounded AND complete, and check each shared contract has a single owning slice. **Citation-resolution rule: resolve every `path:line` citation by opening the file and locating the named symbol/content — the line number is a navigation hint, not a claim. A line number that points near but not exactly at the cited symbol is NEVER a finding, at any severity — do not report it, do not mention it in feedback: downstream stages locate code by symbol, so drift wastes fix rounds without ever blocking anything. The only citation findings that exist: the file does not exist, the named symbol/content does not exist in it, or the code does not do what the artifact claims it does.** For `completeness` / `actionability`, judge the artifact's own content. **On `correctness`, also rule every plan-authored risk flag** (see "Plan-authored risk flags" above) — verify each `risks:` claim against the code and record a `risk_rulings` entry. **With `--prior`, also adjudicate every prior finding** (see "Prior-round adjudication" above) — verify each against artifact + code and record a `finding_rulings` entry. Collect findings — each is `{ detail, where }` (`where` = `path:line` or a section heading; for slice dimensions, cite the offending `## Slice N`). Where a `design-readiness` finding fires, the `feedback` must name the exact re-cut (which slice to split and along which seam, which under-cited grounding to add, or which overlap to separate) so the re-slice can act on it.
119
+ 5. **Decide** `pass` (against the pass bar), `score` (0–100), `severity` (`none` | `low` | `medium` | `high` = the worst finding), and `feedback`. **`severity` is gate-load-bearing: the workflow treats any verdict whose worst finding is `low`/`none` as passing, even on `pass: false`, and only a `medium`+ finding blocks the gate.** So set `severity` to honestly reflect blocking weight — `low`/`none` for a cosmetic nit (a stylistic phrasing, a naming quibble that doesn't change behavior; line-number drift is not even a nit — per the citation-resolution rule it is never a finding), `medium`+ for a finding a downstream stage genuinely cannot proceed past (a cited file or symbol that does not exist, a missing step, an executable edit that would fail as written, a boundary violation), **or for a claim about behavior you verified is false that sits in text the implementer copies verbatim (a code block, JSDoc, or comment) — behavior that happens to be correct anyway does not make it a nit; the shipped false claim is itself the defect**. Do **not** mark a real blocker `low` to be lenient, and do **not** mark a cosmetic nit `medium`+ to force a re-run — the gate reads `severity`, so mis-rating it either ships a defect or stalls the loop. **Every string you emit (`feedback` and each `findings[].detail` / `where`) MUST be JSON-safe: a single line, no literal newlines or tabs, no backticks or code fences, double-quotes escaped as `\"`. Put `path:line` citations in `findings[].where` — never paste code snippets into `feedback`.**
120
120
  - `pass: false` → `feedback` is a **surgical, concrete instruction set** telling `amend` exactly what to change to clear this dimension, citing `where`. This field is the only thing `amend` reads — make it sufficient but concise (≤ ~500 chars; lean on `findings[]` for specifics).
121
+ - `pass: false` on `design-readiness` where **every** finding's remedy is pure citation bookkeeping — add a named seed to a slice's `Draws on`, or move a named item to `Out of scope`, with **no** split/merge/renumber/re-fence needed: additionally emit top-level `"remedy": "cite"` and give **each** finding a `"requires": "<path>:<lines>"` naming the exact seed. The slice gate then verifies deterministically that the re-cut map satisfies every finding with the slice structure unchanged, and skips the re-grade panel. Emit `remedy` ONLY when those citation edits alone would flip your verdict to pass — any structural doubt, or any finding without a concrete `requires` seed, → omit it and the normal re-grade runs. (There is no "refresh a drifted line number" remedy — per the citation-resolution rule, drifted line numbers are not findings.)
121
122
  - `pass: true` → `feedback` is **one short sentence, or empty** — never a multi-sentence essay. A long free-text value on a pass is pure JSON-malform risk with no consumer.
122
123
  6. **Write the verdict** with the Write tool to `.rpiv/artifacts/verdicts/<artifact-basename-without-ext>__<dimension>__<slug>.json` (`<slug>` from the Metadata block). Do **not** overwrite a prior round's verdict for this `(artifact, dimension)` pair — the round-distinct `<slug>` preserves each round's findings, so the round-1 findings that drove a fix stay in the trail instead of being clobbered by round 4. The panel folds by latest-per-dimension, so the newest round still decides the gate. **Always write it, even on pass** — the panel collects this file to score the gate. **Emit machine-valid JSON only**: every string single-line with quotes escaped, no literal newlines, no backticks/code fences, no raw control characters. **After writing, re-read the file and confirm it parses as JSON; if it doesn't (an unescaped quote, a stray comma, a code fence in a value), rewrite it minimally until it parses.**
123
124
  7. **Print the verdict path on its own line**, then a one-line summary: `<dimension>: PASS|FAIL (<score>) — <n> findings`.
@@ -147,7 +148,7 @@ Grade against the row matching `--dimension`. "Pass bar" is the line; meet it
147
148
  }
148
149
  ```
149
150
 
150
- Include `risk_rulings` **only** on a `correctness` verdict when the artifact declares `risks:` — one entry per flag. Omit the key entirely on every other dimension and when the artifact declares no risks. Include `finding_rulings` **only** when `--prior` was given — one entry per prior finding and per prior failed risk ruling, none omitted (see "Prior-round adjudication"); omit the key entirely otherwise. Every `evidence` string follows the same JSON-safety rules as `feedback`.
151
+ Include `risk_rulings` **only** on a `correctness` verdict when the artifact declares `risks:` — one entry per flag. Omit the key entirely on every other dimension and when the artifact declares no risks. Include `finding_rulings` **only** when `--prior` was given — one entry per prior finding and per prior failed risk ruling, none omitted (see "Prior-round adjudication"); omit the key entirely otherwise. Include top-level `"remedy": "cite"` plus a per-finding `"requires"` **only** on a `design-readiness` fail whose every finding is discharged by adding the named citation (see step 5); omit them otherwise. Every `evidence` string follows the same JSON-safety rules as `feedback`.
151
152
 
152
153
  ## Hard rules
153
154
 
@@ -85,7 +85,7 @@ After implementing a phase:
85
85
  - Fix any issues before proceeding
86
86
  - Update your progress in both the plan and your todos
87
87
  - Check off completed items in the plan file itself using Edit
88
- - Anchor each checkbox-flip `Edit` on the **full unique line** — the item's phase-specific tail (the verification command, file path, or criterion text), never just the shared `- [ ]`/`- [x]` prefix. That shared prefix repeats identically across phases, so a prefix-only anchor collides and Pi rejects the whole atomic edit batch with a "Found N occurrences" error (run a777 lost an atomic 9-edit batch this way). A full-line anchor is unique per item.
88
+ - Anchor each checkbox-flip `Edit` on the **full unique line** — the item's phase-specific tail (the verification command, file path, or criterion text), never just the shared `- [ ]`/`- [x]` prefix. That shared prefix repeats identically across phases, so a prefix-only anchor collides and Pi rejects the whole atomic edit batch with a "Found N occurrences" error (an observed run lost an atomic 9-edit batch this way). A full-line anchor is unique per item.
89
89
  - If the input scopes you to a single phase, stop immediately after the named phase's own checks pass — do not advance to other phases
90
90
 
91
91
  Don't let verification interrupt your flow - batch it at natural stopping points.
@@ -404,7 +404,7 @@ Success Criteria are **authored upstream in `/skill:design` Step 6.1** and verif
404
404
 
405
405
  **Write-scope rule (per-phase, mandatory before parallel implement):** every command in a phase's `#### Automated Verification:` block must be **write-scoped to that phase's own `files:` set** — running it must not modify anything outside the phase's `files:`. Phases run concurrently under build's parallel implement lane, so a command that rewrites the wider tree corrupts a sibling phase's in-flight edit; narrow any formatter or auto-fixer to the phase's paths (take the project's command vocabulary from its guidance `# Commands` table — where the table gives only an unscoped form, narrow it to the phase's paths rather than substituting a different tool). Read-only repo-wide commands (a type check, a non-fixing lint, a scoped test selection) are permitted. Whole-repo build/test verification belongs to the plan's final whole-plan block, owned by `validate` — never to a phase.
406
406
 
407
- **Exit-0 contract (the `reconcile` stage re-runs AV lines verbatim):** after implement, `reconcile` re-executes the FIRST backtick span of every `- [ ]` line in `#### Automated Verification:` via `execFileSync` — arg-array (no shell: no `|`/`&&`/redirection), stdin ignored, exit 0 the ONLY pass signal. Prose around the span never executes, and a non-zero exit halts the run with no fix arm. So every AV line must be ONE self-contained command that exits 0 exactly when the criterion holds: name the target file INSIDE the span (never "over `<file>`" in prose — the command then greps an empty stdin and always fails); never assert absence ("returns nothing" — grep exits 1 on no match, so that line can ONLY fail; restate it to exit 0 on success, e.g. a `node -e` probe that inverts the check, or move it to `#### Manual Verification:`); never rely on prose expected counts ("returns `4`" — fold the assertion into the command itself); never point a formatter at paths outside its configured scope (Biome on a doc-only phase's `.md` exits non-zero with "No files were processed"). The `plan-cite-check`/`code-cite-check` floor lints these shapes and routes violations into a plan-fix round; anything it cannot catch statically still kills the run at `reconcile`.
407
+ **Who runs AV lines:** `implement` runs each phase's own `#### Automated Verification:` commands in its shell and flips the checkboxes; `validate` re-runs them agent-side over the whole finished plan. Both are agents with a real shell and judgment — no deterministic harness re-executes these lines. Still prefer ONE self-contained command per line that exits 0 when the criterion holds, with the target path inside the backtick span; prose around the span is context for the agent, not executed syntax. Remember AV lines are written before sibling phases land: a check asserting another phase's rename target or source may be true at phase time and false on the final tree — scope each line to what YOUR phase owns.
408
408
 
409
409
  **Format example:**
410
410
  ```markdown
@@ -108,7 +108,7 @@ You are re-cutting an existing slice map from its verdicts. Unlike a surgical re
108
108
  - **dropped coverage unit** (from `--slice-check`) → re-attach its `id` to the `covers:` of whichever slice now delivers it; never resolve this by deleting the unit.
109
109
  - **unbacked `file:line` citation** (from `--slice-check`) → correct the `Draws on:` reference to a real **repo-root-relative** `file:line` (not a bare basename), or drop the line numbers; never leave a fabricated citation.
110
110
  3. **Rebuild the invariants** — renumber `n` contiguously `1..N`, recompute `slice_count`, fix `deps`, carry `coverage:` forward verbatim and reassign `covers:` so the union still claims every unit, and keep exactly one `## Slice N:` heading per entry.
111
- 4. **Re-emit** the slice map (same Output shape, `status: ready`). **Non-interactive**: the verdict feedback IS the instruction — no confirm step, no `ask_user_question`.
111
+ 4. **Re-emit** the slice map (same Output shape, `status: ready`). **Non-interactive**: the verdict feedback IS the instruction — no confirm step, no `ask_user_question`. If you add a revision note documenting refreshed citations, quote each replaced citation ONLY as an `old→new` arrow pair (e.g. `` `:3699→:3721` ``) or inside a fenced code block — the deterministic cite-discharge treats arrow-adjacent and fenced occurrences as quotation; an old citation quoted bare in prose reads as still-live and forfeits the discharge, costing a full re-grade panel.
112
112
  5. **Print** the path, then `re-sliced: <N> slices (was <M>) — addressed <failing dimensions>`.
113
113
 
114
114
  ## Output document