pi-doc-injector 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-doc-injector",
3
- "version": "0.5.3",
4
- "description": "Auto-inject relevant project documentation into Pi's LLM context based on keyword matching",
3
+ "version": "0.7.0",
4
+ "description": "Inject project docs into Pi context when their filename appears in the conversation",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
7
7
  "exports": {
@@ -15,7 +15,11 @@
15
15
  ],
16
16
  "scripts": {
17
17
  "test": "vitest run",
18
- "test:watch": "vitest"
18
+ "test:watch": "vitest",
19
+ "typecheck": "tsc --noEmit",
20
+ "format": "prettier --write .",
21
+ "format:check": "prettier --check .",
22
+ "prepare": "husky"
19
23
  },
20
24
  "keywords": [
21
25
  "pi-package",
@@ -35,18 +39,20 @@
35
39
  ]
36
40
  },
37
41
  "dependencies": {
38
- "picomatch": "^4.0.2"
42
+ "picomatch": "^4.0.2",
43
+ "typebox": "^1.1.38"
39
44
  },
40
45
  "peerDependencies": {
41
- "@mariozechner/pi-coding-agent": "*"
46
+ "@earendil-works/pi-coding-agent": "^1.5.2"
42
47
  },
43
48
  "devDependencies": {
44
49
  "@types/node": "^22.0.0",
50
+ "husky": "^9.1.7",
51
+ "prettier": "^3.8.4",
45
52
  "typescript": "^5.7.0",
46
53
  "vitest": "^3.0.0"
47
54
  },
48
55
  "publishConfig": {
49
56
  "access": "public"
50
- },
51
- "packageManager": "npm@11.5.2"
57
+ }
52
58
  }
package/picomatch.d.ts CHANGED
@@ -5,7 +5,10 @@ declare module "picomatch" {
5
5
 
6
6
  type Matcher = (input: string) => boolean;
7
7
 
8
- function picomatch(patterns: string | string[], options?: PicomatchOptions): Matcher;
8
+ function picomatch(
9
+ patterns: string | string[],
10
+ options?: PicomatchOptions,
11
+ ): Matcher;
9
12
 
10
13
  export default picomatch;
11
14
  }
package/registry.ts CHANGED
@@ -6,9 +6,15 @@
6
6
  * 2. readFile(filePath) → parse frontmatter or generate keywords
7
7
  */
8
8
  import type { Dirent } from "node:fs";
9
- import { readdir, readFile, stat } from "node:fs/promises";
9
+ import { lstat, readdir, readFile, stat } from "node:fs/promises";
10
10
  import { basename, extname, join, relative, resolve } from "node:path";
11
- import { LLM_CACHE_SENTINEL, type CacheEntry, type DocEntry, type DocInjectorConfig, type KeywordCache } from "./types";
11
+ import {
12
+ LLM_CACHE_SENTINEL,
13
+ type CacheEntry,
14
+ type DocEntry,
15
+ type DocInjectorConfig,
16
+ type KeywordCache,
17
+ } from "./types";
12
18
  import type { Notifier } from "./notifier";
13
19
  import { createGlobFilter } from "./globber";
14
20
  import { generateKeywords } from "./keyword-gen";
@@ -17,7 +23,9 @@ import { generateKeywords } from "./keyword-gen";
17
23
  * Shared parser for frontmatter block content (title + keywords).
18
24
  * Extracts title and keywords from YAML-like content between delimiters.
19
25
  */
