@leolastforce/chalice-code-index 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +58 -2
- package/index.ts +1 -0
- package/package.json +48 -5
- package/src/chunking.ts +305 -0
- package/src/config.ts +245 -0
- package/src/embeddings.ts +130 -0
- package/src/filtering.ts +221 -0
- package/src/index.ts +480 -0
- package/src/indexer.ts +153 -0
- package/src/project.ts +76 -0
- package/src/section.ts +159 -0
- package/src/store.ts +208 -0
- package/src/tagging.ts +247 -0
- package/src/tool.ts +146 -0
- package/src/types.ts +146 -0
- package/src/ui.ts +45 -0
- package/src/watcher.ts +168 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { clearIndex, loadManifest, manifestCompatible } from "./store.ts";
|
|
3
|
+
import { buildTagResolver, computeTagStats, EMPTY_TAGS_HELP, formatDeclaredTags, listDeclaredTags } from "./tagging.ts";
|
|
4
|
+
import { getProjectInfo } from "./project.ts";
|
|
5
|
+
import {
|
|
6
|
+
describeCredentials,
|
|
7
|
+
loadGlobalConfig,
|
|
8
|
+
loadProjectState,
|
|
9
|
+
loadStoredApiKey,
|
|
10
|
+
PROVIDER_PRESETS,
|
|
11
|
+
resolveConfig,
|
|
12
|
+
saveGlobalConfig,
|
|
13
|
+
saveProjectState,
|
|
14
|
+
saveStoredApiKey,
|
|
15
|
+
} from "./config.ts";
|
|
16
|
+
import { estimateIndex, incrementalRefresh, reindexProject, removeNonIndexableFiles, type ProgressUpdate } from "./indexer.ts";
|
|
17
|
+
import { estimateChunksForFile } from "./chunking.ts";
|
|
18
|
+
import type { IndexEstimate, Manifest, ProviderId, ResolvedConfig } from "./types.ts";
|
|
19
|
+
import { listIndexableFiles, readSourceFile } from "./filtering.ts";
|
|
20
|
+
import { registerTools } from "./tool.ts";
|
|
21
|
+
import { confirmEstimate, estimateText, updateFooter } from "./ui.ts";
|
|
22
|
+
import { registerCodeIndexSettings } from "./section.ts";
|
|
23
|
+
import { CodeIndexWatcher } from "./watcher.ts";
|
|
24
|
+
import type { ProjectInfo, RuntimeStatus } from "./types.ts";
|
|
25
|
+
|
|
26
|
+
const MIN_INDEXING_STATUS_MS = 500;
|
|
27
|
+
|
|
28
|
+
export default function codeIndexExtension(pi: ExtensionAPI): void {
|
|
29
|
+
registerCodeIndexSettings(pi);
|
|
30
|
+
let watcher: CodeIndexWatcher | undefined;
|
|
31
|
+
let status: RuntimeStatus = { state: "off" };
|
|
32
|
+
let indexingStatusSince: number | undefined;
|
|
33
|
+
let readyStatusTimer: NodeJS.Timeout | undefined;
|
|
34
|
+
let sessionGeneration = 0;
|
|
35
|
+
let sessionActive = false;
|
|
36
|
+
|
|
37
|
+
function isStaleContextError(error: unknown): boolean {
|
|
38
|
+
return error instanceof Error && error.message.includes("This extension ctx is stale");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function shouldApplyStatus(generation: number): boolean {
|
|
42
|
+
return sessionActive && generation === sessionGeneration;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function clearReadyStatusTimer(): void {
|
|
46
|
+
if (readyStatusTimer) clearTimeout(readyStatusTimer);
|
|
47
|
+
readyStatusTimer = undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function applyStatus(ctx: ExtensionContext, next: RuntimeStatus): void {
|
|
51
|
+
status = next;
|
|
52
|
+
try {
|
|
53
|
+
updateFooter(ctx, status);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (isStaleContextError(error)) return;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function setStatus(ctx: ExtensionContext, next: RuntimeStatus, generation = sessionGeneration): void {
|
|
61
|
+
if (!shouldApplyStatus(generation)) return;
|
|
62
|
+
if (next.state === "indexing") {
|
|
63
|
+
clearReadyStatusTimer();
|
|
64
|
+
indexingStatusSince = Date.now();
|
|
65
|
+
applyStatus(ctx, next);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (next.state === "ready" && status.state === "indexing" && indexingStatusSince !== undefined) {
|
|
70
|
+
const remainingMs = MIN_INDEXING_STATUS_MS - (Date.now() - indexingStatusSince);
|
|
71
|
+
if (remainingMs > 0) {
|
|
72
|
+
clearReadyStatusTimer();
|
|
73
|
+
readyStatusTimer = setTimeout(() => {
|
|
74
|
+
readyStatusTimer = undefined;
|
|
75
|
+
if (!shouldApplyStatus(generation)) return;
|
|
76
|
+
indexingStatusSince = undefined;
|
|
77
|
+
applyStatus(ctx, next);
|
|
78
|
+
}, remainingMs);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
clearReadyStatusTimer();
|
|
84
|
+
indexingStatusSince = undefined;
|
|
85
|
+
applyStatus(ctx, next);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function computeStatus(project: ProjectInfo): Promise<RuntimeStatus> {
|
|
89
|
+
const { project: state, resolved } = await resolveConfig(project);
|
|
90
|
+
if (!project.safe) return { state: "error", lastError: project.reason, message: project.reason };
|
|
91
|
+
if (!state.enabled) return { state: "off" };
|
|
92
|
+
const manifest = await loadManifest(project);
|
|
93
|
+
if (!manifest) return { state: "not-indexed" };
|
|
94
|
+
const compatible = manifestCompatible(manifest, resolved);
|
|
95
|
+
if (!compatible.ok) return { state: "stale", message: compatible.reason };
|
|
96
|
+
return { state: "ready", chunks: manifest.chunkCount };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function stopWatcher(): Promise<void> {
|
|
100
|
+
if (watcher) await watcher.stop();
|
|
101
|
+
watcher = undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function startWatcher(ctx: ExtensionContext, project: ProjectInfo, generation = sessionGeneration): Promise<void> {
|
|
105
|
+
await stopWatcher();
|
|
106
|
+
if (!shouldApplyStatus(generation)) return;
|
|
107
|
+
const { resolved } = await resolveConfig(project);
|
|
108
|
+
if (!shouldApplyStatus(generation)) return;
|
|
109
|
+
const nextWatcher = new CodeIndexWatcher(project, resolved, {
|
|
110
|
+
onIndexing: (path) => setStatus(ctx, { state: "indexing", message: path }, generation),
|
|
111
|
+
onReady: async () => setStatus(ctx, await computeStatus(project), generation),
|
|
112
|
+
onBulkPending: (count) => setStatus(ctx, { state: "bulk-pending", message: `${count} changes pending · run /index update` }, generation),
|
|
113
|
+
onError: (error) => setStatus(ctx, { state: "error", lastError: error instanceof Error ? error.message : String(error) }, generation),
|
|
114
|
+
});
|
|
115
|
+
watcher = nextWatcher;
|
|
116
|
+
await nextWatcher.start();
|
|
117
|
+
if (!shouldApplyStatus(generation)) await nextWatcher.stop();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function pendingIndexChanges(
|
|
121
|
+
project: ProjectInfo,
|
|
122
|
+
config: ResolvedConfig,
|
|
123
|
+
manifest: Manifest,
|
|
124
|
+
): Promise<{ count: number; indexableFiles: string[] }> {
|
|
125
|
+
const indexableFiles = await listIndexableFiles(project, config);
|
|
126
|
+
const indexableSet = new Set(indexableFiles);
|
|
127
|
+
const pending = new Set<string>();
|
|
128
|
+
for (const path of Object.keys(manifest.files)) {
|
|
129
|
+
if (!indexableSet.has(path)) pending.add(path);
|
|
130
|
+
}
|
|
131
|
+
for (const path of indexableFiles) {
|
|
132
|
+
const source = await readSourceFile(project, path, config);
|
|
133
|
+
const entry = manifest.files[path];
|
|
134
|
+
if (!source) {
|
|
135
|
+
if (entry) pending.add(path);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (!entry || entry.fileHash !== source.fileHash) pending.add(path);
|
|
139
|
+
}
|
|
140
|
+
return { count: pending.size, indexableFiles };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function runIncrementalUpdate(
|
|
144
|
+
ctx: ExtensionContext,
|
|
145
|
+
project: ProjectInfo,
|
|
146
|
+
config: ResolvedConfig,
|
|
147
|
+
signal: AbortSignal | undefined,
|
|
148
|
+
indexableFiles?: string[],
|
|
149
|
+
generation = sessionGeneration,
|
|
150
|
+
): Promise<Manifest | undefined> {
|
|
151
|
+
const manifest = await loadManifest(project);
|
|
152
|
+
if (!manifest) return undefined;
|
|
153
|
+
const files = indexableFiles ?? (await listIndexableFiles(project, config));
|
|
154
|
+
await removeNonIndexableFiles(project, manifest, new Set(files));
|
|
155
|
+
return incrementalRefresh(project, config, signal, (p: ProgressUpdate) =>
|
|
156
|
+
setStatus(ctx, { state: "indexing", filesDone: p.filesDone, filesTotal: p.filesTotal, chunks: p.chunks, message: "updating" }, generation),
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function reconcileOnSessionStart(ctx: ExtensionContext, project: ProjectInfo, generation: number, signal: AbortSignal | undefined): Promise<void> {
|
|
161
|
+
const { resolved } = await resolveConfig(project);
|
|
162
|
+
if (!shouldApplyStatus(generation)) return;
|
|
163
|
+
const manifest = await loadManifest(project);
|
|
164
|
+
const compatible = manifestCompatible(manifest, resolved);
|
|
165
|
+
if (!manifest || !compatible.ok) return;
|
|
166
|
+
const pending = await pendingIndexChanges(project, resolved, manifest);
|
|
167
|
+
if (!shouldApplyStatus(generation) || pending.count === 0) return;
|
|
168
|
+
if (pending.count > resolved.watcherBulkThreshold) {
|
|
169
|
+
watcher?.markBulkPending(pending.count);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (!resolved.apiKeyPresent && resolved.provider !== "local") {
|
|
173
|
+
setStatus(ctx, { state: "error", lastError: `Missing API key: ${describeCredentials(resolved)}` }, generation);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
setStatus(ctx, { state: "indexing", message: "startup update" }, generation);
|
|
177
|
+
const refreshed = await runIncrementalUpdate(ctx, project, resolved, signal, pending.indexableFiles, generation);
|
|
178
|
+
if (!shouldApplyStatus(generation)) return;
|
|
179
|
+
watcher?.clearPending();
|
|
180
|
+
setStatus(ctx, { state: "ready", chunks: refreshed?.chunkCount ?? manifest.chunkCount }, generation);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function showStatus(ctx: ExtensionContext): Promise<void> {
|
|
184
|
+
const project = await getProjectInfo(ctx.cwd);
|
|
185
|
+
const { project: state, resolved } = await resolveConfig(project);
|
|
186
|
+
const manifest = await loadManifest(project);
|
|
187
|
+
const compatible = manifestCompatible(manifest, resolved);
|
|
188
|
+
const lines = [
|
|
189
|
+
`Project: ${project.root}`,
|
|
190
|
+
`Safe: ${project.safe ? "yes" : `no (${project.reason})`}`,
|
|
191
|
+
`Enabled: ${state.enabled ? "yes" : "no"}`,
|
|
192
|
+
`Provider: ${resolved.provider}`,
|
|
193
|
+
`Model: ${resolved.model}`,
|
|
194
|
+
`Base URL: ${resolved.baseUrl}`,
|
|
195
|
+
`API key: ${describeCredentials(resolved)}`,
|
|
196
|
+
`Index: ${manifest ? `${manifest.fileCount} files, ${manifest.chunkCount} chunks, dim ${manifest.embeddingDim}` : "not built"}`,
|
|
197
|
+
`Compatibility: ${compatible.ok ? "ok" : compatible.reason}`,
|
|
198
|
+
state.lastError ? `Last error: ${state.lastError}` : undefined,
|
|
199
|
+
].filter(Boolean);
|
|
200
|
+
ctx.ui.notify(lines.join("\n"), compatible.ok || !manifest ? "info" : "warning");
|
|
201
|
+
setStatus(ctx, await computeStatus(project));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function runReindex(ctx: ExtensionContext, project: ProjectInfo, forceConfirm = false): Promise<void> {
|
|
205
|
+
const { resolved } = await resolveConfig(project);
|
|
206
|
+
if (!resolved.apiKeyPresent && resolved.provider !== "local") throw new Error(`Missing API key: ${describeCredentials(resolved)}`);
|
|
207
|
+
const estimate = await estimateIndex(project, resolved);
|
|
208
|
+
const needsConfirm = forceConfirm || estimate.chunks >= resolved.largeRepoConfirmChunks;
|
|
209
|
+
const ok = await confirmEstimate(ctx, estimate, needsConfirm);
|
|
210
|
+
if (!ok) {
|
|
211
|
+
ctx.ui.notify("Indexing cancelled", "info");
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
setStatus(ctx, { state: "indexing", filesDone: 0, filesTotal: estimate.files, chunks: 0 });
|
|
215
|
+
const manifest = await reindexProject(project, resolved, ctx.signal, (p: ProgressUpdate) => {
|
|
216
|
+
setStatus(ctx, { state: "indexing", filesDone: p.filesDone, filesTotal: p.filesTotal, chunks: p.chunks, message: p.phase });
|
|
217
|
+
});
|
|
218
|
+
setStatus(ctx, { state: "ready", chunks: manifest.chunkCount });
|
|
219
|
+
ctx.ui.notify(`Code index ready: ${manifest.fileCount} files, ${manifest.chunkCount} chunks`, "info");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function runOnboardingSetup(ctx: ExtensionContext): Promise<void> {
|
|
223
|
+
if (!ctx.hasUI) {
|
|
224
|
+
ctx.ui.notify("Semantic indexing setup requires an interactive session", "error");
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const providers: Array<{ id: Exclude<ProviderId, "custom">; label: string }> = [
|
|
229
|
+
{ id: "voyage", label: `${PROVIDER_PRESETS.voyage.label} (recommended)` },
|
|
230
|
+
{ id: "openrouter", label: PROVIDER_PRESETS.openrouter.label },
|
|
231
|
+
{ id: "local", label: `${PROVIDER_PRESETS.local.label} (no API key)` },
|
|
232
|
+
];
|
|
233
|
+
const skipLabel = "Skip semantic indexing for now";
|
|
234
|
+
const choice = await ctx.ui.select(
|
|
235
|
+
"Step 3/3 - Semantic file indexing provider (optional but highly recommended) It's basically a smart file search that saves context memory, time, and increases preciseness. It's really useful and often overlooked.",
|
|
236
|
+
[...providers.map((provider) => provider.label), skipLabel],
|
|
237
|
+
);
|
|
238
|
+
const provider = providers.find((option) => option.label === choice)?.id;
|
|
239
|
+
if (!provider) {
|
|
240
|
+
ctx.ui.notify("Semantic indexing setup skipped. You can run /index onboarding later.", "info");
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const preset = PROVIDER_PRESETS[provider];
|
|
245
|
+
if (provider !== "local") {
|
|
246
|
+
const envKey = preset.apiKeyEnv ? process.env[preset.apiKeyEnv]?.trim() : undefined;
|
|
247
|
+
const storedKey = await loadStoredApiKey(provider);
|
|
248
|
+
if (!envKey && !storedKey) {
|
|
249
|
+
const key = await ctx.ui.input(
|
|
250
|
+
`${preset.label} API key (saved to pi's auth.json; leave empty to skip):`,
|
|
251
|
+
);
|
|
252
|
+
if (!key?.trim()) {
|
|
253
|
+
ctx.ui.notify("No API key entered; semantic indexing setup skipped.", "info");
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
await saveStoredApiKey(provider, key);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const current = await loadGlobalConfig();
|
|
261
|
+
await saveGlobalConfig({
|
|
262
|
+
...current,
|
|
263
|
+
provider,
|
|
264
|
+
baseUrl: undefined,
|
|
265
|
+
model: undefined,
|
|
266
|
+
apiKeyEnv: undefined,
|
|
267
|
+
embeddingDim: undefined,
|
|
268
|
+
pricePerMillionTokens: undefined,
|
|
269
|
+
});
|
|
270
|
+
const keyStatus =
|
|
271
|
+
provider === "local"
|
|
272
|
+
? "no API key required"
|
|
273
|
+
: preset.apiKeyEnv && process.env[preset.apiKeyEnv]
|
|
274
|
+
? `${preset.apiKeyEnv} environment variable`
|
|
275
|
+
: "key saved in pi auth.json";
|
|
276
|
+
ctx.ui.notify(
|
|
277
|
+
`Semantic indexing configured for ${preset.label} (${keyStatus}). Run /index on to build the index.`,
|
|
278
|
+
"info",
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
pi.registerCommand("index", {
|
|
283
|
+
description: "Manage semantic code index: onboarding|status|on|off|update|reindex|clear|config|tags|help",
|
|
284
|
+
handler: async (args, ctx) => {
|
|
285
|
+
const sub = (args || "status").trim().split(/\s+/)[0] || "status";
|
|
286
|
+
const project = await getProjectInfo(ctx.cwd);
|
|
287
|
+
try {
|
|
288
|
+
if (sub === "status") return showStatus(ctx);
|
|
289
|
+
if (sub === "onboarding") {
|
|
290
|
+
await runOnboardingSetup(ctx);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (sub === "config") {
|
|
294
|
+
ctx.ui.notify("HELLO FELLOW HUMAN. The index settings are in /chalicesettings or if you don't have the chalice settings extension, see settings.json and go to the chalice doc. WHY would you not get the original extension if you are using this standalone? no-one will ever know. Unless you like chalice branding of course, nice. Okkk cya!");
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
if (!project.safe) throw new Error(project.reason ?? "unsafe project root");
|
|
298
|
+
const state = await loadProjectState(project);
|
|
299
|
+
if (sub === "off") {
|
|
300
|
+
await saveProjectState(project, { ...state, enabled: false });
|
|
301
|
+
await stopWatcher();
|
|
302
|
+
setStatus(ctx, { state: "off" });
|
|
303
|
+
ctx.ui.notify("Code index disabled for this project", "info");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (sub === "clear") {
|
|
307
|
+
await clearIndex(project);
|
|
308
|
+
setStatus(ctx, state.enabled ? { state: "not-indexed" } : { state: "off" });
|
|
309
|
+
ctx.ui.notify("Code index cleared", "info");
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (sub === "on") {
|
|
313
|
+
if (!state.dataEgressConfirmed) {
|
|
314
|
+
const { resolved } = await resolveConfig(project);
|
|
315
|
+
if (resolved.provider !== "local") {
|
|
316
|
+
if (!ctx.hasUI) throw new Error("First /index on requires interactive confirmation because source code will be sent to the embedding provider.");
|
|
317
|
+
const ok = await ctx.ui.confirm("Code indexing data egress", `Indexing sends source-code chunks to ${resolved.provider} (${resolved.baseUrl}) for embeddings. Secret-pattern files are skipped. Continue?`);
|
|
318
|
+
if (!ok) return;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
await saveProjectState(project, { ...state, enabled: true, dataEgressConfirmed: true, lastError: undefined });
|
|
322
|
+
await stopWatcher(); // stop any watcher from a prior session/enable before touching the index
|
|
323
|
+
const { resolved } = await resolveConfig(project);
|
|
324
|
+
const manifest = await loadManifest(project);
|
|
325
|
+
const compatible = manifestCompatible(manifest, resolved);
|
|
326
|
+
if (!manifest || !compatible.ok) {
|
|
327
|
+
await runReindex(ctx, project, !manifest);
|
|
328
|
+
} else {
|
|
329
|
+
// Existing compatible index: reconcile files changed while pi was closed.
|
|
330
|
+
// Incremental (only changed files re-embed) — never a full reindex on enable.
|
|
331
|
+
setStatus(ctx, { state: "indexing", message: "reconciling" });
|
|
332
|
+
const refreshed = await incrementalRefresh(project, resolved, ctx.signal, (p: ProgressUpdate) => setStatus(ctx, { state: "indexing", filesDone: p.filesDone, filesTotal: p.filesTotal, chunks: p.chunks, message: "reconciling" }));
|
|
333
|
+
setStatus(ctx, { state: "ready", chunks: refreshed?.chunkCount ?? manifest.chunkCount });
|
|
334
|
+
ctx.ui.notify("Code index enabled; reconciled, watcher running", "info");
|
|
335
|
+
}
|
|
336
|
+
await startWatcher(ctx, project); // start only after (re)build/reconcile so it cannot race the rebuild
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (sub === "reindex") {
|
|
340
|
+
await saveProjectState(project, { ...state, enabled: true, lastError: undefined });
|
|
341
|
+
await stopWatcher(); // stop any prior watcher before clearIndex wipes the index dir
|
|
342
|
+
await runReindex(ctx, project, true);
|
|
343
|
+
await startWatcher(ctx, project); // start after the rebuild completes
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
if (sub === "update") {
|
|
347
|
+
const manifest = await loadManifest(project);
|
|
348
|
+
if (!manifest) {
|
|
349
|
+
ctx.ui.notify("No index found. Run /index reindex first.", "error");
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const { resolved } = await resolveConfig(project);
|
|
353
|
+
const compatible = manifestCompatible(manifest, resolved);
|
|
354
|
+
if (!compatible.ok) {
|
|
355
|
+
ctx.ui.notify(`Index is stale (${compatible.reason}). Run /index reindex.`, "error");
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
// Phase 1 (free): remove chunks for files that are no longer indexable
|
|
359
|
+
setStatus(ctx, { state: "indexing", message: "pruning removed/excluded files" });
|
|
360
|
+
const indexableFiles = await listIndexableFiles(project, resolved);
|
|
361
|
+
const indexableSet = new Set(indexableFiles);
|
|
362
|
+
const removed = await removeNonIndexableFiles(project, manifest, indexableSet);
|
|
363
|
+
// Phase 2: compute the real incremental embed cost (new + hash-changed files)
|
|
364
|
+
const freshManifest = await loadManifest(project) ?? manifest;
|
|
365
|
+
// Identify files that actually need embedding: new (not in manifest) or content-changed.
|
|
366
|
+
const toEmbedPaths: string[] = [];
|
|
367
|
+
for (const p of indexableFiles) {
|
|
368
|
+
const source = await readSourceFile(project, p, resolved);
|
|
369
|
+
if (!source) continue;
|
|
370
|
+
const entry = freshManifest.files[p];
|
|
371
|
+
if (!entry || entry.fileHash !== source.fileHash) toEmbedPaths.push(p);
|
|
372
|
+
}
|
|
373
|
+
if (toEmbedPaths.length > 0) {
|
|
374
|
+
if (!resolved.apiKeyPresent && resolved.provider !== "local") {
|
|
375
|
+
throw new Error(`Missing API key env ${resolved.apiKeyEnv}`);
|
|
376
|
+
}
|
|
377
|
+
// Accumulate real incremental chunks/tokens/cost for the files that need embedding.
|
|
378
|
+
let incChunks = 0;
|
|
379
|
+
let incTokens = 0;
|
|
380
|
+
for (const p of toEmbedPaths) {
|
|
381
|
+
const source = await readSourceFile(project, p, resolved);
|
|
382
|
+
if (!source) continue;
|
|
383
|
+
const est = await estimateChunksForFile(source, project.root, resolved);
|
|
384
|
+
incChunks += est.chunks.length;
|
|
385
|
+
incTokens += est.tokens;
|
|
386
|
+
}
|
|
387
|
+
const incCost = resolved.pricePerMillionTokens === undefined ? undefined : (incTokens / 1_000_000) * resolved.pricePerMillionTokens;
|
|
388
|
+
const incEstimate: IndexEstimate = { files: toEmbedPaths.length, chunks: incChunks, estimatedTokens: incTokens, estimatedCost: incCost, model: resolved.model, baseUrl: resolved.baseUrl };
|
|
389
|
+
// Align with reindex confirmation threshold: chunks (not file count) vs largeRepoConfirmChunks.
|
|
390
|
+
const needsConfirm = incChunks >= resolved.largeRepoConfirmChunks;
|
|
391
|
+
const ok = await confirmEstimate(ctx, incEstimate, needsConfirm);
|
|
392
|
+
if (!ok) {
|
|
393
|
+
ctx.ui.notify(`Update cancelled. Removed ${removed} files' chunks (free).`, "info");
|
|
394
|
+
setStatus(ctx, await computeStatus(project));
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
setStatus(ctx, { state: "indexing", message: "embedding new/changed files" });
|
|
399
|
+
const refreshed = await incrementalRefresh(project, resolved, ctx.signal, (p: ProgressUpdate) =>
|
|
400
|
+
setStatus(ctx, { state: "indexing", filesDone: p.filesDone, filesTotal: p.filesTotal, chunks: p.chunks, message: "updating" }),
|
|
401
|
+
);
|
|
402
|
+
// Clear bulk-pending flag now that the index is up to date
|
|
403
|
+
if (watcher) watcher.clearPending();
|
|
404
|
+
setStatus(ctx, { state: "ready", chunks: refreshed?.chunkCount ?? freshManifest.chunkCount });
|
|
405
|
+
ctx.ui.notify(`removed ${removed} chunks (free) · embedded ${toEmbedPaths.length} files`, "info");
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (sub === "tags") {
|
|
409
|
+
const { resolved: tagsResolved } = await resolveConfig(project);
|
|
410
|
+
const tagMap = await listDeclaredTags(project.root, new Set(tagsResolved.excludeDirs));
|
|
411
|
+
if (tagMap.size === 0) {
|
|
412
|
+
ctx.ui.notify(EMPTY_TAGS_HELP, "info");
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const manifest = await loadManifest(project);
|
|
416
|
+
const filePaths = manifest ? Object.keys(manifest.files) : [];
|
|
417
|
+
const tagResolver = await buildTagResolver(project.root, new Set(tagsResolved.excludeDirs));
|
|
418
|
+
const stats = computeTagStats(filePaths, (p) => tagResolver.resolveTags(p));
|
|
419
|
+
ctx.ui.notify(formatDeclaredTags(tagMap, stats), "info");
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
if (sub === "help") {
|
|
423
|
+
const helpText = [
|
|
424
|
+
"/index subcommands:",
|
|
425
|
+
" onboarding — choose a semantic indexing provider and API key (optional)",
|
|
426
|
+
" status — show index state, file/chunk counts, config",
|
|
427
|
+
" on — enable indexing for this project (builds index if needed)",
|
|
428
|
+
" off — disable indexing and stop watcher",
|
|
429
|
+
" update — incremental sync: removes excluded/deleted chunks (free), embeds new/changed files (with cost confirmation)",
|
|
430
|
+
" reindex — full rebuild from scratch (always confirms cost)",
|
|
431
|
+
" clear — wipe the index without disabling",
|
|
432
|
+
" config — open settings wizard",
|
|
433
|
+
" tags — list all tags declared in .index_tag files (read-only, no reindex needed)",
|
|
434
|
+
" help — show this message",
|
|
435
|
+
"",
|
|
436
|
+
"Ignore layers (most authoritative first):",
|
|
437
|
+
" 1. git (all four layers: .gitignore, nested .gitignore, core.excludesFile, .git/info/exclude)",
|
|
438
|
+
" 2. .indexignore — project-local extra excludes for the code index",
|
|
439
|
+
" 3. .contextignore — shared context exclusions",
|
|
440
|
+
" 4. excludeDirs config — built-in directory exclusions",
|
|
441
|
+
"",
|
|
442
|
+
"Use .indexignore to narrow what gets indexed without touching git ignore rules.",
|
|
443
|
+
].join("\n");
|
|
444
|
+
ctx.ui.notify(helpText, "info");
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
ctx.ui.notify(`Unknown /index subcommand: ${sub}. Run /index help for usage.`, "error");
|
|
448
|
+
} catch (error) {
|
|
449
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
450
|
+
const state = await loadProjectState(project).catch(() => ({ enabled: false }));
|
|
451
|
+
await saveProjectState(project, { ...state, lastError: message }).catch(() => undefined);
|
|
452
|
+
setStatus(ctx, { state: "error", lastError: message });
|
|
453
|
+
ctx.ui.notify(`Code index error: ${message}`, "error");
|
|
454
|
+
}
|
|
455
|
+
},
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
registerTools(pi);
|
|
459
|
+
|
|
460
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
461
|
+
const generation = ++sessionGeneration;
|
|
462
|
+
sessionActive = true;
|
|
463
|
+
const signal = ctx.signal;
|
|
464
|
+
const project = await getProjectInfo(ctx.cwd);
|
|
465
|
+
const state = await loadProjectState(project);
|
|
466
|
+
setStatus(ctx, await computeStatus(project), generation);
|
|
467
|
+
if (project.safe && state.enabled) {
|
|
468
|
+
await startWatcher(ctx, project, generation);
|
|
469
|
+
await reconcileOnSessionStart(ctx, project, generation, signal);
|
|
470
|
+
}
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
pi.on("session_shutdown", async () => {
|
|
474
|
+
sessionActive = false;
|
|
475
|
+
sessionGeneration++;
|
|
476
|
+
clearReadyStatusTimer();
|
|
477
|
+
indexingStatusSince = undefined;
|
|
478
|
+
await stopWatcher();
|
|
479
|
+
});
|
|
480
|
+
}
|
package/src/indexer.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import type { IndexEstimate, Manifest, ProjectInfo, ResolvedConfig } from "./types.ts";
|
|
3
|
+
import { INDEX_VERSION } from "./types.ts";
|
|
4
|
+
import { chunkSourceFile, estimateChunksForFile, estimateTokens } from "./chunking.ts";
|
|
5
|
+
import { embedTexts } from "./embeddings.ts";
|
|
6
|
+
import { listIndexableFiles, readSourceFile } from "./filtering.ts";
|
|
7
|
+
import { clearIndex, deleteFileChunks, getFileChunkVectors, loadManifest, manifestCompatible, maybeBuildAnnIndex, newManifest, saveManifest, upsertFileChunks } from "./store.ts";
|
|
8
|
+
|
|
9
|
+
export interface ProgressUpdate {
|
|
10
|
+
filesDone: number;
|
|
11
|
+
filesTotal: number;
|
|
12
|
+
chunks: number;
|
|
13
|
+
phase: "scanning" | "embedding" | "writing" | "done";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function estimateIndex(project: ProjectInfo, config: ResolvedConfig): Promise<IndexEstimate> {
|
|
17
|
+
const files = await listIndexableFiles(project, config);
|
|
18
|
+
let chunks = 0;
|
|
19
|
+
let estimatedTokens = 0;
|
|
20
|
+
for (const path of files) {
|
|
21
|
+
const source = await readSourceFile(project, path, config);
|
|
22
|
+
if (!source) continue;
|
|
23
|
+
const est = await estimateChunksForFile(source, project.root, config);
|
|
24
|
+
chunks += est.chunks.length;
|
|
25
|
+
estimatedTokens += est.tokens;
|
|
26
|
+
}
|
|
27
|
+
const estimatedCost = config.pricePerMillionTokens === undefined ? undefined : (estimatedTokens / 1_000_000) * config.pricePerMillionTokens;
|
|
28
|
+
return { files: files.length, chunks, estimatedTokens, estimatedCost, model: config.model, baseUrl: config.baseUrl };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function reindexProject(project: ProjectInfo, config: ResolvedConfig, signal?: AbortSignal, onProgress?: (p: ProgressUpdate) => void): Promise<Manifest> {
|
|
32
|
+
await clearIndex(project);
|
|
33
|
+
const files = await listIndexableFiles(project, config);
|
|
34
|
+
let manifest: Manifest | undefined;
|
|
35
|
+
let filesDone = 0;
|
|
36
|
+
let chunksDone = 0;
|
|
37
|
+
onProgress?.({ filesDone, filesTotal: files.length, chunks: chunksDone, phase: "scanning" });
|
|
38
|
+
for (const path of files) {
|
|
39
|
+
if (signal?.aborted) throw new Error("indexing aborted");
|
|
40
|
+
const source = await readSourceFile(project, path, config);
|
|
41
|
+
if (!source) {
|
|
42
|
+
filesDone++;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const chunks = await chunkSourceFile(source, project.root, config);
|
|
46
|
+
if (chunks.length === 0) {
|
|
47
|
+
filesDone++;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
onProgress?.({ filesDone, filesTotal: files.length, chunks: chunksDone, phase: "embedding" });
|
|
51
|
+
const embedded = await embedTexts(config, chunks.map((c) => c.embeddedText), signal, "document");
|
|
52
|
+
manifest ??= newManifest(project, config, embedded.dimension);
|
|
53
|
+
if (manifest.embeddingDim && manifest.embeddingDim !== embedded.dimension) throw new Error(`embedding dimension changed: ${embedded.dimension} != ${manifest.embeddingDim}`);
|
|
54
|
+
manifest.embeddingDim = embedded.dimension;
|
|
55
|
+
const withVectors = chunks.map((c, i) => ({ ...c, vector: embedded.vectors[i] }));
|
|
56
|
+
if (withVectors.some((c) => !c.vector || c.vector.length !== embedded.dimension)) throw new Error(`internal: incomplete vector set for ${path}`);
|
|
57
|
+
onProgress?.({ filesDone, filesTotal: files.length, chunks: chunksDone, phase: "writing" });
|
|
58
|
+
await upsertFileChunks(project, withVectors, manifest);
|
|
59
|
+
// Checkpoint after every completed file so a later provider error can resume via /index on.
|
|
60
|
+
await saveManifest(project, manifest);
|
|
61
|
+
filesDone++;
|
|
62
|
+
chunksDone += chunks.length;
|
|
63
|
+
onProgress?.({ filesDone, filesTotal: files.length, chunks: chunksDone, phase: "embedding" });
|
|
64
|
+
}
|
|
65
|
+
manifest ??= newManifest(project, config, config.embeddingDim ?? 0);
|
|
66
|
+
manifest.version = INDEX_VERSION;
|
|
67
|
+
await maybeBuildAnnIndex(project, manifest, config);
|
|
68
|
+
await saveManifest(project, manifest);
|
|
69
|
+
onProgress?.({ filesDone, filesTotal: files.length, chunks: chunksDone, phase: "done" });
|
|
70
|
+
return manifest;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function updateChangedFile(project: ProjectInfo, config: ResolvedConfig, relPath: string, signal?: AbortSignal): Promise<Manifest | undefined> {
|
|
74
|
+
const manifest = await loadManifest(project);
|
|
75
|
+
const compatible = manifestCompatible(manifest, config);
|
|
76
|
+
if (!manifest || !compatible.ok) return manifest;
|
|
77
|
+
const source = await readSourceFile(project, relPath, config);
|
|
78
|
+
if (!source) {
|
|
79
|
+
await deleteFileChunks(project, relPath, manifest);
|
|
80
|
+
await saveManifest(project, manifest);
|
|
81
|
+
return manifest;
|
|
82
|
+
}
|
|
83
|
+
const prev = manifest.files[relPath];
|
|
84
|
+
if (prev?.fileHash === source.fileHash) return manifest;
|
|
85
|
+
const chunks = await chunkSourceFile(source, project.root, config);
|
|
86
|
+
if (chunks.length === 0) {
|
|
87
|
+
await deleteFileChunks(project, relPath, manifest);
|
|
88
|
+
await saveManifest(project, manifest);
|
|
89
|
+
return manifest;
|
|
90
|
+
}
|
|
91
|
+
// Reuse vectors of chunks whose content is unchanged; only embed the ones that actually changed.
|
|
92
|
+
const cached = await getFileChunkVectors(project, relPath);
|
|
93
|
+
const vectors = new Array<number[]>(chunks.length);
|
|
94
|
+
const missing: number[] = [];
|
|
95
|
+
chunks.forEach((c, i) => {
|
|
96
|
+
const hit = cached.get(c.contentHash);
|
|
97
|
+
if (hit && hit.length === manifest.embeddingDim) vectors[i] = hit;
|
|
98
|
+
else missing.push(i);
|
|
99
|
+
});
|
|
100
|
+
if (missing.length > 0) {
|
|
101
|
+
const embedded = await embedTexts(config, missing.map((i) => chunks[i].embeddedText), signal, "document");
|
|
102
|
+
if (embedded.dimension !== manifest.embeddingDim) throw new Error(`embedding dimension ${embedded.dimension} differs from manifest ${manifest.embeddingDim}; run /index reindex`);
|
|
103
|
+
missing.forEach((idx, j) => (vectors[idx] = embedded.vectors[j]));
|
|
104
|
+
}
|
|
105
|
+
if (vectors.some((v) => !v || v.length !== manifest.embeddingDim)) throw new Error(`internal: incomplete vector set for ${relPath}`);
|
|
106
|
+
await deleteFileChunks(project, relPath, manifest);
|
|
107
|
+
await upsertFileChunks(project, chunks.map((c, i) => ({ ...c, vector: vectors[i] })), manifest);
|
|
108
|
+
await saveManifest(project, manifest);
|
|
109
|
+
return manifest;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function removeDeletedFiles(project: ProjectInfo, manifest: Manifest): Promise<Manifest> {
|
|
113
|
+
for (const path of Object.keys(manifest.files)) {
|
|
114
|
+
const exists = await stat(`${project.root}/${path}`).then((s) => s.isFile(), () => false);
|
|
115
|
+
if (!exists) await deleteFileChunks(project, path, manifest);
|
|
116
|
+
}
|
|
117
|
+
await saveManifest(project, manifest);
|
|
118
|
+
return manifest;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Remove chunks for files that are no longer indexable — either disk-deleted or newly excluded by
|
|
122
|
+
// ignore rules. Returns the number of files whose chunks were removed (all free, no embed calls).
|
|
123
|
+
export async function removeNonIndexableFiles(project: ProjectInfo, manifest: Manifest, indexableSet: Set<string>): Promise<number> {
|
|
124
|
+
let removed = 0;
|
|
125
|
+
for (const path of Object.keys(manifest.files)) {
|
|
126
|
+
const stillIndexable = indexableSet.has(path);
|
|
127
|
+
if (!stillIndexable) {
|
|
128
|
+
await deleteFileChunks(project, path, manifest);
|
|
129
|
+
removed++;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
await saveManifest(project, manifest);
|
|
133
|
+
return removed;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function incrementalRefresh(project: ProjectInfo, config: ResolvedConfig, signal?: AbortSignal, onProgress?: (p: ProgressUpdate) => void): Promise<Manifest | undefined> {
|
|
137
|
+
const manifest = await loadManifest(project);
|
|
138
|
+
const compatible = manifestCompatible(manifest, config);
|
|
139
|
+
if (!manifest || !compatible.ok) return manifest;
|
|
140
|
+
const files = await listIndexableFiles(project, config);
|
|
141
|
+
let done = 0;
|
|
142
|
+
for (const path of files) {
|
|
143
|
+
const source = await readSourceFile(project, path, config);
|
|
144
|
+
if (!source) continue;
|
|
145
|
+
if (manifest.files[path]?.fileHash !== source.fileHash) await updateChangedFile(project, config, path, signal);
|
|
146
|
+
done++;
|
|
147
|
+
onProgress?.({ filesDone: done, filesTotal: files.length, chunks: manifest.chunkCount, phase: "embedding" });
|
|
148
|
+
}
|
|
149
|
+
// updateChangedFile re-loads/saves the manifest itself, so the snapshot above is now stale.
|
|
150
|
+
// Reload fresh before pruning deleted files, otherwise this save would clobber those updates.
|
|
151
|
+
const fresh = (await loadManifest(project)) ?? manifest;
|
|
152
|
+
return removeDeletedFiles(project, fresh);
|
|
153
|
+
}
|