@blackbelt-technology/pi-dashboard-kb 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/bin/kb.mjs +12 -7
  2. package/dist/chunker.js +48 -2
  3. package/dist/cli.js +48 -16
  4. package/dist/config.d.ts +47 -0
  5. package/dist/config.js +130 -2
  6. package/dist/dox-row.d.ts +9 -0
  7. package/dist/dox-row.js +32 -0
  8. package/dist/dox-triage.d.ts +1 -2
  9. package/dist/dox-triage.js +8 -8
  10. package/dist/dox.js +18 -11
  11. package/dist/git-scope/commits.d.ts +26 -0
  12. package/dist/git-scope/commits.js +243 -0
  13. package/dist/git-scope/deps.d.ts +41 -0
  14. package/dist/git-scope/deps.js +78 -0
  15. package/dist/git-scope/forge/cli.d.ts +16 -0
  16. package/dist/git-scope/forge/cli.js +66 -0
  17. package/dist/git-scope/forge/gitea.d.ts +15 -0
  18. package/dist/git-scope/forge/gitea.js +98 -0
  19. package/dist/git-scope/forge/github.d.ts +8 -0
  20. package/dist/git-scope/forge/github.js +50 -0
  21. package/dist/git-scope/forge/gitlab.d.ts +8 -0
  22. package/dist/git-scope/forge/gitlab.js +49 -0
  23. package/dist/git-scope/forge/index.d.ts +7 -0
  24. package/dist/git-scope/forge/index.js +13 -0
  25. package/dist/git-scope/forge/types.d.ts +70 -0
  26. package/dist/git-scope/forge/types.js +21 -0
  27. package/dist/git-scope/index.d.ts +4 -0
  28. package/dist/git-scope/index.js +2 -0
  29. package/dist/git-scope/lease.d.ts +24 -0
  30. package/dist/git-scope/lease.js +80 -0
  31. package/dist/git-scope/links.d.ts +23 -0
  32. package/dist/git-scope/links.js +61 -0
  33. package/dist/git-scope/repo.d.ts +36 -0
  34. package/dist/git-scope/repo.js +99 -0
  35. package/dist/git-scope/scope.d.ts +78 -0
  36. package/dist/git-scope/scope.js +406 -0
  37. package/dist/git-scope/store.d.ts +16 -0
  38. package/dist/git-scope/store.js +71 -0
  39. package/dist/git-scope/sync.d.ts +44 -0
  40. package/dist/git-scope/sync.js +215 -0
  41. package/dist/gitignore.d.ts +19 -6
  42. package/dist/gitignore.js +99 -37
  43. package/dist/index-gate.d.ts +27 -0
  44. package/dist/index-gate.js +71 -0
  45. package/dist/index-run.d.ts +66 -5
  46. package/dist/index-run.js +317 -60
  47. package/dist/index.d.ts +10 -3
  48. package/dist/index.js +6 -2
  49. package/dist/indexer.d.ts +22 -0
  50. package/dist/indexer.js +70 -14
  51. package/dist/migrate-file-index.js +4 -4
  52. package/dist/migrate-runner.js +7 -5
  53. package/dist/seed.d.ts +59 -0
  54. package/dist/seed.js +235 -0
  55. package/dist/sqlite-store.d.ts +72 -6
  56. package/dist/sqlite-store.js +270 -42
  57. package/dist/types.d.ts +41 -0
  58. package/dist/verdict.d.ts +10 -2
  59. package/dist/verdict.js +19 -10
  60. package/engine-fingerprint.json +3 -3
  61. package/package.json +3 -3
  62. package/src/chunker.ts +46 -2
  63. package/src/cli.ts +46 -15
  64. package/src/config.ts +145 -2
  65. package/src/dox-row.ts +35 -0
  66. package/src/dox-triage.ts +8 -8
  67. package/src/dox.ts +17 -11
  68. package/src/git-scope/commits.ts +267 -0
  69. package/src/git-scope/deps.ts +111 -0
  70. package/src/git-scope/forge/cli.ts +76 -0
  71. package/src/git-scope/forge/gitea.ts +124 -0
  72. package/src/git-scope/forge/github.ts +73 -0
  73. package/src/git-scope/forge/gitlab.ts +71 -0
  74. package/src/git-scope/forge/index.ts +17 -0
  75. package/src/git-scope/forge/types.ts +88 -0
  76. package/src/git-scope/index.ts +6 -0
  77. package/src/git-scope/lease.ts +80 -0
  78. package/src/git-scope/links.ts +73 -0
  79. package/src/git-scope/repo.ts +108 -0
  80. package/src/git-scope/scope.ts +424 -0
  81. package/src/git-scope/store.ts +73 -0
  82. package/src/git-scope/sync.ts +240 -0
  83. package/src/gitignore.ts +106 -39
  84. package/src/index-gate.ts +73 -0
  85. package/src/index-run.ts +362 -58
  86. package/src/index.ts +10 -3
  87. package/src/indexer.ts +84 -14
  88. package/src/migrate-file-index.ts +4 -4
  89. package/src/migrate-runner.ts +6 -4
  90. package/src/node-sqlite.d.ts +9 -0
  91. package/src/seed.ts +249 -0
  92. package/src/sources.ts +4 -1
  93. package/src/sqlite-store.ts +269 -42
  94. package/src/types.ts +43 -1
  95. package/src/verdict.ts +29 -15
