@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/src/project.ts ADDED
@@ -0,0 +1,76 @@
1
+ import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
2
+ import { stat } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
4
+ import { basename, dirname, join, parse, resolve } from "node:path";
5
+ import { DATA_DIR } from "./config.ts";
6
+ import type { ProjectInfo } from "./types.ts";
7
+
8
+ const PROJECT_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "deno.json", "bun.lock", "pnpm-lock.yaml", "yarn.lock"];
9
+ const DENY_BASENAMES = new Set(["Desktop", "Documents", "Downloads", "Pictures", "Music", "Movies", "Videos", "Public", "Templates", "Applications", "Library", "System", "Volumes", "Users", "Program Files", "Program Files (x86)", "ProgramData", "Windows", "PerfLogs", "AppData", "OneDrive", "Dropbox", "Google Drive", "iCloud Drive"]);
10
+
11
+ async function exists(path: string): Promise<boolean> {
12
+ try {
13
+ await stat(path);
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ async function hasMarker(dir: string): Promise<boolean> {
21
+ for (const marker of PROJECT_MARKERS) {
22
+ if (await exists(join(dir, marker))) return true;
23
+ }
24
+ return false;
25
+ }
26
+
27
+ export async function findProjectRoot(cwd: string): Promise<string> {
28
+ const start = resolve(cwd);
29
+ const home = process.env.HOME ? resolve(process.env.HOME) : undefined;
30
+ let cur = start;
31
+ while (true) {
32
+ // Never auto-select $HOME (or above) as the root unless pi was literally started there.
33
+ // Otherwise a stray package.json in $HOME hijacks a cwd like ~/Workspace and the safe-root
34
+ // check then refuses the whole thing.
35
+ if (home && cur === home && start !== home) return start;
36
+ if (await hasMarker(cur)) return cur;
37
+ const parent = dirname(cur);
38
+ if (parent === cur) return start;
39
+ cur = parent;
40
+ }
41
+ }
42
+
43
+ export function projectHash(root: string): string {
44
+ return createHash("sha256").update(root).digest("hex").slice(0, 16);
45
+ }
46
+
47
+ export function isSafeProjectRoot(root: string): { safe: boolean; reason?: string } {
48
+ const resolved = resolve(root);
49
+ const parsed = parse(resolved);
50
+ if (resolved === parsed.root) return { safe: false, reason: "refusing to index filesystem root" };
51
+ if (resolved === process.env.HOME) return { safe: false, reason: "refusing to index home directory" };
52
+ if (DENY_BASENAMES.has(basename(resolved))) return { safe: false, reason: `refusing protected directory ${basename(resolved)}` };
53
+ return { safe: true };
54
+ }
55
+
56
+ export async function getProjectInfo(cwd: string): Promise<ProjectInfo> {
57
+ const root = await findProjectRoot(cwd);
58
+ const hash = projectHash(root);
59
+ const projectPi = join(root, CONFIG_DIR_NAME);
60
+ const indexDir = join(DATA_DIR, "indexes", hash);
61
+ const safety = isSafeProjectRoot(root);
62
+ return {
63
+ cwd,
64
+ root,
65
+ hash,
66
+ statePath: join(projectPi, "code-index.json"),
67
+ indexDir,
68
+ manifestPath: join(indexDir, "manifest.json"),
69
+ safe: safety.safe,
70
+ reason: safety.reason,
71
+ };
72
+ }
73
+
74
+ export function relPath(root: string, absPath: string): string {
75
+ return resolve(absPath).slice(resolve(root).length + 1).replaceAll("\\", "/");
76
+ }
package/src/section.ts ADDED
@@ -0,0 +1,159 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type ChaliceCustomSetting,
4
+ type ChaliceSettingsSection,
5
+ registerChaliceSettingsSection,
6
+ } from "@leolastforce/chalice-shared";
7
+ import { INDEX_AFFECTING_KEYS, PROVIDER_PRESETS, readGlobalConfigSync, saveGlobalConfig } from "./config.ts";
8
+ import type { GlobalConfig, ProviderId } from "./types.ts";
9
+
10
+ type NumericKey =
11
+ | "batchSize"
12
+ | "requestConcurrency"
13
+ | "chunkLines"
14
+ | "chunkOverlap"
15
+ | "chunkOverlapChars"
16
+ | "largeRepoConfirmChunks"
17
+ | "annIndexThreshold"
18
+ | "maxChunkChars"
19
+ | "maxFileBytes"
20
+ | "maxTopK"
21
+ | "scoreThreshold"
22
+ | "watcherDebounceMs";
23
+
24
+ type TextKey = "baseUrl" | "model" | "apiKeyEnv";
25
+
26
+ interface NumericField {
27
+ key: NumericKey;
28
+ label: string;
29
+ min: number;
30
+ max?: number;
31
+ integer: boolean;
32
+ }
33
+
34
+ // Everything the old `/index config` wizard exposed, so `/chalicesettings` is at parity with it.
35
+ const NUMERIC_FIELDS: readonly NumericField[] = [
36
+ { key: "maxTopK", label: "Max top-K (search)", min: 1, max: 256, integer: true },
37
+ { key: "scoreThreshold", label: "Score threshold (0=off)", min: 0, max: 1, integer: false },
38
+ { key: "chunkOverlapChars", label: "Chunk overlap chars (0=off)", min: 0, max: 4000, integer: true },
39
+ { key: "maxChunkChars", label: "Max chunk chars", min: 200, max: 60_000, integer: true },
40
+ { key: "chunkLines", label: "Window size (lines)", min: 10, max: 2000, integer: true },
41
+ { key: "chunkOverlap", label: "Window overlap (lines)", min: 0, max: 500, integer: true },
42
+ { key: "requestConcurrency", label: "Request concurrency", min: 1, max: 16, integer: true },
43
+ { key: "batchSize", label: "Embed batch size", min: 1, max: 256, integer: true },
44
+ { key: "watcherDebounceMs", label: "Watcher debounce (ms)", min: 0, max: 60_000, integer: true },
45
+ { key: "largeRepoConfirmChunks", label: "Large-repo confirm (chunks)", min: 0, integer: true },
46
+ { key: "annIndexThreshold", label: "ANN index threshold", min: 0, integer: true },
47
+ { key: "maxFileBytes", label: "Max file bytes", min: 1024, integer: true },
48
+ ];
49
+
50
+ const PROVIDER_IDS = Object.keys(PROVIDER_PRESETS) as ProviderId[];
51
+
52
+ /** Merge a patch over the current file so unrelated keys survive, the same way the wizard saved. */
53
+ async function save(patch: Partial<GlobalConfig>): Promise<void> {
54
+ await saveGlobalConfig({ ...readGlobalConfigSync(), ...patch });
55
+ }
56
+
57
+ function numberSetting(field: NumericField): ChaliceCustomSetting {
58
+ return {
59
+ id: field.key,
60
+ type: "custom",
61
+ label: field.label,
62
+ edit: "input",
63
+ get: () => String(readGlobalConfigSync()[field.key]),
64
+ set: async (ctx, _pi, display) => {
65
+ const trimmed = display.trim();
66
+ const value = Number(trimmed);
67
+ // Number() rather than parseInt: it rejects trailing garbage like "12abc".
68
+ if (
69
+ trimmed === "" ||
70
+ !Number.isFinite(value) ||
71
+ (field.integer && !Number.isInteger(value)) ||
72
+ value < field.min ||
73
+ (field.max !== undefined && value > field.max)
74
+ ) {
75
+ return `need ${field.integer ? "an integer" : "a number"} in [${field.min}, ${field.max ?? "∞"}]`;
76
+ }
77
+ await save({ [field.key]: value } as Partial<GlobalConfig>);
78
+ // Same source of truth as manifestCompatible, so the prompt and the stale check cannot drift.
79
+ if ((INDEX_AFFECTING_KEYS as readonly string[]).includes(field.key)) {
80
+ ctx.ui.notify(`${field.label} changes stored vectors — run /index reindex to apply.`, "info");
81
+ }
82
+ return undefined;
83
+ },
84
+ };
85
+ }
86
+
87
+ function textSetting(key: TextKey, label: string, description: string, placeholder: string): ChaliceCustomSetting {
88
+ return {
89
+ id: key,
90
+ type: "custom",
91
+ label,
92
+ description,
93
+ edit: "input",
94
+ placeholder,
95
+ get: () => readGlobalConfigSync()[key] ?? "",
96
+ set: async (_ctx, _pi, display) => {
97
+ await save({ [key]: display.trim() || undefined } as Partial<GlobalConfig>);
98
+ return undefined;
99
+ },
100
+ };
101
+ }
102
+
103
+ const providerSetting: ChaliceCustomSetting = {
104
+ id: "provider",
105
+ type: "custom",
106
+ label: "Provider",
107
+ description: "Embedding provider. Changing it clears custom endpoint overrides.",
108
+ edit: "select",
109
+ values: PROVIDER_IDS,
110
+ get: () => readGlobalConfigSync().provider,
111
+ set: async (_ctx, _pi, display) => {
112
+ const provider = PROVIDER_IDS.find((id) => id === display);
113
+ if (!provider) return `unknown provider: ${display}`;
114
+ await save({
115
+ provider,
116
+ baseUrl: undefined,
117
+ model: undefined,
118
+ apiKeyEnv: undefined,
119
+ embeddingDim: undefined,
120
+ pricePerMillionTokens: undefined,
121
+ });
122
+ return undefined;
123
+ },
124
+ };
125
+
126
+ export const CODE_INDEX_SECTION: ChaliceSettingsSection = {
127
+ id: "code-index",
128
+ title: "Code index",
129
+ description: "Semantic code search: embedding provider, chunking and search limits.",
130
+ order: 60,
131
+ items: [
132
+ providerSetting,
133
+ textSetting("model", "Model", "Blank uses the provider preset.", "provider default"),
134
+ textSetting("baseUrl", "Base URL", "Blank uses the provider preset.", "provider default"),
135
+ textSetting("apiKeyEnv", "API key env", "Environment variable holding the key. Blank uses the preset.", "VOYAGE_API_KEY"),
136
+ ...NUMERIC_FIELDS.map(numberSetting),
137
+ {
138
+ id: "excludeDirs",
139
+ type: "custom",
140
+ label: "Exclude dirs",
141
+ description: "Comma-separated directory names skipped by the indexer.",
142
+ edit: "input",
143
+ get: () => readGlobalConfigSync().excludeDirs.join(","),
144
+ set: async (_ctx, _pi, display) => {
145
+ const dirs = display
146
+ .split(",")
147
+ .map((entry) => entry.trim())
148
+ .filter(Boolean);
149
+ if (dirs.length === 0) return "cannot be empty";
150
+ await save({ excludeDirs: dirs });
151
+ return undefined;
152
+ },
153
+ },
154
+ ],
155
+ };
156
+
157
+ export function registerCodeIndexSettings(pi: ExtensionAPI): void {
158
+ registerChaliceSettingsSection(pi, CODE_INDEX_SECTION);
159
+ }
package/src/store.ts ADDED
@@ -0,0 +1,208 @@
1
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import type { CodeChunk, Manifest, ManifestFileEntry, ProjectInfo, ResolvedConfig } from "./types.ts";
4
+ import { INDEX_VERSION } from "./types.ts";
5
+ import { DEFAULT_CONFIG, INDEX_AFFECTING_KEYS } from "./config.ts";
6
+
7
+ const TABLE_NAME = "chunks";
8
+
9
+ // LanceDB is an optional native dependency. It must only be resolved when the
10
+ // index is actually accessed — never at extension load time — so a missing or
11
+ // not-yet-installed package degrades to an actionable error on /index use
12
+ // instead of crashing CLI startup ("Failed to load extension").
13
+ async function loadLanceDb(): Promise<typeof import("@lancedb/lancedb")> {
14
+ try {
15
+ return await import("@lancedb/lancedb");
16
+ } catch (error) {
17
+ const detail = error instanceof Error ? error.message : String(error);
18
+ throw new Error(
19
+ `Code index could not load @lancedb/lancedb: ${detail}. Run \`npm install --ignore-scripts\` from the repo root, then retry.`,
20
+ { cause: error },
21
+ );
22
+ }
23
+ }
24
+
25
+ async function readJson<T>(path: string): Promise<T | undefined> {
26
+ try {
27
+ return JSON.parse(await readFile(path, "utf8")) as T;
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ async function writeJson(path: string, data: unknown): Promise<void> {
34
+ await mkdir(join(path, ".."), { recursive: true });
35
+ await writeFile(path, `${JSON.stringify(data, null, "\t")}\n`, "utf8");
36
+ }
37
+
38
+ export async function loadManifest(project: ProjectInfo): Promise<Manifest | undefined> {
39
+ return readJson<Manifest>(project.manifestPath);
40
+ }
41
+
42
+ export async function saveManifest(project: ProjectInfo, manifest: Manifest): Promise<void> {
43
+ manifest.updatedAt = new Date().toISOString();
44
+ manifest.fileCount = Object.keys(manifest.files).length;
45
+ manifest.chunkCount = Object.values(manifest.files).reduce((sum, f) => sum + f.chunkIds.length, 0);
46
+ await writeJson(project.manifestPath, manifest);
47
+ }
48
+
49
+ export function newManifest(project: ProjectInfo, config: ResolvedConfig, dimension: number): Manifest {
50
+ const now = new Date().toISOString();
51
+ return {
52
+ version: INDEX_VERSION,
53
+ projectRoot: project.root,
54
+ baseUrl: config.baseUrl,
55
+ model: config.model,
56
+ embeddingDim: dimension,
57
+ indexParams: Object.fromEntries(INDEX_AFFECTING_KEYS.map((k) => [k, config[k]])),
58
+ createdAt: now,
59
+ updatedAt: now,
60
+ chunkCount: 0,
61
+ fileCount: 0,
62
+ annIndexBuilt: false,
63
+ files: {},
64
+ };
65
+ }
66
+
67
+ export function manifestCompatible(manifest: Manifest | undefined, config: ResolvedConfig): { ok: boolean; reason?: string } {
68
+ if (!manifest) return { ok: false, reason: "not indexed" };
69
+ if (manifest.version !== INDEX_VERSION) return { ok: false, reason: `index schema version ${manifest.version} is stale` };
70
+ if (manifest.model !== config.model || manifest.baseUrl !== config.baseUrl) return { ok: false, reason: `index model/provider is stale (${manifest.model})` };
71
+ if (config.embeddingDim && manifest.embeddingDim !== config.embeddingDim) return { ok: false, reason: `index dimension ${manifest.embeddingDim} is stale` };
72
+ // Chunking/file-scope params change the stored vectors without touching the embedding model, so
73
+ // they get their own staleness gate — driven by the SAME INDEX_AFFECTING_KEYS the settings UI uses
74
+ // to prompt reindex (single source of truth, so the two sets can't drift). Old manifests predate
75
+ // indexParams → fall back to DEFAULT_CONFIG so an existing index isn't flagged while config matches.
76
+ for (const k of INDEX_AFFECTING_KEYS) {
77
+ if ((manifest.indexParams?.[k] ?? DEFAULT_CONFIG[k]) !== config[k]) return { ok: false, reason: `index chunking config (${k}) is stale, run /index reindex` };
78
+ }
79
+ return { ok: true };
80
+ }
81
+
82
+ async function db(project: ProjectInfo) {
83
+ await mkdir(join(project.indexDir, "lancedb"), { recursive: true });
84
+ const lancedb = await loadLanceDb();
85
+ return lancedb.connect(join(project.indexDir, "lancedb"));
86
+ }
87
+
88
+ async function tableExists(project: ProjectInfo): Promise<boolean> {
89
+ const conn = await db(project);
90
+ return (await conn.tableNames()).includes(TABLE_NAME);
91
+ }
92
+
93
+ export async function clearIndex(project: ProjectInfo): Promise<void> {
94
+ await rm(project.indexDir, { recursive: true, force: true });
95
+ await mkdir(project.indexDir, { recursive: true });
96
+ }
97
+
98
+ function escapeSql(value: string): string {
99
+ return value.replaceAll("'", "''");
100
+ }
101
+
102
+ function rowFromChunk(chunk: CodeChunk & { vector: number[] }) {
103
+ return {
104
+ id: chunk.id,
105
+ projectRoot: chunk.projectRoot,
106
+ path: chunk.path,
107
+ language: chunk.language,
108
+ symbol: chunk.symbol ?? "",
109
+ startLine: chunk.startLine,
110
+ endLine: chunk.endLine,
111
+ content: chunk.content,
112
+ embeddedText: chunk.embeddedText,
113
+ contentHash: chunk.contentHash,
114
+ fileHash: chunk.fileHash,
115
+ mtimeMs: chunk.mtimeMs,
116
+ size: chunk.size,
117
+ vector: chunk.vector,
118
+ };
119
+ }
120
+
121
+ export async function upsertFileChunks(project: ProjectInfo, chunks: Array<CodeChunk & { vector: number[] }>, manifest: Manifest): Promise<void> {
122
+ if (chunks.length === 0) return;
123
+ const conn = await db(project);
124
+ let table: any;
125
+ if ((await conn.tableNames()).includes(TABLE_NAME)) {
126
+ table = await conn.openTable(TABLE_NAME);
127
+ await table.delete(`path = '${escapeSql(chunks[0].path)}'`).catch(() => undefined);
128
+ await table.add(chunks.map(rowFromChunk));
129
+ } else {
130
+ table = await conn.createTable(TABLE_NAME, chunks.map(rowFromChunk));
131
+ }
132
+ const first = chunks[0];
133
+ manifest.files[first.path] = {
134
+ path: first.path,
135
+ fileHash: first.fileHash,
136
+ mtimeMs: first.mtimeMs,
137
+ size: first.size,
138
+ chunkIds: chunks.map((c) => c.id),
139
+ } satisfies ManifestFileEntry;
140
+ manifest.chunkCount = Object.values(manifest.files).reduce((sum, f) => sum + f.chunkIds.length, 0);
141
+ }
142
+
143
+ export async function deleteFileChunks(project: ProjectInfo, relPath: string, manifest?: Manifest): Promise<void> {
144
+ if (await tableExists(project)) {
145
+ const conn = await db(project);
146
+ const table = await conn.openTable(TABLE_NAME);
147
+ await table.delete(`path = '${escapeSql(relPath)}'`).catch(() => undefined);
148
+ }
149
+ if (manifest) delete manifest.files[relPath];
150
+ }
151
+
152
+ // Existing embeddings for a file, keyed by contentHash, so the incremental indexer can reuse the
153
+ // vectors of chunks that did not change instead of paying to re-embed them.
154
+ export async function getFileChunkVectors(project: ProjectInfo, relPath: string): Promise<Map<string, number[]>> {
155
+ const map = new Map<string, number[]>();
156
+ if (!(await tableExists(project))) return map;
157
+ const conn = await db(project);
158
+ const table = await conn.openTable(TABLE_NAME);
159
+ const rows = await table
160
+ .query()
161
+ .where(`path = '${escapeSql(relPath)}'`)
162
+ .toArray()
163
+ .catch(() => [] as any[]);
164
+ for (const r of rows) {
165
+ if (typeof r.contentHash === "string" && r.vector) map.set(r.contentHash, Array.from(r.vector as ArrayLike<number>));
166
+ }
167
+ return map;
168
+ }
169
+
170
+ export async function maybeBuildAnnIndex(project: ProjectInfo, manifest: Manifest, config: ResolvedConfig): Promise<void> {
171
+ if (manifest.annIndexBuilt || manifest.chunkCount < config.annIndexThreshold) return;
172
+ try {
173
+ const conn = await db(project);
174
+ const table = await conn.openTable(TABLE_NAME);
175
+ await table.createIndex("vector");
176
+ manifest.annIndexBuilt = true;
177
+ } catch {
178
+ // Flat scan remains correct. Leave ANN absent if LanceDB cannot build it for this dataset.
179
+ }
180
+ }
181
+
182
+ export interface SearchResult {
183
+ path: string;
184
+ language: string;
185
+ symbol?: string;
186
+ startLine: number;
187
+ endLine: number;
188
+ content: string;
189
+ score: number;
190
+ }
191
+
192
+ export async function searchIndex(project: ProjectInfo, vector: number[], topK: number, filter?: string): Promise<SearchResult[]> {
193
+ if (!(await tableExists(project))) return [];
194
+ const conn = await db(project);
195
+ const table = await conn.openTable(TABLE_NAME);
196
+ let q = table.vectorSearch(vector).limit(topK);
197
+ if (filter) q = q.where(filter);
198
+ const rows = await q.toArray();
199
+ return rows.map((r: any) => ({
200
+ path: r.path,
201
+ language: r.language,
202
+ symbol: r.symbol || undefined,
203
+ startLine: r.startLine,
204
+ endLine: r.endLine,
205
+ content: r.content,
206
+ score: typeof r._distance === "number" ? 1 / (1 + r._distance) : 0,
207
+ }));
208
+ }
package/src/tagging.ts ADDED
@@ -0,0 +1,247 @@
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+
4
+ /** Normalize a raw tag token: lowercase, trim, keep only [a-z0-9_-]. Returns undefined if nothing valid remains. */
5
+ export function normalizeTag(raw: string): string | undefined {
6
+ const s = raw.toLowerCase().trim().replace(/[^a-z0-9_-]/g, "");
7
+ return s.length > 0 ? s : undefined;
8
+ }
9
+
10
+ interface TagFileResult {
11
+ tags: Set<string>;
12
+ description?: string;
13
+ }
14
+
15
+ /** Parse a single `.index_tag` file. `#` comment lines are skipped for tags; the first `#` comment
16
+ * line (stripped of the leading `#` and trimmed) is used as a human-readable description (truncated
17
+ * to ~120 characters to avoid layout issues). */
18
+ async function parseTagFile(absPath: string): Promise<TagFileResult> {
19
+ let text: string;
20
+ try {
21
+ text = await readFile(absPath, "utf8");
22
+ } catch {
23
+ return { tags: new Set() };
24
+ }
25
+ const tags = new Set<string>();
26
+ let description: string | undefined;
27
+ for (const line of text.split(/\r?\n/)) {
28
+ const trimmed = line.trim();
29
+ if (!trimmed) continue;
30
+ if (trimmed.startsWith("#")) {
31
+ if (description === undefined) {
32
+ const raw = trimmed.slice(1).trim();
33
+ if (raw) description = raw.length > 120 ? `${raw.slice(0, 117)}...` : raw;
34
+ }
35
+ continue;
36
+ }
37
+ for (const token of trimmed.split(/[\s,]+/)) {
38
+ const tag = normalizeTag(token);
39
+ if (tag) tags.add(tag);
40
+ }
41
+ }
42
+ return { tags, description };
43
+ }
44
+
45
+ async function isDirectory(absPath: string): Promise<boolean> {
46
+ try {
47
+ return (await stat(absPath)).isDirectory();
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ interface TagFileEntry {
54
+ tags: Set<string>;
55
+ description?: string;
56
+ }
57
+
58
+ /** Walk directory tree rooted at `root`, collect all `.index_tag` files, return a map of dir→{tags,description}.
59
+ * Directory basenames in `excludeDirs` (e.g. node_modules, .git) are skipped entirely. */
60
+ async function collectTagFiles(root: string, excludeDirs: Set<string>): Promise<Map<string, TagFileEntry>> {
61
+ const result = new Map<string, TagFileEntry>();
62
+
63
+ async function walk(dir: string): Promise<void> {
64
+ let names: string[];
65
+ try {
66
+ names = await readdir(dir);
67
+ } catch {
68
+ return;
69
+ }
70
+ if (names.includes(".index_tag")) {
71
+ const { tags, description } = await parseTagFile(join(dir, ".index_tag"));
72
+ result.set(dir, { tags, description });
73
+ }
74
+ await Promise.all(
75
+ names.map(async (name) => {
76
+ if (excludeDirs.has(name)) return;
77
+ const child = join(dir, name);
78
+ if (await isDirectory(child)) await walk(child);
79
+ }),
80
+ );
81
+ }
82
+
83
+ await walk(root);
84
+ return result;
85
+ }
86
+
87
+ export interface TagResolver {
88
+ /** Return the union of all tags declared in ancestor `.index_tag` files for the given project-relative path. */
89
+ resolveTags(relPath: string): Set<string>;
90
+ /** Whether any `.index_tag` files were found (i.e. the project uses tag declarations). */
91
+ hasTags: boolean;
92
+ }
93
+
94
+ /**
95
+ * Build a TagResolver for the given project root. Walks the directory tree once to read all `.index_tag`
96
+ * files, then resolves per-file tags by walking the ancestor chain and taking the union.
97
+ *
98
+ * Designed to be constructed once per query — `.index_tag` files are few and the walk is lightweight.
99
+ */
100
+ // Cache the walked .index_tag map briefly: the inline tag hint builds a resolver on EVERY search
101
+ // (even tag-free ones), so back-to-back searches would otherwise re-walk the source tree each time.
102
+ // Short TTL keeps .index_tag edits effectively immediate (visible within a few seconds).
103
+ const RESOLVER_TTL_MS = 3000;
104
+ const resolverCache = new Map<string, { resolver: TagResolver; builtAt: number }>();
105
+
106
+ export async function buildTagResolver(projectRoot: string, excludeDirs: Set<string>): Promise<TagResolver> {
107
+ const cached = resolverCache.get(projectRoot);
108
+ if (cached && Date.now() - cached.builtAt < RESOLVER_TTL_MS) return cached.resolver;
109
+ const dirTagMap = await collectTagFiles(projectRoot, excludeDirs);
110
+
111
+ function resolveTags(relPath: string): Set<string> {
112
+ const absPath = join(projectRoot, relPath);
113
+ const fileDir = dirname(absPath);
114
+ const union = new Set<string>();
115
+ let cur = fileDir;
116
+ while (true) {
117
+ const entry = dirTagMap.get(cur);
118
+ if (entry) {
119
+ for (const t of entry.tags) union.add(t);
120
+ }
121
+ if (cur === projectRoot) break;
122
+ const parent = dirname(cur);
123
+ if (parent === cur) break; // filesystem root guard
124
+ cur = parent;
125
+ }
126
+ return union;
127
+ }
128
+
129
+ const resolver: TagResolver = { resolveTags, hasTags: dirTagMap.size > 0 };
130
+ resolverCache.set(projectRoot, { resolver, builtAt: Date.now() });
131
+ return resolver;
132
+ }
133
+
134
+ export interface TagStats {
135
+ /** Per-tag hit count across the given file paths. */
136
+ perTag: Map<string, number>;
137
+ /** Number of files with no tags at all. */
138
+ untagged: number;
139
+ /** Total file count. */
140
+ total: number;
141
+ }
142
+
143
+ /**
144
+ * Compute per-tag file counts and the untagged count by walking `filePaths` through `resolve`.
145
+ * Purely path-based — never reads file contents.
146
+ */
147
+ export function computeTagStats(filePaths: string[], resolve: (p: string) => Set<string>): TagStats {
148
+ const perTag = new Map<string, number>();
149
+ let untagged = 0;
150
+ for (const p of filePaths) {
151
+ const tags = resolve(p);
152
+ if (tags.size === 0) {
153
+ untagged++;
154
+ } else {
155
+ for (const t of tags) {
156
+ perTag.set(t, (perTag.get(t) ?? 0) + 1);
157
+ }
158
+ }
159
+ }
160
+ return { perTag, untagged, total: filePaths.length };
161
+ }
162
+
163
+ export interface DeclaredTagInfo {
164
+ /** Sorted project-relative directories that declare this tag. */
165
+ dirs: string[];
166
+ /** First `#` comment line from the .index_tag file(s) declaring this tag, if any. */
167
+ description?: string;
168
+ }
169
+
170
+ /**
171
+ * Walk the project tree, collect all `.index_tag` declarations, and return a sorted map of
172
+ * tag → { dirs, description }. Used by `/index tags` and `list_code_tags`.
173
+ */
174
+ export async function listDeclaredTags(projectRoot: string, excludeDirs: Set<string>): Promise<Map<string, DeclaredTagInfo>> {
175
+ const dirTagMap = await collectTagFiles(projectRoot, excludeDirs);
176
+ const tagToDirs = new Map<string, Set<string>>();
177
+ const tagToDesc = new Map<string, string>();
178
+ for (const [absDir, { tags, description }] of dirTagMap) {
179
+ const relDir = absDir === projectRoot ? "." : absDir.slice(projectRoot.length + 1);
180
+ for (const tag of tags) {
181
+ if (!tagToDirs.has(tag)) tagToDirs.set(tag, new Set());
182
+ tagToDirs.get(tag)!.add(relDir);
183
+ // First description seen for this tag wins.
184
+ if (description && !tagToDesc.has(tag)) tagToDesc.set(tag, description);
185
+ }
186
+ }
187
+ const result = new Map<string, DeclaredTagInfo>();
188
+ for (const [tag, dirs] of [...tagToDirs.entries()].sort(([a], [b]) => a.localeCompare(b))) {
189
+ result.set(tag, { dirs: [...dirs].sort(), description: tagToDesc.get(tag) });
190
+ }
191
+ return result;
192
+ }
193
+
194
+ /** Agent-facing help shown when no .index_tag files exist. */
195
+ export const EMPTY_TAGS_HELP = [
196
+ "No .index_tag files in this project yet.",
197
+ "To organize areas for filtered search, create a .index_tag in any directory:",
198
+ " # one-line description of what these tags mean",
199
+ " test, e2e",
200
+ "Subdirectories inherit. Filter with include_tags / exclude_tags. No reindex needed.",
201
+ ].join("\n");
202
+
203
+ /**
204
+ * Format declared tags + stats into the agent-facing list (shared by `list_code_tags` and `/index tags`).
205
+ * Alignment uses only the ASCII tag and count columns; the (possibly CJK) description is placed last so
206
+ * its display width can't break the layout.
207
+ */
208
+ export function formatDeclaredTags(tagMap: Map<string, DeclaredTagInfo>, stats: TagStats): string {
209
+ const total = stats.total || 1;
210
+ const maxTagLen = [...tagMap.keys()].reduce((m, t) => Math.max(m, t.length), 0);
211
+ const lines = ["Tags declared in this project (.index_tag files):", ""];
212
+ for (const [tag, { dirs, description }] of tagMap) {
213
+ const count = stats.perTag.get(tag) ?? 0;
214
+ const pct = Math.round((count / total) * 100);
215
+ const head = ` ${tag.padEnd(maxTagLen)} ${`${count} files · ${pct}%`.padEnd(16)}`;
216
+ lines.push(description ? `${head} ${description}` : head.trimEnd());
217
+ lines.push(` ${" ".repeat(maxTagLen)} declared in: ${dirs.join(", ")}`);
218
+ }
219
+ if (stats.untagged > 0) {
220
+ const pct = Math.round((stats.untagged / total) * 100);
221
+ lines.push(` (untagged: ${stats.untagged} files · ${pct}% — excluded by include_tags)`);
222
+ }
223
+ lines.push("", "Filter semantic_code_search:");
224
+ lines.push(` exclude_tags: ["test"] skip tagged areas (untagged unaffected)`);
225
+ lines.push(` include_tags: ["core","harness"] whitelist: keep files matching ANY (untagged excluded)`);
226
+ return lines.join("\n");
227
+ }
228
+
229
+ /**
230
+ * D3 filter semantics:
231
+ * - `exclude_tags`: if the file's tags contain ANY exclude tag → filtered out. Untagged files are unaffected.
232
+ * - `include_tags`: strict whitelist — only files with ANY include tag pass. Untagged files are excluded.
233
+ * - Both empty → no filtering (pass-through).
234
+ */
235
+ export function matchesTagFilter(
236
+ fileTags: Set<string>,
237
+ includeTags?: string[],
238
+ excludeTags?: string[],
239
+ ): boolean {
240
+ if (excludeTags && excludeTags.length > 0) {
241
+ if (excludeTags.some((t) => fileTags.has(t))) return false;
242
+ }
243
+ if (includeTags && includeTags.length > 0) {
244
+ if (!includeTags.some((t) => fileTags.has(t))) return false;
245
+ }
246
+ return true;
247
+ }