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