@juicesharp/rpiv-pi 2.6.3 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/docs/workflows.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +10 -13
  3. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  4. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  5. package/extensions/rpiv-core/built-in-workflows.ts +233 -3514
  6. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  7. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  8. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  10. package/extensions/rpiv-core/built-ins/index.ts +46 -0
  11. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  15. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  16. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  17. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  18. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  19. package/extensions/rpiv-core/constants.ts +5 -1
  20. package/extensions/rpiv-core/lane-console.ts +9 -2
  21. package/extensions/rpiv-core/lane-list.ts +10 -1
  22. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  23. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  24. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  25. package/package.json +2 -2
  26. package/skills/elaborate/SKILL.md +1 -1
  27. package/skills/grade/SKILL.md +1 -1
  28. package/skills/implement/SKILL.md +1 -0
  29. package/skills/plan/SKILL.md +3 -1
  30. package/skills/remediate/SKILL.md +1 -0
  31. package/skills/synthesize/SKILL.md +1 -0
  32. package/skills/validate/SKILL.md +25 -19
  33. package/skills/validate/templates/validation.md +1 -1
@@ -0,0 +1,357 @@
1
+ /**
2
+ * The deterministic file:line citation verifier: resolves every `file:line`
3
+ * citation in an artifact body against the working tree, with basename-index
4
+ * suffix fallback and tiebreaks. Findings are advisory; blocking severity on
5
+ * the shared structure verdict comes only from the plan coverage floor.
6
+ */
7
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
8
+ import { basename, join, sep } from "node:path";
9
+ import { fencedSpans } from "./markdown-fence.js";
10
+ import { containedPath, FILE_LINE_CITATION_RE, type StructureFinding } from "./shared.js";
11
+
12
+ /**
13
+ * Verify every `file:line` citation in `body` resolves against the working tree:
14
+ * the cited file must exist AND carry at least the cited line (a range's high end).
15
+ * A path that misses direct (repo-root/absolute) resolution falls back to the
16
+ * tree file whose path ends with it on whole segments — bare basenames and
17
+ * package-relative forms both back the citation iff exactly ONE tree file
18
+ * matches; an ambiguous suffix stays unresolved (the finding names the
19
+ * candidates so the fix arm can disambiguate) unless one of two tiebreaks names
20
+ * a single candidate: the caller's declared-`files:` union, then the nearest
21
+ * preceding prose mention of a candidate's full path. A bare `path` with no
22
+ * `:line` is not checked (the contract is "verifiable line numbers, or omit
23
+ * them"). Returns one finding per bad citation.
24
+ *
25
+ * EVERY finding this verifier emits is ADVISORY (`StructureFinding.advisory`):
26
+ * an advisory-only structure verdict rates `low`, which the gates'
27
+ * `allDimensionsPass` severity floor rides through, so citation-resolution
28
+ * findings are recorded on the trail — and handed to the ship grade panel via
29
+ * `--cite-check` for symbol-level adjudication — but never stop a run. Blocking
30
+ * severity on the shared structure
31
+ * verdict comes ONLY from `verifyPhaseFilesCoverage` (an undeclared write
32
+ * corrupts dep derivation — that floor stays load-bearing).
33
+ */
34
+ /** Trees a citation must never resolve INTO — vendored deps, build copies, or
35
+ * prior pipeline artifacts (a stale artifact copy would back a fabricated line).
36
+ * `.rpiv` is skipped with one carve-out: the walk re-enters `.rpiv/guidance`
37
+ * (see `buildBasenameIndex`) — the guidance shadow tree is a legitimate,
38
+ * routinely-cited and routinely-edited target, and skipping it made every
39
+ * suffix-form `architecture.md` citation a false "does not exist". */
40
+ const CITATION_WALK_SKIP: ReadonlySet<string> = new Set(["node_modules", ".git", "dist", "coverage", ".rpiv"]);
41
+ /** Backstop so a pathological tree can't stall the deterministic cite floor. */
42
+ const CITATION_WALK_FILE_CAP = 50_000;
43
+
44
+ /** The lazily-built basename → absolute-path(s) index backing the suffix
45
+ * fallback in `resolveCitationPath`. `truncated` marks a partial walk past
46
+ * `CITATION_WALK_FILE_CAP`, which disables the fallback (uniqueness
47
+ * untrustworthy). */
48
+ type BasenameIndex = { index: Map<string, string[]>; truncated: boolean };
49
+
50
+ /**
51
+ * Index every source file's basename → its absolute path(s) under `cwd` — the
52
+ * candidate pool behind the suffix fallback in `verifyCitations`. The generative
53
+ * producers (slice/synthesize/elaborate) routinely cite a file by bare basename
54
+ * (`built-in-workflows.ts:1431`) or by a package-relative suffix
55
+ * (`validate/stage-rules.ts:70` for `packages/rpiv-workflow/validate/stage-rules.ts`)
56
+ * — mechanical path-prefix omissions, not fabricated references. The basename
57
+ * keys the candidates; `verifyCitations` narrows them by whole-segment suffix.
58
+ * A UNIQUE match backs the citation; an AMBIGUOUS one stays unresolved — unless
59
+ * one of `verifyCitations`' tiebreaks (the caller's declared-`files:` union,
60
+ * then the nearest preceding prose mention) names exactly one
61
+ * candidate — so the producer must disambiguate with the repo-root-relative
62
+ * path. Skips
63
+ * vendored/generated trees so a citation never resolves to a build copy or a
64
+ * prior artifact. Bounded by the file cap.
65
+ */
66
+ const buildBasenameIndex = (cwd: string): BasenameIndex => {
67
+ // Unreadable dir → empty listing, never a throw from the deterministic floor.
68
+ const listDir = (dir: string) => {
69
+ try {
70
+ return readdirSync(dir, { withFileTypes: true });
71
+ } catch {
72
+ return [];
73
+ }
74
+ };
75
+ const index = new Map<string, string[]>();
76
+ const stack: string[] = [cwd];
77
+ let seen = 0;
78
+ while (stack.length > 0) {
79
+ const dir = stack.pop() as string;
80
+ for (const e of listDir(dir)) {
81
+ if (e.isDirectory()) {
82
+ if (!CITATION_WALK_SKIP.has(e.name)) stack.push(join(dir, e.name));
83
+ // The guidance carve-out — see CITATION_WALK_SKIP's note. A missing
84
+ // guidance dir degrades to an empty listing.
85
+ else if (e.name === ".rpiv") stack.push(join(dir, e.name, "guidance"));
86
+ continue;
87
+ }
88
+ if (!e.isFile()) continue;
89
+ // Past the cap the index is INCOMPLETE, so "exactly one match" can no
90
+ // longer be trusted — mark it truncated and let the caller disable the
91
+ // fallback (strict direct-resolution only) rather than back a possibly
92
+ // wrong file off a partial walk.
93
+ if (++seen > CITATION_WALK_FILE_CAP) return { index, truncated: true };
94
+ const abs = join(dir, e.name);
95
+ const arr = index.get(e.name);
96
+ if (arr) arr.push(abs);
97
+ else index.set(e.name, [abs]);
98
+ }
99
+ }
100
+ return { index, truncated: false };
101
+ };
102
+
103
+ /** Outcome of resolving a single citation's `path` against `cwd`. `abs` is the
104
+ * one backing file when resolution is unique; `ambiguous` carries the candidate
105
+ * list (absolute paths) when more than one tree file matches, so the caller can
106
+ * render the disambiguation finding text. `undefined` ⇒ no match
107
+ * (does-not-exist). This is the minimal-deviation return shape — a plain
108
+ * `string | undefined` would drop the candidate list the disambiguation finding
109
+ * text depends on. */
110
+ type CitationResolution = { abs: string } | { ambiguous: string[] };
111
+
112
+ /** Strategy 4 of `resolveCitationPath`: tree files whose REPO-RELATIVE path ends
113
+ * with the cited `path` on WHOLE segments. A bare basename is the one-segment
114
+ * case; a multi-segment citation narrows the basename's candidates at a `/`
115
+ * boundary, so `workflow/validate/x.ts` can never match inside
116
+ * `rpiv-workflow/validate/x.ts`. Compared repo-relative (never against the
117
+ * absolute path) so the checkout directory's own name can never back a citation
118
+ * — `src/utils.ts` must not resolve to `<cwd>/utils.ts` just because the repo
119
+ * happens to be cloned at `/tmp/src`. Reads/writes the shared `indexHolder` so
120
+ * the basename index is built lazily ONCE and shared across citations (the
121
+ * first direct-resolution miss pays the tree walk). */
122
+ const suffixMatchesFor = (path: string, cwd: string, indexHolder: { value: BasenameIndex | undefined }): string[] => {
123
+ indexHolder.value ??= buildBasenameIndex(cwd);
124
+ if (indexHolder.value.truncated) return []; // partial index ⇒ uniqueness untrustworthy ⇒ strict
125
+ const candidates = indexHolder.value.index.get(basename(path)) ?? [];
126
+ if (!path.includes("/")) return candidates;
127
+ const suffix = `/${path}`;
128
+ return candidates.filter((abs) =>
129
+ `/${abs
130
+ .slice(cwd.length + 1)
131
+ .split(sep)
132
+ .join("/")}`.endsWith(suffix),
133
+ );
134
+ };
135
+
136
+ /** Resolve a citation's `path` to one backing file under `cwd`, encapsulating
137
+ * all four strategies in order: (1) direct — `path` or `cwd/path`; (2,3)
138
+ * dependency probes — `node_modules/<path>` and `node_modules/@<path>` (the
139
+ * latter because the citation regex cannot carry `@`, so a cited
140
+ * `node_modules/@scope/pkg/f.js` parses as `scope/pkg/f.js`); DIRECT probes
141
+ * only — the suffix walk still skips `node_modules` (per `CITATION_WALK_SKIP`),
142
+ * so a bare basename never resolves into a dep; (4) suffix fallback — a UNIQUE
143
+ * tree-file suffix match backs the citation, an AMBIGUOUS one returns the
144
+ * candidate list. PURE: emits no findings and throws never — all finding text
145
+ * lives in `verifyCitations`. The lazily-built basename index is shared across
146
+ * calls via `indexHolder`. */
147
+ const resolveCitationPath = (
148
+ path: string,
149
+ cwd: string,
150
+ indexHolder: { value: BasenameIndex | undefined },
151
+ ): CitationResolution | undefined => {
152
+ // existsSync-then-statSync races a concurrent delete into a throw OUT of the
153
+ // deterministic floor (⇒ FAIL_SCRIPT_THREW) — one guarded probe instead.
154
+ const isTreeFile = (p: string): boolean => {
155
+ try {
156
+ return statSync(p).isFile();
157
+ } catch {
158
+ return false;
159
+ }
160
+ };
161
+ // Strategy 1 — direct. Containment-guarded (`containedPath`): a `..`-escaping
162
+ // citation must not resolve to a file OUTSIDE the tree — an existing out-of-cwd
163
+ // target would read as a BACKED citation (and leak its line count into the
164
+ // verdict). An escaping path falls through to the suffix fallback and lands as
165
+ // an ordinary unbacked/ambiguous finding.
166
+ const direct = containedPath(cwd, path);
167
+ if (direct !== undefined && isTreeFile(direct)) return { abs: direct };
168
+ // Strategies 2 & 3 — dependency probes (lockfile-pinned dep source; the regex
169
+ // cannot carry `@`, so `node_modules/@scope/pkg/f.js` is cited as `scope/pkg/f.js`).
170
+ for (const candidate of [join("node_modules", path), join("node_modules", `@${path}`)]) {
171
+ const abs = containedPath(cwd, candidate);
172
+ if (abs !== undefined && isTreeFile(abs)) return { abs };
173
+ }
174
+ // Strategy 4 — suffix fallback: back the citation iff exactly ONE tree file matches.
175
+ const matches = suffixMatchesFor(path, cwd, indexHolder);
176
+ if (matches.length === 1) return { abs: matches[0] };
177
+ if (matches.length > 1) return { ambiguous: matches };
178
+ return undefined;
179
+ };
180
+
181
+ /** Example-path namespaces the skill prompts use in illustrative citations
182
+ * (`path/to/file.ext:12`, `packages/x/y.ts:42`). Artifacts quote — and models
183
+ * imitate — these examples in unfenced prose, where the fence skip cannot
184
+ * reach them; a citation under one of these prefixes is documentation shape,
185
+ * never a claim about the tree, and prosecuting one buys a full LLM fix round
186
+ * for zero risk averted (three of f329's floor failures were this class). */
187
+ const PLACEHOLDER_CITATION_PREFIXES: readonly string[] = ["path/to/", "packages/x/"];
188
+
189
+ /**
190
+ * Proximity tiebreak for a citation left ambiguous by the declared-`files:`
191
+ * intersection: resolve to the candidate whose repo-root-relative path has the
192
+ * nearest PRECEDING prose mention — the common artifact idiom of naming a file
193
+ * once in full, then citing it by bare basename. Prose only: mentions inside
194
+ * YAML frontmatter (`files:` ordering carries no authorial intent — a tie there
195
+ * stays a tie) or fenced spans (example/fixture territory) don't count, and
196
+ * matches are token-bounded so a candidate never back-matches inside a longer
197
+ * path mention (`a/dup.ts` inside `x/a/dup.ts`). Returns the winner's absolute
198
+ * path, or `undefined` — the citation then stays unbacked as before.
199
+ */
200
+ const nearestProseMention = (
201
+ body: string,
202
+ upTo: number,
203
+ candidates: readonly string[],
204
+ cwd: string,
205
+ fenced: readonly [number, number][],
206
+ proseStart: number,
207
+ ): string | undefined => {
208
+ let bestAbs: string | undefined;
209
+ let bestIdx = -1;
210
+ for (const abs of candidates) {
211
+ if (!abs.startsWith(cwd + sep)) continue;
212
+ const rel = abs
213
+ .slice(cwd.length + 1)
214
+ .split(sep)
215
+ .join("/");
216
+ // Walk mentions nearest-first; the first CLEAN one (token-bounded, in
217
+ // prose, outside fences) is this candidate's best — earlier ones can't win.
218
+ let from = upTo - rel.length;
219
+ while (from >= 0) {
220
+ const i = body.lastIndexOf(rel, from);
221
+ if (i < 0 || i < proseStart) break;
222
+ from = i - 1;
223
+ const prev = i > 0 ? (body[i - 1] as string) : "";
224
+ const next = body[i + rel.length] ?? "";
225
+ if (prev !== "" && /[\w.@/-]/.test(prev)) continue;
226
+ if (next !== "" && /[\w-]/.test(next)) continue;
227
+ if (fenced.some(([s, e]) => i >= s && i < e)) continue;
228
+ if (i > bestIdx) {
229
+ bestIdx = i;
230
+ bestAbs = abs;
231
+ }
232
+ break;
233
+ }
234
+ }
235
+ return bestAbs;
236
+ };
237
+
238
+ const verifyCitations = (body: string, cwd: string, declared?: ReadonlySet<string>): StructureFinding[] => {
239
+ const findings: StructureFinding[] = [];
240
+ const seen = new Set<string>();
241
+ // Fenced text is example/fixture territory, not prose asserting a real
242
+ // file:line — a fenced placeholder shaped like a citation must not fail the
243
+ // floor (it false-failed the very plan that fixes this). Span check, not a
244
+ // placeholder-pattern skip: a REAL citation that merely looks placeholder-ish
245
+ // still verifies when it appears in prose.
246
+ const fenced = fencedSpans(body);
247
+ // Prose begins past the YAML frontmatter: the proximity tiebreak must not
248
+ // read the `files:` array as a mention (its ordering carries no intent — a
249
+ // tie inside the declared set stays a tie).
250
+ let proseStart = 0;
251
+ if (body.startsWith("---\n")) {
252
+ const end = body.indexOf("\n---\n", 3);
253
+ if (end !== -1) proseStart = end + "\n---\n".length;
254
+ }
255
+ // Built lazily and reused across citations — only the first direct-resolution
256
+ // miss pays the tree walk, and only when at least one such citation exists.
257
+ const indexHolder: { value: BasenameIndex | undefined } = { value: undefined };
258
+ for (const m of body.matchAll(FILE_LINE_CITATION_RE)) {
259
+ const [, path, startStr, endStr] = m;
260
+ if (!path || !startStr) continue;
261
+ if (fenced.some(([s, e]) => m.index >= s && m.index < e)) continue;
262
+ if (PLACEHOLDER_CITATION_PREFIXES.some((p) => path.startsWith(p))) continue;
263
+ const key = `${path}:${startStr}${endStr ? `-${endStr}` : ""}`;
264
+ if (seen.has(key)) continue;
265
+ seen.add(key);
266
+ let resolved = resolveCitationPath(path, cwd, indexHolder);
267
+ if (resolved && "ambiguous" in resolved && declared !== undefined) {
268
+ // Declared-write-set tiebreak: when the caller supplies the artifact's own
269
+ // declared `files:` union and exactly ONE ambiguous candidate is in it, the
270
+ // artifact has already named the file it means — resolve there instead of
271
+ // halting the run over a path-prefix omission. A tie INSIDE the declared
272
+ // set (two declared `command.ts` files) stays ambiguous: the citation is
273
+ // then genuinely unreadable even against the artifact's own write-set.
274
+ const declaredMatches = resolved.ambiguous.filter(
275
+ (abs) =>
276
+ abs.startsWith(cwd + sep) &&
277
+ declared.has(
278
+ abs
279
+ .slice(cwd.length + 1)
280
+ .split(sep)
281
+ .join("/"),
282
+ ),
283
+ );
284
+ if (declaredMatches.length === 1) resolved = { abs: declaredMatches[0] };
285
+ }
286
+ if (resolved && "ambiguous" in resolved) {
287
+ // Proximity tiebreak: the nearest preceding prose mention of a
288
+ // candidate's full path names the file the author means.
289
+ const near = nearestProseMention(body, m.index, resolved.ambiguous, cwd, fenced, proseStart);
290
+ if (near !== undefined) resolved = { abs: near };
291
+ }
292
+ if (resolved && "ambiguous" in resolved) {
293
+ // More than one tree file matches — name the candidates so the fix arm can disambiguate.
294
+ const shown = resolved.ambiguous
295
+ .slice(0, 3)
296
+ .map((a) => (a.startsWith(cwd + sep) ? a.slice(cwd.length + 1) : a));
297
+ findings.push({
298
+ 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.`,
299
+ where: key,
300
+ // Every candidate is a REAL tree file — advisory per the tier above.
301
+ advisory: true,
302
+ });
303
+ continue;
304
+ }
305
+ let abs = resolved?.abs;
306
+ if (abs === undefined && declared !== undefined) {
307
+ // Declared-write-set rescue on a NO-MATCH resolution — the ambiguity
308
+ // tiebreak's missing twin. A unique whole-segment suffix match inside
309
+ // the plan's own `files:` names the file the author means: verify
310
+ // against it when it exists on disk; a declared file ABSENT from the
311
+ // tree is a planned CREATE — the citation is a forward reference to
312
+ // planned content, unverifiable at this revision, so no finding.
313
+ const matches = [...declared].filter((d) => d === path || `/${d}`.endsWith(`/${path}`));
314
+ if (matches.length === 1) {
315
+ const cand = join(cwd, matches[0]);
316
+ if (!existsSync(cand)) continue;
317
+ abs = cand;
318
+ }
319
+ }
320
+ if (!abs) {
321
+ findings.push({
322
+ 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.`,
323
+ where: key,
324
+ // Advisory like every citation-resolution finding — see the tier
325
+ // note in the function header.
326
+ advisory: true,
327
+ });
328
+ continue;
329
+ }
330
+ // A file that vanishes or turns unreadable between resolution and the read
331
+ // is an unbacked citation, never a throw out of the deterministic floor.
332
+ let lineCount: number;
333
+ try {
334
+ lineCount = readFileSync(abs, "utf-8").split("\n").length;
335
+ } catch {
336
+ findings.push({
337
+ 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.`,
338
+ where: key,
339
+ // The file EXISTS (it resolved) — advisory per the tier above.
340
+ advisory: true,
341
+ });
342
+ continue;
343
+ }
344
+ const high = Math.max(Number(startStr), endStr ? Number(endStr) : 0);
345
+ if (high > lineCount) {
346
+ findings.push({
347
+ 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.`,
348
+ where: key,
349
+ // The file exists; only the ordinate drifted — advisory per the tier above.
350
+ advisory: true,
351
+ });
352
+ }
353
+ }
354
+ return findings;
355
+ };
356
+
357
+ export { verifyCitations };