pi-gauntlet 5.22.0 → 5.23.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## v5.23.0 - 2026-09-27
4
+
5
+ ### Added
6
+
7
+ - `gauntlet-spec-index` gains `--corpus specs|docs` (default `specs`, output unchanged). `--corpus docs` indexes project documentation - tracked and untracked non-gitignored `*.md` files matching `**/doc/**/*.md`, `**/docs/**/*.md`, `README.md`, `AGENTS.md`, replaceable through `- docs: <glob>` bullets under `## Spec index` in the gauntlet overrides file - into a second FTS5 table in the same cache, minus `doc(s)/specs`, `doc(s)/plans`, `node_modules`, `.pi/gauntlet`, `.worktrees`, symlinks and context drafts, and prints `score`, `path`, `title`, `snippet`. Both corpora share one confidence rule driven by a corpus descriptor (strong fields `title`/`goal` for specs, `title`/`headings` for docs). The brainstorming scout runs the docs query and renders `Docs touched: <path> - <section heading>` lines that round 2 weighs as documentation-impact candidates.
8
+
9
+ ### Changed
10
+
11
+ - Spec-index cache schema is 3 (the `files` table is keyed by `(corpus, path)`); existing caches rebuild on first query. `#`/`##`/`###` lines inside fenced code blocks no longer count as the title or headings in either corpus.
12
+
3
13
  ## v5.22.0 - 2026-09-26
4
14
 
5
15
  ### Added
