pi-doc-injector 0.7.0 → 0.9.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/README.md CHANGED
@@ -8,8 +8,19 @@ A [Pi](https://pi.dev) extension that adds relevant project docs to the conversa
8
8
  pi install npm:pi-doc-injector
9
9
  ```
10
10
 
11
+ Or install directly from GitHub:
12
+
13
+ ```bash
14
+ pi install git:github.com/lmn451/pi-docs@master
15
+ ```
16
+
17
+ Replace `master` with a branch, tag, or commit to select another revision.
18
+ If switching from npm, run `pi remove npm:pi-doc-injector` first to avoid loading both copies.
19
+
11
20
  Requires Pi 1.5.2 or newer within the 1.x series.
12
21
 
22
+ The Pi transcript shows injected documents collapsed by default. Press Pi’s **Expand tools** shortcut (`Ctrl+O` by default) to show or hide their contents along with other expandable transcript items. This changes only what you see. The model still receives the complete documents.
23
+
13
24
  ## Simple mode (default)
14
25
 
15
26
  Create `docs/auth.md`. When **auth** appears as a complete word in a user message, assistant text, or assistant thinking, the extension selects that file. Matching ignores case. A user match injects the doc before the assistant responds. An assistant match injects it at Pi's completed `turn_end` boundary, after the assistant response and any tool results are saved. Pi persists a `custom_message` entry and continues the **same** run with the document available to the next provider request.
@@ -45,6 +56,10 @@ Optional `.pi/doc-injector.json` in your project:
45
56
 
46
57
  Set `"mode": "keywords"` to use frontmatter keywords, heuristic keyword generation, or optional LLM keyword generation. It also supports nested docs and `.txt` files. The existing `matchThreshold` (default: 2), `streamWindowSize` (default: 500), `recursive`, `autoKeywords`, `llmKeywords`, and `llmBatchSize` settings apply to this mode. Keyword-mode assistant matches still accumulate across streaming updates and wait for the next agent run; they do not request same-run continuation. Neither mode aborts an active response. `streamWindowSize` and `matchThreshold` do not affect simple matching.
47
58
 
59
+ Keyword mode lazily compiles and reuses one matcher per assistant message. Registry, keyword, injection-state, and configuration changes invalidate that matcher; accumulated keyword hits remain until the message ends.
60
+
61
+ Cache writes merge under Pi's per-file mutation queue for heuristic and LLM updates. This coordinates writers only within the Pi process; it is not a cross-process lock or an atomic filesystem transaction.
62
+
48
63
  Example doc:
49
64
 
50
65
  ```md
@@ -80,6 +95,23 @@ The history is newest-first and has one record per document in each saved inject
80
95
 
81
96
  Reason metadata is versioned and stored in `details` on the existing Pi custom messages; it does not duplicate document bodies or write a separate `debug.log`. The history reflects saved injection messages, not an acknowledgement that the model received or read the documents. It is read from native current-branch session history on each command, so it survives extension reload; in-memory injection marks are separate and are rebuilt on reload. Older injection messages without usable reasons metadata are reported unavailable by the command rather than assigned guessed reasons.
82
97
 
98
+ ## Documentation authoring skill
99
+
100
+ The repository includes `skills/doc-authoring/SKILL.md` for creating and
101
+ validating docs folders. It defaults to top-level filename matching, supports
102
+ opt-in keyword mode, and checks file eligibility, sizes, links, and runtime
103
+ registration without resetting injection state automatically.
104
+
105
+ To install it globally from a repository checkout:
106
+
107
+ ```bash
108
+ mkdir -p ~/.pi/agent/skills/doc-authoring
109
+ cp skills/doc-authoring/SKILL.md ~/.pi/agent/skills/doc-authoring/SKILL.md
110
+ ```
111
+
112
+ Run `/reload` in an active Pi session, then use
113
+ `/skill:doc-authoring create or validate this project's docs folder`.
114
+
83
115
  ## Development
84
116
 
85
117
  ```bash
@@ -88,6 +120,14 @@ npm run typecheck
88
120
  npm run format:check
89
121
  ```
90
122
 
123
+ The runtime glob filter uses `minimatch`. Pi supplies the required
124
+ `@earendil-works/pi-coding-agent` and `typebox` peer APIs; local development
125
+ installs them as dev dependencies, and tests run with Vitest 4.1.12. Its current
126
+ Vite 8.3.8 toolchain resolves vulnerable `picomatch@4.0.7`
127
+ (GHSA-fc5q-39xc-vjpf); npm audit also flags the related `tinyglobby`, `fdir`,
128
+ Vite, and Vitest development-graph nodes. This is dev-only, not the runtime glob
129
+ engine; no patched picomatch release is available.
130
+
91
131
  Lifecycle tests cover full input and long completed thinking/output, block boundaries and partial words, persisted same-run injection, duplicate suppression, abort/error outcomes, the continuation limit, context guards, and keyword-mode streaming regressions.
92
132
 
93
133
  Injection marks live in memory. Reloading the extension rebuilds this state; it does not reconstruct marks from saved or compacted history.
package/cache.ts CHANGED
@@ -6,9 +6,14 @@
6
6
  *
7
7
  * Invalid files (wrong version, bad JSON, ENOENT) result in an empty cache.
8
8
  */
9
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
9
10
  import { mkdir, readFile, writeFile } from "node:fs/promises";
10
- import { dirname, join } from "node:path";
11
- import type { KeywordCache } from "./types";
11
+ import { dirname, join, resolve } from "node:path";
12
+ import {
13
+ LLM_CACHE_SENTINEL,
14
+ type CacheEntry,
15
+ type KeywordCache,
16
+ } from "./types";
12
17
  import type { Notifier } from "./notifier";
13
18
 
14
19
  const CACHE_FILENAME = ".pi/doc-injector-cache.json";
@@ -71,6 +76,31 @@ export async function saveCache(
71
76
  await writeFile(cachePath, JSON.stringify(cache, null, 2), "utf-8");
72
77
  }
73
78
 
79
+ /**
80
+ * Merge dirty keyword entries into the latest on-disk cache and save it under
81
+ * Pi's per-file mutation queue.
82
+ */
83
+ export async function mergeAndSaveCache(
84
+ cwd: string,
85
+ dirtyEntries: Record<string, CacheEntry>,
86
+ notifier: Notifier,
87
+ ): Promise<void> {
88
+ await withFileMutationQueue(resolve(cwd, CACHE_FILENAME), async () => {
89
+ const cache = await loadCache(cwd, notifier);
90
+ for (const [path, entry] of Object.entries(dirtyEntries)) {
91
+ const current = cache.files[path];
92
+ if (
93
+ current?.mtimeMs === LLM_CACHE_SENTINEL &&
94
+ entry.mtimeMs !== LLM_CACHE_SENTINEL
95
+ ) {
96
+ continue;
97
+ }
98
+ cache.files[path] = entry;
99
+ }
100
+ await saveCache(cwd, cache);
101
+ });
102
+ }
103
+
74
104
  /** Check that a parsed value matches the KeywordCache shape. */
75
105
  function isValidCache(value: unknown): value is KeywordCache {
76
106
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
package/commands.ts CHANGED
@@ -13,6 +13,7 @@ import type { DocInjectorConfig } from "./types";
13
13
  /** Dependencies injected into the command registrar. */
14
14
  export interface CommandDeps {
15
15
  getRegistry: () => DocRegistry | null;
16
+ resetInjectionState: () => void;
16
17
  getEnabled: () => boolean;
17
18
  setEnabled: (v: boolean) => void;
18
19
  reloadRegistry: () => Promise<number>;
@@ -81,7 +82,7 @@ export function registerCommands(pi: ExtensionAPI, deps: CommandDeps): void {
81
82
  } else if (a === "reset") {
82
83
  const reg = deps.getRegistry();
83
84
  if (reg) {
84
- reg.markAllNotInjected();
85
+ deps.resetInjectionState();
85
86
  ctx.ui.notify("📄 Injection state reset", "info");
86
87
  } else {
87
88
  ctx.ui.notify("📄 No registry loaded", "warning");
@@ -162,10 +163,9 @@ export function registerCommands(pi: ExtensionAPI, deps: CommandDeps): void {
162
163
 
163
164
  const targetPath = args.trim();
164
165
 
165
- // Filter to keyword-less entries (keywordSource !== "frontmatter", "cache", or "llm")
166
+ // Heuristic keywords remain eligible for upgrade after cache-backed reloads.
166
167
  let candidates = reg.getEntries().filter((e) => {
167
168
  if (e.keywordSource === "frontmatter") return false;
168
- if (e.keywordSource === "cache") return false;
169
169
  if (e.keywordSource === "llm") return false; // already LLM-generated
170
170
  return true;
171
171
  });
@@ -0,0 +1,38 @@
1
+ # TypeScript hardening
2
+
3
+ `npm run typecheck` runs the existing whole-project check and a stricter,
4
+ dependency-light core check. `npm run typecheck:core` runs only the latter.
5
+ The core covers shared types, matching, local and LLM keyword prompt generation,
6
+ and injection formatting. It enables `noUncheckedIndexedAccess`,
7
+ `exactOptionalPropertyTypes`, and dependency declaration checking, with no emit.
8
+ It does not claim stricter coverage of Pi SDK integration or filesystem modules.
9
+
10
+ Negative contracts in `typechecks/core.test-d.ts` verify that unchecked array
11
+ access and explicit undefined option overrides are rejected. These contracts
12
+ are deliberately outside the normal test compilation. Runtime tests in
13
+ `test/typescript-config.test.ts` protect the scope, flags and mandatory script
14
+ chain. Existing matching tests cover Unicode boundaries and rolling windows.
15
+
16
+ ## Provenance
17
+
18
+ The method was recovered locally from `/Users/applesucks/dev/pi-agents`, whose
19
+ package is `pi-subagentura`. The relevant work is from November 14, 2026:
20
+
21
+ - `efaa6eb15630a72ebe0fc3a48003c6a247dd57b6`, 16:05:16 +0200:
22
+ Harden extension execution and TypeScript boundaries (#235).
23
+ - `ffd2e5c445eb57e0371d0acda5ecfe9edcd711b7`, 14:03:14 +0200:
24
+ Incremental strict core typechecks, negative contracts and mandatory script
25
+ wiring.
26
+ - `74282f7e32ead66f430849dabaf0505d56b6f248`, 14:01:33 +0200:
27
+ Worker JavaScript and RPC checks. Those worker-specific changes are not needed
28
+ here because this extension has no JavaScript worker.
29
+
30
+ Pi session history under `~/.pi/agent/sessions` was also inspected. The concrete
31
+ implementation evidence is the local Git history and its checked-in compiler,
32
+ contract and test artifacts. The inspected hardening precedent does not define
33
+ ISO, so this work does not assign a meaning to that acronym.
34
+
35
+ A reusable global Pi skill is installed at
36
+ `~/.pi/agent/skills/typescript-hardening/SKILL.md`, using the existing global
37
+ skill directory and YAML frontmatter conventions. Its human-readable name is
38
+ TypeScript hardening and its skill name is `typescript-hardening`.
package/globber.ts CHANGED
@@ -1,10 +1,33 @@
1
1
  /**
2
2
  * Glob filter for include/exclude pattern matching.
3
- * Uses picomatch (0 deps, ~18 KB) to compile patterns once for O(1) matching.
3
+ * Patterns are compiled once into Minimatch's non-recursive matchers.
4
4
  */
5
- import picomatch from "picomatch";
5
+ import { Minimatch } from "minimatch";
6
6
  import type { GlobFilter } from "./types";
7
7
 
8
+ // Preserve literal # and leading-! behavior while keeping extglobs enabled.
9
+ const globOptions = { dot: true, nocomment: true, nonegate: false };
10
+
11
+ function compilePatterns(patterns: string[]): Minimatch[] {
12
+ const matchers: Minimatch[] = [];
13
+ for (const pattern of patterns) {
14
+ matchers.push(new Minimatch(pattern, globOptions));
15
+ }
16
+ return matchers;
17
+ }
18
+
19
+ function matchesAny(
20
+ matchers: readonly Minimatch[],
21
+ relativePath: string,
22
+ ): boolean {
23
+ for (const matcher of matchers) {
24
+ if (matcher.match(relativePath)) {
25
+ return true;
26
+ }
27
+ }
28
+ return false;
29
+ }
30
+
8
31
  /**
9
32
  * Create a glob filter from include and exclude patterns.
10
33
  *
@@ -22,20 +45,18 @@ export function createGlobFilter(
22
45
  include: string[],
23
46
  exclude: string[],
24
47
  ): GlobFilter {
25
- const includeMatcher =
26
- include.length > 0 ? picomatch(include, { dot: true }) : null;
48
+ const includeMatchers = include.length > 0 ? compilePatterns(include) : null;
27
49
 
28
- const excludeMatcher =
29
- exclude.length > 0 ? picomatch(exclude, { dot: true }) : null;
50
+ const excludeMatchers = exclude.length > 0 ? compilePatterns(exclude) : null;
30
51
 
31
52
  return {
32
53
  match(relativePath: string): boolean {
33
54
  // If include patterns are specified, path must match at least one
34
- if (includeMatcher && !includeMatcher(relativePath)) {
55
+ if (includeMatchers && !matchesAny(includeMatchers, relativePath)) {
35
56
  return false;
36
57
  }
37
58
  // Path must not match any exclude pattern
38
- if (excludeMatcher && excludeMatcher(relativePath)) {
59
+ if (excludeMatchers && matchesAny(excludeMatchers, relativePath)) {
39
60
  return false;
40
61
  }
41
62
  return true;
package/index.ts CHANGED
@@ -12,9 +12,10 @@ import type {
12
12
  ExtensionAPI,
13
13
  ExtensionContext,
14
14
  } from "@earendil-works/pi-coding-agent";
15
+ import { Box, Text } from "@earendil-works/pi-tui";
15
16
  import { Type } from "typebox";
16
17
  import { resolve } from "node:path";
17
- import { loadCache, saveCache } from "./cache";
18
+ import { loadCache, mergeAndSaveCache } from "./cache";
18
19
  import { loadConfig } from "./config";
19
20
  import {
20
21
  type InjectionAuditDetails,
@@ -36,6 +37,18 @@ import {
36
37
  import { registerCommands } from "./commands";
37
38
 
38
39
  export default async function docInjectorExtension(pi: ExtensionAPI) {
40
+ pi.registerMessageRenderer("doc-injector", (_message, options, theme) => {
41
+ // Let Pi render the original Markdown when transcript output is expanded.
42
+ if (options.expanded) return undefined;
43
+ const label = theme.fg("customMessageLabel", "Injected documents");
44
+ const hint = options.keyHint("app.tools.expand", "to expand");
45
+ const box = new Box(options.outputPad, 1, (line) =>
46
+ theme.bg("customMessageBg", line),
47
+ );
48
+ box.addChild(new Text(`${label} (${hint})`, 0, 0));
49
+ return box;
50
+ });
51
+
39
52
  // ---- State ----
40
53
  // The notifier buffers warnings emitted during startup (loadConfig,
41
54
  // loadCache, initRegistry) and flushes them via ctx.ui.notify() in
@@ -87,37 +100,24 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
87
100
  let llmBatchesCompleted = 0;
88
101
  let llmTotalFiles = 0;
89
102
  let cache: KeywordCache = { version: 1, files: {} };
103
+ // Reuse compiled patterns across chunks; discard them when the registry changes.
104
+ let streamMatcher: KeywordMatcher | null = null;
90
105
 
91
106
  // ---- Helpers ----
92
107
  const getRegistry = () => registry;
108
+ const invalidateStreamMatcher = () => {
109
+ streamMatcher = null;
110
+ };
111
+ const resetInjectionState = () => {
112
+ registry?.markAllNotInjected();
113
+ invalidateStreamMatcher();
114
+ };
93
115
  const getEnabled = () => enabled;
94
116
  const setEnabled = (v: boolean) => {
95
117
  enabled = v;
96
118
  };
97
119
  const getConfig = () => config;
98
120
 
99
- const safeSaveCache = async (
100
- cwd: string,
101
- dirtyEntries: Record<string, CacheEntry>,
102
- ) => {
103
- // MAJOR-2 fix: before saveCache, re-read cache from disk to merge
104
- // LLM-written entries that may have landed during the scan.
105
- const freshCache = await loadCache(cwd, notifier);
106
- const mergedCache: KeywordCache = { version: 1, files: {} };
107
-
108
- // Start with fresh (disk) entries — includes any LLM writes during scan
109
- for (const [key, entry] of Object.entries(freshCache.files)) {
110
- mergedCache.files[key] = entry;
111
- }
112
-
113
- // Overlay dirty entries from this scan (scan results take precedence)
114
- for (const [key, entry] of Object.entries(dirtyEntries)) {
115
- mergedCache.files[key] = entry;
116
- }
117
-
118
- await saveCache(cwd, mergedCache);
119
- };
120
-
121
121
  const initRegistry = async (cwd: string) => {
122
122
  config = await loadConfig(cwd, notifier);
123
123
  const docsPath = resolve(cwd, config.docsPath);
@@ -126,10 +126,11 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
126
126
  ? await loadCache(cwd, notifier)
127
127
  : { version: 1, files: {} };
128
128
  registry = await DocRegistry.create(docsPath, config, cache, notifier);
129
+ invalidateStreamMatcher();
129
130
 
130
131
  const dirty = registry.getDirtyCache();
131
132
  if (Object.keys(dirty).length > 0) {
132
- await safeSaveCache(cwd, dirty);
133
+ await mergeAndSaveCache(cwd, dirty, notifier);
133
134
  }
134
135
  };
135
136
 
@@ -155,8 +156,6 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
155
156
  };
156
157
 
157
158
  // P5.4a — Inline tool registration (BLOCKER-2 fix).
158
- // Registered inside the factory for closure access to cache, cwd, saveCache,
159
- // and llmBatchesCompleted. Uses real mtime from stat().
160
159
  pi.registerTool({
161
160
  name: "_doc_injector_keywords",
162
161
  label: "Doc Injector Keywords",
@@ -177,6 +176,7 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
177
176
  }>;
178
177
  const { stat } = await import("node:fs/promises");
179
178
  let saved = 0;
179
+ const dirtyEntries: Record<string, CacheEntry> = {};
180
180
  for (const item of generated) {
181
181
  // Only documents in the registry may receive generated keywords.
182
182
  const entry = registry
@@ -185,13 +185,16 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
185
185
  if (config.mode !== "keywords" || !entry) continue;
186
186
  const fileStat = await stat(entry.filePath).catch(() => null);
187
187
  if (!fileStat?.isFile()) continue;
188
- cache.files[item.path] = {
188
+ dirtyEntries[item.path] = {
189
189
  mtimeMs: LLM_CACHE_SENTINEL,
190
190
  keywords: item.keywords.map((k) => k.toLowerCase()).slice(0, 20),
191
191
  };
192
192
  saved++;
193
193
  }
194
- if (saved > 0) await saveCache(ctx.cwd, cache);
194
+ if (saved > 0) {
195
+ await mergeAndSaveCache(ctx.cwd, dirtyEntries, notifier);
196
+ invalidateStreamMatcher();
197
+ }
195
198
  llmBatchesCompleted++;
196
199
  llmTotalFiles += saved;
197
200
  return {
@@ -215,6 +218,7 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
215
218
  streamHits.clear();
216
219
  continuedForDocs = false;
217
220
  continuationLimitNotified = false;
221
+ invalidateStreamMatcher();
218
222
 
219
223
  // Bind the notifier to the live context FIRST so any warnings emitted
220
224
  // during initRegistry below go directly to the TUI instead of being
@@ -245,10 +249,11 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
245
249
  }
246
250
 
247
251
  await registry.rebuild();
252
+ invalidateStreamMatcher();
248
253
 
249
254
  const dirty = registry.getDirtyCache();
250
255
  if (Object.keys(dirty).length > 0) {
251
- await safeSaveCache(effectiveCwd, dirty);
256
+ await mergeAndSaveCache(effectiveCwd, dirty, notifier);
252
257
  }
253
258
 
254
259
  const count = registry.getEntries().length;
@@ -303,16 +308,17 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
303
308
  const textBuffer = extractText(content);
304
309
  if (!textBuffer) return;
305
310
 
306
- // Discovery matcher: threshold 1 finds any keyword present in the rolling
307
- // tail window. The real matchThreshold is applied below against the
308
- // keywords accumulated across all chunks of this message.
309
- const matcher = buildMatcher({
310
- matchThreshold: 1,
311
- windowSize: config.streamWindowSize,
312
- });
313
- if (!matcher) return;
311
+ // Discovery uses threshold 1 per chunk; streamHits applies the configured
312
+ // threshold across the whole message. Reuse compiled patterns between chunks.
313
+ if (!streamMatcher) {
314
+ streamMatcher = buildMatcher({
315
+ matchThreshold: 1,
316
+ windowSize: config.streamWindowSize,
317
+ });
318
+ }
319
+ if (!streamMatcher) return;
314
320
 
315
- const results = matcher.match(textBuffer);
321
+ const results = streamMatcher.match(textBuffer);
316
322
 
317
323
  for (const result of results) {
318
324
  const filePath = result.entry.filePath;
@@ -332,6 +338,7 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
332
338
  // Hits belong to one assistant message. Clear them after any message ends.
333
339
  pi.on("message_end", async () => {
334
340
  streamHits.clear();
341
+ invalidateStreamMatcher();
335
342
  });
336
343
 
337
344
  const prepareInjection = (
@@ -413,6 +420,7 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
413
420
  // Pi exposes no post-commit callback for returned messages/drafts. Mark
414
421
  // only after preparation succeeds, immediately before proposing them.
415
422
  registry.markInjected(matchedEntries.map((e) => e.filePath));
423
+ invalidateStreamMatcher();
416
424
  clearPendingMatches();
417
425
  return { content, details };
418
426
  };
@@ -508,6 +516,7 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
508
516
  // ---- Commands ----
509
517
  registerCommands(pi, {
510
518
  getRegistry,
519
+ resetInjectionState,
511
520
  getEnabled,
512
521
  setEnabled,
513
522
  reloadRegistry,
package/injector.ts CHANGED
@@ -62,6 +62,9 @@ export function formatInjectionHistory(
62
62
 
63
63
  for (let index = total - 1; index >= total - shown; index--) {
64
64
  const record = history.records[index];
65
+ if (record === undefined) {
66
+ throw new Error("Injection history must not contain empty records");
67
+ }
65
68
  formatInjectionHistoryRecord(record, lines);
66
69
  if (index > total - shown) lines.push("");
67
70
  }
package/keyword-gen.ts CHANGED
@@ -234,7 +234,9 @@ function addFromHeadings(content: string, out: string[]): void {
234
234
  const headingRegex = /^#{1,6}\s+(.+)$/gm;
235
235
  let match: RegExpExecArray | null;
236
236
  while ((match = headingRegex.exec(content)) !== null) {
237
- const headingText = match[1].trim();
237
+ const heading = match[1];
238
+ if (heading === undefined) continue;
239
+ const headingText = heading.trim();
238
240
  // Split heading into words
239
241
  const words = headingText.split(/\s+/);
240
242
  for (const word of words) {
@@ -255,6 +257,7 @@ function addFromCodeSymbols(content: string, out: string[]): void {
255
257
  let match: RegExpExecArray | null;
256
258
  while ((match = symbolRegex.exec(content)) !== null) {
257
259
  const name = match[1];
260
+ if (name === undefined) continue;
258
261
  const cleaned = name.toLowerCase();
259
262
  if (cleaned.length >= 3 && !STOP_WORDS.has(cleaned)) {
260
263
  out.push(cleaned);
package/matcher.ts CHANGED
@@ -55,8 +55,10 @@ function escapeRegExp(s: string): string {
55
55
  function buildKeywordRegex(keyword: string, caseSensitive: boolean): RegExp {
56
56
  const escaped = escapeRegExp(keyword);
57
57
  const characters = Array.from(keyword);
58
- const left = WORD_CHAR.test(characters[0]) ? "(?<![\\p{L}\\p{N}_])" : "";
59
- const right = WORD_CHAR.test(characters[characters.length - 1])
58
+ const left = WORD_CHAR.test(characters[0] ?? "")
59
+ ? "(?<![\\p{L}\\p{N}_])"
60
+ : "";
61
+ const right = WORD_CHAR.test(characters[characters.length - 1] ?? "")
60
62
  ? "(?![\\p{L}\\p{N}_])"
61
63
  : "";
62
64
  return new RegExp(`${left}${escaped}${right}`, caseSensitive ? "gu" : "giu");
@@ -110,9 +112,18 @@ export class KeywordMatcher {
110
112
  // window aren't lost.
111
113
  const { windowSize } = this.options;
112
114
  const sliced = windowSize > 0 && text.length > windowSize;
113
- // Keep one preceding character so the left word boundary sees the true text.
114
- const scanText = sliced ? text.slice(-windowSize - 1) : text;
115
- const minStart = sliced ? 1 : 0;
115
+ // Preserve the complete preceding code point, including surrogate pairs.
116
+ const windowStart = sliced ? text.length - windowSize : 0;
117
+ let scanStart = Math.max(0, windowStart - 1);
118
+ if (
119
+ scanStart > 0 &&
120
+ /[\uDC00-\uDFFF]/.test(text.charAt(scanStart)) &&
121
+ /[\uD800-\uDBFF]/.test(text.charAt(scanStart - 1))
122
+ ) {
123
+ scanStart--;
124
+ }
125
+ const scanText = text.slice(scanStart);
126
+ const minStart = windowStart - scanStart;
116
127
 
117
128
  const results: MatchResult[] = [];
118
129
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-doc-injector",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Inject project docs into Pi context when their filename appears in the conversation",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -16,7 +16,8 @@
16
16
  "scripts": {
17
17
  "test": "vitest run",
18
18
  "test:watch": "vitest",
19
- "typecheck": "tsc --noEmit",
19
+ "typecheck": "tsc --noEmit && npm run typecheck:core",
20
+ "typecheck:core": "tsc -p tsconfig.core.json",
20
21
  "format": "prettier --write .",
21
22
  "format:check": "prettier --check .",
22
23
  "prepare": "husky"
@@ -39,18 +40,22 @@
39
40
  ]
40
41
  },
41
42
  "dependencies": {
42
- "picomatch": "^4.0.2",
43
- "typebox": "^1.1.38"
43
+ "minimatch": "^11.0.9"
44
44
  },
45
45
  "peerDependencies": {
46
- "@earendil-works/pi-coding-agent": "^1.5.2"
46
+ "@earendil-works/pi-coding-agent": "*",
47
+ "@earendil-works/pi-tui": "*",
48
+ "typebox": "*"
47
49
  },
48
50
  "devDependencies": {
51
+ "@earendil-works/pi-coding-agent": "^1.5.2",
52
+ "@earendil-works/pi-tui": "1.5.2",
49
53
  "@types/node": "^22.0.0",
50
54
  "husky": "^9.1.7",
51
55
  "prettier": "^3.8.4",
56
+ "typebox": "^1.3.27",
52
57
  "typescript": "^5.7.0",
53
- "vitest": "^3.0.0"
58
+ "vitest": "^4.1.12"
54
59
  },
55
60
  "publishConfig": {
56
61
  "access": "public"
package/picomatch.d.ts DELETED
@@ -1,14 +0,0 @@
1
- declare module "picomatch" {
2
- interface PicomatchOptions {
3
- dot?: boolean;
4
- }
5
-
6
- type Matcher = (input: string) => boolean;
7
-
8
- function picomatch(
9
- patterns: string | string[],
10
- options?: PicomatchOptions,
11
- ): Matcher;
12
-
13
- export default picomatch;
14
- }