@juicesharp/rpiv-pi 2.1.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.
Files changed (45) hide show
  1. package/README.md +9 -8
  2. package/docs/lanes.md +3 -2
  3. package/docs/models-config.md +6 -6
  4. package/docs/workflows.md +4 -18
  5. package/extensions/rpiv-core/artifact-collector.ts +2 -2
  6. package/extensions/rpiv-core/bash-timeout.ts +16 -0
  7. package/extensions/rpiv-core/built-in-workflows.ts +2289 -318
  8. package/extensions/rpiv-core/guidance.ts +35 -19
  9. package/extensions/rpiv-core/index.ts +2 -2
  10. package/extensions/rpiv-core/lane-console.ts +62 -5
  11. package/extensions/rpiv-core/lane-list.ts +84 -32
  12. package/extensions/rpiv-core/lane-progress.ts +13 -77
  13. package/extensions/rpiv-core/lane-switcher.ts +114 -33
  14. package/extensions/rpiv-core/lane-usage.ts +25 -0
  15. package/extensions/rpiv-core/models-config-validate.ts +1 -1
  16. package/extensions/rpiv-core/models-config.ts +38 -3
  17. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  18. package/extensions/rpiv-core/run-lane-registry.ts +80 -69
  19. package/extensions/rpiv-core/sdk-workflow-host.ts +43 -3
  20. package/extensions/rpiv-core/subagent-usage.ts +147 -0
  21. package/extensions/rpiv-core/workflow-execution-host.ts +24 -7
  22. package/package.json +3 -3
  23. package/skills/amend/SKILL.md +7 -3
  24. package/skills/annotate-guidance/SKILL.md +1 -0
  25. package/skills/architecture-review/SKILL.md +1 -0
  26. package/skills/blueprint/SKILL.md +10 -4
  27. package/skills/changelog/SKILL.md +1 -0
  28. package/skills/commit/SKILL.md +1 -0
  29. package/skills/design/SKILL.md +4 -3
  30. package/skills/design-review/SKILL.md +1 -0
  31. package/skills/design-slice/SKILL.md +2 -1
  32. package/skills/discover/SKILL.md +1 -1
  33. package/skills/elaborate/SKILL.md +21 -9
  34. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +88 -0
  35. package/skills/explore/SKILL.md +1 -0
  36. package/skills/frontend-design/SKILL.md +1 -0
  37. package/skills/grade/SKILL.md +24 -6
  38. package/skills/implement/SKILL.md +10 -2
  39. package/skills/plan/SKILL.md +10 -6
  40. package/skills/research/SKILL.md +9 -8
  41. package/skills/resume-handoff/SKILL.md +1 -0
  42. package/skills/revise/SKILL.md +1 -0
  43. package/skills/slice/SKILL.md +4 -3
  44. package/skills/synthesize/SKILL.md +16 -7
  45. package/skills/validate/SKILL.md +1 -0