package/README.md CHANGED
@@ -137,7 +137,7 @@ Pin an exact release with `npm:pi-gauntlet@X.Y.Z`. See [doc/install-internals.md
137
137
 
138
138
  ## Spec search index
139
139
 
140
- `gauntlet-spec-index` provides lexical search across `doc/specs/*.md` at the repository root and one service level down. From a repository worktree, run `node <pi-gauntlet-package>/bin/gauntlet-spec-index.mjs --query "<text>" [--limit N] [--exclude <repo-relative path>]...`; it requires Node >=24.15.0, refreshes its FTS5 index on every query, and prints tab-separated `score`, `path`, `service`, `title`, `status`, `shipped_at`, `state`, `files`, and `snippet` columns. Rows pass a confidence rule before `--limit` applies: a query term is evidence when it occurs in fewer than half the indexed specs (stem variants of one word count once); query tokens split on word boundaries, so `gauntlet-spec-index` searches as three words; a row is returned only when it matches at least two distinct evidence terms in its `title` or `goal`, and rows scoring below half the best live row's score are dropped. A query with no real match therefore prints the header only and exits 0, and a corpus of two or fewer specs never returns rows. `--exclude` (repeatable) removes a path before the rule runs, so the spec under review never sets the bar. `state` is `superseded` when a `> **Superseded by:** ... - fully` banner sits in the block directly under the title and `live` otherwise; named-section banners and consumer-defined banner syntaxes both read as `live`. Live rows sort before superseded rows, then by score. The `files` column is a `;`-separated list of repo-relative paths the spec's shipped change modified and that still exist in the repository, the literal `missing` when the spec's telemetry record has no `derived.modified_files` list, or blank when there is no readable record or no recorded path remains. The per-worktree cache lives at `.pi/gauntlet/index.sqlite`, and its first creation adds `/.pi/gauntlet/index.sqlite*` to Git's `info/exclude` so the database and SQLite sidecars stay out of `git status`. `/skill:brainstorming` queries the index twice: the scout at gather time from the request, and the main loop at spec-writing from the finished spec's title, goal, and headings, surfacing new `live` candidates at the review gate.
140
+ `gauntlet-spec-index` provides lexical search over two corpora in one per-worktree cache. From a repository worktree, run `node <pi-gauntlet-package>/bin/gauntlet-spec-index.mjs --query "<text>" [--corpus specs|docs] [--limit N] [--exclude <repo-relative path>]...`; it requires Node >=24.15.0 and refreshes its FTS5 index on every query. `--corpus specs` (the default) searches `doc/specs/*.md` at the repository root and one service level down and prints tab-separated `score`, `path`, `service`, `title`, `status`, `shipped_at`, `state`, `files`, and `snippet` columns. `--corpus docs` searches project documentation and prints `score`, `path`, `title`, and `snippet`; the snippet is the matched `##`/`###` heading line when one holds a query term, else a body fragment. Docs candidates are the tracked and untracked, non-gitignored `*.md` files (`git ls-files -co --exclude-standard`, so nested repositories and submodules are not indexed) matching an include list - default `**/doc/**/*.md`, `**/docs/**/*.md`, `README.md`, `AGENTS.md`, where a slash-free entry also matches one service level down - minus the fixed exclusions `**/doc/specs/**`, `**/docs/specs/**`, `**/doc/plans/**`, `**/docs/plans/**`, `**/node_modules/**`, `.pi/gauntlet/**`, `.worktrees/**`, symlinks, and files whose first line is the context-draft marker; `**` never matches a dot directory, so `.pi/*.md` or `.github/*.md` is indexed only through an explicit include. A project replaces the include list with `- docs: <glob>` bullets under a `## Spec index` heading in its gauntlet overrides file (see [Project-specific overrides](#project-specific-overrides)); the exclusions are not configurable. Both corpora pass the same confidence rule before `--limit` applies: a query term is evidence when it occurs in fewer than half the rows of the queried table (stem variants of one word count once); query tokens split on word boundaries, so `gauntlet-spec-index` searches as three words; a row is returned only when it matches at least two distinct evidence terms in the corpus's strong fields - `title` or `goal` for specs, `title` or `headings` for docs - and rows scoring below half the best live row's score are dropped (every docs row is live). A query with no real match therefore prints the header only and exits 0, and a corpus of two or fewer files never returns rows. `--exclude` (repeatable) removes a path before the rule runs, so the spec under review never sets the bar. `state` is `superseded` when a `> **Superseded by:** ... - fully` banner sits in the block directly under the title and `live` otherwise; named-section banners and consumer-defined banner syntaxes both read as `live`. Live rows sort before superseded rows, then by score. The `files` column is a `;`-separated list of repo-relative paths the spec's shipped change modified and that still exist in the repository, the literal `missing` when the spec's telemetry record has no `derived.modified_files` list, or blank when there is no readable record or no recorded path remains. The cache lives at `.pi/gauntlet/index.sqlite`, and its first creation adds `/.pi/gauntlet/index.sqlite*` to Git's `info/exclude` so the database and SQLite sidecars stay out of `git status`. `/skill:brainstorming` queries the specs corpus twice - the scout at gather time from the request, and the main loop at spec-writing from the finished spec's title, goal, and headings, surfacing new `live` candidates at the review gate - and the scout queries the docs corpus once to render `Docs touched:` lines that round 2 weighs as documentation-impact candidates.
141
141
 
142
142
  ## Performance digest
143
143
 
@@ -279,10 +279,18 @@ Use the project's wrapper: `script/worktree create <name>`. It provisions an iso
279
279
  database and copies `.env.local`. Never call `git worktree add` directly.
280
280
  ```
281
281
 
282
- Beyond `## conventions` and skill-named sections, headings a skill reads by name are documented in their owning skills; other headings retain topic/workflow-convention matching. The override file is read by skill instructions, not by the Pi runtime itself. Missing or empty `## conventions` adds no rules; a lower-priority file cannot supplement the selected file.
282
+ Beyond `## conventions` and skill-named sections, headings a skill reads by name are documented in their owning skills; other headings retain topic/workflow-convention matching. The override file is read by skill instructions and, for its `## Spec index` section only, by `gauntlet-spec-index`; the Pi runtime itself never reads it. Missing or empty `## conventions` adds no rules; a lower-priority file cannot supplement the selected file.
283
283
 
284
284
  **Discovery ladder:** skills check three locations, in order, and use the first one found - never merged: `.pi/gauntlet-overrides.md`, then `<repo root>/gauntlet-overrides.md`, then `<repo root>/doc/gauntlet-overrides.md` (`<repo root>` = `git rev-parse --show-toplevel`, or the current directory outside a repo). Pick one location per repo.
285
285
 
286
+ **`## Spec index` section:** `gauntlet-spec-index --corpus docs` reads `- docs: <glob>` bullets under this heading as the docs include list, replacing the default (`**/doc/**/*.md`, `**/docs/**/*.md`, `README.md`, `AGENTS.md`). Backticks or quotes around the glob are stripped; no other key under the heading is read, and the fixed exclusions always apply. For example:
287
+
288
+ ```markdown
289
+ ## Spec index
290
+ - docs: `**/doc/**/*.md`
291
+ - docs: `handbook/**/*.md`
292
+ ```
293
+
286
294
  **`## Issue tracker` section:** `shape-ticket` resolves tracker access through a capability ladder, and this is its first rung - it overrides the zero-config `gh` (GitHub) / `linearis` (Linear) defaults for any other tracker. Name the CLI's read, search, create, update, and post comment commands explicitly. For a Jira CLI, for example:
287
295
 
288
296
  ```markdown
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
- // Lexical search over the spec corpus. Build-on-query: refresh a per-worktree
3
- // FTS5 cache by mtime+size, then rank with bm25 and join telemetry at output.
4
- import { readFileSync, appendFileSync, existsSync, statSync, readdirSync, mkdirSync, rmSync, realpathSync } from "node:fs";
5
- import { join, dirname, basename, isAbsolute } from "node:path";
2
+ // Lexical search over spec and docs corpora (FTS5, bm25, shared confidence rule); telemetry joined for specs only.
3
+ import { readFileSync, appendFileSync, existsSync, statSync, lstatSync, readdirSync, mkdirSync, rmSync, realpathSync, openSync, readSync, closeSync } from "node:fs";
4
+ import { join, dirname, basename, isAbsolute, matchesGlob } from "node:path";
6
5
  import { execFileSync } from "node:child_process";
7
6
  import process from "node:process";
8
7
  import { parse as parseYaml } from "yaml";
9
8
 
10
- const SCHEMA_VERSION = 2;
9
+ const SCHEMA_VERSION = 3;
11
10
  const EVIDENCE_DF_FRACTION = 0.5;
12
11
  const MIN_EVIDENCE_TOKENS = 2;
13
12
  const SCORE_RATIO = 0.5;
@@ -18,17 +17,23 @@ const MIN_NODE = [24, 15, 0];
18
17
  const DRAFT_MARKER = "# CONTEXT DRAFT - NOT A SPEC - fully replaced at spec-writing";
19
18
  const EXCLUDE_LINE = "/.pi/gauntlet/index.sqlite*";
20
19
  const SKIP_DIRS = new Set([".worktrees", "node_modules", "build"]);
21
- const HEADER = ["score", "path", "service", "title", "status", "shipped_at", "state", "files", "snippet"];
20
+ const FENCE = /^\s*(`{3,}|~{3,})/;
21
+ const DOC_INCLUDES = ["**/doc/**/*.md", "**/docs/**/*.md", "README.md", "AGENTS.md"];
22
+ const DOC_EXCLUDES = ["**/doc/specs/**", "**/docs/specs/**", "**/doc/plans/**", "**/docs/plans/**", "**/node_modules/**", ".pi/gauntlet/**", ".worktrees/**"];
23
+ const OVERRIDES_FILES = [".pi/gauntlet-overrides.md", "gauntlet-overrides.md", "doc/gauntlet-overrides.md"];
22
24
  const SCHEMA = `
23
25
  CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
24
- CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, mtime_ms INTEGER, size INTEGER);
26
+ CREATE TABLE IF NOT EXISTS files (corpus TEXT NOT NULL, path TEXT NOT NULL, mtime_ms INTEGER, size INTEGER, PRIMARY KEY (corpus, path));
25
27
  CREATE VIRTUAL TABLE IF NOT EXISTS specs USING fts5(
26
28
  path UNINDEXED, service UNINDEXED, title, goal, headings, body, state UNINDEXED,
27
29
  tokenize = 'porter unicode61');
30
+ CREATE VIRTUAL TABLE IF NOT EXISTS docs USING fts5(
31
+ path UNINDEXED, title, headings, body,
32
+ tokenize = 'porter unicode61');
28
33
  `;
29
34
 
30
35
  const usage = () => {
31
- process.stderr.write('usage: gauntlet-spec-index --query "<text>" [--limit N] [--exclude <repo-relative path>]...\n');
36
+ process.stderr.write('usage: gauntlet-spec-index --query "<text>" [--corpus specs|docs] [--limit N] [--exclude <repo-relative path>]...\n');
32
37
  process.exit(1);
33
38
  };
34
39
  const die = (msg) => {
@@ -38,16 +43,18 @@ const die = (msg) => {
38
43
 
39
44
  function parseArgs(argv) {
40
45
  let query;
46
+ let corpus = "specs";
41
47
  let limit = 10;
42
48
  const exclude = [];
43
49
  for (let i = 0; i < argv.length; i++) {
44
50
  if (argv[i] === "--query" && argv[i + 1] !== undefined) query = argv[++i];
51
+ else if (argv[i] === "--corpus" && Object.hasOwn(CORPORA, argv[i + 1] ?? "")) corpus = argv[++i];
45
52
  else if (argv[i] === "--limit" && /^[1-9]\d*$/.test(argv[i + 1] ?? "")) limit = Number(argv[++i]);
46
53
  else if (argv[i] === "--exclude" && argv[i + 1] !== undefined) exclude.push(argv[++i]);
47
54
  else usage();
48
55
  }
49
56
  if (query === undefined) usage();
50
- return { query, limit, exclude };
57
+ return { query, corpus, limit, exclude };
51
58
  }
52
59
 
53
60
  function nodeOk() {
@@ -88,11 +95,64 @@ function discover(root) {
88
95
  }
89
96
  };
90
97
  collect("doc/specs", "root");
91
- const entries = readdirSync(root, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
92
- for (const e of entries) {
93
- if (e.name.startsWith(".") || SKIP_DIRS.has(e.name)) continue;
94
- if (!e.isDirectory() && !e.isSymbolicLink()) continue;
95
- collect(`${e.name}/doc/specs`, e.name);
98
+ for (const s of services(root).sort((a, b) => a.localeCompare(b))) collect(`${s}/doc/specs`, s);
99
+ return out;
100
+ }
101
+
102
+ // Top-level directories discover() would scan; a slash-free include also matches one level under them.
103
+ function services(root) {
104
+ return readdirSync(root, { withFileTypes: true })
105
+ .filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".") && !SKIP_DIRS.has(e.name))
106
+ .map((e) => e.name);
107
+ }
108
+
109
+ function includes(root) {
110
+ const file = OVERRIDES_FILES.map((rel) => join(root, rel)).find((abs) => existsSync(abs));
111
+ if (!file) return DOC_INCLUDES;
112
+ const globs = [];
113
+ let inSection = false;
114
+ let text;
115
+ try {
116
+ text = readFileSync(file, "utf8");
117
+ } catch (e) {
118
+ die(`gauntlet-spec-index: unreadable overrides file ${file}: ${e.message}`);
119
+ }
120
+ for (const line of text.split(/\r?\n/)) {
121
+ if (/^## /.test(line)) { inSection = line.trim() === "## Spec index"; continue; }
122
+ if (!inSection) continue;
123
+ const m = /^-\s+docs:\s*(.+?)\s*$/.exec(line);
124
+ if (m) globs.push(m[1].replace(/^[`"']+|[`"']+$/g, ""));
125
+ }
126
+ return globs.length ? globs : DOC_INCLUDES;
127
+ }
128
+
129
+ function firstLine(abs) {
130
+ const fd = openSync(abs, "r");
131
+ try {
132
+ const buf = Buffer.alloc(128);
133
+ const n = readSync(fd, buf, 0, 128, 0);
134
+ return buf.toString("utf8", 0, n).split(/\r?\n/, 1)[0];
135
+ } finally {
136
+ closeSync(fd);
137
+ }
138
+ }
139
+
140
+ function discoverDocs(root, globs) {
141
+ const svc = services(root);
142
+ const patterns = globs.flatMap((g) => (g.includes("/") ? [g] : [g, ...svc.map((s) => `${s}/${g}`)]));
143
+ const listed = execFileSync("git", ["-C", root, "ls-files", "-co", "--exclude-standard", "-z", "--", "*.md"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\0").filter(Boolean);
144
+ const out = [];
145
+ for (const rel of listed) {
146
+ if (!patterns.some((p) => matchesGlob(rel, p))) continue;
147
+ if (DOC_EXCLUDES.some((p) => matchesGlob(rel, p))) continue;
148
+ let st;
149
+ try {
150
+ st = lstatSync(join(root, rel));
151
+ if (!st.isFile() || firstLine(join(root, rel)) === DRAFT_MARKER) continue;
152
+ } catch {
153
+ continue;
154
+ }
155
+ out.push({ path: rel, mtime_ms: Math.trunc(st.mtimeMs), size: st.size });
96
156
  }
97
157
  return out;
98
158
  }
@@ -145,17 +205,34 @@ async function openDb(root) {
145
205
  }
146
206
  }
147
207
 
208
+ function fenceMask(lines) {
209
+ const mask = new Array(lines.length).fill(false);
210
+ let open = null;
211
+ for (let i = 0; i < lines.length; i++) {
212
+ const m = FENCE.exec(lines[i]);
213
+ if (open) {
214
+ mask[i] = true;
215
+ if (m && m[1][0] === open.ch && m[1].length >= open.len) open = null;
216
+ } else if (m) {
217
+ mask[i] = true;
218
+ open = { ch: m[1][0], len: m[1].length };
219
+ }
220
+ }
221
+ return mask;
222
+ }
223
+
148
224
  function extract(text, path) {
149
225
  const lines = text.split(/\r?\n/);
150
- const h1 = lines.findIndex((l) => l.startsWith("# "));
226
+ const fenced = fenceMask(lines);
227
+ const h1 = lines.findIndex((l, i) => !fenced[i] && l.startsWith("# "));
151
228
  const title = (h1 >= 0 ? lines[h1].slice(2).trim() : "") || basename(path, ".md");
152
229
  const goal = lines.find((l) => l.startsWith("**Goal:**"))?.slice("**Goal:**".length).trim() ?? "";
153
- const headings = lines.filter((l) => /^##{1,2} /.test(l)).map((l) => l.replace(/^#+ /, "")).join("\n");
230
+ const headings = lines.filter((l, i) => !fenced[i] && /^##{1,2} /.test(l)).map((l) => l.replace(/^#+ /, "")).join("\n");
154
231
  let state = "live";
155
232
  if (h1 >= 0) {
156
233
  // Title block: everything after the H1 up to the first H2 heading or code fence.
157
234
  for (const l of lines.slice(h1 + 1)) {
158
- if (/^## /.test(l) || /^\s*(`{3,}|~{3,})/.test(l)) break;
235
+ if (/^## /.test(l) || FENCE.test(l)) break;
159
236
  if (FULLY_BANNER.test(l)) { state = "superseded"; break; }
160
237
  }
161
238
  }
@@ -163,24 +240,25 @@ function extract(text, path) {
163
240
  }
164
241
 
165
242
  function refresh(db, root, corpus) {
166
- const known = new Map(db.prepare("SELECT path, mtime_ms, size FROM files").all().map((r) => [r.path, r]));
167
- const present = new Set(corpus.map((f) => f.path));
168
- const delSpec = db.prepare("DELETE FROM specs WHERE path = ?");
169
- const delFile = db.prepare("DELETE FROM files WHERE path = ?");
170
- const insSpec = db.prepare("INSERT INTO specs (path, service, title, goal, headings, body, state) VALUES (?, ?, ?, ?, ?, ?, ?)");
171
- const putFile = db.prepare("INSERT OR REPLACE INTO files (path, mtime_ms, size) VALUES (?, ?, ?)");
243
+ const { table } = corpus;
244
+ const found = corpus.discover(root);
245
+ const known = new Map(db.prepare("SELECT path, mtime_ms, size FROM files WHERE corpus = ?").all(table).map((r) => [r.path, r]));
246
+ const present = new Set(found.map((f) => f.path));
247
+ const delRow = db.prepare(`DELETE FROM ${table} WHERE path = ?`);
248
+ const delFile = db.prepare("DELETE FROM files WHERE corpus = ? AND path = ?");
249
+ const insRow = db.prepare(`INSERT INTO ${table} (${corpus.columns.join(", ")}) VALUES (${corpus.columns.map(() => "?").join(", ")})`);
250
+ const putFile = db.prepare("INSERT OR REPLACE INTO files (corpus, path, mtime_ms, size) VALUES (?, ?, ?, ?)");
172
251
  db.exec("BEGIN IMMEDIATE");
173
252
  try {
174
- for (const path of known.keys()) if (!present.has(path)) { delSpec.run(path); delFile.run(path); }
175
- for (const f of corpus) {
253
+ for (const path of known.keys()) if (!present.has(path)) { delRow.run(path); delFile.run(table, path); }
254
+ for (const f of found) {
176
255
  const k = known.get(f.path);
177
256
  if (k && k.mtime_ms === f.mtime_ms && k.size === f.size) continue;
178
257
  const text = readFileSync(join(root, f.path), "utf8");
179
- delSpec.run(f.path);
180
- if (text.split(/\r?\n/, 1)[0] === DRAFT_MARKER) { delFile.run(f.path); continue; }
181
- const x = extract(text, f.path);
182
- insSpec.run(f.path, f.service, x.title, x.goal, x.headings, text, x.state);
183
- putFile.run(f.path, f.mtime_ms, f.size);
258
+ delRow.run(f.path);
259
+ if (text.split(/\r?\n/, 1)[0] === DRAFT_MARKER) { delFile.run(table, f.path); continue; }
260
+ insRow.run(...corpus.row(text, f));
261
+ putFile.run(table, f.path, f.mtime_ms, f.size);
184
262
  }
185
263
  db.exec("COMMIT");
186
264
  } catch (e) {
@@ -212,32 +290,32 @@ function representatives(db, toks) {
212
290
  function confidenceFilter(rows, evidence) {
213
291
  return rows.filter((r) => {
214
292
  const hits = evidence.filter((e) => e.all.has(r.rowid)).length;
215
- const titleGoal = evidence.filter((e) => e.titleGoal.has(r.rowid)).length;
216
- return hits >= MIN_EVIDENCE_TOKENS && titleGoal >= MIN_EVIDENCE_TOKENS;
293
+ const strong = evidence.filter((e) => e.strong.has(r.rowid)).length;
294
+ return hits >= MIN_EVIDENCE_TOKENS && strong >= MIN_EVIDENCE_TOKENS;
217
295
  });
218
296
  }
219
297
 
220
- function query(db, toks, { limit, exclude }) {
221
- const n = db.prepare("SELECT count(*) AS n FROM specs").get().n;
222
- const rowids = (match) => new Set(db.prepare("SELECT rowid FROM specs WHERE specs MATCH ?").all(match).map((r) => r.rowid));
298
+ function query(db, corpus, toks, { limit, exclude }) {
299
+ const { table } = corpus;
300
+ const n = db.prepare(`SELECT count(*) AS n FROM ${table}`).get().n;
301
+ const rowids = (match) => new Set(db.prepare(`SELECT rowid FROM ${table} WHERE ${table} MATCH ?`).all(match).map((r) => r.rowid));
223
302
  const reps = representatives(db, toks);
224
303
  const terms = [...new Set(reps.values())];
225
304
  const evidence = [];
226
305
  for (const tok of terms) {
227
306
  const all = rowids(quote(tok));
228
307
  if (all.size === 0 || all.size >= n * EVIDENCE_DF_FRACTION) continue;
229
- evidence.push({ all, titleGoal: rowids(`title:${quote(tok)} OR goal:${quote(tok)}`) });
308
+ evidence.push({ all, strong: rowids(corpus.strong.map((f) => `${f}:${quote(tok)}`).join(" OR ")) });
230
309
  }
231
310
  if (evidence.length < MIN_EVIDENCE_TOKENS) return [];
232
311
  const rows = db.prepare(
233
- `SELECT rowid, path, service, title, state,
234
- bm25(specs, 0, 0, 10.0, 5.0, 2.0, 1.0, 0) AS score,
235
- snippet(specs, 5, '', '', '...', 12) AS snippet
236
- FROM specs WHERE specs MATCH ?`,
312
+ `SELECT rowid, ${corpus.select}, bm25(${table}, ${corpus.weights.map((w) => w.toFixed(1)).join(", ")}) AS score
313
+ FROM ${table} WHERE ${table} MATCH ?`,
237
314
  ).all(toMatch(terms)).filter((r) => !exclude.includes(r.path));
238
315
  const kept = confidenceFilter(rows, evidence);
239
- kept.sort((a, b) => (a.state !== "live") - (b.state !== "live") || a.score - b.score);
240
- const best = kept.find((r) => r.state === "live");
316
+ const live = (r) => !corpus.hasState || r.state === "live";
317
+ kept.sort((a, b) => Number(!live(a)) - Number(!live(b)) || a.score - b.score);
318
+ const best = kept.find(live);
241
319
  const cut = best ? kept.filter((r) => Math.abs(r.score) >= SCORE_RATIO * Math.abs(best.score)) : kept;
242
320
  return cut.slice(0, limit);
243
321
  }
@@ -265,20 +343,60 @@ const cell = (v) => (v === null || v === undefined ? "" : String(v).replace(/\s+
265
343
  // Paths keep their spaces; only column and row delimiters are neutralised.
266
344
  const filesCell = (v) => v.replace(/[\t\r\n]+/g, " ");
267
345
 
346
+ function docSnippet(r) {
347
+ if (!r.hsnip.includes("\u0001")) return r.bsnip;
348
+ const fragment = r.hsnip.split("\n").find((line) => line.includes("\u0001")).replace(/[\u0001\u0002]/g, "");
349
+ return r.headings.split("\n").find((line) => line.includes(fragment));
350
+ }
351
+
352
+ const CORPORA = {
353
+ specs: {
354
+ table: "specs",
355
+ columns: ["path", "service", "title", "goal", "headings", "body", "state"],
356
+ strong: ["title", "goal"],
357
+ weights: [0, 0, 10, 5, 2, 1, 0],
358
+ hasState: true,
359
+ header: ["score", "path", "service", "title", "status", "shipped_at", "state", "files", "snippet"],
360
+ select: "path, service, title, state, snippet(specs, 5, '', '', '...', 12) AS snippet",
361
+ discover,
362
+ row: (text, f) => {
363
+ const x = extract(text, f.path);
364
+ return [f.path, f.service, x.title, x.goal, x.headings, text, x.state];
365
+ },
366
+ format: (root, r) => {
367
+ const t = telemetry(root, r.path);
368
+ return [...[r.score.toFixed(3), r.path, r.service, r.title, t.status, t.shipped_at, r.state].map(cell), filesCell(t.files), cell(r.snippet)];
369
+ },
370
+ },
371
+ docs: {
372
+ table: "docs",
373
+ columns: ["path", "title", "headings", "body"],
374
+ strong: ["title", "headings"],
375
+ weights: [0, 10, 3, 1],
376
+ hasState: false,
377
+ header: ["score", "path", "title", "snippet"],
378
+ select: "path, title, headings, snippet(docs, 2, '\u0001', '\u0002', '', 12) AS hsnip, snippet(docs, 3, '', '', '...', 12) AS bsnip",
379
+ discover: (root) => discoverDocs(root, includes(root)),
380
+ row: (text, f) => {
381
+ const x = extract(text, f.path);
382
+ return [f.path, x.title, x.headings, text];
383
+ },
384
+ format: (root, r) => [r.score.toFixed(3), r.path, r.title, docSnippet(r)].map(cell),
385
+ },
386
+ };
387
+
268
388
  async function main() {
269
389
  if (!nodeOk()) die(`gauntlet-spec-index needs Node >=24.15.0 (found ${process.versions.node})`);
270
- const { query: text, limit, exclude } = parseArgs(process.argv.slice(2));
390
+ const { query: text, corpus: name, limit, exclude } = parseArgs(process.argv.slice(2));
271
391
  const toks = tokens(text);
272
392
  if (!toks.length) usage();
273
393
  const root = repoRoot();
394
+ const corpus = CORPORA[name];
274
395
  const db = await openDb(root);
275
- refresh(db, root, discover(root));
276
- const rows = query(db, toks, { limit, exclude });
277
- const out = [HEADER.join("\t")];
278
- for (const r of rows) {
279
- const t = telemetry(root, r.path);
280
- out.push([...[r.score.toFixed(3), r.path, r.service, r.title, t.status, t.shipped_at, r.state].map(cell), filesCell(t.files), cell(r.snippet)].join("\t"));
281
- }
396
+ refresh(db, root, corpus);
397
+ const rows = query(db, corpus, toks, { limit, exclude });
398
+ const out = [corpus.header.join("\t")];
399
+ for (const r of rows) out.push(corpus.format(root, r).join("\t"));
282
400
  process.stdout.write(out.join("\n") + "\n");
283
401
  db.close();
284
402
  }
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync } from "node:fs";
3
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync, symlinkSync } from "node:fs";
4
4
  import { join, dirname } from "node:path";
5
5
  import { tmpdir } from "node:os";
6
6
  import { spawnSync } from "node:child_process";
@@ -10,6 +10,22 @@ import { DatabaseSync } from "node:sqlite";
10
10
  const CLI = join(dirname(fileURLToPath(import.meta.url)), "gauntlet-spec-index.mjs");
11
11
  const DRAFT = "# CONTEXT DRAFT - NOT A SPEC - fully replaced at spec-writing";
12
12
  const HEADER = ["score", "path", "service", "title", "status", "shipped_at", "state", "files", "snippet"];
13
+ const DOCS_HEADER = ["score", "path", "title", "snippet"];
14
+ const docFiller = (n) => `# Filler ${n}\n\n## Design\n\nnothing of note here\n`;
15
+ const decoy = "# ptarmigan gannet decoy\n\n## ptarmigan gannet\n\nbody\n";
16
+ const docsRepo = () => {
17
+ const root = gitRepo();
18
+ write(root, "doc/guide.md", "# Guide\n\n## Configuring the ptarmigan gannet\n\nprose about setup\n");
19
+ write(root, "README.md", "# Repo\n\nThe body mentions ptarmigan once.\n");
20
+ for (let n = 1; n <= 4; n++) write(root, `doc/filler-${n}.md`, docFiller(n));
21
+ for (const p of ["doc/specs/a.md", "docs/specs/b.md", "doc/plans/p.md", "docs/plans/q.md", "node_modules/x/doc/a.md", "build/doc/b.md", ".pi/gauntlet/n.md", ".worktrees/w/doc/g.md"]) write(root, p, decoy);
22
+ write(root, ".gitignore", "build/\n");
23
+ write(root, "doc/draft.md", `${DRAFT}\n\n## ptarmigan gannet\n`);
24
+ commit(root);
25
+ return root;
26
+ };
27
+ const docsPaths = (root) => withDb(root, (db) => db.prepare("SELECT path FROM docs ORDER BY path").all().map((r) => r.path));
28
+ const overrides = (root, globs) => write(root, ".pi/gauntlet-overrides.md", `## Issue tracker\ntracker: none\n\n## Spec index\n${globs.map((g) => `- docs: \`${g}\``).join("\n")}\n\n## release\nnothing\n`);
13
29
 
14
30
  const write = (root, rel, text) => {
15
31
  mkdirSync(join(root, dirname(rel)), { recursive: true });
@@ -44,7 +60,7 @@ const repo = () => {
44
60
  const run = (cwd, args) => {
45
61
  const r = spawnSync(process.execPath, [CLI, ...args], { cwd, encoding: "utf8" });
46
62
  const lines = r.stdout.split("\n").filter(Boolean);
47
- return { status: r.status, stderr: r.stderr, header: lines[0]?.split("\t"), rows: lines.slice(1).map((l) => l.split("\t")) };
63
+ return { status: r.status, stderr: r.stderr, stdout: r.stdout, header: lines[0]?.split("\t"), rows: lines.slice(1).map((l) => l.split("\t")) };
48
64
  };
49
65
  const paths = (res) => res.rows.map((r) => r[1]);
50
66
  const withDb = (root, fn) => {
@@ -104,7 +120,7 @@ test("4: schema_version mismatch rebuilds the db", (t) => {
104
120
  const r = run(root, ["--query", "zephyr widget"]);
105
121
  assert.equal(r.status, 0, r.stderr);
106
122
  assert.equal(paths(r).length, 2);
107
- assert.equal(withDb(root, (database) => database.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get().value), "2");
123
+ assert.equal(withDb(root, (database) => database.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get().value), "3");
108
124
  });
109
125
 
110
126
  test("5: a non-SQLite database is rebuilt", (t) => {
@@ -114,7 +130,7 @@ test("5: a non-SQLite database is rebuilt", (t) => {
114
130
  const r = run(root, ["--query", "zephyr widget"]);
115
131
  assert.equal(r.status, 0, r.stderr);
116
132
  assert.deepEqual(paths(r), ["doc/specs/a.md", "svc-a/doc/specs/b.md"]);
117
- assert.equal(withDb(root, (database) => database.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get().value), "2");
133
+ assert.equal(withDb(root, (database) => database.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get().value), "3");
118
134
  });
119
135
 
120
136
  test("6: telemetry join is output-only and tolerant", (t) => {
@@ -340,3 +356,205 @@ test("16: punctuation splits into distinct evidence terms and query order does n
340
356
  assert.deepEqual(paths(distinct), ["doc/specs/cfg.md"]);
341
357
  assert.deepEqual(paths(run(root, ["--query", "config config-file"])), paths(run(root, ["--query", "config-file config"])));
342
358
  });
359
+
360
+ test("D1: --corpus specs and omitted --corpus are byte-identical; nine columns", (t) => {
361
+ const root = repo();
362
+ t.after(() => rmSync(root, { recursive: true, force: true }));
363
+ const plain = run(root, ["--query", "zephyr widget"]);
364
+ const explicit = run(root, ["--query", "zephyr widget", "--corpus", "specs"]);
365
+ assert.equal(explicit.status, 0, explicit.stderr);
366
+ assert.equal(explicit.stdout, plain.stdout);
367
+ assert.deepEqual(explicit.header, HEADER);
368
+ });
369
+
370
+ test("D11: unknown --corpus exits 1 with usage", (t) => {
371
+ const root = repo();
372
+ t.after(() => rmSync(root, { recursive: true, force: true }));
373
+ const r = run(root, ["--query", "zephyr widget", "--corpus", "notes"]);
374
+ assert.equal(r.status, 1);
375
+ assert.match(r.stderr, /usage:/);
376
+ assert.equal(run(root, ["--query", "zephyr widget", "--corpus"]).status, 1);
377
+ });
378
+
379
+ test("D12: a schema 2 cache is rebuilt to 3 with both tables present", (t) => {
380
+ const root = repo();
381
+ t.after(() => rmSync(root, { recursive: true, force: true }));
382
+ run(root, ["--query", "zephyr widget"]);
383
+ withDb(root, (database) => database.prepare("UPDATE meta SET value = '2' WHERE key = 'schema_version'").run());
384
+ const r = run(root, ["--query", "zephyr widget"]);
385
+ assert.equal(r.status, 0, r.stderr);
386
+ assert.equal(withDb(root, (database) => database.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get().value), "3");
387
+ const tables = withDb(root, (database) => database.prepare("SELECT name FROM sqlite_master WHERE name IN ('specs', 'docs') ORDER BY name").all().map((row) => row.name));
388
+ assert.deepEqual(tables, ["docs", "specs"]);
389
+ const cols = withDb(root, (database) => database.prepare("PRAGMA table_info(files)").all().map((row) => row.name));
390
+ assert.deepEqual(cols, ["corpus", "path", "mtime_ms", "size"]);
391
+ });
392
+
393
+ test("D10-specs: a `## ` line inside a code fence is not a heading", (t) => {
394
+ const root = repo();
395
+ t.after(() => rmSync(root, { recursive: true, force: true }));
396
+ write(root, "doc/specs/fenced.md", "# Fenced pelican\n\n**Goal:** pelican.\n\n```markdown\n## Not a heading pelican\n```\n\n## Real heading\n");
397
+ run(root, ["--query", "zephyr widget"]);
398
+ const h = withDb(root, (database) => database.prepare("SELECT headings FROM specs WHERE path = 'doc/specs/fenced.md'").get().headings);
399
+ assert.equal(h, "Real heading");
400
+ });
401
+
402
+ test("D2: docs include defaults and fixed exclusions", (t) => {
403
+ const root = docsRepo();
404
+ t.after(() => rmSync(root, { recursive: true, force: true }));
405
+ const r = run(root, ["--corpus", "docs", "--query", "ptarmigan gannet"]);
406
+ assert.equal(r.status, 0, r.stderr);
407
+ assert.deepEqual(r.header, DOCS_HEADER);
408
+ assert.deepEqual(paths(r), ["doc/guide.md"]);
409
+ assert.equal(r.rows[0].length, 4);
410
+ assert.deepEqual(docsPaths(root), ["README.md", ...[1, 2, 3, 4].map((n) => `doc/filler-${n}.md`), "doc/guide.md"]);
411
+ overrides(root, [".pi/**/*.md", ".worktrees/**/*.md", "doc/**/*.md"]);
412
+ assert.equal(run(root, ["--corpus", "docs", "--query", "ptarmigan gannet"]).status, 0);
413
+ assert.deepEqual(docsPaths(root), [".pi/gauntlet-overrides.md", ...[1, 2, 3, 4].map((n) => `doc/filler-${n}.md`), "doc/guide.md"]);
414
+ const two = gitRepo();
415
+ t.after(() => rmSync(two, { recursive: true, force: true }));
416
+ write(two, "doc/x.md", decoy);
417
+ write(two, "doc/y.md", decoy);
418
+ commit(two);
419
+ const tiny = run(two, ["--corpus", "docs", "--query", "ptarmigan gannet"]);
420
+ assert.equal(tiny.status, 0, tiny.stderr);
421
+ assert.deepEqual(tiny.header, DOCS_HEADER);
422
+ assert.deepEqual(tiny.rows, []);
423
+ });
424
+
425
+ test("D3: shared confidence rejects common body-only hits", (t) => {
426
+ const root = gitRepo();
427
+ t.after(() => rmSync(root, { recursive: true, force: true }));
428
+ write(root, "doc/strong.md", "# Strong heron ibis\n\n## jackal\n\nbody\n");
429
+ for (let n = 1; n <= 5; n++) write(root, `doc/p${n}.md`, `# Plain doc ${n}\n\nThe body mentions the common shared vocabulary.\n`);
430
+ commit(root);
431
+ const r = run(root, ["--corpus", "docs", "--query", "heron ibis jackal common", "--limit", "10"]);
432
+ assert.equal(r.status, 0, r.stderr);
433
+ assert.deepEqual(paths(r), ["doc/strong.md"]);
434
+ });
435
+
436
+ test("D4: no cross-corpus leakage", (t) => {
437
+ const root = repo();
438
+ t.after(() => rmSync(root, { recursive: true, force: true }));
439
+ write(root, "doc/guide.md", "# zephyr widget guide\n\n## zephyr widget\n");
440
+ for (let n = 1; n <= 4; n++) write(root, `doc/filler-${n}.md`, docFiller(n));
441
+ assert.deepEqual(paths(run(root, ["--query", "zephyr widget"])), ["doc/specs/a.md", "svc-a/doc/specs/b.md"]);
442
+ const docs = run(root, ["--corpus", "docs", "--query", "zephyr widget"]);
443
+ assert.deepEqual(paths(docs), ["doc/guide.md"]);
444
+ assert.deepEqual(docs.header, DOCS_HEADER);
445
+ });
446
+
447
+ test("D5: independent cache refresh in both directions", (t) => {
448
+ const root = repo();
449
+ t.after(() => rmSync(root, { recursive: true, force: true }));
450
+ write(root, "doc/guide.md", "# Guide\n\n## zephyr widget\n");
451
+ run(root, ["--query", "zephyr widget"]);
452
+ run(root, ["--corpus", "docs", "--query", "zephyr widget"]);
453
+ const files = () => withDb(root, (db) => Object.fromEntries(db.prepare("SELECT corpus, path, mtime_ms FROM files").all().map((r) => [`${r.corpus}:${r.path}`, r.mtime_ms])));
454
+ const before = files();
455
+ utimesSync(join(root, "doc/specs/a.md"), new Date(), new Date(Date.now() + 5000));
456
+ run(root, ["--corpus", "docs", "--query", "zephyr widget"]);
457
+ assert.deepEqual(files(), before);
458
+ run(root, ["--query", "zephyr widget"]);
459
+ assert.notEqual(files()["specs:doc/specs/a.md"], before["specs:doc/specs/a.md"]);
460
+ assert.equal(files()["docs:doc/guide.md"], before["docs:doc/guide.md"]);
461
+ assert.deepEqual(docsPaths(root), ["doc/guide.md"]);
462
+ });
463
+
464
+ test("D6: overrides replace defaults but cannot bypass exclusions", (t) => {
465
+ const root = docsRepo();
466
+ t.after(() => rmSync(root, { recursive: true, force: true }));
467
+ write(root, "notes/a.md", decoy);
468
+ write(root, "CONTRIBUTING.md", decoy);
469
+ write(root, "svc/CONTRIBUTING.md", decoy);
470
+ write(root, "svc/doc/inner.md", decoy);
471
+ commit(root);
472
+ const search = () => run(root, ["--corpus", "docs", "--query", "ptarmigan gannet"]);
473
+ overrides(root, ["notes/**/*.md"]);
474
+ assert.equal(search().status, 0);
475
+ assert.deepEqual(docsPaths(root), ["notes/a.md"]);
476
+ overrides(root, ["**/*.md"]);
477
+ assert.equal(search().status, 0);
478
+ const all = docsPaths(root);
479
+ for (const p of ["doc/specs/a.md", "docs/specs/b.md", "doc/plans/p.md", "docs/plans/q.md", "node_modules/x/doc/a.md", "build/doc/b.md", "doc/draft.md", ".pi/gauntlet/n.md", ".worktrees/w/doc/g.md"]) assert.ok(!all.includes(p), p);
480
+ assert.ok(all.includes("doc/guide.md"));
481
+ overrides(root, ["CONTRIBUTING.md"]);
482
+ assert.equal(search().status, 0);
483
+ assert.deepEqual(docsPaths(root), ["CONTRIBUTING.md", "svc/CONTRIBUTING.md"]);
484
+ write(root, ".pi/gauntlet-overrides.md", "## Spec index\n\nno bullets here\n");
485
+ assert.equal(search().status, 0);
486
+ assert.ok(docsPaths(root).includes("doc/guide.md"));
487
+ assert.ok(docsPaths(root).includes("svc/doc/inner.md"));
488
+ });
489
+
490
+ test("D6b: overrides file resolution order", (t) => {
491
+ const root = docsRepo();
492
+ t.after(() => rmSync(root, { recursive: true, force: true }));
493
+ write(root, "doc/gauntlet-overrides.md", "## Spec index\n- docs: `notes/**/*.md`\n");
494
+ write(root, "notes/a.md", decoy);
495
+ const search = () => run(root, ["--corpus", "docs", "--query", "ptarmigan gannet"]);
496
+ assert.equal(search().status, 0);
497
+ assert.deepEqual(docsPaths(root), ["notes/a.md"]);
498
+ write(root, "gauntlet-overrides.md", "## Spec index\n- docs: `other/**/*.md`\n");
499
+ write(root, "other/b.md", decoy);
500
+ assert.equal(search().status, 0);
501
+ assert.deepEqual(docsPaths(root), ["other/b.md"]);
502
+ overrides(root, ["doc/**/*.md"]);
503
+ assert.equal(search().status, 0);
504
+ assert.deepEqual(docsPaths(root), ["doc/filler-1.md", "doc/filler-2.md", "doc/filler-3.md", "doc/filler-4.md", "doc/gauntlet-overrides.md", "doc/guide.md"]);
505
+ });
506
+
507
+ test("D7: heading hits are strong, body-only hits are not", (t) => {
508
+ const root = gitRepo();
509
+ t.after(() => rmSync(root, { recursive: true, force: true }));
510
+ write(root, "doc/h.md", "# H\n\n## Setup\n\n## Feeding the kudu wombat\n\nprose\n");
511
+ write(root, "doc/b.md", "# B\n\n## Setup\n\nkudu wombat in the body only\n");
512
+ for (let n = 1; n <= 4; n++) write(root, `doc/filler-${n}.md`, docFiller(n));
513
+ commit(root);
514
+ const r = run(root, ["--corpus", "docs", "--query", "kudu wombat"]);
515
+ assert.equal(r.status, 0, r.stderr);
516
+ assert.deepEqual(paths(r), ["doc/h.md"]);
517
+ });
518
+
519
+ test("D8: snippet selects heading line or body fallback", (t) => {
520
+ const root = gitRepo();
521
+ t.after(() => rmSync(root, { recursive: true, force: true }));
522
+ const longHeading = "Feeding the wandering herds across twelve distant valleys before finally finding the kudu wombat";
523
+ write(root, "doc/h.md", `# H\n\n## Setup\n\n## ${longHeading}\n\nprose\n`);
524
+ write(root, "doc/t.md", "# lynx ocelot title\n\n## Unrelated\n\nbody says lynx ocelot here\n");
525
+ for (let n = 1; n <= 4; n++) write(root, `doc/filler-${n}.md`, docFiller(n));
526
+ commit(root);
527
+ const heading = run(root, ["--corpus", "docs", "--query", "kudu wombat"]);
528
+ assert.deepEqual(paths(heading), ["doc/h.md"]);
529
+ assert.equal(heading.rows[0][3], longHeading);
530
+ const body = run(root, ["--corpus", "docs", "--query", "lynx ocelot"]);
531
+ assert.deepEqual(paths(body), ["doc/t.md"]);
532
+ assert.match(body.rows[0][3], /body says lynx ocelot/);
533
+ assert.doesNotMatch(body.rows[0][3], /[\u0001\u0002]/);
534
+ });
535
+
536
+ test("D9: deleted files and symlinks are skipped, stale rows removed", (t) => {
537
+ const root = docsRepo();
538
+ t.after(() => rmSync(root, { recursive: true, force: true }));
539
+ write(root, "doc/gone.md", "# Gone\n\n## ptarmigan gannet\n");
540
+ commit(root);
541
+ run(root, ["--corpus", "docs", "--query", "ptarmigan gannet"]);
542
+ assert.ok(docsPaths(root).includes("doc/gone.md"));
543
+ rmSync(join(root, "doc/gone.md"));
544
+ symlinkSync(join(root, "doc/specs/a.md"), join(root, "doc/link.md"));
545
+ symlinkSync(join(root, "doc/nowhere.md"), join(root, "doc/dangling.md"));
546
+ const r = run(root, ["--corpus", "docs", "--query", "ptarmigan gannet"]);
547
+ assert.equal(r.status, 0, r.stderr);
548
+ assert.deepEqual(paths(r), ["doc/guide.md"]);
549
+ for (const p of ["doc/gone.md", "doc/link.md", "doc/dangling.md"]) assert.ok(!docsPaths(root).includes(p), p);
550
+ assert.equal(withDb(root, (db) => db.prepare("SELECT count(*) AS c FROM files WHERE corpus = 'docs' AND path = 'doc/gone.md'").get().c), 0);
551
+ });
552
+
553
+ test("D10: fenced headings and shorter nested fences are ignored", (t) => {
554
+ const root = docsRepo();
555
+ t.after(() => rmSync(root, { recursive: true, force: true }));
556
+ write(root, "doc/f.md", "# F\n\n```\n## kudu wombat\n```\n\nbody\n");
557
+ write(root, "doc/nested.md", "# N\n\n````markdown\n```js\n## inner heading\n```\n## still fenced\n````\n");
558
+ run(root, ["--corpus", "docs", "--query", "ptarmigan gannet"]);
559
+ for (const p of ["doc/f.md", "doc/nested.md"]) assert.equal(withDb(root, (db) => db.prepare("SELECT headings FROM docs WHERE path = ?").get(p).headings), "");
560
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gauntlet",
3
- "version": "5.22.0",
3
+ "version": "5.23.0",
4
4
  "description": "Opinionated, gated workflow skills, subagent personas, and runtime extensions for the pi coding agent.",
5
5
  "author": "Jacek Juraszek",
6
6
  "type": "module",
@@ -104,7 +104,7 @@ Prefer clear testable boundaries, YAGNI, existing conventions, the owning schema
104
104
 
105
105
  ### 6. Present the design in two rounds
106
106
 
107
- Use two rounds, targeting 300-500 words each, with one approval each; revisions remain within that approval point. Ask once per round; round-1 approval without correction confirms the predecessor. Round 1 covers architecture, responsibilities, data flow, and `supersedes <path>, <scope>` when applicable. Round 2 covers errors, edges, tests, and `## Documentation impact`.
107
+ Use two rounds, targeting 300-500 words each, with one approval each; revisions remain within that approval point. Ask once per round; round-1 approval without correction confirms the predecessor. Round 1 covers architecture, responsibilities, data flow, and `supersedes <path>, <scope>` when applicable. Round 2 covers errors, edges, tests, and `## Documentation impact`. In round 2, cite the draft's `Docs touched:` entries as candidates for "Materially amended existing docs"; admit or drop each by the materiality bar in `reference/documentation-impact.md`, never list them automatically.
108
108
 
109
109
  `## Documentation impact` is required. Cite `reference/documentation-impact.md` by relative path, do not restate its categories, and reproduce this template verbatim:
110
110
 
@@ -82,7 +82,22 @@ Scout (always dispatched):
82
82
  > from the directory-listing fallback) contributes no path and no `missing` line. When
83
83
  > no path and no `missing` line results - including whenever the index was unavailable -
84
84
  > omit the section entirely; `Predecessor: none` produces no anchors section. The anchors
85
- > are a recon hint, never a selection input. End with an
85
+ > are a recon hint, never a selection input.
86
+ > Docs check: run `node <SPEC_INDEX> --corpus docs --query '<the same keywords>' --limit 10`
87
+ > from the worktree root. Its rows are project documentation that already speaks about the
88
+ > request's topic; open at most five whose topic matches and let them inform the "already
89
+ > solves this?" finding and the current-contract recon. If the command fails, write
90
+ > `Docs index unavailable - docs check used recon only.` in your handoff and continue. After
91
+ > the `Predecessor:` line(s) and any `Predecessor anchors` section, render at most
92
+ > five `Docs touched: <path> - <section heading>` lines, one per document that
93
+ > genuinely covers the request's topic - an opened index row or a document your own
94
+ > recon found - where
95
+ > `<section heading>` is the `##`/`###` heading of the covering section as read in the
96
+ > document (the row's `snippet` column is a hint to it), or the document title when no single
97
+ > section applies; or `Docs touched: none`. Judge by topic; a lexical hit alone is not
98
+ > coverage. Zero rows means the index found no evidence, not that no document covers the
99
+ > topic. This query supplements the code and documentation recon you already perform; it
100
+ > never replaces it - keep reading the files the request touches. End with an
86
101
  > "Open questions that matter for the spec"
87
102
  > section. Compact handoff, not a dump.
88
103