@juicesharp/rpiv-pi 2.6.2 → 2.6.3

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.
@@ -66,13 +66,21 @@ handles the working directory, but it still checks
66
66
 
67
67
  Delivery is a hidden message with `customType: "rpiv-guidance"`. An in-process set
68
68
  deduplicates it, cleared on `session_start`, `session_compact`, and `session_shutdown`.
69
- Run `pi --rpiv-debug` to see the messages as they are sent.
69
+ A compaction hook never sends context directly: sending while overflow recovery is active
70
+ creates steering queue items. Instead, the compacted session is marked by identity and
71
+ root guidance is merged with the pipeline pointer and a forced-fresh Git read in one hidden
72
+ `before_agent_start` message on that session's next real user turn. The per-session marker
73
+ and forced reads prevent concurrent detached sessions from consuming its restoration. Overflow retry itself
74
+ resumes from the compaction summary without a synthetic last message. Run
75
+ `pi --rpiv-debug` to see the messages as they are sent.
70
76
 
71
77
  ## Git context injection
72
78
 
73
- Branch, short commit, and user are injected at `session_start`, re-injected after
74
- `session_compact`, and on `before_agent_start` only when they changed — a git-mutating
75
- bash command invalidates the cache. `customType: "rpiv-git-context"`, also revealed by
79
+ Branch, short commit, and user are injected at `session_start`; after
80
+ `session_compact` they join the one deferred next-user-turn context message; otherwise
81
+ `before_agent_start` injects them only when they changed — a git-mutating bash command
82
+ invalidates the cache. Standalone messages use `customType: "rpiv-git-context"`; the
83
+ merged recovery message uses `"rpiv-post-compact-context"`. Both are revealed by
76
84
  `--rpiv-debug`.
77
85
 
78
86
  Git is optional. If the `git` calls fail, the injection is skipped and nothing else
@@ -82,8 +90,9 @@ changes. When `git config user.name` is empty, `$USER` is used, then `unknown`.
82
90
 
83
91
  20 of the 29 skills set `disable-model-invocation: true`, which hides them from the
84
92
  model's skill list so it cannot wander into a design pass mid-conversation. To keep them
85
- discoverable, a roughly 120-token stage index is injected at `session_start` — hidden
86
- by default, visible under `--rpiv-debug`.
93
+ discoverable, a roughly 120-token stage index is injected at `session_start` and folded
94
+ into the first real user turn after compaction — hidden by default, visible under
95
+ `--rpiv-debug`.
87
96
 
88
97
  ## Sibling coupling
89
98
 
package/docs/skills.md CHANGED
@@ -31,7 +31,7 @@ whether the model may reach for it on its own.
31
31
 
32
32
  | Skill | Auto | Consumes | Writes | What it does |
33
33
  | --- | :---: | --- | --- | --- |
34
- | `design` | — | `research` or `solutions` | `designs/` | Decomposes a feature into vertical slices, generates code slice by slice with per-slice `slice-verifier` dispatch, and emits architecture decisions, slice breakdown, and file map. |
34
+ | `design` | — | `research` or `solutions`; `--resume` accepts an in-progress `design` | `designs/` | Decomposes a feature into vertical slices, generates and verifies one slice per session, and emits architecture decisions, slice breakdown, and file map. After each approved non-final slice, its exact payload is written to the artifact and re-read to confirm the match and the skill stops with a fresh-session `--resume` command so conversational compaction never carries approved code. |
35
35
  | `design-slice` | — | `slices` (+ upstream `design`) | `designs/` | Designs exactly ONE slice in isolation — decisions, file map, key interfaces, integration points, success criteria. A fanout unit, not standalone. |
36
36
  | `design-review` | — | every per-slice `design` + the `slices` map | in-place edits | One consolidated developer checkpoint over a whole design fanout: accept or adjust the proposed shape, adjustments applied surgically and cascaded to dependent slices. |
37
37
  | `synthesize` | — | N `designs` (or N `subplans`) | `plans/`, `subplans/` | Merges independent per-slice designs into one coherent phased plan, reconciling overlaps and ordering phases by slice dependency. Runs hierarchically for large slice maps via `--as-subplan`. |
package/docs/workflows.md CHANGED
@@ -49,7 +49,7 @@ code is elaborated into it. Three automated gates plus one human checkpoint.
49
49
 
50
50
  `goal → research → plan → plan-cite-check → grade → implement → implement-scope-check → reconcile → validate → commit`
51
51
 
52
- Ship a small, well-understood task in one lightweight forward pass. The verbatim brief is the goal artifact; a trimmed research stage (at most two `codebase-analyzer` dispatches — not a full `/skill:research` pass) grounds a single unsliced plan from `quick-plan`, which receives the verbatim goal alongside the research doc and must explicitly defer any goal ask it narrows out; a deterministic citation floor and one tier-independent three-dimension grade (correctness, completeness, architecture-fit — architecture-fit cannot be dropped from a light roster) gate the plan before `implement`. Every gate is stop-on-fail — no fix loops, confirm panels, snapshots, or code-elaboration lane — and a red gate surfaces as `stopped at <gate>: <reason>` in the end-of-run toast and lane recap (never a ✓); a goal-anchored `validate` judges the landing before `commit`. Best for tasks small enough to plan in one pass; prefer `build` for anything needing decomposition.
52
+ Ship a small, well-understood task in one lightweight forward pass. The verbatim brief is the goal artifact; a trimmed research stage (at most two `codebase-analyzer` dispatches — not a full `/skill:research` pass) grounds a single unsliced plan from `quick-plan`, which receives the verbatim goal alongside the research doc and must explicitly defer any goal ask it narrows out; a deterministic citation floor and one tier-independent three-dimension grade (correctness, completeness, architecture-fit — architecture-fit cannot be dropped from a light roster) gate the plan before `implement`. The citation floor stops the run only on a fabrication-shaped defect — a cited path that resolves to no tree file by any strategy, or a phase body edit missing from its `files:` declaration; citation ambiguity and line drift are advisory (recorded on the verdict, severity `low`) and ride to the grade panel, whose correctness unit receives the floor's verdict as `--cite-check` and adjudicates each finding by symbol instead of the run dying over a path-prefix omission. Every gate is stop-on-fail — no fix loops, confirm panels, snapshots, or code-elaboration lane — and a red gate surfaces as `stopped at <gate>: <reason>` in the end-of-run toast and lane recap (never a ✓); a goal-anchored `validate` judges the landing before `commit`. Best for tasks small enough to plan in one pass; prefer `build` for anything needing decomposition.
53
53
 
54
54
  ## Review loops
55
55
 