@@ -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;
@@ -433,6 +469,10 @@ export class SdkWorkflowHost implements WorkflowHostContext {
433
469
  // runner THIS child's `aborted` stop was a tool-timeout (→ soft-halt), not a
434
470
  // run/user abort. Undefined until/unless the watchdog fires.
435
471
  toolTimeout: () => watchdog.timedOut(),
472
+ // Recovery twin: clear the verdict + pending timers so the resumed turn's next
473
+ // bash call re-arms a fresh per-toolCallId timer via the still-live subscribe
474
+ // listener. Same watchdog handle armed once per child; dispose() still runs in finally.
475
+ resetToolTimeout: () => watchdog.reset(),
436
476
  sessionManager: {
437
477
  // The transcript reader (`transcript.ts`) expects the ENVELOPED branch
438
478
  // shape `{ type: "message", message: {...} }` (SessionEntry[]) — the same
@@ -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
+ }
@@ -18,9 +18,10 @@
18
18
  */
19
19
 
20
20
  import type { ExtensionAPI, ExtensionUIContext } from "@earendil-works/pi-coding-agent";
21
- import type { ModelSelection, WorkflowHostContext } from "@juicesharp/rpiv-workflow";
21
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
22
+ import type { BranchEntry, ModelSelection, WorkflowHostContext } from "@juicesharp/rpiv-workflow";
22
23
  import { isLaneRelayUiContext } from "./lane-relay-ui.js";
23
- import { loadModelsConfig, resolveStageModel } from "./models-config.js";
24
+ import { loadModelsConfig, resolveMaxConcurrency, resolveStageModel } from "./models-config.js";
24
25
  import { getFocusedRun, getLane, recordRun, retireRun, setLaneAbort } from "./run-lane-registry.js";
25
26
  import { SdkWorkflowHost } from "./sdk-workflow-host.js";
26
27
  import { getCapturedModelRegistry, getCapturedUiContext } from "./session-capture.js";
@@ -34,11 +35,12 @@ type WorkflowExecution = {
34
35
  };
35
36
 
36
37
  /**
37
- * Background-lane concurrency cap. Rate limits, not CPU, are the real cap.
38
- * 4 is the default; a later step can make it config-driven
39
- * via the models/workflow config. Declared once, here, at the registration site.
38
+ * Background-lane concurrency cap, re-exported from models-config.ts (the single
39
+ * source of truth alongside `resolveMaxConcurrency`). Re-exported here to
40
+ * preserve the tested public surface; the live cap is driven through
41
+ * `resolveMaxConcurrency(loadModelsConfig())` at the consumer below.
40
42
  */
41
- export const DEFAULT_MAX_CONCURRENCY = 4;
43
+ export { DEFAULT_MAX_CONCURRENCY } from "./models-config.js";
42
44
 
43
45
  /**
44
46
  * Map the config layer's `ResolvedModelConfig` ({ model?, thinking? }) to the
@@ -95,7 +97,7 @@ export function createWorkflowExecution(
95
97
  cwd: observer.cwd,
96
98
  runId,
97
99
  childSessionsDir, // resolved by the runner; rpiv-pi does not synthesize the path
98
- maxConcurrency: DEFAULT_MAX_CONCURRENCY, // 4 — background-lane cap
100
+ maxConcurrency: resolveMaxConcurrency(loadModelsConfig()), // config-driven background-lane cap (default 4)
99
101
  });
100
102
 
101
103
  // Record this run as a switchable lane at launch (appears in the ambient
@@ -176,6 +178,21 @@ export async function registerWorkflowExecutionHostProvider(): Promise<void> {
176
178
  registerWorkflowExecutionHost({
177
179
  createHost: createWorkflowExecution,
178
180
  resolveModel: ({ stage, skill }) => toModelSelection(resolveStageModel(loadModelsConfig(), { stage, skill })),
181
+ // Death-scene reader — re-open the just-failed session's persisted JSONL
182
+ // and return its branch, narrowed to the workflow-owned BranchEntry shape
183
+ // (the SDK's SessionEntry union carries private discriminators — the
184
+ // `as unknown as` double-cast is duplicated by necessity, not a mirror:
185
+ // this module sits on the entry graph, so sibling-import-graph.test.ts
186
+ // forbids a value-import of `readBranch` from the peer
187
+ // packages/rpiv-workflow/transcript.ts. That twin cast stays untouched —
188
+ // peer package, out of write scope). Fail-soft: any open/read error ⇒ undefined.
189
+ readSessionBranch: (file: string) => {
190
+ try {
191
+ return SessionManager.open(file).getBranch() as unknown as BranchEntry[] | undefined;
192
+ } catch {
193
+ return undefined;
194
+ }
195
+ },
179
196
  });
180
197
  } catch (err) {
181
198
  if (isModuleNotFound(err)) return; // sibling absent — /rpiv-setup guides the user
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-pi",
3
- "version": "2.1.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.1.0",
52
+ "@juicesharp/rpiv-config": "^2.3.0",
53
53
  "typebox": "^1.1.24"
54
54
  },
55
55
  "peerDependencies": {
@@ -19,7 +19,9 @@ You surgically fix **one** artifact so it clears the dimensions a grade panel ma
19
19
  `$ARGUMENTS` — flags the orchestrator wires from the gate's channels. Parse them **generically**, agnostic to the channel name:
20
20
 
21
21
  - **Verdicts** — every flag whose name ends in `-verdicts` (e.g. `--research-verdicts`, `--plan-verdicts`), repeatable. Each value is a verdict JSON path.
22
- - **Artifact** — the single remaining `--<channel>` flag (the one **not** ending in `-verdicts`). Its value is the artifact to fix and re-emit.
22
+ - **Citation floors** — every flag whose name ends in `-cite-check` (e.g. `--plan-cite-check`, `--code-cite-check`), repeatable. Each value is a cite-check verdict JSON path.
23
+ - **Lineage sources** — the read-only context flags `--goal`, `--research`, and `--subplans` (repeatable; build's fix arms only). `--goal` is the verbatim brief, `--research` the architecture/precedent findings, `--subplans` the per-cluster sub-plans. They are context, never the artifact to re-emit.
24
+ - **Artifact** — the single remaining `--<channel>` flag that is **not** a verdicts, citation-floor, or lineage-source flag (i.e. not ending in `-verdicts` or `-cite-check`, and not `--goal`/`--research`/`--subplans`). Its value is the artifact to fix and re-emit; for both build fix arms this resolves to `--plans`.
23
25
 
24
26
  If you can't identify exactly one artifact flag and at least one verdicts flag, print an error and stop.
25
27
 
@@ -34,14 +36,16 @@ The first tab-separated field is `<iso>` (use as `last_updated`).
34
36
  ## Steps
35
37
 
36
38
  1. **Read the artifact fully** (no limit/offset) and **read every verdict JSON**.
37
- 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`. If none fail, the artifact already passes: re-emit it unchanged (only bump `last_updated`) and report — the panel will confirm.
38
- 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.
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.
39
41
  4. **Confirm coverage** — every failing finding maps to an edit you made. Do not introduce changes no finding asked for.
40
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.
41
43
  6. **Print the artifact path**, then a one-line summary: `amended for <dimensions>: <k> findings addressed`.
42
44
 
43
45
  ## Hard rules
44
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.
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.
45
49
  - **Surgical, not wholesale.** Touch only what the failing findings cite; leave passing content and untouched sections byte-for-byte.
46
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.
47
51
  - **Re-emit in place.** Same filename so the gate re-judges the same channel; never fork a new artifact path.
@@ -210,6 +210,7 @@ You are tasked with generating architecture guidance files for a brownfield proj
210
210
  - Write each file to `.rpiv/guidance/{relative_path}/architecture.md`. For the root file, write to `.rpiv/guidance/architecture.md`. Create any intermediate directories that do not exist.
211
211
  - Write ALL files at once using the Write tool
212
212
  - Do NOT ask for confirmation before each file — batch mode
213
+ - **Record both forms of a formatter/auto-fixer.** Where the project has a formatter or auto-fixer, record BOTH its repo-wide form AND its path-scoped form (the invocation that rewrites only the paths it is given) in the `# Commands` table — phase-scoped verification depends on the scoped form being known, because a phase's `#### Automated Verification:` command must be write-scoped to that phase's own `files:` set.
213
214
  - After writing, present a summary:
214
215
  ```
215
216
  ## Architecture Guidance Files Created
@@ -69,6 +69,7 @@ The final artifact is blueprint-consumable per phase.
69
69
  ### Step 1: Identify the Target
70
70
 
71
71
  1. **Argument is empty:** use the `ask_user_question` tool with the following question: "What are we reviewing?". Header: "Target". Options: "Single module" (one package / project / crate / namespace directory); "Single subdirectory" (a subtree inside a module); "Single file" (deep review of one large file). The automatic `Type something.` row accepts a custom target.
72
+ - `Header` is capped at ≤16 characters (`MAX_HEADER_LENGTH = 16` — longer values are rejected).
72
73
 
73
74
  2. **Validate the target exists**. Use `ls` via the Bash tool on the resolved path. If missing, ask for a corrected path.
74
75
 
@@ -150,6 +150,7 @@ Use the grounded-questions-one-at-a-time pattern. Use a **❓ Question:** prefix
150
150
  - Reference real findings with `file:line` evidence
151
151
  - Present concrete options (not abstract choices)
152
152
  - Pull a DECISION from the developer, not confirm what you already found
153
+ - Keep `Header` ≤16 characters (`MAX_HEADER_LENGTH = 16` — longer values are rejected).
153
154
 
154
155
  **Directional confirms first.** Before the one-at-a-time questions, clear every **directional** finding from Step 3 in a single batched `ask_user_question` (up to 4 per call). Do not mark the "follow" option Recommended.
155
156
 
@@ -176,7 +177,7 @@ Use the grounded-questions-one-at-a-time pattern. Use a **❓ Question:** prefix
176
177
 
177
178
  - **`ask_user_question` tool** — concrete options include evidence and trade-offs in every description. The user can type a custom answer through the automatically appended `Type something.` row; do not author `Other`. Example:
178
179
 
179
- > Use the `ask_user_question` tool with the following question: "Found 2 mapping approaches — which should new code follow?". Header: "Pattern". Options: "Manual mapping (Recommended)" (Used in OrderService (src/services/OrderService.ts:45) — 8 occurrences); "AutoMapper" (Used in UserService (src/services/UserService.ts:12) — 2 occurrences).
180
+ > Use the `ask_user_question` tool with the following question: "Found 2 mapping approaches — which should new code follow?". Header: "Pattern". Options: "Manual mapping (Recommended)" (Used in OrderService (src/services/OrderService.ts:NN) — 8 occurrences); "AutoMapper" (Used in UserService (src/services/UserService.ts:NN) — 2 occurrences).
180
181
 
181
182
  - **Open-ended** — still use `ask_user_question`; supply 2-4 concrete hypotheses with behavior, `file:line` evidence, impact, and decision context, then let the automatic `Type something.` row capture unanticipated detail.
182
183
 
@@ -370,6 +371,11 @@ Use the `ask_user_question` tool to confirm. Question: "Slice {N/M}: {slice name
370
371
  - [ ] New widget renders correctly above the editor
371
372
  - [ ] Performance acceptable with 1000+ todo items
372
373
  ```
374
+
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
+
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
+
373
379
  5. Update the Plan History section: `- Phase N: {name} — approved as generated`
374
380
  6. Decrement frontmatter `unresolved_phase_count` by 1
375
381
  - Proceed to next slice
@@ -393,11 +399,11 @@ The artifact was created as a skeleton in Step 5 and filled progressively in Ste
393
399
 
394
400
  If any check fails, return to Step 6. Do NOT flip status. (7.1 and 7.2 guard the same invariant — empty content ↔ unresolved counter.)
395
401
 
396
- Then **rebuild the `phases:` frontmatter array from the `## Phase N:` headings** — one `{ n, title }` entry per section, in body order:
402
+ Then **rebuild the `phases:` frontmatter array from the `## Phase N:` headings** — one `{ n, title, files, depends_on }` entry per section, in body order. Populate `files:` from each phase's `#### N. path/to/file.ext` + `**File**:` entries and `depends_on` (lower `n` only) from the decomposition's `Depends on:` lines:
397
403
  ```yaml
398
404
  phases:
399
- - { n: 1, title: Schema layer }
400
- - { n: 2, title: Runtime wiring }
405
+ - { n: 1, title: Schema layer, files: [src/schema.ts], depends_on: [] }
406
+ - { n: 2, title: Runtime wiring, files: [src/runtime.ts], depends_on: [1] }
401
407
  ```
402
408
 
403
409
  3. **Update frontmatter** via Edit: `status: in-progress` → `status: in-review` (Step 9 flips to `ready` after triage — keeps consumers off an artifact still being edited). Leave `last_updated` / `last_updated_by` as-is.
@@ -155,6 +155,7 @@ What this example demonstrates:
155
155
  2. Print the proposed `[Unreleased]` body for each affected CHANGELOG, in full.
156
156
  3. Call `ask_user_question`:
157
157
  - Question: "Apply regenerated `[Unreleased]` to {N} CHANGELOG(s)?"
158
+ - `Header` is capped at ≤16 characters (`MAX_HEADER_LENGTH = 16` — longer values are rejected).
158
159
  - Header: "Changelog"
159
160
  - Options:
160
161
  - "Apply (Recommended)" — Write the regenerated sections to disk. Refinement, if needed, happens afterward in normal chat (`Edit` tool) or via `git restore` to roll back.
@@ -67,6 +67,7 @@ node "${SKILL_DIR}/../_shared/git-changes.mjs" --baseline <path>
67
67
  - List the files you plan to add for each commit
68
68
  - Show the commit message(s) you'll use
69
69
  - Use the `ask_user_question` tool to confirm the commit plan. Question: "{N} commit(s) with {M} files. Proceed?". Header: "Commit". Options: "Commit (Recommended)" (Create the commit(s) as planned); "Adjust" (Change the grouping or commit messages); "Review files" (Show me the full diff before committing).
70
+ - `Header` is capped at ≤16 characters (`MAX_HEADER_LENGTH = 16` — longer values are rejected).
70
71
 
71
72
  4. **Execute upon confirmation:**
72
73
  - Use `git add` with specific files (never use `-A` or `.`) — and stage **only** files from the `---status---` block. Any path under `---pre-existing (do NOT commit …)---` is out of scope: leave it dirty, never stage it.
@@ -136,6 +136,7 @@ Use the grounded-questions-one-at-a-time pattern. Use a **❓ Question:** prefix
136
136
  - Reference real findings with `file:line` evidence
137
137
  - Present concrete options (not abstract choices)
138
138
  - Pull a DECISION from the developer, not confirm what you already found
139
+ - Keep `Header` ≤16 characters (`MAX_HEADER_LENGTH = 16` — longer values are rejected).
139
140
 
140
141
  **Directional confirms first.** Before the one-at-a-time questions, clear every **directional** finding from Step 3 in a single batched `ask_user_question` (up to 4 per call). Do not mark the "follow" option Recommended.
141
142
 
@@ -276,7 +277,7 @@ Generate complete, copy-pasteable code AND the slice's `### Success Criteria:` f
276
277
  - **Modified files**: read current file FULLY, generate only the modified/added code scoped to changed sections (no full "Current" block — the original is on disk)
277
278
  - **Test files**: complete test suites following project patterns
278
279
  - **Wiring**: show where new code hooks into existing code
279
- - **Success Criteria**: derive `### Success Criteria:` from this slice's file changes plus `## Verification Notes` entries that map to this slice's scope. Use the same `- [ ]` format as 6.4 (see template below). Project-baseline checks (`npm run check`, `npm test`) go on the terminal slice only. Commands in backticks. Criteria authored here flow through to plan as the phase's Success Criteria — slice ≡ phase, 1:1.
280
+ - **Success Criteria**: derive `### Success Criteria:` from this slice's file changes plus `## Verification Notes` entries that map to this slice's scope. Use the same `- [ ]` format as 6.4 (see template below). Project-baseline checks (the project's whole-repo build/test commands, from its guidance `# Commands` table) go on the terminal slice only. Commands in backticks. Criteria authored here flow through to plan as the phase's Success Criteria — slice ≡ phase, 1:1.
280
281
 
281
282
  If additional context is needed, spawn a targeted **codebase-analyzer** agent.
282
283
 
@@ -336,8 +337,8 @@ Use the `ask_user_question` tool to confirm. Question: "Slice {N/M}: {slice name
336
337
  **Files**: `path/to/file1.ext`, `path/to/file2.ext`
337
338
 
338
339
  #### Automated Verification:
339
- - [ ] Type checking passes: `npm run check`
340
- - [ ] Tests pass: `npm test`
340
+ - [ ] Type checking passes: `{project typecheck command}`
341
+ - [ ] Tests pass: `{project test command}`
341
342
  - [ ] Grep pattern from Verification Note: `grep -r "newApi" packages/ | wc -l` returns >= 3
342
343
 
343
344
  #### Manual Verification:
@@ -55,6 +55,7 @@ The first tab-separated field is `<iso>` (use as `last_updated` when you edit a
55
55
  Lead with the data types and interface surface — that is the contract the developer is signing off on.
56
56
 
57
57
  3. **Ask the developer to accept or adjust** with the `ask_user_question` tool. Question: "Proposed design across {N} slices ({F} files). Accept, or adjust a slice?". Header: "Design". Options: "Accept (Recommended)" (Proceed to synthesis — merge the per-slice designs into the plan); "Adjust a slice" (Change a slice's approach, interfaces, data types, or scope before synthesis — describe which slice and what). The developer may use the automatically appended `Type something.` row to provide an unanticipated adjustment; do not author an `Other` option.
58
+ - `Header` is capped at ≤16 characters (`MAX_HEADER_LENGTH = 16` — longer values are rejected).
58
59
 
59
60
  4. **On Adjust — apply surgically and cascade, then re-present (loop back to Step 2).** Classify the change:
60
61
 
@@ -61,6 +61,7 @@ Copy values verbatim. `<iso>` is the first tab-separated field; `<slug>` is the
61
61
  - **Integration points** — where this slice wires into existing code (and into sibling slices it depends on, by file/symbol — referencing the real shapes from the upstream `## Key Interfaces`).
62
62
  - **Success criteria** — concrete `- [ ]` checks that prove the slice works.
63
63
  5. **Resolve ambiguity:** decide from the slice map, the upstream designs, research, and code wherever you can. Use `ask_user_question` (2–4 concrete options, one at a time) ONLY when you can't settle it from those inputs — either a genuine design fork within this slice, **or** a contract this slice depends on is still an undecided fork in an upstream's `## Notes / Deferred`. Do **not** ask the user to approve the finished design — the grade panel owns that.
64
+ - `Header` is capped at ≤16 characters (`MAX_HEADER_LENGTH = 16` — longer values are rejected).
64
65
  6. **Write the design doc** (below), `status: ready`.
65
66
  7. **Print the path**, then a one-line summary: `Slice N design: <k> files, <m> success criteria`.
66
67
 
@@ -97,7 +98,7 @@ tags: [design, slice]
97
98
 
98
99
  ## Integration Points
99
100
  - `path:line` — <how this slice wires in; name sibling slices it couples to>
100
- <!-- `path` is the repo-root-relative path (`packages/.../foo.ts:42`), never a subdirectory-relative form or a bare basename: the plan's deterministic cite-check floor verifies it, and an ambiguous or unresolvable path fails. -->
101
+ <!-- `path` is the repo-root-relative path (`packages/.../foo.ts:NN`), never a subdirectory-relative form or a bare basename: the plan's deterministic cite-check floor verifies it, and an ambiguous or unresolvable path fails. -->
101
102
 
102
103
  ## Success Criteria
103
104
  - [ ] <concrete, checkable>
@@ -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, Grep, Glob, Write
5
+ allowed-tools: Read, Edit, Write, Grep, Glob, Bash
6
6
  shell-timeout: 10
7
7
  disable-model-invocation: true
8
8
  contract:
@@ -52,8 +52,18 @@ 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. **Write the elaboration doc** (below), `status: ready`. Its filename pairs to the plan so the splice can fold it back deterministically — see Output document.
56
- 7. **Print the path**, then a one-line summary: `Phase N elaborated: <k> files, <m> code blocks`.
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
+ - **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 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
+ - **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
+ - **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 applicable check above. A clean phase still emits unchanged — the self-check is a no-op pass that reverts byte-identical.
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
+ 8. **Print the path**, then a one-line summary: `Phase N elaborated: <k> files, <m> code blocks`.
57
67
 
58
68
  ## Output document
59
69
 
@@ -80,15 +90,15 @@ tags: [elaboration]
80
90
 
81
91
  ### Changes
82
92
 
83
- #### `path/to/file.ts`
93
+ #### `path/to/file.ext`
84
94
  <one line: what and why>
85
- ```ts
95
+ ```<lang>
86
96
  <implement-ready code — the function/section to add, or the exact edit, grounded in the current file>
87
97
  ```
88
98
 
89
- #### `path/to/other.ts`
99
+ #### `path/to/other.ext`
90
100
  <one line>
91
- ```ts
101
+ ```<lang>
92
102
  <code>
93
103
  ```
94
104
 
@@ -106,7 +116,9 @@ tags: [elaboration]
106
116
 
107
117
  - **One phase only.** Never write code for a file another phase owns; reference its interfaces by the shape `synthesize` already fixed.
108
118
  - **Implement-ready code, grounded in the current tree.** Read the cited files first; emit code blocks, not prose hand-waving ("handle appropriately", "etc.").
109
- - **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:42`), never a subdirectory-relative form (`src/invoice.ts:42`) 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.
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.
110
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`.
111
- - **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.
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 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.
112
124
  - **No subagents. No self-review. No `ask_user_question`.** Decide, record any deferral in Notes, write — the grade panel is the validation.