package/bin/kb.mjs CHANGED
@@ -24,14 +24,19 @@ import { computeDistHash, computeSrcHash, computeTsconfigHash, FINGERPRINT_MALFO
24
24
  const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
25
25
  const distCli = join(pkgRoot, "dist", "cli.js");
26
26
 
27
- /** Nearest typescript install walking up from the package (the workspace root
28
- * in this monorepo — packages/kb declares no typescript dep of its own). */
27
+ /** The compiler entry to spawn: the repo's TypeScript 7 wrapper
28
+ * (`<repo>/scripts/tsc7.mjs`, found walking up) when present, else the nearest
29
+ * `node_modules/typescript/lib/tsc.js` (the published kb tarball has no repo
30
+ * `scripts/`). See change: migrate-typecheck-to-ts7. */
29
31
  function findTsc() {
30
- for (let d = pkgRoot; ; d = dirname(d)) {
31
- const c = join(d, "node_modules", "typescript", "lib", "tsc.js");
32
- if (existsSync(c)) return c;
33
- if (d === dirname(d)) return null; // filesystem root
34
- }
32
+ const walkUp = (rel) => {
33
+ for (let d = pkgRoot; ; d = dirname(d)) {
34
+ const c = join(d, ...rel);
35
+ if (existsSync(c)) return c;
36
+ if (d === dirname(d)) return null; // filesystem root
37
+ }
38
+ };
39
+ return walkUp(["scripts", "tsc7.mjs"]) ?? walkUp(["node_modules", "typescript", "lib", "tsc.js"]);
35
40
  }
36
41
 
37
42
  function staleness() {
package/dist/chunker.js CHANGED
@@ -8,6 +8,52 @@ import { parseFrontmatter } from "./frontmatter.js";
8
8
  export const MIN_CHUNK_CHARS = 100;
9
9
  export const MAX_CHUNK_CHARS = 4000;
10
10
  export const sha = (s) => createHash("sha256").update(s).digest("hex");
11
+ /**
12
+ * `[[x]]` scanner. Linear: `close` (next `]`) only moves forward, so unclosed
13
+ * openers never rescan (the old `/\[\[([^\]]+)\]\]/g` was quadratic).
14
+ */
15
+ function scanWikilinks(text) {
16
+ const out = [];
17
+ let close = -1;
18
+ let i = text.indexOf("[[");
19
+ while (i !== -1) {
20
+ if (close < i + 2) {
21
+ close = text.indexOf("]", i + 2);
22
+ if (close === -1)
23
+ break;
24
+ }
25
+ if (close > i + 2 && text[close + 1] === "]") {
26
+ out.push(text.slice(i + 2, close).trim());
27
+ i = text.indexOf("[[", close + 2);
28
+ }
29
+ else {
30
+ i = text.indexOf("[[", i + 1);
31
+ }
32
+ }
33
+ return out;
34
+ }
35
+ /** `](x.md)` / `](x.mdx)` scanner; same forward-only `close` pointer (next `)`). */
36
+ function scanMdLinks(text) {
37
+ const out = [];
38
+ let close = -1;
39
+ let i = text.indexOf("](");
40
+ while (i !== -1) {
41
+ if (close < i + 2) {
42
+ close = text.indexOf(")", i + 2);
43
+ if (close === -1)
44
+ break;
45
+ }
46
+ const len = close - (i + 2);
47
+ if ((len >= 4 && text.endsWith(".md", close)) || (len >= 5 && text.endsWith(".mdx", close))) {
48
+ out.push(text.slice(i + 2, close).trim());
49
+ i = text.indexOf("](", close + 1);
50
+ }
51
+ else {
52
+ i = text.indexOf("](", i + 1);
53
+ }
54
+ }
55
+ return out;
56
+ }
11
57
  export function chunkMarkdown(input) {
12
58
  const docType = input.docType ?? "doc";
13
59
  const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
@@ -106,7 +152,7 @@ export function chunkMarkdown(input) {
106
152
  body: c.body.trimEnd(),
107
153
  bodyHash: sha(c.body.trim()),
108
154
  }));
109
- const wikilinks = [...input.text.matchAll(/\[\[([^\]]+)\]\]/g)].map((m) => m[1].trim());
110
- const mdLinks = [...input.text.matchAll(/\]\(([^)]+\.mdx?)\)/g)].map((m) => m[1].trim());
155
+ const wikilinks = scanWikilinks(input.text);
156
+ const mdLinks = scanMdLinks(input.text);
111
157
  return { chunks, frontmatter: fm, wikilinks, mdLinks, parseFailed };
112
158
  }
package/dist/cli.js CHANGED
@@ -2,19 +2,21 @@
2
2
  // kb CLI (Phase 1): index | search | neighbors | backlinks | get | config
3
3
  // Run (dev): NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts <cmd> ...
4
4
  // Shipped bin builds to dist/cli.js (build step deferred).
5
- import { readFileSync } from "node:fs";
5
+ import { existsSync, readFileSync } from "node:fs";
6
6
  import { join, relative, resolve } from "node:path";