@@ -1037,14 +1037,30 @@ const sliceCovers = (entry: Record<string, unknown>): string[] => {
1037
1037
  * matches; an ambiguous suffix stays unresolved (the finding names the
1038
1038
  * candidates so the fix arm can disambiguate) unless one of two tiebreaks names
1039
1039
  * a single candidate: the caller's declared-`files:` union, then the nearest
1040
- * preceding prose mention of a candidate's full path. A citation that names no real
1041
- * file, or points past end-of-file, is UNBACKED precision — a fabricated
1042
- * reference that must fail the gate rather than propagate into design. A bare
1043
- * `path` with no `:line` is not checked (the contract is "verifiable line
1044
- * numbers, or omit them"). Returns one finding per bad citation.
1040
+ * preceding prose mention of a candidate's full path. A bare `path` with no
1041
+ * `:line` is not checked (the contract is "verifiable line numbers, or omit
1042
+ * them"). Returns one finding per bad citation.
1043
+ *
1044
+ * EVERY finding this verifier emits is ADVISORY (`StructureFinding.advisory`):
1045
+ * an advisory-only structure verdict rates `low`, which the gates'
1046
+ * `allDimensionsPass` severity floor rides through, so citation-resolution
1047
+ * findings are recorded on the trail — and handed to the ship grade panel via
1048
+ * `--cite-check` for symbol-level adjudication — but never stop a run. The
1049
+ * run-history audit forced this: across three months, 71 distinct flagged
1050
+ * paths yielded ZERO fabrications — the no-match population was resolver
1051
+ * limitations (suffix/dep/skipped-tree gaps), meta-plan fixture prose, and one
1052
+ * garbled-but-real path — while the blocking tier cost ~8h of fix rounds, two
1053
+ * dead ship runs, and one four-round identical-findings churn loop. Blocking
1054
+ * severity on the shared structure verdict comes ONLY from
1055
+ * `verifyPhaseFilesCoverage` (an undeclared write corrupts dep derivation —
1056
+ * that floor stays load-bearing).
1045
1057
  */
1046
1058
  /** Trees a citation must never resolve INTO — vendored deps, build copies, or
1047
- * prior pipeline artifacts (a stale artifact copy would back a fabricated line). */
1059
+ * prior pipeline artifacts (a stale artifact copy would back a fabricated line).
1060
+ * `.rpiv` is skipped with one carve-out: the walk re-enters `.rpiv/guidance`
1061
+ * (see `buildBasenameIndex`) — the guidance shadow tree is a legitimate,
1062
+ * routinely-cited and routinely-edited target, and skipping it made every
1063
+ * suffix-form `architecture.md` citation a false "does not exist". */
1048
1064
  const CITATION_WALK_SKIP: ReadonlySet<string> = new Set(["node_modules", ".git", "dist", "coverage", ".rpiv"]);
1049
1065
  /** Backstop so a pathological tree can't stall the deterministic cite floor. */
1050
1066
  const CITATION_WALK_FILE_CAP = 50_000;
@@ -1088,6 +1104,11 @@ const buildBasenameIndex = (cwd: string): BasenameIndex => {
1088
1104
  for (const e of listDir(dir)) {
1089
1105
  if (e.isDirectory()) {
1090
1106
  if (!CITATION_WALK_SKIP.has(e.name)) stack.push(join(dir, e.name));
1107
+ // `.rpiv` is skipped for its artifact/run trees (a stale artifact
1108
+ // copy must never back a citation), but the guidance shadow tree
1109
+ // under it is a first-class citation target the pipeline itself
1110
+ // edits — carve it back into the walk (missing dir ⇒ empty listing).
1111
+ else if (e.name === ".rpiv") stack.push(join(dir, e.name, "guidance"));
1091
1112
  continue;
1092
1113
  }
1093
1114
  if (!e.isFile()) continue;
@@ -1154,13 +1175,22 @@ const resolveCitationPath = (
1154
1175
  cwd: string,
1155
1176
  indexHolder: { value: BasenameIndex | undefined },
1156
1177
  ): CitationResolution | undefined => {
1178
+ // existsSync-then-statSync races a concurrent delete into a throw OUT of the
1179
+ // deterministic floor (⇒ FAIL_SCRIPT_THREW) — one guarded probe instead.
1180
+ const isTreeFile = (p: string): boolean => {
1181
+ try {
1182
+ return statSync(p).isFile();
1183
+ } catch {
1184
+ return false;
1185
+ }
1186
+ };
1157
1187
  // Strategy 1 — direct.
1158
1188
  const direct = isAbsolute(path) ? path : join(cwd, path);
1159
- if (existsSync(direct) && statSync(direct).isFile()) return { abs: direct };
1189
+ if (isTreeFile(direct)) return { abs: direct };
1160
1190
  // Strategies 2 & 3 — dependency probes (lockfile-pinned dep source; the regex
1161
1191
  // cannot carry `@`, so `node_modules/@scope/pkg/f.js` is cited as `scope/pkg/f.js`).
1162
1192
  for (const candidate of [join(cwd, "node_modules", path), join(cwd, "node_modules", `@${path}`)]) {
1163
- if (existsSync(candidate) && statSync(candidate).isFile()) return { abs: candidate };
1193
+ if (isTreeFile(candidate)) return { abs: candidate };
1164
1194
  }
1165
1195
  // Strategy 4 — suffix fallback: back the citation iff exactly ONE tree file matches.
1166
1196
  const matches = suffixMatchesFor(path, cwd, indexHolder);
@@ -1226,12 +1256,8 @@ const nearestProseMention = (
1226
1256
  return bestAbs;
1227
1257
  };
1228
1258
 
1229
- const verifyCitations = (
1230
- body: string,
1231
- cwd: string,
1232
- declared?: ReadonlySet<string>,
1233
- ): { detail: string; where: string }[] => {
1234
- const findings: { detail: string; where: string }[] = [];
1259
+ const verifyCitations = (body: string, cwd: string, declared?: ReadonlySet<string>): StructureFinding[] => {
1260
+ const findings: StructureFinding[] = [];
1235
1261
  const seen = new Set<string>();
1236
1262
  // Fenced text is example/fixture territory, not prose asserting a real
1237
1263
  // file:line — a fenced placeholder shaped like a citation must not fail the
@@ -1292,14 +1318,38 @@ const verifyCitations = (
1292
1318
  findings.push({
1293
1319
  detail: `Unbacked citation ${key} — ${path} matches ${resolved.ambiguous.length} tree files (${shown.join(", ")}${resolved.ambiguous.length > shown.length ? ", …" : ""}); a citation must name ONE file. Disambiguate with the repo-root-relative path.`,
1294
1320
  where: key,
1321
+ // Every candidate is a REAL tree file — advisory per the tier above.
1322
+ advisory: true,
1295
1323
  });
1296
1324
  continue;
1297
1325
  }
1298
- const abs = resolved?.abs;
1326
+ let abs = resolved?.abs;
1327
+ if (abs === undefined && declared !== undefined) {
1328
+ // Declared-write-set rescue on a NO-MATCH resolution — the ambiguity
1329
+ // tiebreak's missing twin (observed live: a declared `.rpiv/guidance/**`
1330
+ // file's suffix citation landed here as "does not exist" because the
1331
+ // suffix walk skips that tree, and the declared set was never asked).
1332
+ // A unique whole-segment suffix match inside the plan's own `files:`
1333
+ // names the file the author means: verify against it when it exists on
1334
+ // disk; a declared file ABSENT from the tree is a planned CREATE — the
1335
+ // citation is a forward reference to planned content, unverifiable at
1336
+ // this revision, so it yields no finding.
1337
+ const matches = [...declared].filter((d) => d === path || `/${d}`.endsWith(`/${path}`));
1338
+ if (matches.length === 1) {
1339
+ const cand = join(cwd, matches[0]);
1340
+ if (!existsSync(cand)) continue;
1341
+ abs = cand;
1342
+ }
1343
+ }
1299
1344
  if (!abs) {
1300
1345
  findings.push({
1301
1346
  detail: `Unbacked citation ${key} — the cited file does not exist at this revision. A file:line citation must resolve, or the line numbers must be omitted. Fix the path (repo-root-relative, or node_modules/<pkg>/… for an installed dependency file) or drop the citation.`,
1302
1347
  where: key,
1348
+ // Advisory like every citation-resolution finding: the observed
1349
+ // no-match population was garbled-but-real paths, skipped-tree
1350
+ // files, and fixture prose — the grade panel adjudicates via
1351
+ // `--cite-check` instead of the floor blocking on it.
1352
+ advisory: true,
1303
1353
  });
1304
1354
  continue;
1305
1355
  }
@@ -1312,6 +1362,8 @@ const verifyCitations = (
1312
1362
  findings.push({
1313
1363
  detail: `Unbacked citation ${key} — ${path} resolved but could not be read at this revision. A file:line citation must be verifiable, or the line numbers must be omitted. Fix the path (repo-root-relative) or drop the citation.`,
1314
1364
  where: key,
1365
+ // The file EXISTS (it resolved) — advisory per the tier above.
1366
+ advisory: true,
1315
1367
  });
1316
1368
  continue;
1317
1369
  }
@@ -1320,6 +1372,8 @@ const verifyCitations = (
1320
1372
  findings.push({
1321
1373
  detail: `Unbacked citation ${key} — ${path} has ${lineCount} lines, so line ${high} matches no version of the file. A file:line citation must be verifiable, or the line numbers must be omitted. Correct the range or drop the line numbers.`,
1322
1374
  where: key,
1375
+ // The file exists; only the ordinate drifted — advisory per the tier above.
1376
+ advisory: true,
1323
1377
  });
1324
1378
  }
1325
1379
  }
@@ -1754,11 +1808,15 @@ const EXTENSIONLESS_FILENAME_RE =
1754
1808
  * stripping a `:line` suffix (the blueprint MODIFY heading — `#### N. path/to/file.ext`
1755
1809
  * with a `:12-30` range appended — carries a line range the bare form rejects).
1756
1810
  * Extensionless recognition is allowlist-only (never "any `/`-bearing token"):
1757
- * prose like `and/or` must not read as a declared write. */
1811
+ * prose like `and/or` must not read as a declared write. The extension is
1812
+ * bounded to 1–5 chars starting with a letter (mirroring
1813
+ * FILE_LINE_CITATION_RE) so a dotted IDENTIFIER never reads as a file — a
1814
+ * backticked `deps.finalize` in a phase body cost a live run a blocking
1815
+ * coverage finding and a full code-fix round. */
1758
1816
  const isPathLike = (s: string): boolean => {
1759
1817
  if (/\s/.test(s)) return false;
1760
1818
  if (EXTENSIONLESS_FILENAME_RE.test(s.slice(s.lastIndexOf("/") + 1))) return true;
1761
- return /\.[A-Za-z0-9]+$/.test(s) && (s.includes("/") || /^[\w.-]+\.[A-Za-z0-9]+$/.test(s));
1819
+ return /\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(s) && (s.includes("/") || /^[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(s));
1762
1820
  };
1763
1821
 
1764
1822
  /**
@@ -1783,19 +1841,30 @@ const editPathsOfPhase = (phaseBody: string): string[] => {
1783
1841
  const stripped = stripLineSuffix(raw.replace(/[`*]/g, "").trim());
1784
1842
  if (stripped && isPathLike(stripped)) files.add(stripped);
1785
1843
  };
1844
+ // The list-item form is scoped to a Changes section (`### Changes` heading or
1845
+ // a `**Changes**:` field line): a backticked bullet elsewhere in the body is
1846
+ // a REFERENCE ("mirror `x/state.ts`"), not a declared write — unscoped, those
1847
+ // read as coverage gaps and block. Any other heading or `**Field**:` label
1848
+ // exits the scope; `**File(s)**:` lines don't flip it (they're the path form
1849
+ // themselves and legitimately precede `**Changes**:`).
1850
+ let inChanges = false;
1786
1851
  forEachLineOutsideFences(phaseBody, (line) => {
1852
+ const heading = line.match(/^#{2,5}\s+(.*)$/);
1853
+ if (heading) inChanges = /^changes\b/i.test(heading[1].trim());
1787
1854
  const fm = line.match(/^\*\*Files?\*\*:\s*(.+)$/);
1788
1855
  if (fm) {
1789
1856
  for (const tok of fm[1].split(/[,\s]+/)) add(tok);
1790
1857
  return;
1791
1858
  }
1859
+ const label = line.match(/^\*\*([A-Za-z][A-Za-z ]*)\*\*:/);
1860
+ if (label?.[1]) inChanges = /^changes$/i.test(label[1].trim());
1792
1861
  const hm = line.match(/^#{3,4}\s+\d+\.\s+(\S+)/);
1793
1862
  if (hm) {
1794
1863
  add(hm[1]);
1795
1864
  return;
1796
1865
  }
1797
1866
  const lm = line.match(/^-\s+`([^`]+)`/);
1798
- if (lm) add(lm[1]);
1867
+ if (lm && inChanges) add(lm[1]);
1799
1868
  });
1800
1869
  return [...files];
1801
1870
  };
@@ -1838,6 +1907,13 @@ const verifyPhaseFilesCoverage = (content: string, who: string, path: string): {
1838
1907
  const declared = new Set(phaseFiles(entry));
1839
1908
  for (const editPath of editPathsOfPhase(body)) {
1840
1909
  if (declared.has(editPath)) continue;
1910
+ // Whole-segment suffix tolerance: a body form citing the file by bare
1911
+ // basename or partial path (`#### 2. config.ts` for a declared
1912
+ // `packages/x/config.ts`) is covered by the declaration — exact-match
1913
+ // only made such a heading unfixable except by polluting `files:` with
1914
+ // the bare name (which then corrupts dep derivation and the scope
1915
+ // floor, the very consumers this floor protects).
1916
+ if ([...declared].some((d) => `/${d}`.endsWith(`/${editPath}`) || `/${editPath}`.endsWith(`/${d}`))) continue;
1841
1917
  findings.push({
1842
1918
  detail: `Phase ${n} names edit path ${editPath} in its body but does not declare it in its frontmatter 'files:' array. Every path a phase creates or edits must be listed in 'files:' (repo-root-relative, never a bare basename) so the plan-time coverage floor and the dep-gated implement fanout see the phase's full write set. Add ${editPath} to phase ${n}'s 'files:' array, or drop the body reference if the write belongs to another phase.`,
1843
1919
  where: `${who} ${path} phase ${n}: ${editPath}`,
@@ -3047,7 +3123,11 @@ const CODE_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-ver
3047
3123
  * correctness), and the `freshVerdicts` / `latestVerdictPerDimension` /
3048
3124
  * `dimensionsToRegrade` carry-forward so a re-grade emits only still-pending
3049
3125
  * dimensions. Tier-independence is structural: the roster never shrinks, so a
3050
- * light run still grades `architecture-fit`.
3126
+ * light run still grades `architecture-fit`. Ship-only addition: the
3127
+ * correctness unit carries `--cite-check <verdict>` when the deterministic
3128
+ * citation floor recorded findings — advisory by construction here, since a
3129
+ * blocking finding STOPs at the cite gate before grade ever runs — so the
3130
+ * grader adjudicates them rather than leaving them unread.
3051
3131
  */
3052
3132
  export const SHIP_DIMENSION_FANOUT = fanout({
3053
3133
  source: "plans",
@@ -3061,6 +3141,15 @@ export const SHIP_DIMENSION_FANOUT = fanout({
3061
3141
  const contextFlag = research?.handle.kind === "fs" ? ` --context ${handleToString(research.handle)}` : "";
3062
3142
  const goal = latestFsArtifact(state, "goal");
3063
3143
  const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
3144
+ // The floor's findings (advisory by construction — see the fanout doc
3145
+ // above) thread as `--cite-check`; no findings ⇒ no flag.
3146
+ const cite = latestFsArtifact(state, "plan-cite-check");
3147
+ const citeFindings = (state.named["plan-cite-check"]?.at(-1)?.data as { findings?: unknown[] } | undefined)
3148
+ ?.findings;
3149
+ const citeFlag =
3150
+ cite?.handle.kind === "fs" && Array.isArray(citeFindings) && citeFindings.length > 0
3151
+ ? ` --cite-check ${handleToString(cite.handle)}`
3152
+ : "";
3064
3153
  // Tier-independent roster: SHIP_DIMENSIONS verbatim — never gateRoster(gateTier(...)).
3065
3154
  const roster = SHIP_DIMENSIONS;
3066
3155
  const latest = latestVerdictPerDimension(freshVerdicts(state.named["ship-verdicts"], target));
@@ -3068,7 +3157,7 @@ export const SHIP_DIMENSION_FANOUT = fanout({
3068
3157
  const pending = dimensionsToRegrade(roster, latest, risks);
3069
3158
  const carryForward = pending.length > 0 ? pending : roster;
3070
3159
  return carryForward.map((d) => ({
3071
- prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}`,
3160
+ prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}${d === "correctness" ? citeFlag : ""}`,
3072
3161
  label: d,
3073
3162
  id: `plans-dim-${d}`,
3074
3163
  }));
@@ -3985,7 +4074,11 @@ const buildWorkflow = defineWorkflow({
3985
4074
  */
3986
4075
  const shipCiteStopNote = (state: RunView): string => {
3987
4076
  const data = state.named["plan-cite-check"]?.at(-1)?.data as { findings?: unknown } | undefined;
3988
- const n = Array.isArray(data?.findings) ? data.findings.length : 0;
4077
+ // Blocking findings only — the gate passes an advisory-only (severity `low`)
4078
+ // verdict, so when this note renders the blockers are what stopped the run.
4079
+ const n = Array.isArray(data?.findings)
4080
+ ? data.findings.filter((f) => (f as { advisory?: boolean } | null)?.advisory !== true).length
4081
+ : 0;
3989
4082
  return n > 0 ? `plan citation check failed (${n} finding${n === 1 ? "" : "s"})` : "plan citation check failed";
3990
4083
  };
3991
4084
  const shipGradeStopNote = (state: RunView): string => {
@@ -4009,7 +4102,10 @@ const shipGradeStopNote = (state: RunView): string => {
4009
4102
  // Named (not inline) so the stop branch can self-reference for setRouteNote —
4010
4103
  // the same closure-over-own-binding pattern gate()/match() use internally.
4011
4104
  // Citation-floor gate. Pass ⇒ grade; fail ⇒ STOP (no fix arm — the lightweight
4012
- // preset terminates on any red gate). The route folds `allDimensionsPass` over
4105
+ // preset terminates on any red gate). Only BLOCKING findings fail here: an
4106
+ // advisory-only verdict rates `low` and rides through `allDimensionsPass`'
4107
+ // severity floor to grade, where the correctness unit adjudicates it
4108
+ // (`--cite-check`). The route folds `allDimensionsPass` over
4013
4109
  // the stage's OWN published channel, NOT `match("verdict", …)`:
4014
4110
  // `writeStructureVerdict` (the floor's envelope) carries no `verdict` field, so
4015
4111
  // a verdict match would misread — this mirrors build's `planGatePasses` first
@@ -4055,7 +4151,7 @@ const shipGradeGate: EdgeFn = defineRoute(
4055
4151
  const shipWorkflow = defineWorkflow({
4056
4152
  name: "ship",
4057
4153
  description:
4058
- "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with at most two targeted codebase-analyzer dispatches (no /skill:research) → one lightweight quick-plan pass → deterministic citation floor → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate terminates the run on fail; no fix loops.",
4154
+ "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with at most two targeted codebase-analyzer dispatches (no /skill:research) → one lightweight quick-plan pass → deterministic citation floor (fabricated paths and coverage gaps stop; ambiguity and line drift pass as advisory findings the grade panel adjudicates) → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate terminates the run on fail; no fix loops.",
4059
4155
  start: "goal",
4060
4156
  stages: {
4061
4157
  // build's verbatim goal capture — the brief on its own channel, plus the
@@ -4079,7 +4175,10 @@ const shipWorkflow = defineWorkflow({
4079
4175
  // explicitly instead of silently inheriting the drop.
4080
4176
  plan: produces({ skill: "quick-plan", reads: ["research", "goal"] }),
4081
4177
  // Deterministic citation floor BEFORE the LLM gate — build's verifier
4082
- // verbatim. A fabricated `file:line` fails structurally and STOPs the run.
4178
+ // verbatim. A fabricated `file:line` (resolving to NOTHING) or a `files:`
4179
+ // coverage gap fails structurally and STOPs the run; advisory findings
4180
+ // (ambiguity/drift — see verifyCitations' tier) rate `low`, pass the gate,
4181
+ // and reach the grade panel's correctness unit as `--cite-check`.
4083
4182
  "plan-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("plan-cite-check") }),
4084
4183
  // Single PRE-implement grade over the fixed three-dimension roster
4085
4184
  // (SHIP_DIMENSION_FANOUT — tier-independent, no confirm/snapshot arms);
@@ -78,8 +78,11 @@ const VERDICT_FAIL_SCORE = 0;
78
78
  const FILE_LINE_CITATION_RE = /((?:(?<![\w.])\.)?(?<!\w)[\w][\w./-]*\.[a-zA-Z][a-zA-Z0-9]{0,4}):(\d+)(?:-(\d+))?/g;
79
79
 
80
80
  /** A structure-dimension finding — the shared shape the deterministic verdict
81
- * checks emit (`detail` is the actionable message, `where` locates the defect). */
82
- type StructureFinding = { detail: string; where: string };
81
+ * checks emit (`detail` is the actionable message, `where` locates the defect).
82
+ * `advisory: true` marks a finding that must be RECORDED but never BLOCK a gate
83
+ * (citation ambiguity/drift — resolver limitations, not fabrication signal);
84
+ * absent means blocking. */
85
+ type StructureFinding = { detail: string; where: string; advisory?: true };
83
86
 
84
87
  /** An `fs` artifact handle (the only handle kind the verdict checks operate on). */
85
88
  type FsHandle = { kind: "fs"; path: string };
@@ -93,10 +96,14 @@ type FsHandle = { kind: "fs"; path: string };
93
96
  * idempotent across fix/reslice/re-dispatch rounds); `handle` is the artifact
94
97
  * the check inspected (serialized into `data.artifact` and basename-keyed).
95
98
  *
96
- * The `severity: pass ? "none" : "high"` floor is load-bearing: the gate routes
97
- * via `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently
98
- * passes a `pass:false` verdict rated `low`/`none`; a structural defect MUST
99
- * rate `high` or it ships. The `score` is the binary verdict scale (100 = clean,
99
+ * The severity tier is load-bearing: the gate routes via
100
+ * `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently passes
101
+ * a `pass:false` verdict rated `low`/`none`. Any BLOCKING finding rates the
102
+ * verdict `high` (a structural defect MUST rate `high` or it ships); a verdict
103
+ * whose findings are ALL `advisory` rates `low` — honest (`pass: false`, the
104
+ * findings persist on the trail and downstream readers see them) but
105
+ * deliberately below the gate floor, so a resolver limitation never terminates
106
+ * a loop-less preset. The `score` is the binary verdict scale (100 = clean,
100
107
  * 0 = finding; the gate keys off `severity`, never this number).
101
108
  *
102
109
  * `extra` lets a caller stamp additional gate-readable fields onto the verdict
@@ -111,11 +118,12 @@ const writeStructureVerdict = (
111
118
  extra?: Record<string, unknown>,
112
119
  ): Omit<Output, "meta"> => {
113
120
  const pass = findings.length === 0;
121
+ const blocking = findings.some((f) => f.advisory !== true);
114
122
  const data = {
115
123
  dimension: "structure",
116
124
  pass,
117
125
  score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
118
- severity: pass ? "none" : "high",
126
+ severity: pass ? "none" : blocking ? "high" : "low",
119
127
  artifact: handleToString(handle),
120
128
  findings,
121
129
  feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
@@ -2,6 +2,7 @@ export const FLAG_DEBUG = "rpiv-debug";
2
2
  export const MSG_TYPE_GIT_CONTEXT = "rpiv-git-context";
3
3
  export const MSG_TYPE_GUIDANCE = "rpiv-guidance";
4
4
  export const MSG_TYPE_PIPELINE_INDEX = "rpiv-pipeline-index";
5
+ export const MSG_TYPE_POST_COMPACT_CONTEXT = "rpiv-post-compact-context";
5
6
  /** Timeout for git exec calls (milliseconds). */
6
7
  export const GIT_EXEC_TIMEOUT_MS = 5000;
7
8
  /** Grace period before SIGKILL when terminating a timed-out pi install process. */
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Cached branch + short commit. Injected into the transcript once at
3
- * session_start, re-injected on session_compact (transcript cleared) and
4
- * only when the cached value changes (e.g. after a mutating git command).
3
+ * session_start; after session_compact it joins the one deferred next-user-turn
4
+ * context message; otherwise emitted only when the cached value changes (e.g.
5
+ * after a mutating git command).
5
6
  * Two parallel `git rev-parse` calls — one call can't combine
6
7
  * `--abbrev-ref` and `--short` cleanly because the `--abbrev-ref` mode
7
8
  * persists to subsequent revs. git itself resolves worktree gitdir
@@ -63,16 +64,36 @@ export function resetInjectedMarker(): void {
63
64
  lastInjectedSig = null;
64
65
  }
65
66
 
67
+ function signature(g: GitContext): string {
68
+ return `${g.branch}\n${g.commit}\n${g.user}`;
69
+ }
70
+
71
+ function formatGitContext(g: GitContext): string {
72
+ return `## Git Context\n- Branch: ${g.branch}\n- Commit: ${g.commit}\n- User: ${g.user}`;
73
+ }
74
+
75
+ /**
76
+ * Force a fresh read for one specifically compacted session. The ordinary cache
77
+ * and signature are process-global, so a concurrent session could otherwise
78
+ * consume the reset marker before the compacted session's next user turn.
79
+ */
80
+ export async function refreshGitContextForInjection(pi: ExtensionAPI): Promise<string | null> {
81
+ cache = await loadGitContext(pi);
82
+ if (!cache) return null;
83
+ lastInjectedSig = signature(cache);
84
+ return formatGitContext(cache);
85
+ }
86
+
66
87
  // Returns the message content to inject, or null if the transcript is
67
88
  // already up-to-date or we're not in a git repo. Updates the marker
68
89
  // whenever it returns non-null.
69
90
  export async function takeGitContextIfChanged(pi: ExtensionAPI): Promise<string | null> {
70
91
  const g = await getGitContext(pi);
71
92
  if (!g) return null;
72
- const sig = `${g.branch}\n${g.commit}\n${g.user}`;
93
+ const sig = signature(g);
73
94
  if (sig === lastInjectedSig) return null;
74
95
  lastInjectedSig = sig;
75
- return `## Git Context\n- Branch: ${g.branch}\n- Commit: ${g.commit}\n- User: ${g.user}`;
96
+ return formatGitContext(g);
76
97
  }
77
98
 
78
99
  export function isGitMutatingCommand(cmd: string): boolean {
@@ -125,34 +125,45 @@ export function clearInjectionState() {
125
125
  // ---------------------------------------------------------------------------
126
126
 
127
127
  /**
128
- * Inject the root `.rpiv/guidance/architecture.md` at session start.
128
+ * Take the root `.rpiv/guidance/architecture.md` payload without sending it.
129
129
  *
130
- * Called from `session_start` so the root guidance is available before the
131
- * first agent turn — without waiting for a read/edit/write tool_call.
132
- * Uses the same `injectedGuidance` Set for dedup, so `handleToolCallGuidance`
133
- * won't re-inject it later.
130
+ * The split between take and send lets `before_agent_start` merge deferred
131
+ * post-compaction context into ONE message. Calling `pi.sendMessage` from
132
+ * `session_compact` queues a steering turn while overflow recovery is active;
133
+ * one-at-a-time delivery can otherwise make the model answer injected context
134
+ * instead of resuming the interrupted user task. `force` bypasses the
135
+ * process-global dedup marker for a specifically compacted SessionManager, so
136
+ * another concurrent session cannot suppress that session's restoration.
134
137
  */
135
- export function injectRootGuidance(cwd: string, pi: ExtensionAPI): void {
138
+ export function takeRootGuidance(cwd: string, trigger = "auto-loaded at session start", force = false): string | null {
136
139
  const relativePath = ROOT_GUIDANCE_KEY;
137
140
 
138
- if (injectedGuidance.has(relativePath)) return;
141
+ if (!force && injectedGuidance.has(relativePath)) return null;
139
142
 
140
143
  const absolutePath = join(cwd, relativePath);
141
- if (!existsSync(absolutePath)) return;
144
+ if (!existsSync(absolutePath)) return null;
142
145
 
143
146
  let content: string;
144
147
  try {
145
148
  content = readFileSync(absolutePath, "utf-8");
146
149
  } catch {
147
- // Silent failure mirrors handleToolCallGuidance's posture — session_start
148
- // runs before any UI is bound, so a permissions/race error here must not
149
- // crash the hook. Don't mark as injected so a later tool_call can retry.
150
- return;
150
+ // Silent failure mirrors handleToolCallGuidance's posture. Don't mark as
151
+ // injected so a later tool_call can retry.
152
+ return null;
151
153
  }
152
154
  injectedGuidance.add(relativePath);
153
155
 
154
156
  const file: GuidanceFile = { relativePath, absolutePath, content, kind: "architecture" };
155
- sendGuidanceMessage(pi, wrapGuidance(formatLabel(file), content, "auto-loaded at session start"));
157
+ return wrapGuidance(formatLabel(file), content, trigger);
158
+ }
159
+
160
+ /**
161
+ * Inject root guidance at session start, before the first agent turn.
162
+ * Uses the same `injectedGuidance` Set as tool-call injection.
163
+ */
164
+ export function injectRootGuidance(cwd: string, pi: ExtensionAPI): void {
165
+ const content = takeRootGuidance(cwd);
166
+ if (content !== null) sendGuidanceMessage(pi, content);
156
167
  }
157
168
 
158
169
  // ---------------------------------------------------------------------------
@@ -9,9 +9,10 @@
9
9
  * the commands so the agent can route the developer to `/skill:<name>` instead of
10
10
  * improvising the workflow itself.
11
11
  *
12
- * Injected at `session_start` and re-injected after `session_compact`, mirroring
13
- * `injectRootGuidance` (session-hooks.ts owns the wiring). Stateless — both hooks
14
- * fire exactly once per (re)start, right after `resetInjectionState()`.
12
+ * Injected at `session_start`. After `session_compact`, session-hooks folds this
13
+ * constant into ONE deferred `before_agent_start` message on that exact session's
14
+ * next real user turn. It is never sent from the compaction hook: that would queue
15
+ * a steering item into overflow recovery and displace the interrupted task.
15
16
  */
16
17
 
17
18
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
@@ -20,16 +20,17 @@ import {
20
20
  syncBundledAgents,
21
21
  } from "./agents.js";
22
22
  import { renderBanner } from "./banner.js";
23
- import { FLAG_DEBUG, MSG_TYPE_GIT_CONTEXT } from "./constants.js";
23
+ import { FLAG_DEBUG, MSG_TYPE_GIT_CONTEXT, MSG_TYPE_POST_COMPACT_CONTEXT } from "./constants.js";
24
24
  import {
25
25
  clearGitContextCache,
26
26
  isGitMutatingCommand,
27
+ refreshGitContextForInjection,
27
28
  resetInjectedMarker,
28
29
  takeGitContextIfChanged,
29
30
  } from "./git-context.js";
30
- import { clearInjectionState, handleToolCallGuidance, injectRootGuidance } from "./guidance.js";
31
+ import { clearInjectionState, handleToolCallGuidance, injectRootGuidance, takeRootGuidance } from "./guidance.js";
31
32
  import { findMissingSiblings } from "./package-checks.js";
32
- import { injectPipelinePointer } from "./pipeline-pointer.js";
33
+ import { injectPipelinePointer, PIPELINE_POINTER } from "./pipeline-pointer.js";
33
34
  import { isStaleCtxError } from "./utils.js";
34
35
 
35
36
  /**
@@ -46,9 +47,17 @@ import { isStaleCtxError } from "./utils.js";
46
47
  */
47
48
  let startupMaintenanceDone = false;
48
49
 
50
+ /**
51
+ * Sessions whose compacted-away RPIV context must be restored on their next
52
+ * real user turn. Keying by SessionManager identity prevents a detached child
53
+ * compaction from arming the root launcher (or another concurrent child).
54
+ */
55
+ let postCompactSessions = new WeakSet<object>();
56
+
49
57
  /** Test reset — wired into test/setup.ts `beforeEach`. */
50
58
  export function __resetSessionHooksAnnounced(): void {
51
59
  startupMaintenanceDone = false;
60
+ postCompactSessions = new WeakSet<object>();
52
61
  }
53
62
 
54
63
  const msgAgentsAdded = (n: number) => `Copied ${n} rpiv-pi agent(s) to ~/.pi/agent/agents/`;
@@ -77,6 +86,20 @@ function buildGitContextMessage(pi: ExtensionAPI, content: string) {
77
86
  return { customType: MSG_TYPE_GIT_CONTEXT, content, display: !!pi.getFlag(FLAG_DEBUG) };
78
87
  }
79
88
 
89
+ function buildPostCompactContextMessage(pi: ExtensionAPI, rootGuidance: string | null, gitContext: string | null) {
90
+ const parts = [
91
+ "[rpiv post-compaction context — reference material, NOT a task. Do not acknowledge this block. Answer the user's current request; when it says to continue, resume from the compaction summary and authoritative artifacts.]",
92
+ PIPELINE_POINTER,
93
+ rootGuidance,
94
+ gitContext,
95
+ ].filter((part): part is string => part !== null);
96
+ return {
97
+ customType: MSG_TYPE_POST_COMPACT_CONTEXT,
98
+ content: parts.join("\n\n---\n\n"),
99
+ display: !!pi.getFlag(FLAG_DEBUG),
100
+ };
101
+ }
102
+
80
103
  function sendGitContextMessage(pi: ExtensionAPI, content: string) {
81
104
  pi.sendMessage(buildGitContextMessage(pi, content));
82
105
  }
@@ -87,7 +110,7 @@ function sendGitContextMessage(pi: ExtensionAPI, content: string) {
87
110
 
88
111
  export function registerSessionHooks(pi: ExtensionAPI): void {
89
112
  pi.on("session_start", async (_event, ctx) => onSessionStart(_event, ctx, pi));
90
- pi.on("session_compact", async (_event, ctx) => onSessionCompact(_event, ctx, pi));
113
+ pi.on("session_compact", async (_event, ctx) => onSessionCompact(_event, ctx));
91
114
  pi.on("session_shutdown", async () => onSessionShutdown());
92
115
  pi.on("tool_call", async (event, ctx) => onToolCall(event, ctx, pi));
93
116
  pi.on("before_agent_start", async (event, ctx) => onBeforeAgentStart(event, ctx, pi));
@@ -99,9 +122,10 @@ export function registerSessionHooks(pi: ExtensionAPI): void {
99
122
 
100
123
  async function onSessionStart(
101
124
  _event: unknown,
102
- ctx: { cwd: string; hasUI: boolean; ui: UI },
125
+ ctx: { cwd: string; hasUI: boolean; ui: UI; sessionManager: object },
103
126
  pi: ExtensionAPI,
104
127
  ): Promise<void> {
128
+ postCompactSessions.delete(ctx.sessionManager);
105
129
  resetInjectionState();
106
130
  injectRootGuidance(ctx.cwd, pi);
107
131
  injectPipelinePointer(pi);
@@ -124,22 +148,23 @@ async function onSessionStart(
124
148
  }
125
149
  }
126
150
 
127
- async function onSessionCompact(_event: unknown, ctx: { cwd: string }, pi: ExtensionAPI): Promise<void> {
151
+ async function onSessionCompact(_event: unknown, ctx: { sessionManager: object }): Promise<void> {
128
152
  resetInjectionState();
129
153
  clearGitContextCache();
130
154
  resetInjectedMarker();
131
- // Auto-compaction races session disposal: pi-core's AgentSession.dispose()
132
- // invalidates the extension runner while _runAutoCompaction is still emitting
133
- // session_compact, so both `ctx` and `pi` become dead proxies whose
134
- // getters/methods throw the stale error. Guessing a cwd buys nothing — the
135
- // very next pi.sendMessage throws the same way — and the compacting session
136
- // is being discarded anyway: the replacement session's session_start re-runs
137
- // all of this. So on a stale ctx, bail. Any other error is a real bug in
138
- // guidance/git injection and must propagate.
155
+ // NEVER call pi.sendMessage here. Auto-compaction runs before overflow retry
156
+ // settles, so injected messages become steering queue items. With Pi's default
157
+ // one-at-a-time delivery each item can consume its own assistant turn and
158
+ // displace the interrupted task. Mark this exact session instead; its next
159
+ // user-authored turn receives one merged context block from before_agent_start.
160
+ // Overflow retry itself proceeds from the compaction summary with no synthetic
161
+ // last message competing for the model's attention.
162
+ //
163
+ // Auto-compaction can also race session disposal. In that path ctx is a stale
164
+ // proxy and the replacement session's session_start performs normal injection,
165
+ // so swallowing only the canonical stale error remains correct.
139
166
  try {
140
- injectRootGuidance(ctx.cwd, pi);
141
- injectPipelinePointer(pi);
142
- await injectGitContext(pi, (msg) => sendGitContextMessage(pi, msg));
167
+ postCompactSessions.add(ctx.sessionManager);
143
168
  } catch (e) {
144
169
  if (!isStaleCtxError(e)) throw e;
145
170
  }
@@ -167,9 +192,20 @@ async function onToolCall(event: ToolCallEvent, ctx: ExtensionContext, pi: Exten
167
192
  // `takeGitContextIfChanged` which is its own dedup layer.
168
193
  async function onBeforeAgentStart(
169
194
  _event: BeforeAgentStartEvent,
170
- _ctx: ExtensionContext,
195
+ ctx: ExtensionContext,
171
196
  pi: ExtensionAPI,
172
- ): Promise<{ message: ReturnType<typeof buildGitContextMessage> } | undefined> {
197
+ ): Promise<
198
+ | { message: ReturnType<typeof buildGitContextMessage> }
199
+ | { message: ReturnType<typeof buildPostCompactContextMessage> }
200
+ | undefined
201
+ > {
202
+ if (postCompactSessions.has(ctx.sessionManager)) {
203
+ postCompactSessions.delete(ctx.sessionManager);
204
+ const rootGuidance = takeRootGuidance(ctx.cwd, "restored on the first user turn after compaction", true);
205
+ const gitContext = await refreshGitContextForInjection(pi);
206
+ return { message: buildPostCompactContextMessage(pi, rootGuidance, gitContext) };
207
+ }
208
+
173
209
  const content = await takeGitContextIfChanged(pi);
174
210
  if (!content) return undefined;
175
211
  return { message: buildGitContextMessage(pi, content) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-pi",
3
- "version": "2.6.2",
3
+ "version": "2.6.3",
4
4
  "description": "A skill-based development workflow for Pi Agent. 29 contract-carrying skills (discover → research → design → plan → implement → validate → code-review → commit, and more), the 15 named subagents they dispatch, and four built-in /wf workflows that chain them end to end in detached parallel runs.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -50,7 +50,7 @@
50
50
  ]
51
51
  },
52
52
  "dependencies": {
53
- "@juicesharp/rpiv-config": "^2.6.2",
53
+ "@juicesharp/rpiv-config": "^2.6.3",
54
54
  "typebox": "^1.1.24"
55
55
  },
56
56
  "peerDependencies": {
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: design
3
- description: Design complex features by decomposing them into vertical slices, generating code slice-by-slice with per-slice verifier dispatch and post-finalization independent code review, and producing a design artifact (architecture decisions, slice breakdown, file map) in .rpiv/artifacts/designs/. The design feeds the plan or blueprint skill. Use for complex multi-component features touching 6+ files across multiple layers, when the user wants a feature designed before implementation. Requires a research artifact or a solutions artifact (from explore). Prefer design over plan or blueprint when the focus is architecture and decomposition rather than phased execution steps.
4
- argument-hint: "[research artifact path]"
3
+ description: Design complex features by decomposing them into vertical slices, generating and verifying one slice per session, and producing a resumable design artifact (architecture decisions, slice breakdown, file map) in .rpiv/artifacts/designs/. The design feeds the plan or blueprint skill. Use for complex multi-component features touching 6+ files across multiple layers, when the user wants a feature designed before implementation. Requires a research artifact or a solutions artifact (from explore); resume an in-progress design with --resume. Prefer design over plan or blueprint when the focus is architecture and decomposition rather than phased execution steps.
4
+ argument-hint: "[research artifact path] | --resume <in-progress design path>"
5
5
  shell-timeout: 10
6
6
  disable-model-invocation: true
7
7
  contract:
@@ -30,7 +30,10 @@ You are tasked with designing how code will be shaped for a feature or change. T
30
30
 
31
31
  ## Input
32
32
 
33
- `$ARGUMENTS` — path to a research artifact (`.rpiv/artifacts/research/*.md`) or a solutions artifact (`.rpiv/artifacts/solutions/*.md`).
33
+ `$ARGUMENTS` takes two forms:
34
+
35
+ 1. **Start** — path to a research artifact (`.rpiv/artifacts/research/*.md`) or a solutions artifact (`.rpiv/artifacts/solutions/*.md`).
36
+ 2. **Resume** — `--resume <path-to-.rpiv/artifacts/designs/*.md>`. The design must have `status: in-progress`; the artifact, not a compaction summary, is authoritative for locked slices and the next pending slice.
34
37
 
35
38
  ## Metadata
36
39
 
@@ -61,7 +64,14 @@ The final artifact is plan-compatible: `## Slices` boundaries become phase bound
61
64
 
62
65
  When this command is invoked:
63
66
 
64
- 1. **Read research artifact**:
67
+ 1. **Resume mode first** — when `$ARGUMENTS` contains `--resume`:
68
+ - Parse exactly one design artifact path after the flag. If it is missing, outside `.rpiv/artifacts/designs/`, unreadable, or not `status: in-progress`, print the specific error and stop.
69
+ - Read the design artifact FULLY. Extract Decisions, Architecture, Slices, Verification Notes, Developer Context, and Design History.
70
+ - Find the first Design History entry still marked `pending`. Treat every earlier `approved` entry and its persisted code fences/Success Criteria as locked; never reconstruct them from conversation or a compaction summary.
71
+ - Read the current source files for that pending slice FULLY, plus Architecture entries for files the slice shares with locked predecessors.
72
+ - Skip Steps 2–5. Enter Step 6 at the pending slice. If no slice is pending, go directly to Step 7.
73
+
74
+ 2. **Read research artifact**:
65
75
 
66
76
  **Research artifact provided** (argument contains a path to a `.md` file in `.rpiv/artifacts/`):
67
77
  - Read the research artifact FULLY using the Read tool WITHOUT limit/offset
@@ -75,7 +85,7 @@ When this command is invoked:
75
85
  - **Exactly one entry total** — confirm with `ask_user_question`: "Design from this artifact?" with options "Design from `[<source>] <filename>` (Recommended)" and "Pick a different path".
76
86
  - **Two or more entries total** — present up to 4 most-recent across both listings as `ask_user_question` options, each prefixed `[research]` or `[solutions]` to flag source class.
77
87
 
78
- 2. **Read any additional files mentioned** — tickets, related designs, existing implementations. Read them FULLY before proceeding.
88
+ 3. **Read any additional files mentioned** — tickets, related designs, existing implementations. Read them FULLY before proceeding.
79
89
 
80
90
  ### Step 2: Targeted Research
81
91
 
@@ -319,7 +329,7 @@ If the slice introduces a new abstraction where an existing one would serve, or
319
329
 
320
330
  **If the developer asks to see full code**, show it inline — exception, not default.
321
331
 
322
- Use the `ask_user_question` tool to confirm. Question: "Slice {N/M}: {slice name} — {files affected}. {1-line summary}. Approve?". Header: "Slice {N}". Options: "Approve (Recommended)" (Lock this slice, write to artifact, proceed to slice {N+1}); "Revise this slice" (Adjust code before proceeding — describe what to change); "Rethink remaining slices" (This slice reveals a design issue — revisit decomposition); "Revisit a decision" (A Step-4 decision is wrong — return to Step 4 for that decision before continuing).
332
+ Use the `ask_user_question` tool to confirm. Question: "Slice {N/M}: {slice name} — {files affected}. {1-line summary}. Approve?". Header: "Slice {N}". Options: "Approve (Recommended)" (Lock this slice, write it exactly to the artifact, then stop at the session boundary); "Revise this slice" (Adjust code before proceeding — describe what to change); "Rethink remaining slices" (This slice reveals a design issue — revisit decomposition); "Revisit a decision" (A Step-4 decision is wrong — return to Step 4 for that decision before continuing).
323
333
 
324
334
  **Checkpoint cadence**: One slice per checkpoint. Present each slice individually, regardless of slice count.
325
335
 
@@ -329,7 +339,7 @@ Use the `ask_user_question` tool to confirm. Question: "Slice {N/M}: {slice name
329
339
  1. For each file in this slice, Edit the skeleton artifact to replace the empty code fence under that file's Architecture heading with the full generated code from 6.1
330
340
  2. If a later slice contributes to a file already filled by an earlier slice: **rewrite the entire code fence** with the merged result (do not append alongside existing code)
331
341
  3. After merge, verify within Architecture: no duplicate function definitions, imports deduplicated, exports list complete
332
- 4. **Write the slice's `## Slices` entry**: Edit the artifact to add a new `### Slice N: {name}` subsection under the top-level `## Slices` heading, containing:
342
+ 4. **Fill the slice's existing `## Slices` entry**: The skeleton already contains exactly one `### Slice N: {name}` subsection. Edit that subsection in place to replace its placeholder verification content with:
333
343
 
334
344
  ```markdown
335
345
  ### Slice N: {slice name}
@@ -346,9 +356,19 @@ Use the `ask_user_question` tool to confirm. Question: "Slice {N/M}: {slice name
346
356
  - [ ] Performance acceptable with 1000+ todo items
347
357
  ```
348
358
 
349
- This section is the contract handed to `/skill:plan` — slice boundaries become phase boundaries 1:1, and Success Criteria pass through unchanged. The bullets are the same `- [ ]` shape `implement` flips to `- [x]` and `validate` extracts commands from.
359
+ This section is the contract handed to `/skill:plan` — slice boundaries become phase boundaries 1:1, and Success Criteria pass through unchanged. The bullets are the same `- [ ]` shape `implement` flips to `- [x]` and `validate` extracts commands from. Never add a second Slice N heading; replace the skeleton subsection so heading count remains 1:1 with the decomposition.
350
360
  5. Update the Design History section: `- Slice N: {name} — approved as generated`
351
- - Proceed to next slice
361
+ 6. Re-read the just-written code fences and Success Criteria and verify they byte-match the approved payload. A mismatch keeps the slice in progress; correct it before stopping.
362
+ 7. If another slice remains, **STOP THE AGENT RUN**. Do not research, generate, or verify the next slice in this session. Print:
363
+
364
+ ```text
365
+ Slice N locked in `<design-path>`.
366
+ Start a fresh session with `/new`, then run:
367
+ `/skill:design --resume <design-path>`
368
+ ```
369
+
370
+ This hard session boundary prevents a sequence of verifier-heavy slices from growing inside one Pi agent run beyond the model context window. The persisted artifact is the handoff; compaction summaries are never exact-code carriers.
371
+ 8. Only when this was the final slice, continue to Step 7 in the current session.
352
372
 
353
373
  **Revise**: Update code per developer feedback. Re-run verify (6.2). Re-present the same slice (6.3). The artifact is NOT touched — only "Approve" writes to the artifact.
354
374
 
@@ -450,6 +470,7 @@ Spawn multiple agents in parallel when they're searching for different things. E
450
470
  - ALWAYS dispatch slice-verifier at Step 6.2 for every slice before presenting at 6.3; never skip, never batch across slices; slice-verifier sees code AND Success Criteria together
451
471
  - NEVER silently dismiss a slice-verifier VIOLATION — either fix and re-dispatch, or surface the verbatim finding to the developer at 6.3 for ratification
452
472
  - Post-finalization code + coverage review runs in `/skill:plan` Step 4 (not here); design's quality gate is per-slice via slice-verifier at 6.2
473
+ - ALWAYS stop after persisting and byte-checking one approved non-final slice; the next slice starts only through `/skill:design --resume <design-path>` in a fresh session. Never carry multiple verifier-heavy slices in one agent run.
453
474
  - Design flips `status: in-progress` → `status: ready` directly at Step 7; no `in-review` intermediate (no Step 8 reviewer to wait for)
454
475
  - NEVER skip the developer checkpoint — developer input on architectural decisions is the highest-value signal in the design process
455
476
  - NEVER edit source files — all code goes into the design document, not the codebase. This skill produces a document, not implementation. Source file editing is implement's job.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: grade
3
3
  description: Grade ONE artifact along ONE named quality dimension and write a verdict JSON to .rpiv/artifacts/verdicts/. Single-pass, no subagents, no fixes — it only judges. Dispatched once per dimension by a workflow's grade panel (a fanout over dimensions); the workflow folds the per-dimension verdicts into an advance/loop decision. Use as a panel member, not standalone.
4
- argument-hint: "--dimension <name> --artifact <path> [--context <path>] [--goal <path>] [--prior <verdict-path>]"
4
+ argument-hint: "--dimension <name> --artifact <path> [--context <path>] [--goal <path>] [--prior <verdict-path>] [--cite-check <verdict-path>]"
5
5
  allowed-tools: Read, Grep, Glob, Write
6
6
  shell-timeout: 10
7
7
  disable-model-invocation: true
@@ -67,6 +67,7 @@ You grade ONE artifact against ONE quality dimension and emit a verdict JSON. Yo
67
67
  - `--context <path>` *(optional)* — a supporting artifact (e.g. the research doc). **Required for `architecture-fit`.**
68
68
  - `--goal <path>` *(optional)* — the user's original brief, captured verbatim at run start. **Read it only for `completeness` and `correctness`** — every other dimension ignores it. Absent, or the file is empty → grade the artifact on its own content as usual.
69
69
  - `--prior <path>` *(optional)* — a prior round's verdict JSON for this same `(artifact, dimension)`, passed by a CONFIRM panel. Its presence puts you in **confirm mode** (see "Prior-round adjudication" below). If the path is missing or unreadable, grade normally without it — a stale prior is not a wiring error.
70
+ - `--cite-check <path>` *(optional, `correctness` only)* — the deterministic citation floor's verdict JSON for the same artifact, passed when the floor recorded advisory findings (citation ambiguity or line drift; a fabricated path already stopped the workflow before you were dispatched). Treat its `findings[]` as **leads to fold into your spot-check sample**, not conclusions — the Citation-resolution rule (step 4) alone decides whether any becomes a finding of yours. Every other dimension ignores this flag; it never triggers confirm mode and never produces `finding_rulings`. Missing or unreadable path → grade normally without it.
70
71
 
71
72
  **Plan-authored risk flags (the `correctness` dimension only).** When your `--dimension` is `correctness` and the `--artifact` carries a `risks:` frontmatter array (each `{ id, claim }`, described in the plan's `## Risk Flags` section), you are REQUIRED to rule on every flag — this is a first-class channel, not an optional prose aside. For each flag, verify its `claim` against the real codebase / the plan (Read/Grep the relevant `file:line`) and decide `pass` (the concern is unfounded or already handled) or `fail` (the risk is real and unaddressed). A `fail` ruling blocks the gate (the workflow folds these across the panel), so an assumption the plan flagged for review cannot ride a green pass into commit. Other dimensions ignore `risks:`.
72
73
 
@@ -113,9 +114,9 @@ Grade against the row matching `--dimension`. "Pass bar" is the line; meet it
113
114
  ## Steps
114
115
 
115
116
  1. **Parse + validate flags.** Bail per the Input rules above if malformed.
116
- 2. **Read fully** (no limit/offset): `--artifact`, and `--context` / `--goal` / `--prior` if given (skip `--goal` unless your dimension is `completeness` or `correctness`).
117
+ 2. **Read fully** (no limit/offset): `--artifact`, and `--context` / `--goal` / `--prior` / `--cite-check` if given (skip `--goal` unless your dimension is `completeness` or `correctness`; skip `--cite-check` unless your dimension is `correctness`).
117
118
  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. **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
+ 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. **On `correctness` with `--cite-check`, fold each of its findings into your spot-check sample** — the citation-resolution rule decides what, if anything, you report. **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
120
  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
121
  - `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
122
  - `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.)