pi-doc-injector 0.6.0 → 0.8.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
@@ -1,262 +1,137 @@
1
1
  # Pi Doc Injector
2
2
 
3
- A [Pi](https://pi.dev) extension that automatically injects relevant project documentation into the LLM context by monitoring streaming output for keyword matches. Docs are delivered as a `CustomMessage` so the system prompt stays untouched and the provider's prompt cache stays warm.
3
+ A [Pi](https://pi.dev) extension that adds relevant project docs to the conversation as a `CustomMessage`. It does not change the system prompt.
4
4
 
5
- ## Installation
6
-
7
- ### Via npm (recommended)
5
+ ## Install
8
6
 
9
7
  ```bash
10
8
  pi install npm:pi-doc-injector
11
9
  ```
12
10
 
13
- ### Via git
14
-
15
- ```bash
16
- pi install git:github.com/lmn451/pi-doc-injector
17
- ```
18
-
19
- ### Manual
20
-
21
- Copy this repository into your project's `.pi/extensions/doc-injector/` folder, or clone directly:
11
+ Or install directly from GitHub:
22
12
 
23
13
  ```bash
24
- git clone https://github.com/yourname/pi-doc-injector.git .pi/extensions/doc-injector
25
- ```
26
-
27
- ## Quick Start
28
-
29
- 1. Create a `docs/` folder in your project root.
30
- 2. Add markdown files with frontmatter (`title` + `keywords`). See [Document Format](#document-format) for supported formats.
31
- 3. Start Pi. The extension scans `docs/` on session start.
32
- 4. When the user mentions a keyword, the matching doc is injected as a
33
- `CustomMessage` into the conversation **before the assistant responds** —
34
- no one-turn delay. The system prompt is never modified.
35
- 5. If the assistant mentions a NEW keyword mid-response, generation is
36
- automatically aborted and restarted with the doc injected immediately.
37
-
38
- ## Document Format
39
-
40
- Documents are markdown files (`.md` or `.txt`) that the extension scans for injection.
41
- Each file can declare `title` and `keywords` via **frontmatter** — a metadata block at the top of the file.
42
-
43
- ### Supported Frontmatter Formats
44
-
45
- The extension tries formats in this order and uses the first match it finds:
46
-
47
- **1. YAML (recommended)**
48
-
49
- ```md
50
- ---
51
- title: "Testing Workflow"
52
- keywords: [test, testing, jest, vitest]
53
- ---
54
-
55
- # Testing Workflow
56
- ```
57
-
58
- **2. C-style block comment** — useful for `.ts`/`.js` doc files:
59
-
60
- ```md
61
- /*---
62
- title: "Testing Workflow"
63
- keywords: [test, testing, jest, vitest]
64
- ---*/
65
-
66
- # Testing Workflow
14
+ pi install git:github.com/lmn451/pi-docs@master
67
15
  ```
68
16
 
69
- **3. HTML comment** — useful for HTML-generated docs:
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.
70
19
 
71
- ```md
72
- <!--
73
- title: "Testing Workflow"
74
- keywords: [test, testing, jest, vitest]
75
- -->
76
-
77
- # Testing Workflow
78
- ```
79
-
80
- **4. Slash-slash comment** — useful for `.js`/`.ts` sidecar docs:
20
+ Requires Pi 1.5.2 or newer within the 1.x series.
81
21
 
82
- ```md
83
- //---
84
- title: "Testing Workflow"
85
- keywords: [test, testing, jest, vitest]
22
+ ## Simple mode (default)
86
23
 
87
- # Testing Workflow
88
- ```
24
+ 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.
89
25
 
90
- ### Keyword Array Syntax
26
+ Simple mode scans the full user input and each finished assistant thinking/text block independently. It does not scan streaming chunks or use a sliding window. For example, a streamed `auth` prefix that finishes as `authentication` does not match `auth.md`; words and phrases cannot be assembled across blocks.
91
27
 
92
- Both **flow** and **block** keyword array syntaxes are supported:
28
+ The current provider request cannot be changed retroactively: text or tool calls already generated finish before the document is added. The extension never aborts generation, edits the completed response, or sends a synthetic user `continue` message. Aborted and failed turns do not trigger document injection or continuation.
93
29
 
94
- ```md
95
- keywords: [test, testing, jest] # flow: comma-separated in brackets
96
- keywords: # block: one per line
97
- - test
98
- - testing
99
- - jest
100
- ```
30
+ There is **one automatic document injection batch per user run**, with all matching documents in that batch. This fixed limit also applies to turns with tools: Pi's natural tool or steering continuation satisfies the same next request, so no extra request is added after it. Further matches wait for the next user run and produce one notification. Low-level agent restarts/retries do not reset the limit. A new user run resets it; user-input injection does not consume it. This bounds automatic document-triggered continuation chains.
101
31
 
102
- ### Auto-Keywords Fallback
32
+ Simple mode uses only top-level `docs/{name}.md` files. For example, `docs/auth.md` matches `auth`, but not `authentication`. It does not split filenames into words: `docs/api-auth.md` matches `api-auth`, not `auth`. Frontmatter and generated keywords are not needed. Each file is selected for injection at most once per extension session, unless you run `/doc-inject reset`.
103
33
 
104
- If a file has **no frontmatter** and `autoKeywords` is enabled (default: `true`), the extension generates keywords heuristically from the filename and content — no metadata needed.
105
-
106
- If `autoKeywords` is `false`, files without valid frontmatter are **skipped** with a warning.
34
+ The extension stores the injected content in a conversation message, not at the head of the context or in the system prompt. Provider cache hits still depend on the provider's cache policy.
107
35
 
108
36
  ## Configuration
109
37
 
110
- Create `.pi/doc-injector.json` in your project root to customize behavior:
38
+ Optional `.pi/doc-injector.json` in your project:
111
39
 
112
40
  ```json
113
41
  {
42
+ "mode": "simple",
114
43
  "docsPath": "./docs",
115
- "matchThreshold": 2,
116
- "streamWindowSize": 500,
117
- "contextThreshold": 80,
118
- "recursive": true,
119
- "autoKeywords": true,
120
- "llmKeywords": false,
121
- "llmBatchSize": 20
44
+ "contextThreshold": 80
122
45
  }
123
46
  ```
124
47
 
125
- | Option | Default | Description |
126
- | ------------------ | ---------- | -------------------------------------------------------- |
127
- | `docsPath` | `"./docs"` | Path to docs folder (relative to project root) |
128
- | `matchThreshold` | `2` | Minimum distinct keyword matches required to inject a doc |
129
- | `streamWindowSize` | `500` | Rolling tail window (chars) scanned per streaming chunk; matches accumulate across chunks. `0` scans the full buffer |
130
- | `contextThreshold` | `80` | Skip injection when context usage exceeds this % (0–100) |
131
- | `recursive` | `true` | Scan docs subdirectories recursively |
132
- | `autoKeywords` | `true` | Generate keywords heuristically when frontmatter is missing |
133
- | `llmKeywords` | `false` | Enable LLM-based keyword generation (see below) |
134
- | `llmBatchSize` | `20` | Max files per LLM keyword batch |
135
-
136
- ### Keyword Matching
137
-
138
- Matching is case-insensitive and respects word boundaries by default. Once a document is injected, it won't re-match until you run `/doc-inject reset`.
139
-
140
- Injection is also skipped if the current context usage exceeds 80% of the token budget.
141
-
142
- ## Commands
143
-
144
- | Command | Description |
145
- | -------------------- | ---------------------------------------------------- |
146
- | `/doc-inject on` | Enable doc injection |
147
- | `/doc-inject off` | Disable doc injection |
148
- | `/doc-inject toggle` | Toggle doc injection on/off |
149
- | `/doc-inject list` | List all registered docs and their injection status |
150
- | `/doc-inject reset` | Reset all injected flags (docs become re-injectable) |
151
- | `/doc-inject status` | Show current injection status and config |
152
- | `/doc-reload` | Re-scan docs folder and rebuild registry |
153
- | `/doc-keywords-gen` | Generate LLM keywords for files without frontmatter (requires `llmKeywords: true` in config) |
154
-
155
- ## Keyword Generation
48
+ - `mode`: `"simple"` (default) or `"keywords"`.
49
+ - `docsPath`: Folder to scan, relative to the project root.
50
+ - `contextThreshold`: Skip injection and notify if current context usage exceeds this percentage, including at the same-run boundary. This checks existing usage rather than estimating the size of the added documents.
51
+ - `include`, `exclude`, `maxFileSize`, and `maxConcurrent` control scanning. Symlinked files are skipped.
156
52
 
157
- When a document has no frontmatter keywords, the extension handles it in two ways:
53
+ ### Keyword mode (opt-in)
158
54
 
159
- ### Heuristic (Automatic)
55
+ 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.
160
56
 
161
- If `autoKeywords` is `true` (default), keywords are generated automatically from:
57
+ 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.
162
58
 
163
- - **Filename parts**: `"api-authentication.md"` → `[api, authentication]`
164
- - **Markdown headings**: `"# Getting Started"` → `[getting, started]`
165
- - **Code symbols**: `"function foo()"` → `[foo]`
59
+ 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.
166
60
 
167
- All keywords are filtered through a stop-word list, lowercased, and capped at 20.
61
+ Example doc:
168
62
 
169
- ### LLM Generation (Manual)
63
+ ```md
64
+ ---
65
+ title: Authentication
66
+ keywords: [auth, login, sign in]
67
+ ---
170
68
 
171
- For better keywords, enable LLM generation in config:
69
+ # Authentication
172
70
 
173
- ```json
174
- {
175
- "autoKeywords": true,
176
- "llmKeywords": true,
177
- "llmBatchSize": 20
178
- }
71
+ Use these project rules...
179
72
  ```
180
73
 
181
- Then run `/doc-keywords-gen [path]` to generate keywords via LLM. Without a path argument, it processes all keyword-less files.
182
-
183
- The LLM reads each file's content and produces 3–10 relevant, searchable keywords per file. Results are saved to the cache and reused on subsequent scans.
184
-
185
- ### Keyword Source Tracking
74
+ If a file has no frontmatter keywords, keyword mode generates search terms from its filename, headings, and code symbols by default. Set `"autoKeywords": false` to disable that fallback. `/doc-keywords-gen [path]` requests LLM-generated keywords when `"llmKeywords": true`; it does not run in simple mode.
186
75
 
187
- The cache stores which method was used for each file's keywords:
188
-
189
- | Source | How set |
190
- | ------------ | ------------------------------------------------ |
191
- | `frontmatter` | Keywords declared in file frontmatter |
192
- | `cache` | Reused from previous scan (mtime match) |
193
- | `heuristic` | Auto-generated from filename/content |
194
- | `llm` | Generated via `/doc-keywords-gen` |
195
-
196
- Use `/doc-inject list` to see each file's keyword source (shown as `[source]` tag).
197
-
198
- ## Injection Lifecycle
199
-
200
- The extension uses a per-session injection model:
201
-
202
- - On `session_start`, the registry scans `docs/` and indexes all valid documents.
203
- - Within a session, once a document is injected, it won't be re-injected automatically.
204
- - Use `/doc-inject reset` to manually reset all flags and allow docs to be injected again.
205
- - Use `/doc-inject list` to see which docs have been injected (✅) and which are pending (⬜).
206
-
207
- ### Injection Timing
208
-
209
- - **User messages**: matched via the `input` event, injected before the assistant
210
- responds — **same turn**, no delay.
211
- - **Assistant streaming**: if the assistant mentions a NEW keyword mid-response,
212
- generation is aborted and restarted with the doc injected immediately.
76
+ ## Commands
213
77
 
214
- ### Injection Mechanism
78
+ | Command | Action |
79
+ | --------------------------------- | -------------------------------------- |
80
+ | `/doc-inject status` | Show enabled state and document counts |
81
+ | `/doc-inject list` | Show documents and injection state |
82
+ | `/doc-inject on`, `off`, `toggle` | Control injection |
83
+ | `/doc-inject reset` | Allow documents to be injected again |
84
+ | `/doc-inject history` | Show saved injection history |
85
+ | `/doc-reload` | Re-scan the docs folder |
86
+ | `/doc-keywords-gen [path]` | Generate keywords in keyword mode only |
215
87
 
216
- On match, the extension returns a `message` field from `before_agent_start`
217
- with `customType: "doc-injector"`. Pi appends this to the session and sends
218
- it to the LLM as part of the conversation. The system prompt is **never**
219
- mutated.
88
+ ### Injection history
220
89
 
221
- #### Why a CustomMessage, not the system prompt?
90
+ `/doc-inject history` shows the latest 20 document records from the current native session branch. Use `/doc-inject history 5` for a positive count or `/doc-inject history all` for the full history. The output includes how many entries are shown out of the total. There is no keyboard shortcut; the slash command is the convenient entry point.
222
91
 
223
- - The system prompt is the highest-value prompt-cache slot. Each unique
224
- system prompt text breaks the cache (5-min TTL by default). Appending
225
- per-turn doc content there would invalidate the cache on every first
226
- injection.
227
- - A `CustomMessage` only adds to the conversation prefix, leaving the
228
- system prompt byte-identical across turns and the cache warm.
92
+ The history is newest-first and has one record per document in each saved injection message. It shows the session entry's UTC persistence timestamp, relative document path, matching mode, keyword source (`filename`, `frontmatter`, `cache`, `llm`, or `heuristic`), matched terms grouped by `input` or `assistant` (text/thinking), injection boundary (`before_agent_start` or `turn_end`), and optional `turnIndex`.
229
93
 
230
- #### Double-injection prevention
94
+ 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.
231
95
 
232
- Two independent guards make duplicate injection impossible in a session:
96
+ ## Documentation authoring skill
233
97
 
234
- 1. **Matcher guard** — `buildMatcher()` only includes non-injected entries
235
- (via `getNonInjectedEntries()`), so already-injected docs cannot be
236
- re-matched.
237
- 2. **Mark guard** — `markInjected()` runs inside `before_agent_start` before
238
- the LLM call, so even if the matcher ever produced a duplicate, the
239
- mark would still prevent a second send.
98
+ The repository includes `skills/doc-authoring/SKILL.md` for creating and
99
+ validating docs folders. It defaults to top-level filename matching, supports
100
+ opt-in keyword mode, and checks file eligibility, sizes, links, and runtime
101
+ registration without resetting injection state automatically.
240
102
 
241
- In practice, the matcher guard is the primary defense; the mark guard is
242
- defense-in-depth for race conditions (e.g. if `resources_discover` rebuilds
243
- the registry mid-injection).
103
+ To install it globally from a repository checkout:
244
104
 
245
- The `injected` flag is per-session: it's reset on `session_start` and can
246
- be manually cleared with `/doc-inject reset`.
105
+ ```bash
106
+ mkdir -p ~/.pi/agent/skills/doc-authoring
107
+ cp skills/doc-authoring/SKILL.md ~/.pi/agent/skills/doc-authoring/SKILL.md
108
+ ```
247
109
 
248
- For the full source-level verification, see the JSDoc block in `index.ts`.
110
+ Run `/reload` in an active Pi session, then use
111
+ `/skill:doc-authoring create or validate this project's docs folder`.
249
112
 
250
113
  ## Development
251
114
 
252
115
  ```bash
253
- # Run tests
254
116
  npm test
255
-
256
- # Run tests in watch mode
257
- npm run test:watch
117
+ npm run typecheck
118
+ npm run format:check
258
119
  ```
259
120
 
121
+ The runtime glob filter uses `minimatch`. Pi supplies the required
122
+ `@earendil-works/pi-coding-agent` and `typebox` peer APIs; local development
123
+ installs them as dev dependencies, and tests run with Vitest 4.1.12. Its current
124
+ Vite 8.3.8 toolchain resolves vulnerable `picomatch@4.0.7`
125
+ (GHSA-fc5q-39xc-vjpf); npm audit also flags the related `tinyglobby`, `fdir`,
126
+ Vite, and Vitest development-graph nodes. This is dev-only, not the runtime glob
127
+ engine; no patched picomatch release is available.
128
+
129
+ 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.
130
+
131
+ Injection marks live in memory. Reloading the extension rebuilds this state; it does not reconstruct marks from saved or compacted history.
132
+
133
+ Pi commits returned messages and boundary entries after the handler returns and has no extension callback for successful persistence. The extension marks files immediately before returning a prepared injection; another extension rejecting or replacing the boundary proposal can therefore leave a file marked without its content being saved. `/doc-inject reset` allows retrying it.
134
+
260
135
  ## License
261
136
 
262
137
  MIT
package/audit.ts ADDED
@@ -0,0 +1,186 @@
1
+ import type { KeywordSource } from "./types";
2
+
3
+ export type InjectionBoundary = "before_agent_start" | "turn_end";
4
+ export type InjectionMatchSource = "input" | "assistant";
5
+
6
+ export interface InjectionTrigger {
7
+ source: InjectionMatchSource;
8
+ matchedKeywords: string[];
9
+ }
10
+
11
+ export interface InjectionAuditDocument {
12
+ relativePath: string;
13
+ keywordSource: KeywordSource;
14
+ triggers: InjectionTrigger[];
15
+ }
16
+
17
+ export interface InjectionAuditDetails {
18
+ version: 1;
19
+ mode: "simple" | "keywords";
20
+ boundary: InjectionBoundary;
21
+ turnIndex?: number;
22
+ documents: InjectionAuditDocument[];
23
+ }
24
+
25
+ export interface InjectionHistoryRecord {
26
+ timestamp: string;
27
+ entryId: string;
28
+ mode: "simple" | "keywords";
29
+ boundary: InjectionBoundary;
30
+ turnIndex?: number;
31
+ relativePath: string;
32
+ keywordSource: KeywordSource;
33
+ triggers: InjectionTrigger[];
34
+ }
35
+
36
+ export interface InjectionHistory {
37
+ records: InjectionHistoryRecord[];
38
+ unavailableMessages: number;
39
+ }
40
+
41
+ function isKeywordSource(value: unknown): value is KeywordSource {
42
+ return (
43
+ value === "filename" ||
44
+ value === "frontmatter" ||
45
+ value === "heuristic" ||
46
+ value === "llm" ||
47
+ value === "cache"
48
+ );
49
+ }
50
+
51
+ function isRecord(value: unknown): value is Record<string, unknown> {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
54
+
55
+ function isNonemptyString(value: unknown): value is string {
56
+ return typeof value === "string" && value.trim().length > 0;
57
+ }
58
+
59
+ function formatTimestamp(value: unknown): string | null {
60
+ let milliseconds: number;
61
+ if (typeof value === "number" && Number.isFinite(value)) {
62
+ milliseconds = value;
63
+ } else if (typeof value === "string" && value.trim().length > 0) {
64
+ milliseconds = Date.parse(value);
65
+ } else {
66
+ return null;
67
+ }
68
+
69
+ if (!Number.isFinite(milliseconds)) return null;
70
+ const date = new Date(milliseconds);
71
+ if (!Number.isFinite(date.getTime())) return null;
72
+ return date.toISOString();
73
+ }
74
+
75
+ function readDetails(value: unknown): InjectionAuditDetails | null {
76
+ if (!isRecord(value)) return null;
77
+ if (value.version !== 1) return null;
78
+ if (value.mode !== "simple" && value.mode !== "keywords") return null;
79
+ if (value.boundary !== "before_agent_start" && value.boundary !== "turn_end")
80
+ return null;
81
+
82
+ const hasTurnIndex = Object.prototype.hasOwnProperty.call(value, "turnIndex");
83
+ let turnIndex: number | undefined;
84
+ if (hasTurnIndex) {
85
+ const candidate = value.turnIndex;
86
+ if (
87
+ value.boundary !== "turn_end" ||
88
+ typeof candidate !== "number" ||
89
+ !Number.isInteger(candidate) ||
90
+ candidate < 0
91
+ )
92
+ return null;
93
+ turnIndex = candidate;
94
+ }
95
+
96
+ if (!Array.isArray(value.documents) || value.documents.length === 0)
97
+ return null;
98
+
99
+ const documents: InjectionAuditDocument[] = [];
100
+ const rawDocuments: unknown[] = value.documents;
101
+ for (const rawDocument of rawDocuments) {
102
+ if (!isRecord(rawDocument)) return null;
103
+ if (!isNonemptyString(rawDocument.relativePath)) return null;
104
+ if (!isKeywordSource(rawDocument.keywordSource)) return null;
105
+ if (
106
+ !Array.isArray(rawDocument.triggers) ||
107
+ rawDocument.triggers.length === 0
108
+ )
109
+ return null;
110
+
111
+ const triggers: InjectionTrigger[] = [];
112
+ const rawTriggers: unknown[] = rawDocument.triggers;
113
+ for (const rawTrigger of rawTriggers) {
114
+ if (!isRecord(rawTrigger)) return null;
115
+ if (rawTrigger.source !== "input" && rawTrigger.source !== "assistant")
116
+ return null;
117
+ if (!Array.isArray(rawTrigger.matchedKeywords)) return null;
118
+ const matchedKeywords: string[] = [];
119
+ const rawKeywords: unknown[] = rawTrigger.matchedKeywords;
120
+ for (const keyword of rawKeywords) {
121
+ if (!isNonemptyString(keyword)) return null;
122
+ matchedKeywords.push(keyword);
123
+ }
124
+ if (matchedKeywords.length === 0) return null;
125
+ triggers.push({
126
+ source: rawTrigger.source,
127
+ matchedKeywords,
128
+ });
129
+ }
130
+
131
+ documents.push({
132
+ relativePath: rawDocument.relativePath,
133
+ keywordSource: rawDocument.keywordSource,
134
+ triggers,
135
+ });
136
+ }
137
+
138
+ return {
139
+ version: 1,
140
+ mode: value.mode,
141
+ boundary: value.boundary,
142
+ ...(turnIndex !== undefined ? { turnIndex } : {}),
143
+ documents,
144
+ };
145
+ }
146
+
147
+ /** Read structured injection metadata from the native current-branch entries. */
148
+ export function readInjectionHistory(
149
+ entries: readonly unknown[],
150
+ ): InjectionHistory {
151
+ const records: InjectionHistoryRecord[] = [];
152
+ let unavailableMessages = 0;
153
+
154
+ for (const entry of entries) {
155
+ if (
156
+ !isRecord(entry) ||
157
+ entry.type !== "custom_message" ||
158
+ entry.customType !== "doc-injector"
159
+ )
160
+ continue;
161
+
162
+ const timestamp = formatTimestamp(entry.timestamp);
163
+ const details = readDetails(entry.details);
164
+ if (!timestamp || !isNonemptyString(entry.id) || !details) {
165
+ unavailableMessages++;
166
+ continue;
167
+ }
168
+
169
+ for (const document of details.documents) {
170
+ records.push({
171
+ timestamp,
172
+ entryId: entry.id,
173
+ mode: details.mode,
174
+ boundary: details.boundary,
175
+ ...(details.turnIndex !== undefined
176
+ ? { turnIndex: details.turnIndex }
177
+ : {}),
178
+ relativePath: document.relativePath,
179
+ keywordSource: document.keywordSource,
180
+ triggers: document.triggers,
181
+ });
182
+ }
183
+ }
184
+
185
+ return { records, unavailableMessages };
186
+ }
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";
@@ -22,7 +27,10 @@ const CACHE_VERSION = 1;
22
27
  * Recoverable issues (corrupt JSON, wrong version) emit a warning via the
23
28
  * `notifier`. ENOENT (no cache file yet) is silent.
24
29
  */
25
- export async function loadCache(cwd: string, notifier: Notifier): Promise<KeywordCache> {
30
+ export async function loadCache(
31
+ cwd: string,
32
+ notifier: Notifier,
33
+ ): Promise<KeywordCache> {
26
34
  const cachePath = join(cwd, CACHE_FILENAME);
27
35
 
28
36
  try {
@@ -41,7 +49,9 @@ export async function loadCache(cwd: string, notifier: Notifier): Promise<Keywor
41
49
  // ENOENT = no cache file yet, that's fine
42
50
  if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
43
51
  const detail = err instanceof Error ? err.message : String(err);
44
- notifier.warn(`[doc-injector] Failed to read cache at ${cachePath}: ${detail}`);
52
+ notifier.warn(
53
+ `[doc-injector] Failed to read cache at ${cachePath}: ${detail}`,
54
+ );
45
55
  }
46
56
  return emptyCache();
47
57
  }
@@ -66,13 +76,51 @@ export async function saveCache(
66
76
  await writeFile(cachePath, JSON.stringify(cache, null, 2), "utf-8");
67
77
  }
68
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
+
69
104
  /** Check that a parsed value matches the KeywordCache shape. */
70
105
  function isValidCache(value: unknown): value is KeywordCache {
71
- if (!value || typeof value !== "object") return false;
106
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
72
107
  const c = value as Record<string, unknown>;
73
108
  if (c.version !== CACHE_VERSION) return false;
74
- if (!c.files || typeof c.files !== "object") return false;
75
- return true;
109
+ if (!c.files || typeof c.files !== "object" || Array.isArray(c.files)) {
110
+ return false;
111
+ }
112
+ return Object.values(c.files).every((entry) => {
113
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
114
+ return false;
115
+ }
116
+ const record = entry as Record<string, unknown>;
117
+ return (
118
+ typeof record.mtimeMs === "number" &&
119
+ Number.isFinite(record.mtimeMs) &&
120
+ Array.isArray(record.keywords) &&
121
+ record.keywords.every((keyword) => typeof keyword === "string")
122
+ );
123
+ });
76
124
  }
77
125
 
78
126
  /** Return a fresh empty cache. */