7
- import { frontmatterConfigHash, loadConfig } from "./config.js";
7
+ import { indexOptionsFromConfig, loadConfig } from "./config.js";
8
8
  import { agentsChain, doxInit, doxLint, listEmptyPurposeRows } from "./dox.js";
9
9
  import { ackTargets, applyDecisions, buildWorkItems } from "./dox-triage.js";
10
10
  import { evaluate, loadGolden } from "./eval.js";
11
- import { runIndexAtomic } from "./index-run.js";
11
+ import { beginForcedSource, sourceGateIsStale, stampPass, stampSource } from "./index-gate.js";
12
+ import { BUILDING_LINE, isFirstIndexLive, runIndexAtomic } from "./index-run.js";
12
13
  import { indexSource } from "./indexer.js";
13
14
  import { kbInit } from "./init.js";
14
15
  import { renderHits } from "./render.js";
15
16
  import { searchOptsFromConfig } from "./search-opts.js";
17
+ import { seedOptionsFromConfig } from "./seed.js";
16
18
  import { resolveAll } from "./sources.js";
17
- import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
19
+ import { SqliteFtsStore } from "./sqlite-store.js";
18
20
  import { readStaleness } from "./staleness.js";
19
21
  import { defaultPromptTrust } from "./trust.js";
20
22
  import { enrichHits } from "./verdict.js";
@@ -80,24 +82,52 @@ function openStore(cfg) {
80
82
  return store;
81
83
  }
82
84
  async function runIndex(cfg, store, sources, force = false) {
83
- // Apply the same schema-version / facet-config gate as runIndexAtomic so the
84
- // auto-index-on-search path also picks up new structures after an upgrade or a
85
+ // Apply the same per-source schema-version / options-hash gate as runIndexAtomic so
86
+ // the auto-index-on-search path also picks up new structures after an upgrade or a
85
87
  // frontmatter-config change (else the DB stays stale until an explicit `index`).
86
- const hash = frontmatterConfigHash(cfg.frontmatter);
87
- const stale = (store.getUserVersion?.() ?? 0) < SCHEMA_VERSION || (store.getMeta?.("facetConfigHash") ?? null) !== hash;
88
- const eff = force || stale;
88
+ // A source is stamped only after it was walked; skipped/failed ones stay due.
89
89
  let scanned = 0, changed = 0, deleted = 0, chunks = 0;
90
90
  for (const s of sources) {
91
- const st = await indexSource(store, { root: s.id, dir: s.dir }, { force: eff, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter, respectGitignore: cfg.respectGitignore, cwd: cfg.cwd });
91
+ const eff = force || sourceGateIsStale(store, cfg, s.id);
92
+ const st = await indexSource(store, { root: s.id, dir: s.dir }, indexOptionsFromConfig(cfg, { force: eff, onFirstBatch: eff ? beginForcedSource(store, s.id) : undefined }));
93
+ if (!st.missing)
94
+ stampSource(store, cfg, s.id);
92
95
  scanned += st.scanned;
93
96
  changed += st.changed;
94
97
  deleted += st.deleted;
95
98
  chunks += st.chunks;
96
99
  }
97
- store.setUserVersion?.(SCHEMA_VERSION);
98
- store.setMeta?.("facetConfigHash", hash);
100
+ stampPass(store, cfg);
99
101
  return { scanned, changed, deleted, chunks };
100
102
  }
103
+ /** Open the docs store for a non-index command WITHOUT ever creating `dbPath` in place:
104
+ * an absent DB is built through the atomic first-index path (temp file → no-clobber
105
+ * install), or — while another process is building it — reported as still being built
106
+ * (exit 75, EX_TEMPFAIL). With no indexable source nothing is built and an empty
107
+ * in-memory store answers. See change: fix-kb-index-integrity (D2). */
108
+ async function openStoreForQuery(cfg, sources, flags) {
109
+ if (!existsSync(cfg.dbAbsPath)) {
110
+ if (isFirstIndexLive(cfg.dbAbsPath)) {
111
+ console.log(BUILDING_LINE);
112
+ process.exit(75);
113
+ }
114
+ if (!flags["no-reindex"] && sources.some((s) => existsSync(s.dir))) {
115
+ await runIndexAtomic({
116
+ dbPath: cfg.dbAbsPath,
117
+ sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
118
+ indexOpts: indexOptionsFromConfig(cfg),
119
+ gate: cfg,
120
+ seed: seedOptionsFromConfig(cfg, { noSeed: !!flags["no-seed"], explicitSources: !!flags.source?.length, customDb: !!flags.db }),
121
+ });
122
+ }
123
+ else {
124
+ const mem = new SqliteFtsStore(":memory:");
125
+ mem.init();
126
+ return mem;
127
+ }
128
+ }
129
+ return openStore(cfg);
130
+ }
101
131
  /** Resolve sources for a run. --source overrides (filesystem, sync); otherwise
102
132
  * resolve all configured specs (filesystem sync + remote async + TOFU trust). */
