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/commands.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  /**
2
2
  * Slash commands for the Doc Injector extension.
3
3
  */
4
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import type {
5
+ ExtensionAPI,
6
+ ExtensionContext,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { readInjectionHistory } from "./audit";
9
+ import { formatInjectionHistory } from "./injector";
5
10
  import type { DocRegistry } from "./registry";
6
11
  import type { DocInjectorConfig } from "./types";
7
12
 
@@ -12,7 +17,9 @@ export interface CommandDeps {
12
17
  setEnabled: (v: boolean) => void;
13
18
  reloadRegistry: () => Promise<number>;
14
19
  getConfig: () => DocInjectorConfig;
15
- generateKeywordsLLM: (files: Array<{ path: string; snippet: string; existingKeywords: string[] }>) => Promise<void>;
20
+ generateKeywordsLLM: (
21
+ files: Array<{ path: string; snippet: string; existingKeywords: string[] }>,
22
+ ) => Promise<void>;
16
23
  }
17
24
 
18
25
  /**
@@ -20,132 +27,188 @@ export interface CommandDeps {
20
27
  *
21
28
  * Commands:
22
29
  * - `/doc-inject [on|off|toggle|list|reset|status]` — manage injection state
30
+ * - `/doc-inject history [count|all]` — inspect saved injection history
23
31
  * - `/doc-reload` — re-scan docs folder
24
32
  * - `/doc-keywords-gen [path]` — generate LLM keywords for keyword-less files
25
33
  */
26
34
  export function registerCommands(pi: ExtensionAPI, deps: CommandDeps): void {
27
- const cmd = (name: string, desc: string, handler: (args: string, ctx: ExtensionContext) => Promise<void>) => {
35
+ const cmd = (
36
+ name: string,
37
+ desc: string,
38
+ handler: (args: string, ctx: ExtensionContext) => Promise<void>,
39
+ ) => {
28
40
  pi.registerCommand(name, { description: desc, handler });
29
41
  };
30
42
 
31
- cmd("doc-inject", "Doc injector: on|off|toggle|list|reset|status", async (args, ctx) => {
32
- const a = args.trim().toLowerCase();
33
- if (a === "on") {
34
- deps.setEnabled(true);
35
- ctx.ui.notify("📄 Doc injection enabled", "info");
36
- } else if (a === "off") {
37
- deps.setEnabled(false);
38
- ctx.ui.notify("📄 Doc injection disabled", "warning");
39
- } else if (a === "toggle") {
40
- const next = !deps.getEnabled();
41
- deps.setEnabled(next);
42
- ctx.ui.notify(`📄 Doc injection ${next ? "enabled" : "disabled"}`, "info");
43
- } else if (a === "reset") {
44
- const reg = deps.getRegistry();
45
- if (reg) {
46
- reg.markAllNotInjected();
47
- ctx.ui.notify("📄 Injection state reset", "info");
48
- } else {
49
- ctx.ui.notify("📄 No registry loaded", "warning");
50
- }
51
- } else if (a === "list") {
52
- const reg = deps.getRegistry();
53
- if (!reg) {
54
- ctx.ui.notify("📄 No docs loaded", "warning");
43
+ cmd(
44
+ "doc-inject",
45
+ "Doc injector: on|off|toggle|list|reset|status|history [count|all]",
46
+ async (args, ctx) => {
47
+ const a = args.trim().toLowerCase();
48
+ if (/^history(?:\s|$)/.test(a)) {
49
+ const requested = a.slice("history".length).trim();
50
+ let limit: number | "all" = 20;
51
+ if (requested === "all") {
52
+ limit = "all";
53
+ } else if (requested) {
54
+ const count = /^\d+$/.test(requested) ? Number(requested) : NaN;
55
+ if (!Number.isSafeInteger(count) || count <= 0) {
56
+ ctx.ui.notify(
57
+ "Usage: /doc-inject history [count|all] (count must be a positive safe integer)",
58
+ "warning",
59
+ );
60
+ return;
61
+ }
62
+ limit = count;
63
+ }
64
+ const history = readInjectionHistory(ctx.sessionManager.getBranch());
65
+ ctx.ui.notify(formatInjectionHistory(history, limit), "info");
55
66
  return;
56
67
  }
57
- const entries = reg.getEntries();
58
- if (entries.length === 0) {
59
- ctx.ui.notify("📄 No documents found in docs folder", "info");
60
- return;
68
+ if (a === "on") {
69
+ deps.setEnabled(true);
70
+ ctx.ui.notify("📄 Doc injection enabled", "info");
71
+ } else if (a === "off") {
72
+ deps.setEnabled(false);
73
+ ctx.ui.notify("📄 Doc injection disabled", "warning");
74
+ } else if (a === "toggle") {
75
+ const next = !deps.getEnabled();
76
+ deps.setEnabled(next);
77
+ ctx.ui.notify(
78
+ `📄 Doc injection ${next ? "enabled" : "disabled"}`,
79
+ "info",
80
+ );
81
+ } else if (a === "reset") {
82
+ const reg = deps.getRegistry();
83
+ if (reg) {
84
+ reg.markAllNotInjected();
85
+ ctx.ui.notify("📄 Injection state reset", "info");
86
+ } else {
87
+ ctx.ui.notify("📄 No registry loaded", "warning");
88
+ }
89
+ } else if (a === "list") {
90
+ const reg = deps.getRegistry();
91
+ if (!reg) {
92
+ ctx.ui.notify("📄 No docs loaded", "warning");
93
+ return;
94
+ }
95
+ const entries = reg.getEntries();
96
+ if (entries.length === 0) {
97
+ ctx.ui.notify("📄 No documents found in docs folder", "info");
98
+ return;
99
+ }
100
+ const lines = entries.map((e) => {
101
+ const status = e.injected ? "✅" : "⬜";
102
+ const sourceTag = `[${e.keywordSource}]`;
103
+ return `${status} ${sourceTag} ${e.relativePath}: "${e.title}" — keywords: [${e.keywords.join(", ")}]`;
104
+ });
105
+ ctx.ui.notify(`📄 Registered docs:\n${lines.join("\n")}`, "info");
106
+ } else {
107
+ // status (default)
108
+ const reg = deps.getRegistry();
109
+ if (!reg) {
110
+ ctx.ui.notify("📄 Status: No registry loaded", "warning");
111
+ return;
112
+ }
113
+ const entries = reg.getEntries();
114
+ const injected = entries.filter((e) => e.injected).length;
115
+ const kwCount = entries.reduce((sum, e) => sum + e.keywords.length, 0);
116
+ ctx.ui.notify(
117
+ `📄 Doc Injector Status:\n` +
118
+ ` Enabled: ${deps.getEnabled() ? "✅" : "❌"}\n` +
119
+ ` Docs: ${entries.length}\n` +
120
+ ` Keywords: ${kwCount}\n` +
121
+ ` Injected: ${injected}`,
122
+ "info",
123
+ );
61
124
  }
62
- const lines = entries.map((e) => {
63
- const status = e.injected ? "✅" : "⬜";
64
- const sourceTag = `[${e.keywordSource}]`;
65
- return `${status} ${sourceTag} ${e.relativePath}: "${e.title}" — keywords: [${e.keywords.join(", ")}]`;
66
- });
67
- ctx.ui.notify(`📄 Registered docs:\n${lines.join("\n")}`, "info");
68
- } else {
69
- // status (default)
125
+ },
126
+ );
127
+
128
+ cmd(
129
+ "doc-reload",
130
+ "Re-scan docs folder and rebuild registry",
131
+ async (_args, ctx) => {
132
+ try {
133
+ const count = await deps.reloadRegistry();
134
+ ctx.ui.notify(`📄 Reloaded: ${count} documents found`, "info");
135
+ } catch (err) {
136
+ ctx.ui.notify(
137
+ `📄 Reload failed: ${err instanceof Error ? err.message : String(err)}`,
138
+ "error",
139
+ );
140
+ }
141
+ },
142
+ );
143
+
144
+ cmd(
145
+ "doc-keywords-gen",
146
+ "Generate LLM keywords: /doc-keywords-gen [path] — no arg = all keyword-less files",
147
+ async (args, ctx) => {
70
148
  const reg = deps.getRegistry();
71
149
  if (!reg) {
72
- ctx.ui.notify("📄 Status: No registry loaded", "warning");
150
+ ctx.ui.notify("📄 No registry loaded", "warning");
73
151
  return;
74
152
  }
75
- const entries = reg.getEntries();
76
- const injected = entries.filter((e) => e.injected).length;
77
- const kwCount = entries.reduce((sum, e) => sum + e.keywords.length, 0);
78
- ctx.ui.notify(
79
- `📄 Doc Injector Status:\n` +
80
- ` Enabled: ${deps.getEnabled() ? "✅" : "❌"}\n` +
81
- ` Docs: ${entries.length}\n` +
82
- ` Keywords: ${kwCount}\n` +
83
- ` Injected: ${injected}`,
84
- "info",
85
- );
86
- }
87
- });
88
153
 
89
- cmd("doc-reload", "Re-scan docs folder and rebuild registry", async (_args, ctx) => {
90
- try {
91
- const count = await deps.reloadRegistry();
92
- ctx.ui.notify(`📄 Reloaded: ${count} documents found`, "info");
93
- } catch (err) {
94
- ctx.ui.notify(`📄 Reload failed: ${err instanceof Error ? err.message : String(err)}`, "error");
95
- }
96
- });
97
-
98
- cmd("doc-keywords-gen", "Generate LLM keywords: /doc-keywords-gen [path] — no arg = all keyword-less files", async (args, ctx) => {
99
- const reg = deps.getRegistry();
100
- if (!reg) {
101
- ctx.ui.notify("📄 No registry loaded", "warning");
102
- return;
103
- }
154
+ const config = deps.getConfig();
155
+ if (config.mode !== "keywords" || !config.llmKeywords) {
156
+ ctx.ui.notify(
157
+ "📄 LLM keyword generation requires mode: keywords and llmKeywords: true",
158
+ "warning",
159
+ );
160
+ return;
161
+ }
104
162
 
105
- const config = deps.getConfig();
106
- if (!config.llmKeywords) {
107
- ctx.ui.notify("📄 LLM keyword generation is disabled (llmKeywords: false in config)", "warning");
108
- return;
109
- }
163
+ const targetPath = args.trim();
110
164
 
111
- const targetPath = args.trim();
165
+ // Filter to keyword-less entries (keywordSource !== "frontmatter", "cache", or "llm")
166
+ let candidates = reg.getEntries().filter((e) => {
167
+ if (e.keywordSource === "frontmatter") return false;
168
+ if (e.keywordSource === "cache") return false;
169
+ if (e.keywordSource === "llm") return false; // already LLM-generated
170
+ return true;
171
+ });
112
172
 
113
- // Filter to keyword-less entries (keywordSource !== "frontmatter", "cache", or "llm")
114
- let candidates = reg.getEntries().filter((e) => {
115
- if (e.keywordSource === "frontmatter") return false;
116
- if (e.keywordSource === "cache") return false;
117
- if (e.keywordSource === "llm") return false; // already LLM-generated
118
- return true;
119
- });
173
+ if (targetPath) {
174
+ candidates = candidates.filter((e) =>
175
+ e.relativePath.includes(targetPath),
176
+ );
177
+ if (candidates.length === 0) {
178
+ ctx.ui.notify(
179
+ `📄 No keyword-less files matching "${targetPath}"`,
180
+ "info",
181
+ );
182
+ return;
183
+ }
184
+ }
120
185
 
121
- if (targetPath) {
122
- candidates = candidates.filter((e) => e.relativePath.includes(targetPath));
123
186
  if (candidates.length === 0) {
124
- ctx.ui.notify(`📄 No keyword-less files matching "${targetPath}"`, "info");
187
+ ctx.ui.notify("📄 All files already have keywords", "info");
125
188
  return;
126
189
  }
127
- }
128
190
 
129
- if (candidates.length === 0) {
130
- ctx.ui.notify("📄 All files already have keywords", "info");
131
- return;
132
- }
133
-
134
- const batchSize = config.llmBatchSize;
135
- const batches: Array<Array<{ path: string; snippet: string; existingKeywords: string[] }>> = [];
136
- for (let i = 0; i < candidates.length; i += batchSize) {
137
- const batch = candidates.slice(i, i + batchSize).map((e) => ({
138
- path: e.relativePath,
139
- snippet: e.content.slice(0, 500),
140
- existingKeywords: e.keywords,
141
- }));
142
- batches.push(batch);
143
- }
191
+ const batchSize = config.llmBatchSize;
192
+ const batches: Array<
193
+ Array<{ path: string; snippet: string; existingKeywords: string[] }>
194
+ > = [];
195
+ for (let i = 0; i < candidates.length; i += batchSize) {
196
+ const batch = candidates.slice(i, i + batchSize).map((e) => ({
197
+ path: e.relativePath,
198
+ snippet: e.content.slice(0, 500),
199
+ existingKeywords: e.keywords,
200
+ }));
201
+ batches.push(batch);
202
+ }
144
203
 
145
- ctx.ui.notify(`📄 Sending ${batches.length} keyword-generation batch(es) for ${candidates.length} file(s)...`, "info");
204
+ ctx.ui.notify(
205
+ `📄 Sending ${batches.length} keyword-generation batch(es) for ${candidates.length} file(s)...`,
206
+ "info",
207
+ );
146
208
 
147
- for (const batch of batches) {
148
- await deps.generateKeywordsLLM(batch);
149
- }
150
- });
209
+ for (const batch of batches) {
210
+ await deps.generateKeywordsLLM(batch);
211
+ }
212
+ },
213
+ );
151
214
  }
package/config.ts CHANGED
@@ -13,23 +13,25 @@ import type { Notifier } from "./notifier";
13
13
  * if not a number.
14
14
  */
15
15
  function clampInt(
16
- value: unknown,
17
- defaultVal: number,
18
- min: number,
19
- max: number,
20
- fieldName: string,
21
- notifier: Notifier,
16
+ value: unknown,
17
+ defaultVal: number,
18
+ min: number,
19
+ max: number,
20
+ fieldName: string,
21
+ notifier: Notifier,
22
22
  ): number {
23
- if (typeof value !== "number" || Number.isNaN(value)) {
24
- return defaultVal;
25
- }
26
- const intVal = Math.trunc(value);
27
- if (intVal < min || intVal > max) {
28
- const clamped = Math.max(min, Math.min(max, intVal));
29
- notifier.warn(`[doc-injector] ${fieldName} must be ${min}-${max}, got ${intVal}. Clamping to ${clamped}.`);
30
- return clamped;
31
- }
32
- return intVal;
23
+ if (typeof value !== "number" || !Number.isFinite(value)) {
24
+ return defaultVal;
25
+ }
26
+ const intVal = Math.trunc(value);
27
+ if (intVal < min || intVal > max) {
28
+ const clamped = Math.max(min, Math.min(max, intVal));
29
+ notifier.warn(
30
+ `[doc-injector] ${fieldName} must be ${min}-${max}, got ${intVal}. Clamping to ${clamped}.`,
31
+ );
32
+ return clamped;
33
+ }
34
+ return intVal;
33
35
  }
34
36
 
35
37
  /**
@@ -38,22 +40,33 @@ function clampInt(
38
40
  * Warns via the `notifier` for non-string entries.
39
41
  */
40
42
  function validateGlobArray(
41
- value: unknown,
42
- defaultVal: string[],
43
- notifier: Notifier,
43
+ value: unknown,
44
+ defaultVal: string[],
45
+ notifier: Notifier,
44
46
  ): string[] {
45
- if (!Array.isArray(value)) {
46
- return [...defaultVal];
47
+ if (!Array.isArray(value)) {
48
+ return [...defaultVal];
49
+ }
50
+ const result: string[] = [];
51
+ for (const item of value) {
52
+ if (typeof item === "string") {
53
+ result.push(item);
54
+ } else {
55
+ notifier.warn(
56
+ `[doc-injector] Non-string entry in glob array ignored: ${String(item)}`,
57
+ );
47
58
  }
48
- const result: string[] = [];
49
- for (const item of value) {
50
- if (typeof item === "string") {
51
- result.push(item);
52
- } else {
53
- notifier.warn(`[doc-injector] Non-string entry in glob array ignored: ${String(item)}`);
54
- }
55
- }
56
- return result.length > 0 ? result : [...defaultVal];
59
+ }
60
+ return result;
61
+ }
62
+
63
+ /** Keep invalid config values from reaching filesystem and matching code. */
64
+ function validString(value: unknown, fallback: string): string {
65
+ return typeof value === "string" && value.trim() ? value : fallback;
66
+ }
67
+
68
+ function validBoolean(value: unknown, fallback: boolean): boolean {
69
+ return typeof value === "boolean" ? value : fallback;
57
70
  }
58
71
 
59
72
  /**
@@ -62,32 +75,98 @@ function validateGlobArray(
62
75
  * fields. Falls back to DEFAULT_CONFIG if the file doesn't exist or is
63
76
  * invalid. Warnings (clamping, invalid entries) go through the `notifier`.
64
77
  */
65
- export async function loadConfig(cwd: string, notifier: Notifier): Promise<DocInjectorConfig> {
66
- const configPath = join(cwd, ".pi", "doc-injector.json");
78
+ export async function loadConfig(
79
+ cwd: string,
80
+ notifier: Notifier,
81
+ ): Promise<DocInjectorConfig> {
82
+ const configPath = join(cwd, ".pi", "doc-injector.json");
67
83
 
68
- try {
69
- const raw = await readFile(configPath, "utf-8");
70
- const parsed = JSON.parse(raw) as Partial<DocInjectorConfig>;
84
+ try {
85
+ const raw = await readFile(configPath, "utf-8");
86
+ const value: unknown = JSON.parse(raw);
87
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
88
+ throw new Error("Config must be an object");
89
+ }
90
+ const parsed = value as Partial<DocInjectorConfig>;
71
91
 
72
- return {
73
- docsPath: parsed.docsPath ?? DEFAULT_CONFIG.docsPath,
74
- matchThreshold: clampInt(parsed.matchThreshold, DEFAULT_CONFIG.matchThreshold, 1, Infinity, "matchThreshold", notifier),
75
- streamWindowSize: clampInt(parsed.streamWindowSize, DEFAULT_CONFIG.streamWindowSize, 0, Infinity, "streamWindowSize", notifier),
76
- contextThreshold: clampInt(parsed.contextThreshold, DEFAULT_CONFIG.contextThreshold, 0, 100, "contextThreshold", notifier),
77
- recursive: parsed.recursive ?? DEFAULT_CONFIG.recursive,
78
- include: validateGlobArray(parsed.include, DEFAULT_CONFIG.include, notifier),
79
- exclude: validateGlobArray(parsed.exclude, DEFAULT_CONFIG.exclude, notifier),
80
- maxFileSize: clampInt(parsed.maxFileSize, DEFAULT_CONFIG.maxFileSize, 1024, 10 * 1024 * 1024, "maxFileSize", notifier),
81
- autoKeywords: parsed.autoKeywords ?? DEFAULT_CONFIG.autoKeywords,
82
- llmKeywords: parsed.llmKeywords ?? DEFAULT_CONFIG.llmKeywords,
83
- maxConcurrent: clampInt(parsed.maxConcurrent, DEFAULT_CONFIG.maxConcurrent, 1, 100, "maxConcurrent", notifier),
84
- llmBatchSize: clampInt(parsed.llmBatchSize, DEFAULT_CONFIG.llmBatchSize, 1, 100, "llmBatchSize", notifier),
85
- };
86
- } catch (err) {
87
- if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
88
- const detail = err instanceof Error ? err.message : String(err);
89
- notifier.warn(`[doc-injector] Failed to parse config at ${configPath}: ${detail}`);
90
- }
91
- return { ...DEFAULT_CONFIG };
92
+ return {
93
+ mode:
94
+ parsed.mode === "simple" || parsed.mode === "keywords"
95
+ ? parsed.mode
96
+ : DEFAULT_CONFIG.mode,
97
+ docsPath: validString(parsed.docsPath, DEFAULT_CONFIG.docsPath),
98
+ matchThreshold: clampInt(
99
+ parsed.matchThreshold,
100
+ DEFAULT_CONFIG.matchThreshold,
101
+ 1,
102
+ Infinity,
103
+ "matchThreshold",
104
+ notifier,
105
+ ),
106
+ streamWindowSize: clampInt(
107
+ parsed.streamWindowSize,
108
+ DEFAULT_CONFIG.streamWindowSize,
109
+ 0,
110
+ Infinity,
111
+ "streamWindowSize",
112
+ notifier,
113
+ ),
114
+ contextThreshold: clampInt(
115
+ parsed.contextThreshold,
116
+ DEFAULT_CONFIG.contextThreshold,
117
+ 0,
118
+ 100,
119
+ "contextThreshold",
120
+ notifier,
121
+ ),
122
+ recursive: validBoolean(parsed.recursive, DEFAULT_CONFIG.recursive),
123
+ include: validateGlobArray(
124
+ parsed.include,
125
+ DEFAULT_CONFIG.include,
126
+ notifier,
127
+ ),
128
+ exclude: validateGlobArray(
129
+ parsed.exclude,
130
+ DEFAULT_CONFIG.exclude,
131
+ notifier,
132
+ ),
133
+ maxFileSize: clampInt(
134
+ parsed.maxFileSize,
135
+ DEFAULT_CONFIG.maxFileSize,
136
+ 1024,
137
+ 10 * 1024 * 1024,
138
+ "maxFileSize",
139
+ notifier,
140
+ ),
141
+ autoKeywords: validBoolean(
142
+ parsed.autoKeywords,
143
+ DEFAULT_CONFIG.autoKeywords,
144
+ ),
145
+ llmKeywords: validBoolean(parsed.llmKeywords, DEFAULT_CONFIG.llmKeywords),
146
+ maxConcurrent: clampInt(
147
+ parsed.maxConcurrent,
148
+ DEFAULT_CONFIG.maxConcurrent,
149
+ 1,
150
+ 100,
151
+ "maxConcurrent",
152
+ notifier,
153
+ ),
154
+ llmBatchSize: clampInt(
155
+ parsed.llmBatchSize,
156
+ DEFAULT_CONFIG.llmBatchSize,
157
+ 1,
158
+ 100,
159
+ "llmBatchSize",
160
+ notifier,
161
+ ),
162
+ };
163
+ } catch (err) {
164
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
165
+ const detail = err instanceof Error ? err.message : String(err);
166
+ notifier.warn(
167
+ `[doc-injector] Failed to parse config at ${configPath}: ${detail}`,
168
+ );
92
169
  }
170
+ return { ...DEFAULT_CONFIG };
171
+ }
93
172
  }