pi-doc-injector 0.6.0 → 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/README.md +50 -213
- package/audit.ts +186 -0
- package/cache.ts +23 -5
- package/commands.ts +168 -105
- package/config.ts +134 -55
- package/docs/async-subagent-bug.md +4 -196
- package/docs/publish.md +9 -7
- package/docs/test-md.md +16 -1
- package/docs/workflow-md.md +16 -1
- package/globber.ts +2 -6
- package/index.ts +237 -158
- package/injector.ts +90 -5
- package/keyword-gen.ts +157 -36
- package/keyword-llm.ts +24 -16
- package/matcher.ts +46 -19
- package/notifier.ts +36 -36
- package/package.json +10 -6
- package/picomatch.d.ts +4 -1
- package/registry.ts +92 -53
- package/types.ts +9 -1
package/README.md
CHANGED
|
@@ -1,262 +1,99 @@
|
|
|
1
1
|
# Pi Doc Injector
|
|
2
2
|
|
|
3
|
-
A [Pi](https://pi.dev) extension that
|
|
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
|
-
##
|
|
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
|
-
|
|
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:
|
|
22
|
-
|
|
23
|
-
```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
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
**3. HTML comment** — useful for HTML-generated docs:
|
|
70
|
-
|
|
71
|
-
```md
|
|
72
|
-
<!--
|
|
73
|
-
title: "Testing Workflow"
|
|
74
|
-
keywords: [test, testing, jest, vitest]
|
|
75
|
-
-->
|
|
76
|
-
|
|
77
|
-
# Testing Workflow
|
|
78
|
-
```
|
|
11
|
+
Requires Pi 1.5.2 or newer within the 1.x series.
|
|
79
12
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
```md
|
|
83
|
-
//---
|
|
84
|
-
title: "Testing Workflow"
|
|
85
|
-
keywords: [test, testing, jest, vitest]
|
|
86
|
-
|
|
87
|
-
# Testing Workflow
|
|
88
|
-
```
|
|
13
|
+
## Simple mode (default)
|
|
89
14
|
|
|
90
|
-
|
|
15
|
+
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.
|
|
91
16
|
|
|
92
|
-
|
|
17
|
+
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.
|
|
93
18
|
|
|
94
|
-
|
|
95
|
-
keywords: [test, testing, jest] # flow: comma-separated in brackets
|
|
96
|
-
keywords: # block: one per line
|
|
97
|
-
- test
|
|
98
|
-
- testing
|
|
99
|
-
- jest
|
|
100
|
-
```
|
|
19
|
+
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.
|
|
101
20
|
|
|
102
|
-
|
|
21
|
+
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.
|
|
103
22
|
|
|
104
|
-
|
|
23
|
+
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`.
|
|
105
24
|
|
|
106
|
-
|
|
25
|
+
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
26
|
|
|
108
27
|
## Configuration
|
|
109
28
|
|
|
110
|
-
|
|
29
|
+
Optional `.pi/doc-injector.json` in your project:
|
|
111
30
|
|
|
112
31
|
```json
|
|
113
32
|
{
|
|
33
|
+
"mode": "simple",
|
|
114
34
|
"docsPath": "./docs",
|
|
115
|
-
"
|
|
116
|
-
"streamWindowSize": 500,
|
|
117
|
-
"contextThreshold": 80,
|
|
118
|
-
"recursive": true,
|
|
119
|
-
"autoKeywords": true,
|
|
120
|
-
"llmKeywords": false,
|
|
121
|
-
"llmBatchSize": 20
|
|
35
|
+
"contextThreshold": 80
|
|
122
36
|
}
|
|
123
37
|
```
|
|
124
38
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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
|
|
39
|
+
- `mode`: `"simple"` (default) or `"keywords"`.
|
|
40
|
+
- `docsPath`: Folder to scan, relative to the project root.
|
|
41
|
+
- `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.
|
|
42
|
+
- `include`, `exclude`, `maxFileSize`, and `maxConcurrent` control scanning. Symlinked files are skipped.
|
|
156
43
|
|
|
157
|
-
|
|
44
|
+
### Keyword mode (opt-in)
|
|
158
45
|
|
|
159
|
-
|
|
46
|
+
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
47
|
|
|
161
|
-
|
|
48
|
+
Example doc:
|
|
162
49
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
### LLM Generation (Manual)
|
|
50
|
+
```md
|
|
51
|
+
---
|
|
52
|
+
title: Authentication
|
|
53
|
+
keywords: [auth, login, sign in]
|
|
54
|
+
---
|
|
170
55
|
|
|
171
|
-
|
|
56
|
+
# Authentication
|
|
172
57
|
|
|
173
|
-
|
|
174
|
-
{
|
|
175
|
-
"autoKeywords": true,
|
|
176
|
-
"llmKeywords": true,
|
|
177
|
-
"llmBatchSize": 20
|
|
178
|
-
}
|
|
58
|
+
Use these project rules...
|
|
179
59
|
```
|
|
180
60
|
|
|
181
|
-
|
|
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.
|
|
61
|
+
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.
|
|
184
62
|
|
|
185
|
-
|
|
186
|
-
|
|
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.
|
|
213
|
-
|
|
214
|
-
### Injection Mechanism
|
|
215
|
-
|
|
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.
|
|
220
|
-
|
|
221
|
-
#### Why a CustomMessage, not the system prompt?
|
|
222
|
-
|
|
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.
|
|
229
|
-
|
|
230
|
-
#### Double-injection prevention
|
|
63
|
+
## Commands
|
|
231
64
|
|
|
232
|
-
|
|
65
|
+
| Command | Action |
|
|
66
|
+
| --------------------------------- | -------------------------------------- |
|
|
67
|
+
| `/doc-inject status` | Show enabled state and document counts |
|
|
68
|
+
| `/doc-inject list` | Show documents and injection state |
|
|
69
|
+
| `/doc-inject on`, `off`, `toggle` | Control injection |
|
|
70
|
+
| `/doc-inject reset` | Allow documents to be injected again |
|
|
71
|
+
| `/doc-inject history` | Show saved injection history |
|
|
72
|
+
| `/doc-reload` | Re-scan the docs folder |
|
|
73
|
+
| `/doc-keywords-gen [path]` | Generate keywords in keyword mode only |
|
|
233
74
|
|
|
234
|
-
|
|
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.
|
|
75
|
+
### Injection history
|
|
240
76
|
|
|
241
|
-
|
|
242
|
-
defense-in-depth for race conditions (e.g. if `resources_discover` rebuilds
|
|
243
|
-
the registry mid-injection).
|
|
77
|
+
`/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.
|
|
244
78
|
|
|
245
|
-
The
|
|
246
|
-
be manually cleared with `/doc-inject reset`.
|
|
79
|
+
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`.
|
|
247
80
|
|
|
248
|
-
|
|
81
|
+
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.
|
|
249
82
|
|
|
250
83
|
## Development
|
|
251
84
|
|
|
252
85
|
```bash
|
|
253
|
-
# Run tests
|
|
254
86
|
npm test
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
npm run test:watch
|
|
87
|
+
npm run typecheck
|
|
88
|
+
npm run format:check
|
|
258
89
|
```
|
|
259
90
|
|
|
91
|
+
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
|
+
|
|
93
|
+
Injection marks live in memory. Reloading the extension rebuilds this state; it does not reconstruct marks from saved or compacted history.
|
|
94
|
+
|
|
95
|
+
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.
|
|
96
|
+
|
|
260
97
|
## License
|
|
261
98
|
|
|
262
99
|
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
|
@@ -22,7 +22,10 @@ const CACHE_VERSION = 1;
|
|
|
22
22
|
* Recoverable issues (corrupt JSON, wrong version) emit a warning via the
|
|
23
23
|
* `notifier`. ENOENT (no cache file yet) is silent.
|
|
24
24
|
*/
|
|
25
|
-
export async function loadCache(
|
|
25
|
+
export async function loadCache(
|
|
26
|
+
cwd: string,
|
|
27
|
+
notifier: Notifier,
|
|
28
|
+
): Promise<KeywordCache> {
|
|
26
29
|
const cachePath = join(cwd, CACHE_FILENAME);
|
|
27
30
|
|
|
28
31
|
try {
|
|
@@ -41,7 +44,9 @@ export async function loadCache(cwd: string, notifier: Notifier): Promise<Keywor
|
|
|
41
44
|
// ENOENT = no cache file yet, that's fine
|
|
42
45
|
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
43
46
|
const detail = err instanceof Error ? err.message : String(err);
|
|
44
|
-
notifier.warn(
|
|
47
|
+
notifier.warn(
|
|
48
|
+
`[doc-injector] Failed to read cache at ${cachePath}: ${detail}`,
|
|
49
|
+
);
|
|
45
50
|
}
|
|
46
51
|
return emptyCache();
|
|
47
52
|
}
|
|
@@ -68,11 +73,24 @@ export async function saveCache(
|
|
|
68
73
|
|
|
69
74
|
/** Check that a parsed value matches the KeywordCache shape. */
|
|
70
75
|
function isValidCache(value: unknown): value is KeywordCache {
|
|
71
|
-
if (!value || typeof value !== "object") return false;
|
|
76
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
72
77
|
const c = value as Record<string, unknown>;
|
|
73
78
|
if (c.version !== CACHE_VERSION) return false;
|
|
74
|
-
if (!c.files || typeof c.files !== "object")
|
|
75
|
-
|
|
79
|
+
if (!c.files || typeof c.files !== "object" || Array.isArray(c.files)) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
return Object.values(c.files).every((entry) => {
|
|
83
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
const record = entry as Record<string, unknown>;
|
|
87
|
+
return (
|
|
88
|
+
typeof record.mtimeMs === "number" &&
|
|
89
|
+
Number.isFinite(record.mtimeMs) &&
|
|
90
|
+
Array.isArray(record.keywords) &&
|
|
91
|
+
record.keywords.every((keyword) => typeof keyword === "string")
|
|
92
|
+
);
|
|
93
|
+
});
|
|
76
94
|
}
|
|
77
95
|
|
|
78
96
|
/** Return a fresh empty cache. */
|