103
133
  async function sourcesForRun(cfg, flags) {
@@ -115,7 +145,8 @@ async function sourcesForRun(cfg, flags) {
115
145
  const HELP = `kb — markdown knowledge base
116
146
  Usage:
117
147
  kb init [--global] [--source <ref>]... [--dry-run] [--force] [--cwd <dir>]
118
- kb index [--source <dir>...] [--db <path>] [--force] [--refresh]
148
+ kb index [--source <dir>...] [--db <path>] [--force] [--refresh] [--no-seed]
149
+ (--no-seed: skip seeding a linked worktree's first index from the main checkout)
119
150
  kb search "<query>" [--limit N] [--root id] [--doc-type doc|agents|source-md]
120
151
  [--expand-parent|--no-expand-parent] [--expand-graph] [--rerank]
121
152
  [--expand-query] [--json] [--no-reindex] [--source <dir>...] [--db <path>]
@@ -284,15 +315,16 @@ async function runCmd(cmd, flags) {
284
315
  const s = await runIndexAtomic({
285
316
  dbPath: cfg.dbAbsPath,
286
317
  sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
287
- indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter, respectGitignore: cfg.respectGitignore, cwd: cfg.cwd },
288
- facetConfigHash: frontmatterConfigHash(cfg.frontmatter),
318
+ indexOpts: indexOptionsFromConfig(cfg, { force: !!flags.force }),
319
+ gate: cfg,
289
320
  explicit,
321
+ seed: seedOptionsFromConfig(cfg, { noSeed: !!flags["no-seed"], explicitSources: explicit, customDb: !!flags.db }),
290
322
  });
291
323
  console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
292
324
  console.log(JSON.stringify(s.counts));
293
325
  return;
294
326
  }
295
- const store = openStore(cfg);
327
+ const store = await openStoreForQuery(cfg, sources, flags);
296
328
  try {
297
329
  if (cmd === "search") {
298
330
  const q = flags._[1];
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type FacetKeyConfig } from "./frontmatter.js";
2
+ import type { IndexOptions } from "./indexer.js";
2
3
  export interface SourceConfig {
3
4
  kind?: "filesystem" | "npm" | "git" | "https";
4
5
  ref: string;
@@ -87,6 +88,33 @@ export interface DoctrineConfig {
87
88
  inject: "kb" | "off";
88
89
  write: boolean;
89
90
  }
91
+ /** Forge flavours the git scope can talk to. */
92
+ export type ForgeKind = "github" | "gitlab" | "gitea";
93
+ /** `git` scope group (change: add-kb-git-forge-scope, design G8). `forge.hosts`
94
+ * and `forge.gitea.tokenEnv` are honoured from the GLOBAL layer only. */
95
+ export interface GitConfig {
96
+ enabled: boolean;
97
+ remote: string;
98
+ searchWaitMs: number;
99
+ commits: {
100
+ maxInitial: number;
101
+ maxPathsPerCommit: number;
102
+ };
103
+ forge: {
104
+ enabled: boolean;
105
+ minSyncIntervalSeconds: number;
106
+ hintedMinSyncIntervalSeconds: number;
107
+ rateFloorPercent: number;
108
+ firstSyncWindowDays: number;
109
+ firstSyncMaxItems: number;
110
+ pagesPerSync: number;
111
+ leaseSeconds: number;
112
+ hosts: Record<string, ForgeKind>;
113
+ gitea: {
114
+ tokenEnv: string;
115
+ };
116
+ };
117
+ }
90
118
  export interface KbConfig {
91
119
  sources: SourceConfig[];
92
120
  roots?: Array<{
@@ -128,6 +156,9 @@ export interface KbConfig {
128
156
  expand: ExpandConfig;
129
157
  rerank: RerankConfig;
130
158
  queryExpansion: QueryExpansionConfig;
159
+ git: GitConfig;
160
+ /** Seed a linked worktree's first index from the main checkout's index (default true). */
161
+ seedFromMainWorktree: boolean;
131
162
  dbPath: string;
132
163
  }
133
164
  export interface ResolvedSource {
@@ -150,6 +181,22 @@ export declare const DEFAULTS: KbConfig;
150
181
  /** Stable hash of the frontmatter routing config. A change forces a full reindex
151
182
  * (design D6) since existing property rows/meta chunks reflect the old routing. */
152
183
  export declare function frontmatterConfigHash(fm: FrontmatterConfig): string;
184
+ /** The slice of a resolved config the index gate hashes. */
185
+ export interface IndexGateConfig {
186
+ frontmatter: FrontmatterConfig;
187
+ includeSourceMarkdown?: boolean;
188
+ }
189
+ /** Hash of every option that changes what an UNCHANGED file indexes to: the
190
+ * frontmatter routing config and `includeSourceMarkdown` (it flips a file's
191
+ * `doc_type`; unset normalizes to `true`, as the indexer reads it). Selection-only
192
+ * options (include/exclude/extensions/gitignore/agents) are deliberately NOT in it:
193
+ * an unchanged file keeps its rows and the next walk adds/prunes the rest.
194
+ * See change: fix-kb-index-integrity (D6). */
195
+ export declare function indexOptionsHash(cfg: IndexGateConfig): string;
196
+ /** The ONE derivation of indexer options from a resolved config — every docs writer
197
+ * (`kb index`, CLI auto-index, kb-extension reindex, dashboard reindex job) uses it,
198
+ * so none can silently drop `frontmatter` (custom facet keys). */
199
+ export declare function indexOptionsFromConfig(cfg: ResolvedConfig, overrides?: Partial<IndexOptions>): IndexOptions;
153
200
  /** Layer configs left→right, deep-merging the known nested object keys. */
154
201
  export declare function mergeConfig(...layers: Array<Partial<KbConfig> | null | undefined>): Partial<KbConfig>;
155
202
  /** Validate a parsed config shape; throw with a precise message on violation. */
package/dist/config.js CHANGED
@@ -54,6 +54,25 @@ export const DEFAULTS = {
54
54
  // PRF is implemented engine-side but DEFAULT OFF: it is gated on coverage
55
55
  // rerank (which measures as a net regression), and adds ~3x search latency.
56
56
  queryExpansion: { mode: "off", prf: { terms: 6, topK: 10, dfCeiling: 0.1 } },
57
+ git: {
58
+ enabled: true,
59
+ remote: "origin",
60
+ searchWaitMs: 2000,
61
+ commits: { maxInitial: 50000, maxPathsPerCommit: 200 },
62
+ forge: {
63
+ enabled: true,
64
+ minSyncIntervalSeconds: 600,
65
+ hintedMinSyncIntervalSeconds: 60,
66
+ rateFloorPercent: 20,
67
+ firstSyncWindowDays: 365,
68
+ firstSyncMaxItems: 5000,
69
+ pagesPerSync: 5,
70
+ leaseSeconds: 60,
71
+ hosts: {},
72
+ gitea: { tokenEnv: "GITEA_TOKEN" },
73
+ },
74
+ },
75
+ seedFromMainWorktree: true,
57
76
  dbPath: ".pi/dashboard/kb/index.db",
58
77
  };
59
78
  // Nested object keys that need one-level field fill-in (not wholesale replace),
@@ -68,6 +87,45 @@ export function frontmatterConfigHash(fm) {
68
87
  };
69
88
  return createHash("sha256").update(JSON.stringify(norm)).digest("hex").slice(0, 16);
70
89
  }
90
+ /** Hash of every option that changes what an UNCHANGED file indexes to: the
91
+ * frontmatter routing config and `includeSourceMarkdown` (it flips a file's
92
+ * `doc_type`; unset normalizes to `true`, as the indexer reads it). Selection-only
93
+ * options (include/exclude/extensions/gitignore/agents) are deliberately NOT in it:
94
+ * an unchanged file keeps its rows and the next walk adds/prunes the rest.
95
+ * See change: fix-kb-index-integrity (D6). */
96
+ export function indexOptionsHash(cfg) {
97
+ const norm = {
98
+ fm: frontmatterConfigHash(cfg.frontmatter),
99
+ includeSourceMarkdown: cfg.includeSourceMarkdown !== false,
100
+ };
101
+ return createHash("sha256").update(JSON.stringify(norm)).digest("hex").slice(0, 16);
102
+ }
103
+ /** The ONE derivation of indexer options from a resolved config — every docs writer
104
+ * (`kb index`, CLI auto-index, kb-extension reindex, dashboard reindex job) uses it,
105
+ * so none can silently drop `frontmatter` (custom facet keys). */
106
+ export function indexOptionsFromConfig(cfg, overrides = {}) {
107
+ return {
108
+ indexAgentsFiles: cfg.indexAgentsFiles,
109
+ includeSourceMarkdown: cfg.includeSourceMarkdown,
110
+ include: cfg.include,
111
+ exclude: cfg.exclude,
112
+ extensions: cfg.extensions,
113
+ frontmatter: cfg.frontmatter,
114
+ respectGitignore: cfg.respectGitignore,
115
+ cwd: cfg.cwd,
116
+ ...overrides,
117
+ };
118
+ }
119
+ const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
120
+ /** Recursive plain-object merge (right wins on leaves). Used for the `git`
121
+ * group, whose nested levels (`commits`, `forge`, `forge.gitea`) must each keep
122
+ * siblings from earlier layers. */
123
+ function deepMerge(a, b) {
124
+ const out = { ...a };
125
+ for (const [k, v] of Object.entries(b))
126
+ out[k] = isPlainObject(v) && isPlainObject(out[k]) ? deepMerge(out[k], v) : v;
127
+ return out;
128
+ }
71
129
  /** Layer configs left→right, deep-merging the known nested object keys. */
72
130
  export function mergeConfig(...layers) {
73
131
  const out = {};
@@ -75,7 +133,10 @@ export function mergeConfig(...layers) {
75
133
  if (!layer)
76
134
  continue;
77
135
  for (const [k, v] of Object.entries(layer)) {
78
- if (NESTED_KEYS.includes(k) && v && typeof v === "object" && !Array.isArray(v) && out[k] && typeof out[k] === "object") {
136
+ if (k === "git" && isPlainObject(v) && isPlainObject(out[k])) {
137
+ out[k] = deepMerge(out[k], v);
138
+ }
139
+ else if (NESTED_KEYS.includes(k) && v && typeof v === "object" && !Array.isArray(v) && out[k] && typeof out[k] === "object") {
79
140
  out[k] = { ...out[k], ...v };
80
141
  }
81
142
  else {
@@ -102,6 +163,8 @@ export function validateConfig(c, origin = "config") {
102
163
  throw err("maxFileCount must be a number or null");
103
164
  if (typeof merged.dbPath !== "string" || !merged.dbPath)
104
165
  throw err("dbPath must be a non-empty string");
166
+ if (typeof merged.seedFromMainWorktree !== "boolean")
167
+ throw err("seedFromMainWorktree must be a boolean");
105
168
  if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode))
106
169
  throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
107
170
  const gm = merged.readDiscipline?.guard?.mode;
@@ -120,6 +183,7 @@ export function validateConfig(c, origin = "config") {
120
183
  const llm = merged.ranking.laneLeadMargin;
121
184
  if (typeof llm !== "number" || !Number.isFinite(llm) || llm < 0 || llm > 1)
122
185
  throw err("ranking.laneLeadMargin must be a number in [0,1]");
186
+ validateGit(merged.git, err);
123
187
  const fm = merged.frontmatter;
124
188
  if (!fm || !Array.isArray(fm.searchableKeys) || fm.searchableKeys.some((k) => typeof k !== "string"))
125
189
  throw err("frontmatter.searchableKeys must be a string array");
@@ -133,6 +197,68 @@ export function validateConfig(c, origin = "config") {
133
197
  }
134
198
  return merged;
135
199
  }
200
+ function validateGit(g, err) {
201
+ if (!isPlainObject(g))
202
+ throw err("git must be an object");
203
+ const posInt = (key, v) => {
204
+ if (typeof v !== "number" || !Number.isFinite(v) || v <= 0)
205
+ throw err(`${key} must be a positive number`);
206
+ };
207
+ if (typeof g.enabled !== "boolean")
208
+ throw err("git.enabled must be a boolean");
209
+ if (typeof g.remote !== "string" || !g.remote.trim())
210
+ throw err("git.remote must be a non-empty string");
211
+ posInt("git.searchWaitMs", g.searchWaitMs);
212
+ posInt("git.commits.maxInitial", g.commits?.maxInitial);
213
+ posInt("git.commits.maxPathsPerCommit", g.commits?.maxPathsPerCommit);
214
+ const f = g.forge;
215
+ if (!isPlainObject(f))
216
+ throw err("git.forge must be an object");
217
+ if (typeof f.enabled !== "boolean")
218
+ throw err("git.forge.enabled must be a boolean");
219
+ for (const k of ["minSyncIntervalSeconds", "hintedMinSyncIntervalSeconds", "firstSyncWindowDays", "firstSyncMaxItems", "pagesPerSync", "leaseSeconds"])
220
+ posInt(`git.forge.${k}`, f[k]);
221
+ if (typeof f.rateFloorPercent !== "number" || !Number.isFinite(f.rateFloorPercent) || f.rateFloorPercent < 0 || f.rateFloorPercent > 100)
222
+ throw err("git.forge.rateFloorPercent must be a number in [0,100]");
223
+ if (f.hintedMinSyncIntervalSeconds > f.minSyncIntervalSeconds)
224
+ throw err("git.forge.hintedMinSyncIntervalSeconds must not exceed git.forge.minSyncIntervalSeconds");
225
+ if (!isPlainObject(f.hosts))
226
+ throw err("git.forge.hosts must be an object mapping host → github|gitlab|gitea");
227
+ for (const [h, kind] of Object.entries(f.hosts))
228
+ if (!/^(github|gitlab|gitea)$/.test(String(kind)))
229
+ throw err(`git.forge.hosts["${h}"] "${String(kind)}" unknown (github | gitlab | gitea)`);
230
+ if (typeof f.gitea?.tokenEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(f.gitea.tokenEnv))
231
+ throw err("git.forge.gitea.tokenEnv must be an environment variable name");
232
+ }
233
+ /** Project-layer `git.forge.hosts` / `git.forge.gitea.tokenEnv` would let an
234
+ * untrusted clone add a host or pick which env var is read as a token (design
235
+ * G3/G8). Drop them and warn once per config file. */
236
+ const warnedProjectGit = new Set();
237
+ function stripGlobalOnlyGit(project, where) {
238
+ if (!project || !isPlainObject(project.git))
239
+ return project;
240
+ const forge = project.git.forge;
241
+ if (!isPlainObject(forge))
242
+ return project;
243
+ const dropped = [];
244
+ const nextForge = { ...forge };
245
+ if ("hosts" in nextForge) {
246
+ delete nextForge.hosts;
247
+ dropped.push("git.forge.hosts");
248
+ }
249
+ if (isPlainObject(nextForge.gitea) && "tokenEnv" in nextForge.gitea) {
250
+ const { tokenEnv: _drop, ...rest } = nextForge.gitea;
251
+ nextForge.gitea = rest;
252
+ dropped.push("git.forge.gitea.tokenEnv");
253
+ }
254
+ if (!dropped.length)
255
+ return project;
256
+ if (!warnedProjectGit.has(where)) {
257
+ warnedProjectGit.add(where);
258
+ console.warn(`[kb] ignoring ${dropped.join(", ")} from project config ${where}: honoured from the global config only`);
259
+ }
260
+ return { ...project, git: { ...project.git, forge: nextForge } };
261
+ }
136
262
  export function projectConfigPath(cwd) {
137
263
  return join(cwd, ".pi", "dashboard", "knowledge_base.json");
138
264
  }
@@ -151,7 +277,9 @@ function readJson(path) {
151
277
  }
152
278
  /** Merge: defaults < global < project (field-level fill-in). */
153
279
  export function loadConfig(cwd, opts = {}) {
154
- const project = opts.configPath ? readJson(opts.configPath) : readJson(projectConfigPath(cwd));
280
+ const projectPath = opts.configPath ?? projectConfigPath(cwd);
281
+ const rawProject = readJson(projectPath);
282
+ const project = stripGlobalOnlyGit(rawProject, projectPath);
155
283
  const global = readJson(globalConfigPath());
156
284
  const origin = project ? "project" : global ? "global" : "defaults";
157
285
  // KEY-presence (a non-null object, `{}` included) — NOT file-presence. A
@@ -0,0 +1,9 @@
1
+ export interface RowMatch {
2
+ /** Raw backtick group (untrimmed). */
3
+ path: string;
4
+ purpose: string;
5
+ }
6
+ /** `| \`path\` | purpose |` — closing pipe required. */
7
+ export declare function matchRow(line: string): RowMatch | null;
8
+ /** Like `matchRow` but the closing pipe is optional (LLM output). */
9
+ export declare function matchRowLoose(line: string): RowMatch | null;
@@ -0,0 +1,32 @@
1
+ // Linear-time DOX table-row matcher. Leaf module (no imports) so dox.ts,
2
+ // dox-triage.ts, migrate-file-index.ts and migrate-runner.ts can all share it.
3
+ // Replaces lazy-`(.*?)` regexes that were cubic/quadratic on long whitespace runs.
4
+ // Head has no ambiguous repetition: `[^`]+` cannot cross a backtick.
5
+ const HEAD = /^\|\s*`([^`]+)`\s*\|/;
6
+ // The old `(.*?)` could never match these; `\s*` could.
7
+ const TERMINATOR = /[\n\r\u2028\u2029]/;
8
+ /** `| \`path\` | purpose |` — closing pipe required. */
9
+ export function matchRow(line) {
10
+ const m = HEAD.exec(line);
11
+ if (!m)
12
+ return null;
13
+ const t = line.slice(m[0].length).trim();
14
+ if (!t.endsWith("|"))
15
+ return null;
16
+ const purpose = t.slice(0, -1).trim();
17
+ if (TERMINATOR.test(purpose))
18
+ return null;
19
+ return { path: m[1], purpose };
20
+ }
21
+ /** Like `matchRow` but the closing pipe is optional (LLM output). */
22
+ export function matchRowLoose(line) {
23
+ const m = HEAD.exec(line);
24
+ if (!m)
25
+ return null;
26
+ let t = line.slice(m[0].length).trim();
27
+ if (TERMINATOR.test(t))
28
+ return null;
29
+ if (t.endsWith("|"))
30
+ t = t.slice(0, -1).trim();
31
+ return { path: m[1], purpose: t };
32
+ }
@@ -1,6 +1,5 @@
1
- import { type AckRecord } from "./staleness.js";
2
1
  import { type DoxIssue } from "./dox.js";