20
- function parseFrontmatterBlock(block: string): { title: string; keywords: string[] } | null {
26
+ function parseFrontmatterBlock(
27
+ block: string,
28
+ ): { title: string; keywords: string[] } | null {
21
29
  // Extract title
22
30
  const titleMatch = block.match(/^title:\s*["']?([^"'\n]+)["']?$/m);
23
31
  const title = titleMatch ? titleMatch[1].trim() : "";
@@ -26,7 +34,7 @@ function parseFrontmatterBlock(block: string): { title: string; keywords: string
26
34
  const keywords: string[] = [];
27
35
 
28
36
  // Try flow array: keywords: [a, b, c]
29
- const flowMatch = block.match(/keywords:\s*\[([^\]]*)\]/);
37
+ const flowMatch = block.match(/^keywords:[ \t]*\[([^\]]*)\]/m);
30
38
  if (flowMatch) {
31
39
  keywords.push(
32
40
  ...flowMatch[1]
@@ -36,7 +44,9 @@ function parseFrontmatterBlock(block: string): { title: string; keywords: string
36
44
  );
37
45
  } else {
38
46
  // Try block array: keywords:\n - a\n - b
39
- const blockMatches = block.matchAll(/keywords:\s*\n((?:\s*-\s*.+\n?)+)/g);
47
+ const blockMatches = block.matchAll(
48
+ /^keywords:[ \t]*\n((?:[ \t]*-[ \t]*.+\n?)+)/gm,
49
+ );
40
50
  for (const bm of blockMatches) {
41
51
  const items = bm[1].matchAll(/^\s*-\s*["']?([^"'\n]+)["']?$/gm);
42
52
  for (const im of items) {
@@ -172,10 +182,10 @@ export function parseFrontmatter(
172
182
  content: string,
173
183
  ): { title: string; keywords: string[]; body: string } | null {
174
184
  return (
175
- parseYamlFrontmatter(content)
176
- ?? parseCStyleFrontmatter(content)
177
- ?? parseHTMLFrontmatter(content)
178
- ?? parseSlashSlashFrontmatter(content)
185
+ parseYamlFrontmatter(content) ??
186
+ parseCStyleFrontmatter(content) ??
187
+ parseHTMLFrontmatter(content) ??
188
+ parseSlashSlashFrontmatter(content)
179
189
  );
180
190
  }
181
191
 
@@ -226,42 +236,42 @@ class PromisePool {
226
236
  * Document Registry class. Scans a docs folder and maintains an index of DocEntry.
227
237
  */
228
238
  export class DocRegistry {
229
- private entries: DocEntry[] = [];
230
- private docsPath: string;
231
- private config: DocInjectorConfig;
232
- private cache: KeywordCache | null = null;
233
- private dirtyCache: KeywordCache = { version: 1, files: {} };
234
- private notifier: Notifier;
235
- // Per-registry flag: warn about a missing docs folder at most once.
236
- // rebuild() is called twice at startup (once from session_start, once
237
- // from resources_discover); without this flag the user sees the
238
- // same warning twice. Not reset across rebuilds — a missing folder
239
- // is a persistent condition, not a transient one.
240
- private warnedMissingDocs = false;
241
-
242
- private constructor(
243
- docsPath: string,
244
- config: DocInjectorConfig,
245
- cache: KeywordCache | undefined,
246
- notifier: Notifier,
247
- ) {
248
- this.docsPath = docsPath;
249
- this.config = config;
250
- this.cache = cache ?? null;
251
- this.notifier = notifier;
252
- }
239
+ private entries: DocEntry[] = [];
240
+ private docsPath: string;
241
+ private config: DocInjectorConfig;
242
+ private cache: KeywordCache | null = null;
243
+ private dirtyCache: KeywordCache = { version: 1, files: {} };
244
+ private notifier: Notifier;
245
+ // Per-registry flag: warn about a missing docs folder at most once.
246
+ // rebuild() is called twice at startup (once from session_start, once
247
+ // from resources_discover); without this flag the user sees the
248
+ // same warning twice. Not reset across rebuilds — a missing folder
249
+ // is a persistent condition, not a transient one.
250
+ private warnedMissingDocs = false;
251
+
252
+ private constructor(
253
+ docsPath: string,
254
+ config: DocInjectorConfig,
255
+ cache: KeywordCache | undefined,
256
+ notifier: Notifier,
257
+ ) {
258
+ this.docsPath = docsPath;
259
+ this.config = config;
260
+ this.cache = cache ?? null;
261
+ this.notifier = notifier;
262
+ }
253
263
 
254
- /** Create a registry by scanning the docs folder. */
255
- static async create(
256
- docsPath: string,
257
- config: DocInjectorConfig,
258
- cache: KeywordCache | undefined,
259
- notifier: Notifier,
260
- ): Promise<DocRegistry> {
261
- const registry = new DocRegistry(docsPath, config, cache, notifier);
262
- await registry.rebuild();
263
- return registry;
264
- }
264
+ /** Create a registry by scanning the docs folder. */
265
+ static async create(
266
+ docsPath: string,
267
+ config: DocInjectorConfig,
268
+ cache: KeywordCache | undefined,
269
+ notifier: Notifier,
270
+ ): Promise<DocRegistry> {
271
+ const registry = new DocRegistry(docsPath, config, cache, notifier);
272
+ await registry.rebuild();
273
+ return registry;
274
+ }
265
275
 
266
276
  /** Re-scan the docs folder and rebuild the index. */
267
277
  async rebuild(): Promise<void> {
@@ -297,9 +307,11 @@ export class DocRegistry {
297
307
  // Process files concurrently with PromisePool
298
308
  const pool = new PromisePool(this.config.maxConcurrent);
299
309
 
300
- const tasks = scanResults.map((sr) => async (): Promise<DocEntry | null> => {
301
- return this.processFile(sr, preserved);
302
- });
310
+ const tasks = scanResults.map(
311
+ (sr) => async (): Promise<DocEntry | null> => {
312
+ return this.processFile(sr, preserved);
313
+ },
314
+ );
303
315
 
304
316
  const results = await pool.all(tasks);
305
317
  this.entries = results.filter((e): e is DocEntry => e !== null);
@@ -325,8 +337,9 @@ export class DocRegistry {
325
337
  * 4. Skip (no frontmatter, no cache, autoKeywords disabled)
326
338
  *
327
339
  * LLM-generated keywords populate the cache via the `_doc_injector_keywords`
328
- * tool, so they surface as `keywordSource: "cache"` on the next rebuild
329
- * (their `mtimeMs` is set to the file's current mtime when written).
340
+ * tool with `mtimeMs` set to LLM_CACHE_SENTINEL, so they surface as
341
+ * `keywordSource: "llm"` on the next rebuild (the sentinel never matches a
342
+ * real file mtime, keeping them distinct from heuristic cache hits).
330
343
  */
331
344
  private async processFile(
332
345
  { filePath, relativePath, fileName }: ScanResult,
@@ -334,6 +347,8 @@ export class DocRegistry {
334
347
  ): Promise<DocEntry | null> {
335
348
  try {
336
349
  // ─── METADATA ─────────────────────────────────────────────
350
+ const linkStat = await lstat(filePath);
351
+ if (!linkStat.isFile()) return null;
337
352
  const fileStat = await stat(filePath);
338
353
 
339
354
  if (fileStat.size > this.config.maxFileSize) {
@@ -346,6 +361,25 @@ export class DocRegistry {
346
361
  // Read once — needed for frontmatter parse, content, and title.
347
362
  const raw = await readFile(filePath, "utf-8");
348
363
 
364
+ if (this.config.mode === "simple") {
365
+ // Simple mode indexes only docs/{name}.md, not subfolders or metadata.
366
+ if (relativePath !== fileName || extname(fileName) !== ".md") {
367
+ return null;
368
+ }
369
+ const name = fileName.slice(0, -3);
370
+ if (!name) return null;
371
+ return {
372
+ filePath,
373
+ fileName,
374
+ relativePath,
375
+ title: extractTitle(raw, fileName),
376
+ keywords: [name],
377
+ content: raw,
378
+ injected: preserved.get(filePath) ?? false,
379
+ keywordSource: "filename",
380
+ };
381
+ }
382
+
349
383
  // ─── PRIORITY 1: Frontmatter (authoritative) ─────────────
350
384
  const parsed = parseFrontmatter(raw);
351
385
  if (parsed) {
@@ -426,7 +460,9 @@ export class DocRegistry {
426
460
  } catch (err) {
427
461
  // Only warn for unexpected errors, not ENOENT (file deleted/moved after scan)
428
462
  if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
429
- this.notifier.warn(`[doc-injector] Error reading ${relativePath}: ${err instanceof Error ? err.message : String(err)}`);
463
+ this.notifier.warn(
464
+ `[doc-injector] Error reading ${relativePath}: ${err instanceof Error ? err.message : String(err)}`,
465
+ );
430
466
  }
431
467
  return null;
432
468
  }
@@ -449,7 +485,10 @@ export class DocRegistry {
449
485
  private async scanRecursive(dir: string): Promise<ScanResult[]> {
450
486
  const filter = createGlobFilter(this.config.include, this.config.exclude);
451
487
  const results: ScanResult[] = [];
452
- const dirents = await readdir(dir, { recursive: true, withFileTypes: true }) as Dirent[];
488
+ const dirents = (await readdir(dir, {
489
+ recursive: true,
490
+ withFileTypes: true,
491
+ })) as Dirent[];
453
492
 
454
493
  for (const dirent of dirents) {
455
494
  if (!dirent.isFile()) continue;
@@ -459,9 +498,11 @@ export class DocRegistry {
459
498
  // Resolve relative path cross-runtime
460
499
  let relPath: string;
461
500
  if (dirent.name === fileName) {
462
- const parentPath = (dirent as Dirent & { parentPath?: string; path?: string }).parentPath
463
- ?? (dirent as Dirent & { path?: string }).path
464
- ?? "";
501
+ const parentPath =
502
+ (dirent as Dirent & { parentPath?: string; path?: string })
503
+ .parentPath ??
504
+ (dirent as Dirent & { path?: string }).path ??
505
+ "";
465
506
  relPath = parentPath
466
507
  ? relative(dir, join(parentPath, dirent.name))
467
508
  : dirent.name;
@@ -499,7 +540,6 @@ export class DocRegistry {
499
540
  this.cache = cache;
500
541
  }
501
542
 
502
-
503
543
  /**
504
544
  * Get all registered entries.
505
545
  *
package/types.ts CHANGED
@@ -3,7 +3,12 @@
3
3
  */
4
4
 
5
5
  /** Source of keywords for a doc entry. */
6
- export type KeywordSource = "frontmatter" | "heuristic" | "llm" | "cache";
6
+ export type KeywordSource =
7
+ | "filename"
8
+ | "frontmatter"
9
+ | "heuristic"
10
+ | "llm"
11
+ | "cache";
7
12
 
8
13
  /** A parsed document from the docs folder. */
9
14
  export interface DocEntry {
@@ -29,6 +34,12 @@ export interface DocEntry {
29
34
  export interface MatcherOptions {
30
35
  matchThreshold: number;
31
36
  caseSensitive: boolean;
37
+ /**
38
+ * If > 0, only the last `windowSize` characters of the text are scanned.
39
+ * Used by the streaming path to bound per-chunk scan cost; 0 disables
40
+ * windowing (scan the full text), which is the default for one-shot matches.
41
+ */
42
+ windowSize: number;
32
43
  }
33
44
 
34
45
  /** Result from a keyword match. */
@@ -64,10 +75,19 @@ export interface GlobFilter {
64
75
 
65
76
  /** Extension configuration. */
66
77
  export interface DocInjectorConfig {
78
+ /** Simple filename matching (default) or legacy keyword matching. */
79
+ mode: "simple" | "keywords";
67
80
  /** Path to docs folder (relative to cwd) */
68
81
  docsPath: string;
69
82
  /** Minimum keyword matches to trigger injection */
70
83
  matchThreshold: number;
84
+ /**
85
+ * Size (in chars) of the rolling tail window scanned on each streaming chunk.
86
+ * Bounds per-chunk scan cost; matches still accumulate across chunks so the
87
+ * threshold can be met even when keywords scroll out of the window. 0 = scan
88
+ * the full accumulated buffer.
89
+ */
90
+ streamWindowSize: number;
71
91
  /** Skip injection if context usage exceeds this % (0-100) */
72
92
  contextThreshold: number;
73
93
  /** Whether to scan subdirectories */
@@ -90,8 +110,10 @@ export interface DocInjectorConfig {
90
110
 
91
111
  /** Default configuration values. */
92
112
  export const DEFAULT_CONFIG: DocInjectorConfig = {
113
+ mode: "simple",
93
114
  docsPath: "./docs",
94
- matchThreshold: 1,
115
+ matchThreshold: 2,
116
+ streamWindowSize: 500,
95
117
  contextThreshold: 80,
96
118
  recursive: true,
97
119
  include: ["**/*.md", "**/*.txt"],
@@ -107,6 +129,8 @@ export const DEFAULT_CONFIG: DocInjectorConfig = {
107
129
  export const DEFAULT_MATCHER_OPTIONS: MatcherOptions = {
108
130
  matchThreshold: DEFAULT_CONFIG.matchThreshold,
109
131
  caseSensitive: false,
132
+ // Default to no windowing; the streaming caller opts in via streamWindowSize.
133
+ windowSize: 0,
110
134
  };
111
135
 
112
136
  /**