@blackbelt-technology/pi-dashboard-kb 0.5.4 → 0.6.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/dist/cli.js +29 -18
- package/dist/config.js +4 -1
- package/dist/dox.d.ts +17 -0
- package/dist/dox.js +158 -41
- package/dist/index-run.d.ts +23 -0
- package/dist/index-run.js +115 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/indexer.d.ts +2 -1
- package/dist/indexer.js +33 -3
- package/dist/migrate-file-index.d.ts +39 -0
- package/dist/migrate-file-index.js +92 -0
- package/dist/migrate-runner.d.ts +57 -0
- package/dist/migrate-runner.js +172 -0
- package/dist/render.d.ts +11 -0
- package/dist/render.js +27 -0
- package/dist/sqlite-store.d.ts +9 -0
- package/dist/sqlite-store.js +44 -3
- package/dist/types.d.ts +3 -1
- package/package.json +23 -4
- package/src/AGENTS.md +23 -0
- package/src/cli.ts +30 -15
- package/src/config.ts +4 -1
- package/src/dox.ts +144 -41
- package/src/index-run.ts +125 -0
- package/src/index.ts +3 -1
- package/src/indexer.ts +35 -3
- package/src/migrate-file-index.ts +121 -0
- package/src/migrate-runner.ts +191 -0
- package/src/node-sqlite.d.ts +33 -0
- package/src/render.ts +46 -0
- package/src/sqlite-store.ts +41 -3
- package/src/types.ts +1 -1
package/src/cli.ts
CHANGED
|
@@ -5,13 +5,15 @@
|
|
|
5
5
|
import { readFileSync } from "node:fs";
|
|
6
6
|
import { resolve } from "node:path";
|
|
7
7
|
import { loadConfig, type ResolvedConfig, type ResolvedSource } from "./config.js";
|
|
8
|
+
import { agentsChain, doxInit, doxLint } from "./dox.js";
|
|
9
|
+
import { evaluate, type GoldenItem } from "./eval.js";
|
|
10
|
+
import { runIndexAtomic } from "./index-run.js";
|
|
11
|
+
import { indexSource } from "./indexer.js";
|
|
8
12
|
import { kbInit } from "./init.js";
|
|
13
|
+
import { renderHits } from "./render.js";
|
|
14
|
+
import { classifyRef, type ResolvedSource as RResolvedSource, resolveAll } from "./sources.js";
|
|
9
15
|
import { SqliteFtsStore } from "./sqlite-store.js";
|
|
10
|
-
import { indexSource } from "./indexer.js";
|
|
11
|
-
import { evaluate, type GoldenItem } from "./eval.js";
|
|
12
|
-
import { resolveAll, classifyRef, type ResolvedSource as RResolvedSource } from "./sources.js";
|
|
13
16
|
import { defaultPromptTrust } from "./trust.js";
|
|
14
|
-
import { agentsChain, doxInit, doxLint } from "./dox.js";
|
|
15
17
|
import type { DocType, SearchOpts } from "./types.js";
|
|
16
18
|
|
|
17
19
|
interface Flags {
|
|
@@ -68,10 +70,10 @@ function openStore(cfg: ResolvedConfig): SqliteFtsStore {
|
|
|
68
70
|
store.init();
|
|
69
71
|
return store;
|
|
70
72
|
}
|
|
71
|
-
function runIndex(cfg: ResolvedConfig, store: SqliteFtsStore, sources: RResolvedSource[], force = false) {
|
|
73
|
+
async function runIndex(cfg: ResolvedConfig, store: SqliteFtsStore, sources: RResolvedSource[], force = false) {
|
|
72
74
|
let scanned = 0, changed = 0, deleted = 0, chunks = 0;
|
|
73
75
|
for (const s of sources) {
|
|
74
|
-
const st = indexSource(store, { root: s.id, dir: s.dir }, { force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions });
|
|
76
|
+
const st = await indexSource(store, { root: s.id, dir: s.dir }, { force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions });
|
|
75
77
|
scanned += st.scanned; changed += st.changed; deleted += st.deleted; chunks += st.chunks;
|
|
76
78
|
}
|
|
77
79
|
return { scanned, changed, deleted, chunks };
|
|
@@ -176,19 +178,32 @@ async function runCmd(cmd: string, flags: Flags): Promise<void> {
|
|
|
176
178
|
}
|
|
177
179
|
const sources = await sourcesForRun(cfg, flags);
|
|
178
180
|
if (!sources.length && isIndex) { console.error("no sources resolved"); process.exit(2); }
|
|
181
|
+
|
|
182
|
+
if (cmd === "index") {
|
|
183
|
+
// Atomic path: do NOT openStore(cfg) here — opening pre-creates the DB file
|
|
184
|
+
// at dbPath (the husk). runIndexAtomic owns store lifecycle (temp+rename on
|
|
185
|
+
// first index; in-place incremental). See change: harden-kb-index-failure-atomicity.
|
|
186
|
+
const explicit = !!(flags.source as string[] | undefined)?.length;
|
|
187
|
+
const t = performance.now();
|
|
188
|
+
const s = await runIndexAtomic({
|
|
189
|
+
dbPath: cfg.dbAbsPath,
|
|
190
|
+
sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
|
|
191
|
+
indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions },
|
|
192
|
+
explicit,
|
|
193
|
+
});
|
|
194
|
+
console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
|
|
195
|
+
console.log(JSON.stringify(s.counts));
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
|
|
179
199
|
const store = openStore(cfg);
|
|
180
200
|
try {
|
|
181
|
-
if (cmd === "
|
|
182
|
-
const t = performance.now();
|
|
183
|
-
const s = runIndex(cfg, store, sources, !!flags.force);
|
|
184
|
-
console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
|
|
185
|
-
console.log(JSON.stringify(store.counts()));
|
|
186
|
-
} else if (cmd === "search") {
|
|
201
|
+
if (cmd === "search") {
|
|
187
202
|
const q = flags._[1];
|
|
188
203
|
if (!q) { console.error("search needs a query"); process.exit(2); }
|
|
189
204
|
const limit = posInt(flags.limit, "--limit");
|
|
190
205
|
const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
|
|
191
|
-
if (!flags["no-reindex"]) runIndex(cfg, store, sources); // auto incremental freshness
|
|
206
|
+
if (!flags["no-reindex"]) await runIndex(cfg, store, sources); // auto incremental freshness
|
|
192
207
|
const so: SearchOpts = {
|
|
193
208
|
limit: limit ?? 10,
|
|
194
209
|
root: flags.root as string | undefined,
|
|
@@ -204,7 +219,7 @@ async function runCmd(cmd: string, flags: Flags): Promise<void> {
|
|
|
204
219
|
};
|
|
205
220
|
const hits = store.search(q, so);
|
|
206
221
|
if (flags.json) console.log(JSON.stringify(hits, null, 2));
|
|
207
|
-
else
|
|
222
|
+
else if (hits.length) console.log(renderHits(hits, { leading: "score", parentGlyph: "[parent: ", multiline: false }));
|
|
208
223
|
} else if (cmd === "neighbors") {
|
|
209
224
|
const depth = posInt(flags.depth, "--depth") ?? 2;
|
|
210
225
|
const rel = enumFlag(flags.rel, ["child_of", "links_to", "references", "has_tag"], "--rel");
|
|
@@ -224,7 +239,7 @@ async function runCmd(cmd: string, flags: Flags): Promise<void> {
|
|
|
224
239
|
} else if (cmd === "eval") {
|
|
225
240
|
const gf = flags.golden as string | undefined;
|
|
226
241
|
if (!gf) { console.error("eval needs --golden <file.json>"); process.exit(2); }
|
|
227
|
-
if (!flags["no-reindex"]) runIndex(cfg, store, sources);
|
|
242
|
+
if (!flags["no-reindex"]) await runIndex(cfg, store, sources);
|
|
228
243
|
const golden = JSON.parse(readFileSync(resolve(cfg.cwd, gf), "utf8")) as GoldenItem[];
|
|
229
244
|
const m = evaluate(store, golden, { k: flags.limit ? Number(flags.limit) : 10, docType: flags["doc-type"] as DocType | undefined });
|
|
230
245
|
console.log(JSON.stringify(m, null, flags.json ? 2 : 0));
|
package/src/config.ts
CHANGED
|
@@ -97,7 +97,10 @@ export const DEFAULTS: KbConfig = {
|
|
|
97
97
|
chunking: { minHeadingsForStructural: 1, minChunkChars: 120, maxChunkChars: 4000, breadcrumbInBody: true },
|
|
98
98
|
dedup: { exactContentCollapse: true, preferHigherPriorityRoot: true },
|
|
99
99
|
graph: { wikilinks: true, headingTree: true, frontmatter: true },
|
|
100
|
-
|
|
100
|
+
// Pull mode: `kb agents <path>` walks root→nearest AGENTS.md on demand. Safe —
|
|
101
|
+
// no per-turn injection. Push mode stays gated behind the context-cost spike
|
|
102
|
+
// (see change migrate-file-index-to-agents-tree design §5).
|
|
103
|
+
directoryLevelAgents: { enabled: true, claudeMd: true, mode: "pull", fallbackManifest: true },
|
|
101
104
|
doxEnforcement: false,
|
|
102
105
|
ranking: { fieldWeights: { headingPath: 10, heading: 3, body: 1 }, proximityBoost: true, diversity: { enabled: true, lambda: 0.7 } },
|
|
103
106
|
expand: { parent: true, graph: false },
|
package/src/dox.ts
CHANGED
|
@@ -7,10 +7,43 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "nod
|
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
8
8
|
import type { KbStore } from "./types.js";
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
// delta ②: exclude worktree checkouts, archived openspec proposals, and doc-example noise.
|
|
11
|
+
// Also exclude build output (`out`) and the electron bundled/vendored trees
|
|
12
|
+
// (`bundled-extensions`, `electron/resources/server`) — all gitignored, zero
|
|
13
|
+
// tracked md; the walk is fs-based so they surface as bogus missing/companion
|
|
14
|
+
// rows without this. `server` is scoped to `electron/resources/server` so real
|
|
15
|
+
// `server` source dirs (packages/server, kb-plugin/src/server) stay indexed.
|
|
16
|
+
// Also skip scratch/output + narrative dirs (`mockups`, `research`, `site`,
|
|
17
|
+
// `.github`, `Prompt stories` — session-to-guideline playbooks: prose, not
|
|
18
|
+
// navigable source) and self-evident top-level docs (`CHANGELOG.md`, `CLAUDE.md`,
|
|
19
|
+
// repo-root `README.md`) with no per-file DOX value; `README` anchored to root so
|
|
20
|
+
// package READMEs stay documented.
|
|
21
|
+
const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.pi|\.worktrees|openspec|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
|
|
11
22
|
const AGENTS_FILES = ["AGENTS.md"];
|
|
23
|
+
// delta ①: dox init now maps SOURCE, not docs. Source globs, minus type decls and tests.
|
|
24
|
+
const SOURCE_EXT = /\.(ts|tsx|js|jsx)$/;
|
|
25
|
+
const MD_EXT = /\.(md|mdx)$/i;
|
|
26
|
+
function isSourceFile(name: string): boolean {
|
|
27
|
+
return SOURCE_EXT.test(name) && !/\.d\.ts$/.test(name) && !/\.(test|spec)\.[cm]?[jt]sx?$/.test(name);
|
|
28
|
+
}
|
|
29
|
+
function isMdFile(name: string): boolean {
|
|
30
|
+
// `*.AGENTS.md` sidecars (per-file index promotions) and `*.agent.md`
|
|
31
|
+
// companions (pull-only index of a large doc) are DOX index artifacts, not
|
|
32
|
+
// documentable source — exclude from the md walk so they need no row/companion
|
|
33
|
+
// of their own (else a companion needs a companion-of-a-companion, ad infinitum).
|
|
34
|
+
return (
|
|
35
|
+
MD_EXT.test(name) &&
|
|
36
|
+
!AGENTS_FILES.includes(name) &&
|
|
37
|
+
!name.endsWith(".AGENTS.md") &&
|
|
38
|
+
!name.endsWith(".agent.md")
|
|
39
|
+
);
|
|
40
|
+
}
|
|
12
41
|
export const AREA_FILE_THRESHOLD = 8; // ≥ this many md files in a subdir → own AGENTS.md
|
|
13
42
|
export const ROW_CAP = 40;
|
|
43
|
+
// pi auto-injects a dir AGENTS.md on every turn when cwd sits at/below it. Past
|
|
44
|
+
// this byte cap it is "too large" → split file-based: promote the heaviest rows
|
|
45
|
+
// to `<File>.AGENTS.md` sidecars (pull-only) + cap remaining rows to one line.
|
|
46
|
+
export const AGENTS_BYTE_CAP = 30000;
|
|
14
47
|
const COMPANION_LOC = 300;
|
|
15
48
|
const COMPANION_BYTES = 15000;
|
|
16
49
|
|
|
@@ -85,37 +118,101 @@ export interface DoxInitPlan {
|
|
|
85
118
|
appended: { file: string; rows: string[] }[]; // existing files getting new rows
|
|
86
119
|
}
|
|
87
120
|
|
|
88
|
-
|
|
121
|
+
// delta ①: parameterized walker. `dox init` walks source (walkSource); fallbackManifest
|
|
122
|
+
// + doxLint keep walking md (walkMd). __tests__ dirs are always skipped.
|
|
123
|
+
// DEFAULT_EXCLUDE is tested against the path RELATIVE to the walk root, so an
|
|
124
|
+
// ancestor dir named like an excluded token (e.g. running inside .worktrees)
|
|
125
|
+
// does not nuke the whole walk.
|
|
126
|
+
function walkFiles(dir: string, match: (name: string) => boolean, out: string[] = [], root: string = dir): string[] {
|
|
89
127
|
if (!existsSync(dir)) return out;
|
|
90
128
|
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
91
129
|
const abs = join(dir, e.name);
|
|
92
|
-
|
|
93
|
-
if (
|
|
94
|
-
|
|
95
|
-
|
|
130
|
+
if (DEFAULT_EXCLUDE.test(relative(root, abs))) continue;
|
|
131
|
+
if (e.isDirectory()) {
|
|
132
|
+
if (e.name === "__tests__") continue;
|
|
133
|
+
walkFiles(abs, match, out, root);
|
|
134
|
+
} else if (match(e.name)) out.push(abs);
|
|
96
135
|
}
|
|
97
136
|
return out;
|
|
98
137
|
}
|
|
138
|
+
function walkMd(dir: string, out: string[] = []): string[] {
|
|
139
|
+
return walkFiles(dir, isMdFile, out);
|
|
140
|
+
}
|
|
141
|
+
function walkSource(dir: string, out: string[] = []): string[] {
|
|
142
|
+
return walkFiles(dir, isSourceFile, out);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Resolve a DOX row path. Rows document paths RELATIVE TO THEIR OWN AGENTS.md
|
|
146
|
+
* dir. A directory may also document a file that lives OUTSIDE its own dir (a
|
|
147
|
+
* nested AGENTS.md referencing a project-root file) — so fall back to `cwd`
|
|
148
|
+
* when the dir-relative target is absent. Returns the dir-relative candidate
|
|
149
|
+
* when neither exists (caller flags orphan). */
|
|
150
|
+
export function resolveRowPath(agentsDir: string, cwd: string, rp: string): string {
|
|
151
|
+
if (isAbsolute(rp)) return rp;
|
|
152
|
+
const dirRel = resolve(agentsDir, rp);
|
|
153
|
+
if (existsSync(dirRel)) return dirRel;
|
|
154
|
+
const rootRel = resolve(cwd, rp);
|
|
155
|
+
return existsSync(rootRel) ? rootRel : dirRel;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Sidecar-pointer marker written by scripts/split-large-agents.mjs when it
|
|
159
|
+
// promotes a heavy (>INLINE_CAP) row to its pull-only `<File>.AGENTS.md`. A row
|
|
160
|
+
// carrying it holds no inline detail, so it is excluded from the ROW_CAP count.
|
|
161
|
+
const SIDECAR_POINTER = /→ see `[^`]+\.AGENTS\.md`/;
|
|
162
|
+
|
|
163
|
+
/** Count INLINE DOX rows for the ROW_CAP over-threshold check. Excludes
|
|
164
|
+
* sidecar-pointer rows (pull-only, no per-turn injection detail). Sibling to
|
|
165
|
+
* parseRowPaths — never a replacement: parseRowPaths stays a COMPLETE path
|
|
166
|
+
* string[] (consumed cross-package by kb-extension acknowledgeRows/decideNudge
|
|
167
|
+
* + the missing/orphan/staleness checks); the exclusion is count-only. */
|
|
168
|
+
export function countInlineRows(agentsFile: string): number {
|
|
169
|
+
if (!existsSync(agentsFile)) return 0;
|
|
170
|
+
const text = readFileSync(agentsFile, "utf8");
|
|
171
|
+
let inDox = false;
|
|
172
|
+
let count = 0;
|
|
173
|
+
for (const line of text.split("\n")) {
|
|
174
|
+
const h = line.match(/^#{1,6}\s+(.*)$/);
|
|
175
|
+
if (h) { inDox = /^DOX\b/.test(h[1].trim()); continue; }
|
|
176
|
+
if (!inDox) continue;
|
|
177
|
+
const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
|
|
178
|
+
if (!m) continue;
|
|
179
|
+
if (SIDECAR_POINTER.test(line)) continue; // sidecar-pointer row, pull-only
|
|
180
|
+
count++;
|
|
181
|
+
}
|
|
182
|
+
return count;
|
|
183
|
+
}
|
|
99
184
|
|
|
100
185
|
/** Parse existing row paths from an AGENTS.md file. */
|
|
101
186
|
export function parseRowPaths(agentsFile: string): string[] {
|
|
102
187
|
if (!existsSync(agentsFile)) return [];
|
|
103
188
|
const text = readFileSync(agentsFile, "utf8");
|
|
104
189
|
const paths: string[] = [];
|
|
190
|
+
// Only rows under a `# DOX —` heading are file-index rows. Prose tables
|
|
191
|
+
// (Subagent Routing, QA globs, …) under other headings are NOT DOX rows.
|
|
192
|
+
let inDox = false;
|
|
105
193
|
for (const line of text.split("\n")) {
|
|
194
|
+
const h = line.match(/^#{1,6}\s+(.*)$/);
|
|
195
|
+
if (h) { inDox = /^DOX\b/.test(h[1].trim()); continue; }
|
|
196
|
+
if (!inDox) continue;
|
|
106
197
|
const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
|
|
107
198
|
if (m) paths.push(m[1]);
|
|
108
199
|
}
|
|
109
200
|
return paths;
|
|
110
201
|
}
|
|
111
202
|
|
|
112
|
-
|
|
113
|
-
|
|
203
|
+
/** Source-file walk (delta ①②), exported for the file-index migration. */
|
|
204
|
+
export function sourceFiles(cwd: string): string[] {
|
|
205
|
+
return walkSource(cwd);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// delta ③: group source files by FULL parent dir (dirname), not the top-level
|
|
209
|
+
// segment — this is what makes the tree directory-level.
|
|
210
|
+
export function areaFiles(cwd: string): Map<string, string[]> {
|
|
114
211
|
const groups = new Map<string, string[]>();
|
|
115
|
-
for (const f of
|
|
212
|
+
for (const f of walkSource(cwd)) {
|
|
116
213
|
const rel = relative(cwd, f);
|
|
117
|
-
const
|
|
118
|
-
(groups.get(
|
|
214
|
+
const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : ".";
|
|
215
|
+
(groups.get(dir) ?? groups.set(dir, []).get(dir)!).push(rel);
|
|
119
216
|
}
|
|
120
217
|
return groups;
|
|
121
218
|
}
|
|
@@ -127,11 +224,6 @@ export function doxInit(opts: DoxInitOptions): DoxInitPlan {
|
|
|
127
224
|
const plan: DoxInitPlan = { created: [], appended: [] };
|
|
128
225
|
const groups = areaFiles(cwd);
|
|
129
226
|
|
|
130
|
-
const buildRows = (rels: string[], areaDir: string): string[] =>
|
|
131
|
-
rels
|
|
132
|
-
.filter((r) => !AGENTS_FILES.includes(basename(r)))
|
|
133
|
-
.map((r) => `| \`${r}\` | |`);
|
|
134
|
-
|
|
135
227
|
const ensure = (agentsFile: string, rows: string[]) => {
|
|
136
228
|
if (existsSync(agentsFile)) {
|
|
137
229
|
const existing = new Set(parseRowPaths(agentsFile));
|
|
@@ -150,23 +242,15 @@ export function doxInit(opts: DoxInitOptions): DoxInitPlan {
|
|
|
150
242
|
}
|
|
151
243
|
};
|
|
152
244
|
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const rels = groups.get(a)!;
|
|
163
|
-
const areaRows = buildRows(rels, join(cwd, a));
|
|
164
|
-
// split into chunks of ROW_CAP
|
|
165
|
-
for (let i = 0; i < areaRows.length; i += ROW_CAP) {
|
|
166
|
-
const chunk = areaRows.slice(i, i + ROW_CAP);
|
|
167
|
-
const subArea = i === 0 ? join(cwd, a) : join(cwd, a, `part-${Math.floor(i / ROW_CAP) + 1}`);
|
|
168
|
-
ensure(join(subArea, "AGENTS.md"), chunk);
|
|
169
|
-
}
|
|
245
|
+
// delta ④ + granularity A: every directory holding ≥1 source file gets its own
|
|
246
|
+
// AGENTS.md. No AREA_FILE_THRESHOLD gate, no part-N pseudo-dirs, no roll-up.
|
|
247
|
+
// delta ⑤: rows are relative to each AGENTS.md's own directory.
|
|
248
|
+
for (const [dir, rels] of groups) {
|
|
249
|
+
const areaDir = dir === "." ? cwd : join(cwd, dir);
|
|
250
|
+
const rows = rels
|
|
251
|
+
.filter((r) => !AGENTS_FILES.includes(basename(r)))
|
|
252
|
+
.map((r) => `| \`${basename(r)}\` | |`);
|
|
253
|
+
if (rows.length) ensure(join(areaDir, "AGENTS.md"), rows);
|
|
170
254
|
}
|
|
171
255
|
|
|
172
256
|
return plan;
|
|
@@ -179,6 +263,9 @@ export interface DoxIssue {
|
|
|
179
263
|
agentsFile: string;
|
|
180
264
|
path?: string;
|
|
181
265
|
detail: string;
|
|
266
|
+
// over-threshold discriminator: "bytes" = actionable (auto-injected per turn,
|
|
267
|
+
// remedy = sidecar split); "rows" = informational (advisory, no injection cost).
|
|
268
|
+
arm?: "bytes" | "rows";
|
|
182
269
|
}
|
|
183
270
|
export interface DoxLintOptions {
|
|
184
271
|
json?: boolean;
|
|
@@ -205,11 +292,14 @@ export function doxLint(opts: DoxLintOptions): DoxLintResult {
|
|
|
205
292
|
|
|
206
293
|
// find all AGENTS.md
|
|
207
294
|
const agentsFiles: string[] = [];
|
|
295
|
+
// Test the path RELATIVE to cwd (mirrors walkFiles) so an ancestor dir named
|
|
296
|
+
// like an excluded token (e.g. running inside .worktrees) does not nuke the
|
|
297
|
+
// whole walk and yield 0 issues.
|
|
208
298
|
const walkAgents = (dir: string) => {
|
|
209
299
|
if (!existsSync(dir)) return;
|
|
210
300
|
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
211
301
|
const abs = join(dir, e.name);
|
|
212
|
-
if (DEFAULT_EXCLUDE.test(abs)) continue;
|
|
302
|
+
if (DEFAULT_EXCLUDE.test(relative(cwd, abs))) continue;
|
|
213
303
|
if (e.isDirectory()) walkAgents(abs);
|
|
214
304
|
else if (e.name === "AGENTS.md") agentsFiles.push(abs);
|
|
215
305
|
}
|
|
@@ -225,24 +315,37 @@ export function doxLint(opts: DoxLintOptions): DoxLintResult {
|
|
|
225
315
|
const rowPaths = new Set<string>();
|
|
226
316
|
|
|
227
317
|
for (const af of agentsFiles) {
|
|
228
|
-
const rows = parseRowPaths(af);
|
|
229
318
|
const afRel = relative(cwd, af);
|
|
230
|
-
// over-threshold
|
|
231
|
-
|
|
319
|
+
// over-threshold splits into two arms with distinct severity:
|
|
320
|
+
// - byte arm (actionable): file auto-injected per turn past the byte cap;
|
|
321
|
+
// remedy = file-based sidecar split (promote heaviest rows).
|
|
322
|
+
// - row arm (informational): more than ROW_CAP INLINE rows but within the
|
|
323
|
+
// byte cap — no per-turn injection cost; optional directory foldering.
|
|
324
|
+
// Row arm counts INLINE rows only (sidecar-pointer rows excluded) so a
|
|
325
|
+
// split reduces both the byte total AND the counted-row total.
|
|
326
|
+
const afBytes = statSync(af).size;
|
|
327
|
+
if (afBytes > AGENTS_BYTE_CAP) issues.push({ kind: "over-threshold", agentsFile: afRel, arm: "bytes", detail: `${afBytes} bytes > cap ${AGENTS_BYTE_CAP}; auto-injected per turn — actionable: promote heaviest rows to <File>.AGENTS.md sidecars` });
|
|
328
|
+
const inlineCount = countInlineRows(af);
|
|
329
|
+
if (inlineCount > ROW_CAP) issues.push({ kind: "over-threshold", agentsFile: afRel, arm: "rows", detail: `${inlineCount} inline rows > cap ${ROW_CAP}; informational (advisory; no per-turn injection cost) — optional: folder into cohesive subdirectories` });
|
|
232
330
|
const survivingRows: string[] = [];
|
|
233
331
|
const text = readFileSync(af, "utf8").split("\n");
|
|
332
|
+
const afDir = dirname(af);
|
|
333
|
+
let inDox = false;
|
|
234
334
|
for (const line of text) {
|
|
235
|
-
const
|
|
335
|
+
const h = line.match(/^#{1,6}\s+(.*)$/);
|
|
336
|
+
if (h) { inDox = /^DOX\b/.test(h[1].trim()); if (opts.fix) survivingRows.push(line); continue; }
|
|
337
|
+
const m = inDox ? line.match(/^\|\s*`([^`]+)`\s*\|/) : null;
|
|
236
338
|
if (!m) { if (opts.fix) survivingRows.push(line); continue; }
|
|
237
339
|
const rp = m[1];
|
|
238
|
-
|
|
239
|
-
const
|
|
340
|
+
const abs = resolveRowPath(afDir, cwd, rp);
|
|
341
|
+
const rel = relative(cwd, abs);
|
|
342
|
+
rowPaths.add(rel);
|
|
240
343
|
if (!existsSync(abs)) {
|
|
241
344
|
// could be a broken pointer to an area AGENTS.md, or an orphan source row
|
|
242
345
|
const kind = rp.endsWith("AGENTS.md") ? "broken-pointer" : "orphan";
|
|
243
346
|
issues.push({ kind, agentsFile: afRel, path: rp, detail: `${kind}: ${rp} does not exist` });
|
|
244
347
|
if (opts.fix && kind === "orphan") { fixed++; continue; } // prune orphan row
|
|
245
|
-
} else if (staleness[
|
|
348
|
+
} else if (staleness[rel] && fileSha(abs) && staleness[rel] !== fileSha(abs)) {
|
|
246
349
|
issues.push({ kind: "stale", agentsFile: afRel, path: rp, detail: `tracked source-hash drifted` });
|
|
247
350
|
}
|
|
248
351
|
if (opts.fix) survivingRows.push(line);
|
package/src/index-run.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Atomic `kb index` orchestration. Failure-atomicity guarantee: a file at
|
|
2
|
+
// `dbPath` means a successful index ran. See change: harden-kb-index-failure-atomicity.
|
|
3
|
+
//
|
|
4
|
+
// D1 (design.md): branch on whether `dbPath` already exists.
|
|
5
|
+
// - First index (no dbPath): build into `<dbPath>.tmp-<pid>` and rename() onto
|
|
6
|
+
// dbPath only on success. A crash/OOM/SIGKILL leaves only the temp orphan —
|
|
7
|
+
// the real path never appears, so the worktree-init gate correctly re-fires.
|
|
8
|
+
// A create-track → close()+unlink()-on-failure variant is NOT used: that
|
|
9
|
+
// cleanup is dead code under uncatchable termination and would leave the husk.
|
|
10
|
+
// - Incremental (valid dbPath exists): index in place, preserving the in-DB
|
|
11
|
+
// file-state incremental skip needs. A mid-run failure leaves the prior DB
|
|
12
|
+
// valid & queryable; a re-run completes it.
|
|
13
|
+
import { existsSync, readdirSync, unlinkSync } from "node:fs";
|
|
14
|
+
import { basename, dirname, join } from "node:path";
|
|
15
|
+
import { type IndexOptions, type IndexStats, indexSource } from "./indexer.js";
|
|
16
|
+
import { SqliteFtsStore } from "./sqlite-store.js";
|
|
17
|
+
|
|
18
|
+
type StoreCounts = ReturnType<SqliteFtsStore["counts"]>;
|
|
19
|
+
|
|
20
|
+
export interface AtomicIndexSource {
|
|
21
|
+
id: string;
|
|
22
|
+
dir: string;
|
|
23
|
+
}
|
|
24
|
+
export interface RunIndexAtomicOpts {
|
|
25
|
+
dbPath: string;
|
|
26
|
+
sources: AtomicIndexSource[];
|
|
27
|
+
indexOpts?: IndexOptions;
|
|
28
|
+
/** Sources came from an explicit `--source` arg; a missing one is a user typo. */
|
|
29
|
+
explicit?: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** True if `pid` names a live process (existence probe via signal 0). EPERM =
|
|
33
|
+
* alive but not ours; ESRCH = dead. kb is self-contained (no pi-dashboard-shared
|
|
34
|
+
* dep, same as `sources.ts`), so it probes with a raw signal-0 send rather than
|
|
35
|
+
* the shared platform helper — signal 0 is a read-only liveness check, never a
|
|
36
|
+
* termination (see the ban-opt-out marker below). */
|
|
37
|
+
function isProcessAlive(pid: number): boolean {
|
|
38
|
+
try {
|
|
39
|
+
process.kill(pid, 0); // ban:process-kill-ok kb self-contained; signal 0 = liveness probe only
|
|
40
|
+
return true;
|
|
41
|
+
} catch (e) {
|
|
42
|
+
return (e as NodeJS.ErrnoException)?.code === "EPERM";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Remove stale `<dbPath>.tmp-*` orphans (+ WAL sidecars) left by a prior
|
|
47
|
+
* SIGKILL'd first-index run, so temp husks do not accumulate. A temp file whose
|
|
48
|
+
* PID names a LIVE process belongs to a concurrent peer run and is left alone —
|
|
49
|
+
* unlinking it would break that peer's finalize `rename`. */
|
|
50
|
+
export function sweepOrphanTemps(dbPath: string): void {
|
|
51
|
+
const dir = dirname(dbPath);
|
|
52
|
+
const prefix = `${basename(dbPath)}.tmp-`;
|
|
53
|
+
let entries: string[];
|
|
54
|
+
try {
|
|
55
|
+
entries = readdirSync(dir);
|
|
56
|
+
} catch {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
for (const e of entries) {
|
|
60
|
+
if (!e.startsWith(prefix)) continue;
|
|
61
|
+
// filename is `<base>.tmp-<pid>` or a `-wal`/`-shm` sidecar of it.
|
|
62
|
+
const pid = Number(e.slice(prefix.length).split(/[.-]/)[0]);
|
|
63
|
+
if (Number.isInteger(pid) && pid > 0 && isProcessAlive(pid)) continue; // live peer
|
|
64
|
+
{
|
|
65
|
+
try {
|
|
66
|
+
unlinkSync(join(dir, e));
|
|
67
|
+
} catch {}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function runIndexAtomic(opts: RunIndexAtomicOpts): Promise<IndexStats & { counts: StoreCounts }> {
|
|
73
|
+
const { dbPath, sources, indexOpts, explicit } = opts;
|
|
74
|
+
|
|
75
|
+
// D3: an explicit --source dir that does not exist is a typo → hard error,
|
|
76
|
+
// before any store is opened (no husk possible).
|
|
77
|
+
if (explicit) {
|
|
78
|
+
for (const s of sources) {
|
|
79
|
+
if (!existsSync(s.dir)) throw new Error(`kb index: --source directory does not exist: ${s.dir}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Every configured source dir absent → nothing indexable. Checked BEFORE any
|
|
84
|
+
// store is opened so a first index never creates a temp husk in this case.
|
|
85
|
+
if (!sources.some((s) => existsSync(s.dir))) {
|
|
86
|
+
throw new Error("kb index: no configured source directory exists");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
sweepOrphanTemps(dbPath);
|
|
90
|
+
const preexisting = existsSync(dbPath);
|
|
91
|
+
const target = preexisting ? dbPath : `${dbPath}.tmp-${process.pid}`;
|
|
92
|
+
|
|
93
|
+
const store = new SqliteFtsStore(target);
|
|
94
|
+
store.init();
|
|
95
|
+
let ok = false;
|
|
96
|
+
try {
|
|
97
|
+
const total: IndexStats = { scanned: 0, changed: 0, deleted: 0, chunks: 0 };
|
|
98
|
+
for (const s of sources) {
|
|
99
|
+
const st = await indexSource(store, { root: s.id, dir: s.dir }, indexOpts ?? {});
|
|
100
|
+
total.scanned += st.scanned;
|
|
101
|
+
total.changed += st.changed;
|
|
102
|
+
total.deleted += st.deleted;
|
|
103
|
+
total.chunks += st.chunks;
|
|
104
|
+
}
|
|
105
|
+
// Read counts from the still-open store so callers never need a second
|
|
106
|
+
// openStore() connection just to report them (keeps `index` off openStore).
|
|
107
|
+
const counts = store.counts();
|
|
108
|
+
if (preexisting) store.close();
|
|
109
|
+
else store.finalizeRename(dbPath);
|
|
110
|
+
ok = true;
|
|
111
|
+
return { ...total, counts };
|
|
112
|
+
} finally {
|
|
113
|
+
if (!ok) {
|
|
114
|
+
// Only a run that CREATED the file cleans it up; an existing valid DB is
|
|
115
|
+
// left in place (valid & queryable).
|
|
116
|
+
if (preexisting) {
|
|
117
|
+
try {
|
|
118
|
+
store.close();
|
|
119
|
+
} catch {}
|
|
120
|
+
} else {
|
|
121
|
+
store.closeAndUnlink();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -9,6 +9,8 @@ export type {
|
|
|
9
9
|
KbStore,
|
|
10
10
|
SearchOpts,
|
|
11
11
|
} from "./types.js";
|
|
12
|
+
export { renderHits } from "./render.js";
|
|
13
|
+
export type { RenderOpts } from "./render.js";
|
|
12
14
|
export { chunkMarkdown } from "./chunker.js";
|
|
13
15
|
export type { ChunkInput, ParseResult } from "./chunker.js";
|
|
14
16
|
export { SqliteFtsStore } from "./sqlite-store.js";
|
|
@@ -21,5 +23,5 @@ export type { KbConfig, SourceConfig, RankingConfig, ResolvedConfig } from "./co
|
|
|
21
23
|
export { resolveAll, classifyRef, sourceIdentity, resolverFor } from "./sources.js";
|
|
22
24
|
export type { KbSourceKind, ResolvedSource, ResolveCtx, SourceResolver } from "./sources.js";
|
|
23
25
|
export { isTrusted, recordTrust, canonicalSource, sourceHash } from "./trust.js";
|
|
24
|
-
export { agentsChain, doxInit, doxLint, fallbackManifest, parseRowPaths } from "./dox.js";
|
|
26
|
+
export { agentsChain, doxInit, doxLint, fallbackManifest, parseRowPaths, resolveRowPath } from "./dox.js";
|
|
25
27
|
export type { AgentsEntry, DoxInitPlan, DoxIssue, DoxLintResult } from "./dox.js";
|
package/src/indexer.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Indexer: walk a filesystem source, layered mtime→sha256 change detection,
|
|
2
2
|
// structural chunking, Tier-1 graph extraction, transactional upsert (design §5).
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
|
-
import {
|
|
4
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
5
5
|
import { join, relative } from "node:path";
|
|
6
6
|
import { chunkMarkdown } from "./chunker.js";
|
|
7
7
|
import type { DocType, KbStore } from "./types.js";
|
|
@@ -24,11 +24,20 @@ export interface IndexStats {
|
|
|
24
24
|
changed: number;
|
|
25
25
|
deleted: number;
|
|
26
26
|
chunks: number;
|
|
27
|
+
missing?: boolean; // source dir did not exist → skipped (degrade, not abort)
|
|
27
28
|
}
|
|
28
29
|
|
|
29
30
|
const sha = (s: string | Buffer) => createHash("sha256").update(s).digest("hex");
|
|
30
31
|
const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|dist|build|\.next|coverage|\.kb)(\/|$)/;
|
|
31
32
|
|
|
33
|
+
/** Files processed between event-loop yields + batch commits. A long synchronous
|
|
34
|
+
* walk would otherwise pin the single Node thread for its whole duration, so a
|
|
35
|
+
* concurrent `/stats` reader could never observe `indexing:true` (no spinner)
|
|
36
|
+
* and would see no live progress. Committing per batch also releases the WAL
|
|
37
|
+
* write lock so the reader is served. See change: fix-kb-index-feedback. */
|
|
38
|
+
const YIELD_EVERY = 100;
|
|
39
|
+
const yieldToEventLoop = (): Promise<void> => new Promise<void>((r) => setImmediate(r));
|
|
40
|
+
|
|
32
41
|
/** Minimal glob → RegExp (supports **, *, ?). Good enough for include/exclude. */
|
|
33
42
|
function globToRe(g: string): RegExp {
|
|
34
43
|
const body = g
|
|
@@ -58,12 +67,22 @@ function walk(dir: string, base: string, out: string[] = []): string[] {
|
|
|
58
67
|
|
|
59
68
|
function docTypeOf(rel: string, includeSourceMarkdown: boolean): DocType {
|
|
60
69
|
const base = rel.split("/").pop() ?? "";
|
|
61
|
-
|
|
70
|
+
// `<File>.AGENTS.md` = per-file index sidecar (large-row promotion). Classified
|
|
71
|
+
// `agents` so it is searchable, but its name != "AGENTS.md" so pi's native
|
|
72
|
+
// up-walk never auto-injects it (pull-only via kb search).
|
|
73
|
+
if (base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md")) return "agents";
|
|
62
74
|
if (includeSourceMarkdown && /(^|\/)(src|lib|app|packages)\//.test(rel)) return "source-md";
|
|
63
75
|
return "doc";
|
|
64
76
|
}
|
|
65
77
|
|
|
66
|
-
export function indexSource(store: KbStore, src: IndexSource, opts: IndexOptions = {}): IndexStats {
|
|
78
|
+
export async function indexSource(store: KbStore, src: IndexSource, opts: IndexOptions = {}): Promise<IndexStats> {
|
|
79
|
+
// A configured source whose dir is absent degrades to skip-with-warning rather
|
|
80
|
+
// than throwing ENOENT mid-walk. A partial source set still indexes what exists.
|
|
81
|
+
// See change: harden-kb-index-failure-atomicity.
|
|
82
|
+
if (!existsSync(src.dir)) {
|
|
83
|
+
console.warn(`kb index: source directory does not exist, skipping: ${src.dir}`);
|
|
84
|
+
return { scanned: 0, changed: 0, deleted: 0, chunks: 0, missing: true };
|
|
85
|
+
}
|
|
67
86
|
const extRe = opts.extensions?.length ? new RegExp("(" + opts.extensions.map((e) => e.replace(/\./g, "\\.")).join("|") + ")$", "i") : /\.(md|mdx|markdown)$/i;
|
|
68
87
|
const inc = opts.include?.map(globToRe);
|
|
69
88
|
const exc = opts.exclude?.map(globToRe);
|
|
@@ -80,9 +99,22 @@ export function indexSource(store: KbStore, src: IndexSource, opts: IndexOptions
|
|
|
80
99
|
const stats: IndexStats = { scanned: files.length, changed: 0, deleted: 0, chunks: 0 };
|
|
81
100
|
const live = new Set<string>();
|
|
82
101
|
|
|
102
|
+
// Batched transaction: commit + yield every YIELD_EVERY files so the walk does
|
|
103
|
+
// not block the event loop and a concurrent `/stats` read sees live progress.
|
|
104
|
+
// NOTE: this trades whole-walk atomicity for responsiveness — a mid-walk throw
|
|
105
|
+
// leaves earlier batches committed; a reindex is idempotent so a re-run
|
|
106
|
+
// completes it. See change: fix-kb-index-feedback.
|
|
107
|
+
let sinceYield = 0;
|
|
83
108
|
store.begin();
|
|
84
109
|
try {
|
|
85
110
|
for (const abs of files) {
|
|
111
|
+
if (sinceYield >= YIELD_EVERY) {
|
|
112
|
+
store.commit();
|
|
113
|
+
await yieldToEventLoop();
|
|
114
|
+
store.begin();
|
|
115
|
+
sinceYield = 0;
|
|
116
|
+
}
|
|
117
|
+
sinceYield++;
|
|
86
118
|
const rel = relative(src.dir, abs);
|
|
87
119
|
live.add(rel);
|
|
88
120
|
const st = statSync(abs);
|