3
- export declare const ROW_RE: RegExp;
2
+ import { type AckRecord } from "./staleness.js";
4
3
  /** History window scanned for a blob matching the acked hash. */
5
4
  export declare const DEFAULT_DEPTH = 60;
6
5
  /** Per-item diff budget. Keeps a @fast subagent's context small and cheap. */
@@ -16,9 +16,9 @@ import { execFileSync } from "node:child_process"; // ban:child_process-ok (kb p
16
16
  import { createHash } from "node:crypto";
17
17
  import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
18
18
  import { dirname, join, relative } from "node:path";
19
- import { STALENESS_VERSION, readStaleness, stalenessVersionOnDisk } from "./staleness.js";
20
19
  import { resolveRowPath } from "./dox.js";
21
- export const ROW_RE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
20
+ import { matchRow } from "./dox-row.js";
21
+ import { readStaleness, STALENESS_VERSION, stalenessVersionOnDisk } from "./staleness.js";
22
22
  /** History window scanned for a blob matching the acked hash. */
23
23
  export const DEFAULT_DEPTH = 60;
24
24
  /** Per-item diff budget. Keeps a @fast subagent's context small and cheap. */
@@ -26,12 +26,12 @@ export const DIFF_CAP = 6000;
26
26
  export function parseRows(md) {
27
27
  const rows = [];
28
28
  md.split("\n").forEach((line, i) => {
29
- const m = line.match(ROW_RE);
29
+ const m = matchRow(line);
30
30
  if (!m)
31
31
  return;
32
- if (/^-+$/.test(m[1]))
32
+ if (/^-+$/.test(m.path))
33
33
  return;
34
- rows.push({ line: i, path: m[1], purpose: m[2] });
34
+ rows.push({ line: i, path: m.path, purpose: m.purpose });
35
35
  });
36
36
  return rows;
37
37
  }
@@ -41,11 +41,11 @@ export function replaceRowPurpose(md, rowPath, newPurpose) {
41
41
  const out = md.split("\n").map((line) => {
42
42
  if (hit)
43
43
  return line;
44
- const m = line.match(ROW_RE);
45
- if (!m || m[1] !== rowPath)
44
+ const m = matchRow(line);
45
+ if (!m || m.path !== rowPath)
46
46
  return line;
47
47
  hit = true;
48
- return `| \`${m[1]}\` | ${newPurpose} |`;
48
+ return `| \`${m.path}\` | ${newPurpose} |`;
49
49
  });
50
50
  return hit ? out.join("\n") : md;
51
51
  }
package/dist/dox.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { createHash } from "node:crypto";
6
6
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
7
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ import { matchRow } from "./dox-row.js";
8
9
  import { loadGitignoreMatcher } from "./gitignore.js";
9
10
  import { readStaleness } from "./staleness.js";
10
11
  // delta ②: exclude worktree checkouts, archived openspec proposals, and doc-example noise.
@@ -22,7 +23,10 @@ import { readStaleness } from "./staleness.js";
22
23
  // carry per-file DOX rows per the Documentation Update Protocol, and excluding the
23
24
  // whole tree blinded the orphan check there. Only the non-source `.pi` subdirs
24
25
  // (caches, kb index, npm/git mirrors, flow run state) are skipped.
25
- const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.worktrees|\.reverse-spec-scratch|openspec|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)\.pi\/(dashboard|npm|git|flows)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
26
+ // `openspec` is excluded only as an OpenSpec WORKSPACE (`openspec/{changes,specs,
27
+ // groups}`) — a bare `openspec` segment also matched source dirs
28
+ // (`packages/client/src/components/openspec/`), silently blinding lint there.
29
+ const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.worktrees|\.reverse-spec-scratch|openspec\/(?:changes|specs|groups)|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)\.pi\/(dashboard|npm|git|flows)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
26
30
  /**
27
31
  * `AGENTS.override.md` (pi 0.84.0) REPLACES a directory's context rather than
28
32
  * adding to it, so it is listed first and shadows the other candidates in the
@@ -230,10 +234,8 @@ function walkFiles(dir, match, out = [], root = dir, ignore) {
230
234
  if (e.name === "__tests__")
231
235
  continue;
232
236
  const rel = relative(root, abs);
233
- // Conservative dir-pruning (design D3): hard-prune only when the dir
234
- // matches AND no deeper .gitignore could negate it; otherwise descend
235
- // and filter files at match time so deep negations survive.
236
- if (ignore?.isIgnoredDir(rel) && !ignore.hasDeeperGitignore(rel))
237
+ // Excluded-parent rule: an ignored dir is never descended (git semantics).
238
+ if (ignore?.isIgnoredDir(rel))
237
239
  continue;
238
240
  walkFiles(abs, match, out, root, ignore);
239
241
  }
@@ -284,8 +286,6 @@ export function parseRowPaths(agentsFile) {
284
286
  return [];
285
287
  return scanDoxRows(readFileSync(agentsFile, "utf8")).rows.map((r) => r.path);
286
288
  }
287
- // --- dox describe --list (change: inject-dox-doctrine-and-describe) ---
288
- const ROW_PURPOSE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
289
289
  /** Enumerate every `| File | Purpose |` row whose Purpose is empty or
290
290
  * whitespace-only, grouped by owning `AGENTS.md`. `dir` restricts the walk to
291
291
  * one subtree. Read-only: no model, no writes (design D8). Rows are recognized
@@ -314,7 +314,7 @@ export function listEmptyPurposeRows(opts) {
314
314
  if (e.name === "__tests__")
315
315
  continue; // skipped during descent, as in the `dox init` source walk
316
316
  const rel = relative(cwd, abs);
317
- if (gi.isIgnoredDir(rel) && !gi.hasDeeperGitignore(rel))
317
+ if (gi.isIgnoredDir(rel))
318
318
  continue;
319
319
  walk(abs);
320
320
  }
@@ -329,8 +329,8 @@ export function listEmptyPurposeRows(opts) {
329
329
  for (const af of agentsFiles.sort()) {
330
330
  const subjects = [];
331
331
  for (const row of scanDoxRows(readFileSync(af, "utf8")).rows) {
332
- const m = row.line.match(ROW_PURPOSE);
333
- if (m && m[2].trim() === "")
332
+ const m = matchRow(row.line);
333
+ if (m && m.purpose === "")
334
334
  subjects.push(row.path);
335
335
  }
336
336
  if (subjects.length > 0) {
@@ -526,7 +526,7 @@ export function doxLint(opts) {
526
526
  continue;
527
527
  if (e.isDirectory()) {
528
528
  const rel = relative(cwd, abs);
529
- if (gi.isIgnoredDir(rel) && !gi.hasDeeperGitignore(rel))
529
+ if (gi.isIgnoredDir(rel))
530
530
  continue;
531
531
  walkAgents(abs);
532
532
  }
@@ -582,6 +582,13 @@ export function doxLint(opts) {
582
582
  if (!hit)
583
583
  issues.push({ kind: "broken-ref", agentsFile: afRel, path: ref, detail: `broken-ref: row prose cites ${ref}, which does not exist` });
584
584
  }
585
+ // Glob row (`*.glb`, `shots/s*.png`) documents a file family: exists iff
586
+ // any file under the AGENTS.md dir matches. No hash → never stale.
587
+ if (rp.includes("*")) {
588
+ if (!globHit(rp, afDir))
589
+ issues.push({ kind: "orphan", agentsFile: afRel, path: rp, detail: `orphan: no file matches ${rp}` });
590
+ continue;
591
+ }
585
592
  const abs = resolveRowPath(afDir, cwd, rp);
586
593
  const rel = relative(cwd, abs);
587
594
  rowPaths.add(rel);