dsh-code-index 0.1.0 → 0.2.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/buildIndex.ts","../src/extract.ts","../src/scan.ts","../src/store.ts","../src/types.ts","../src/search.ts","../src/repomap.ts","../src/tools.ts","../src/config.ts","../src/index.ts"],"sourcesContent":["/** Build a RepoIndex for a workspace: scan -> extract -> persist. */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport path from 'node:path'\nimport { extractSymbols, languageForFile } from './extract.js'\nimport { scanRepo, DEFAULT_EXCLUDED_DIRS } from './scan.js'\nimport {\n cacheKeyForRoot,\n defaultCachePath,\n legacyCachePath,\n loadIndex,\n saveIndex,\n} from './store.js'\nimport type { IndexOptions, IndexedFile, RepoIndex } from './types.js'\n\n/**\n * Full build: scan + extract every supported file. Existing per-file\n * extraction is reused when `previous` holds an identical mtime for the\n * same rel path (incremental refresh), so touched files alone re-parse.\n */\nexport async function buildIndex(\n root: string,\n options: IndexOptions = {},\n previous: RepoIndex | null = null,\n): Promise<RepoIndex> {\n const scanned = await scanRepo(root, options)\n\n // Index stale/current state from the previous run by rel path.\n const prevByPath = new Map((previous?.files ?? []).map((f) => [f.path, f]))\n const prevMtime = new Map((previous?.files ?? []).map((f) => [f.path, f.mtimeMs]))\n\n const files: IndexedFile[] = []\n const BATCH = 8\n for (let i = 0; i < scanned.length; i += BATCH) {\n const batch = scanned.slice(i, i + BATCH)\n const rows = await Promise.all(\n batch.map(async (f) => {\n const lang = languageForFile(f.abs)\n if (!lang) return null\n if (prevMtime.get(f.rel) === f.mtimeMs) {\n const cached = prevByPath.get(f.rel)!\n return {\n ...cached,\n mtimeMs: f.mtimeMs,\n symbols: cached.symbols.map((symbol) => ({ ...symbol, file: f.rel })),\n }\n }\n let code: string\n try {\n code = await readFile(f.abs, 'utf8')\n } catch {\n return null\n }\n const symbols = await extractSymbols(code, lang)\n // Backfill the repo-relative path: the extractor is file-agnostic and\n // leaves SymbolInfo.file empty, but search/render depend on it.\n return {\n path: f.rel,\n lang,\n mtimeMs: f.mtimeMs,\n symbols: symbols.map((s) => ({ ...s, file: f.rel })),\n } satisfies IndexedFile\n }),\n )\n for (const f of rows) {\n if (f) files.push(f)\n }\n }\n\n return {\n root,\n generatedAt: Date.now(),\n files,\n excludedDirs: [...DEFAULT_EXCLUDED_DIRS, ...(options.excludeDirs ?? [])],\n }\n}\n\n/** Convenience wrapper: evolve an on-disk cache if `root` exists. */\nexport async function buildIndexWithCache(\n root: string,\n options: IndexOptions = {},\n cacheDir?: string,\n): Promise<RepoIndex> {\n const cachePath = defaultCachePath(root, cacheDir)\n let prev = await loadIndex(cachePath)\n let loadedLegacy = false\n if (!prev) {\n const oldPath = legacyCachePath(root, cacheDir)\n if (oldPath !== cachePath) {\n prev = await loadIndex(oldPath)\n loadedLegacy = prev !== null\n }\n }\n const reusable = prev && cacheKeyForRoot(prev.root) === cacheKeyForRoot(root) ? prev : null\n const fresh = await buildIndex(root, options, reusable)\n if (prev && indexesEqual(prev, fresh)) {\n if (loadedLegacy) await saveIndex(cachePath, fresh)\n return loadedLegacy ? fresh : prev\n }\n await saveIndex(cachePath, fresh)\n return fresh\n}\n\nfunction indexesEqual(left: RepoIndex, right: RepoIndex): boolean {\n if (cacheKeyForRoot(left.root) !== cacheKeyForRoot(right.root)) return false\n if (left.files.length !== right.files.length) return false\n if (left.excludedDirs.length !== right.excludedDirs.length) return false\n if (left.excludedDirs.some((value, index) => value !== right.excludedDirs[index])) return false\n\n return left.files.every((file, fileIndex) => {\n const other = right.files[fileIndex]\n if (!other || file.path !== other.path || file.lang !== other.lang || file.mtimeMs !== other.mtimeMs) {\n return false\n }\n if (file.symbols.length !== other.symbols.length) return false\n return file.symbols.every((symbol, symbolIndex) => {\n const candidate = other.symbols[symbolIndex]\n return candidate !== undefined\n && symbol.name === candidate.name\n && symbol.kind === candidate.kind\n && symbol.file === candidate.file\n && symbol.line === candidate.line\n && symbol.endLine === candidate.endLine\n && symbol.exported === candidate.exported\n && symbol.signature === candidate.signature\n })\n })\n}\n\n/**\n * Locate the git repo root for a path by walking up to the nearest `.git`\n * directory. Bounded walk (max `maxLevels` levels); returns `null` when no\n * repo marker is found — callers must NOT index an untagged directory\n * (the fs root is the classic footgun: indexing `C:\\` by accident).\n */\nexport async function findRepoRoot(startDir: string, maxLevels = 12): Promise<string | null> {\n let dir = path.resolve(startDir)\n for (let level = 0; level < maxLevels; level++) {\n try {\n // stat() accepts BOTH a `.git` directory (normal repos) and a `.git`\n // file (worktrees / submodules) — readFile only handled the file form.\n await stat(path.join(dir, '.git'))\n return dir\n } catch {\n // not a repo here — keep walking\n }\n const parent = path.dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n return null\n}\n","/**\n * tree-sitter symbol extraction.\n *\n * Parses a source text with a per-language grammar (web-tree-sitter WASM,\n * static grammars from tree-sitter-wasms) and returns flat SymbolInfo rows.\n *\n * NOTE on the dependency pin: web-tree-sitter must stay at ^0.20.x — newer\n * releases expect dylinked grammar wasm, while tree-sitter-wasms ships\n * static builds. Verified working pair: web-tree-sitter@0.20.8 + tree-sitter-wasms@0.1.13.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport Parser from 'web-tree-sitter'\nimport type { SymbolInfo, SymbolKind } from './types.js'\n\nconst require = createRequire(import.meta.url)\n// web-tree-sitter@0.20.8 is CJS `export = Parser`; default-interop gives the class directly.\n\nexport type LanguageId = 'typescript' | 'javascript'\n\nconst WASM_DIR = path.dirname(require.resolve('tree-sitter-wasms/out/tree-sitter-typescript.wasm'))\n\nconst EXT_TO_LANG: Record<string, LanguageId> = {\n '.ts': 'typescript',\n '.tsx': 'typescript',\n '.mts': 'typescript',\n '.cts': 'typescript',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.mjs': 'javascript',\n '.cjs': 'javascript',\n}\n\nexport function languageForFile(filePath: string): LanguageId | null {\n const ext = path.extname(filePath).toLowerCase()\n return EXT_TO_LANG[ext] ?? null\n}\n\n/** Kind of a capture per query. */\ntype CaptureDef = { kind: SymbolKind; exported?: boolean }\n\n// Query definitions per language. Captures bind to the DECLARATION node\n// (capture OUTSIDE the pattern: `(function_declaration) @function` — the\n// 0.20 query parser rejects a capture sitting directly after the node type\n// inside the parens). Names/signatures/export come from node fields.\nconst QUERIES: Record<LanguageId, string> = {\n typescript: `\n (function_declaration) @function\n (generator_function_declaration) @function\n (method_definition) @method\n (class_declaration) @class\n (interface_declaration) @interface\n (type_alias_declaration) @type\n (enum_declaration) @enum\n (variable_declarator) @variable\n (public_field_definition) @field\n (abstract_class_declaration) @class\n `,\n // JS shares the same query surface; type-related patterns simply never match.\n javascript: `\n (function_declaration) @function\n (generator_function_declaration) @function\n (method_definition) @method\n (class_declaration) @class\n (variable_declarator) @variable\n `,\n}\n\nconst CAPTURE_KINDS: Record<string, CaptureDef> = {\n function: { kind: 'function' },\n method: { kind: 'method' },\n class: { kind: 'class' },\n interface: { kind: 'interface' },\n type: { kind: 'type' },\n enum: { kind: 'enum' },\n variable: { kind: 'variable' },\n field: { kind: 'field' },\n}\n\nlet parserPromise: Promise<Parser> | null = null\n\nasync function getParser(): Promise<Parser> {\n if (!parserPromise) {\n parserPromise = (async () => {\n const wasm = path.join(path.dirname(require.resolve('web-tree-sitter')), 'tree-sitter.wasm')\n await Parser.init({ locateFile: () => wasm })\n const p = new Parser()\n return p\n })()\n }\n return parserPromise\n}\n\nconst languageCache = new Map<LanguageId, Promise<Parser.Language>>()\n\nfunction getLanguage(id: LanguageId): Promise<Parser.Language> {\n let entry = languageCache.get(id)\n if (!entry) {\n entry = getParser().then(async (parser) => {\n const grammarName = id === 'typescript' ? 'tree-sitter-typescript' : 'tree-sitter-javascript'\n const grammarPath = path.join(WASM_DIR, `${grammarName}.wasm`)\n const bytes = await readFile(grammarPath)\n const lang = await Parser.Language.load(bytes)\n // Precompile queries per language to catch authoring errors early.\n const q = lang.query(QUERIES[id])\n q.delete()\n return lang\n })\n languageCache.set(id, entry)\n }\n return entry\n}\n\n/**\n * Extract all top-level symbols from source text of the given language.\n * Returns rows ordered by file line. Never throws for parse errors — a\n * failed parse yields an empty list (the caller logs and continues).\n */\nexport async function extractSymbols(code: string, id: LanguageId): Promise<SymbolInfo[]> {\n const lang = await getLanguage(id)\n const parser = await getParser()\n parser.setLanguage(lang)\n const tree = parser.parse(code)\n try {\n const query = lang.query(QUERIES[id])\n const rows: SymbolInfo[] = []\n try {\n const captures = query.captures(tree.rootNode)\n for (const cap of captures) {\n const def = CAPTURE_KINDS[cap.name]\n if (!def) continue\n const node = cap.node\n const name = nameOf(node)\n if (!name) continue\n rows.push({\n name,\n kind: def.kind,\n file: '', // set by the caller (extractor is file-agnostic)\n line: node.startPosition.row + 1,\n endLine: node.endPosition.row + 1,\n exported: isExported(node),\n signature: signatureFor(node),\n })\n }\n } finally {\n query.delete()\n }\n rows.sort((a, b) => a.line - b.line)\n return rows\n } finally {\n tree.delete()\n }\n}\n\n/** The declared name of a declaration node, via its `name` field. */\nfunction nameOf(node: Parser.SyntaxNode): string {\n const field = node.childForFieldName?.('name')\n if (field) return field.text.trim()\n // e.g. an anonymous default export — skip those.\n return ''\n}\n\n/** Best-effort declaration signature: `name` + parameter list, if any. */\nfunction signatureFor(node: Parser.SyntaxNode): string {\n const name = nameOf(node)\n const params = node.namedChildren.find(\n (c) => c.type === 'formal_parameters' || c.type === 'method_parameters',\n )\n if (params) {\n return `${name}${params.text}`\n }\n const first = node.namedChildren[0]\n return first ? first.text.trim() : name\n}\n\n/** A node is exported when it sits directly inside an `export_statement`. */\nfunction isExported(node: Parser.SyntaxNode): boolean {\n let parent = node.parent\n let depth = 0\n while (parent && depth < 3) {\n if (parent.type === 'export_statement') return true\n if (parent.type === 'statement_block') return false\n parent = parent.parent\n depth++\n }\n return false\n}\n\n/** Compile a symbol query for a code sample (used by tests). */\nexport async function parseFileToSymbols(\n filePath: string,\n repoRoot: string,\n code?: string,\n): Promise<SymbolInfo[]> {\n const lang = languageForFile(filePath)\n if (!lang) return []\n const text = code ?? (await readFile(filePath, 'utf8'))\n const rows = await extractSymbols(text, lang)\n const rel = path.relative(repoRoot, filePath).split(path.sep).join('/')\n return rows.map((r) => ({ ...r, file: rel }))\n}","/** Workspace file discovery with dir exclusions and mtime tracking. */\n\nimport { readdir, stat } from 'node:fs/promises'\nimport path from 'node:path'\nimport type { IndexOptions } from './types.js'\n\nexport const DEFAULT_EXCLUDED_DIRS = [\n 'node_modules',\n '.git',\n '.idea',\n '.vscode',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n '.next',\n '.nuxt',\n '.cache',\n 'target',\n 'vendor',\n '.dsh-code-index',\n]\n\n/** Language-agnostic source extensions we index. */\nexport const SUPPORTED_EXTS = new Set([\n '.ts',\n '.tsx',\n '.mts',\n '.cts',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n])\n\nexport interface ScannedFile {\n /** Absolute path on disk. */\n abs: string\n /** Repo-relative path (forward-slash). */\n rel: string\n mtimeMs: number\n}\n\n/**\n * Recursively walk `root` and return indexed files, skipping excluded dir\n * components at any depth. Uses readdir with `withFileTypes` so we never\n * stat every entry; mtime comes from a targeted stat per candidate file.\n */\nexport async function scanRepo(\n root: string,\n options: IndexOptions = {},\n): Promise<ScannedFile[]> {\n const excluded = new Set([...DEFAULT_EXCLUDED_DIRS, ...(options.excludeDirs ?? [])])\n const results: ScannedFile[] = []\n const queue: Array<[string, string]> = [[root, '']] // [absDir, relDir]\n\n while (queue.length) {\n const [absDir, relDir] = queue.pop()!\n let entries\n try {\n entries = await readdir(absDir, { withFileTypes: true })\n } catch {\n continue // unreadable dir: skip into the void\n }\n for (const entry of entries) {\n const abs = path.join(absDir, entry.name)\n const rel = relDir ? `${relDir}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n if (excluded.has(entry.name)) continue\n queue.push([abs, rel])\n } else if (entry.isFile() && SUPPORTED_EXTS.has(path.extname(entry.name).toLowerCase())) {\n try {\n const st = await stat(abs)\n results.push({ abs, rel, mtimeMs: st.mtimeMs })\n } catch {\n // race: file deleted mid-scan — ignore\n }\n }\n }\n }\n\n results.sort((a, b) => a.rel.localeCompare(b.rel))\n return results\n}","/** On-disk JSON cache for RepoIndex, keyed by repo root. */\n\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { createHash, randomUUID } from 'node:crypto'\nimport type { RepoIndex } from './types.js'\n\nexport const CACHE_DIR_NAME = '.dsh-code-index'\n\n/** Stable root identity for cache hashing, including Windows case aliases. */\nexport function cacheKeyForRoot(root: string): string {\n const resolved = path.resolve(root)\n return process.platform === 'win32' ? resolved.toLowerCase() : resolved\n}\n\n/** Default cache location: `<repoRoot>/.dsh-code-index/index.json`. */\nexport function defaultCachePath(root: string, cacheDir?: string): string {\n const dir = cacheDir ?? path.join(root, CACHE_DIR_NAME)\n const hash = createHash('sha1').update(cacheKeyForRoot(root)).digest('hex').slice(0, 12)\n return path.join(dir, `${hash}.json`)\n}\n\n/** Cache filename used before Windows root casing was canonicalized. */\nexport function legacyCachePath(root: string, cacheDir?: string): string {\n const dir = cacheDir ?? path.join(root, CACHE_DIR_NAME)\n const hash = createHash('sha1').update(root).digest('hex').slice(0, 12)\n return path.join(dir, `${hash}.json`)\n}\n\nexport async function loadIndex(cachePath: string): Promise<RepoIndex | null> {\n try {\n const raw = await readFile(cachePath, 'utf8')\n const parsed = JSON.parse(raw) as RepoIndex\n if (!parsed || typeof parsed.root !== 'string' || !Array.isArray(parsed.files)) return null\n return parsed\n } catch {\n return null // missing or corrupt cache == no cache\n }\n}\n\nexport async function saveIndex(cachePath: string, index: RepoIndex): Promise<void> {\n await mkdir(path.dirname(cachePath), { recursive: true })\n const temporaryPath = `${cachePath}.${process.pid}.${randomUUID()}.tmp`\n try {\n await writeFile(temporaryPath, JSON.stringify(index, null, 2), { encoding: 'utf8', flag: 'wx' })\n await rename(temporaryPath, cachePath)\n } finally {\n await rm(temporaryPath, { force: true })\n }\n}\n","/** Shared data model for dsh-code-index. */\n\nexport type SymbolKind =\n | 'function'\n | 'method'\n | 'class'\n | 'interface'\n | 'type'\n | 'enum'\n | 'variable'\n | 'field'\n | 'import'\n | 'module'\n\nexport interface SymbolInfo {\n /** Symbol name (identifier / type id / member name). */\n name: string\n kind: SymbolKind\n /** Repo-relative path of the containing file, always forward-slash. */\n file: string\n /** 1-based start line. */\n line: number\n /** 1-based end line (inclusive). */\n endLine: number\n /** True when the symbol is exported at module level (export .. / export default). */\n exported: boolean\n /** Short human-readable signature, e.g. `greet(name: string)` — empty when n/a. */\n signature: string\n}\n\nexport interface IndexedFile {\n /** Repo-relative path (forward-slash). */\n path: string\n lang: string\n /** fs mtime of the source file at index time (milliseconds). */\n mtimeMs: number\n symbols: SymbolInfo[]\n}\n\nexport interface RepoIndex {\n /** Absolute source root this index describes. */\n root: string\n /** Unix ms when the index was generated. */\n generatedAt: number\n files: IndexedFile[]\n excludedDirs: string[]\n}\n\nexport function symbolCount(index: RepoIndex): number {\n return index.files.reduce((n, f) => n + f.symbols.length, 0)\n}\n\n/** Optional config consumed by the index build pipeline. */\nexport interface IndexOptions {\n /** Extra directories to exclude, appended to the defaults. */\n excludeDirs?: string[]\n /** Minimum mtime delta (ms) that forces a re-extract in refresh mode. */\n staleToleranceMs?: number\n}","/** Pure search / filter logic over a RepoIndex — unit-testable, no IO. */\n\nimport type { RepoIndex, SymbolInfo, SymbolKind } from './types.js'\n\nexport interface SymbolFilter {\n query?: string\n file?: string\n kind?: SymbolKind\n exportedOnly?: boolean\n}\n\nexport interface RankedHit extends SymbolInfo {\n /** 0..1 relevance. 1 = exact name match; lower = fuzzier. */\n score: number\n}\n\nfunction matchScore(name: string, query: string): number {\n const q = query.toLowerCase()\n const n = name.toLowerCase()\n if (n === q) return 1\n if (n.startsWith(q)) return 0.8\n if (n.includes(q)) return 0.5\n return 0\n}\n\n/** Filter symbols by file/kind/export, then score by name against query (if any). */\nexport function searchSymbols(\n index: RepoIndex,\n filter: SymbolFilter,\n limit = 50,\n): RankedHit[] {\n const q = (filter.query ?? '').trim()\n const filePat = filter.file?.trim().toLowerCase()\n const hits: RankedHit[] = []\n\n for (const file of index.files) {\n if (filePat && !file.path.toLowerCase().includes(filePat)) continue\n for (const sym of file.symbols) {\n if (filter.kind && sym.kind !== filter.kind) continue\n if (filter.exportedOnly && !sym.exported) continue\n const score = q ? matchScore(sym.name, q) : 0.4\n if (q && score === 0) continue\n hits.push({ ...sym, score })\n }\n }\n\n // Export boost, then relevance, then stable name order.\n hits.sort((a, b) => {\n const ab =\n Number(b.exported) - Number(a.exported) ||\n b.score - a.score ||\n a.name.localeCompare(b.name) ||\n a.file.localeCompare(b.file)\n return ab\n })\n return hits.slice(0, limit)\n}\n\n/** Neat one-line rendering of a hit for terminal/chat output. */\nexport function renderHit(hit: RankedHit): string {\n const exportMark = hit.exported ? 'export ' : ''\n const sig = hit.signature || hit.name\n const score = hit.score < 1 ? ` [${hit.score.toFixed(2)}]` : ''\n return `${exportMark}${hit.kind} ${sig}${score} — ${hit.file}:${hit.line}`\n}","/**\n * Bounded, ranked repo map generation — the \"aider-style\" overview the model\n * can turn to before browsing files. Pure logic, no IO.\n */\n\nimport type { IndexedFile, RepoIndex, SymbolInfo, SymbolKind } from './types.js'\n\n/** Higher-weight symbols pull their file up the map. */\nexport const KIND_WEIGHT: Record<SymbolKind, number> = {\n class: 1.0,\n interface: 1.0,\n type: 0.8,\n function: 0.8,\n method: 0.7,\n enum: 0.9,\n variable: 0.25,\n field: 0.2,\n import: 0.05,\n module: 0.3,\n}\n\nexport interface RepoMapOptions {\n /** Max files to include (default 24). */\n topFiles?: number\n /** Max symbols per file (default 18). */\n symbolsPerFile?: number\n /** Hard cap on rendered characters (default 3200). */\n maxChars?: number\n}\n\nexport interface RepoMapEntry {\n path: string\n score: number\n symbols: Array<{ name: string; kind: SymbolKind; line: number; signature: string }>\n}\n\n/** Density-aware file score: weighted symbols minus bloat. */\nexport function scoreFile(file: IndexedFile): number {\n let score = 0\n for (const sym of file.symbols) {\n score += KIND_WEIGHT[sym.kind] ?? 0.3\n if (sym.exported) score += 0.3\n }\n return score / (1 + file.symbols.length * 0.04)\n}\n\n/** Rank files, take the top slice, cap per-file symbols. */\nexport function rankRepoMap(index: RepoIndex, options: RepoMapOptions = {}): RepoMapEntry[] {\n const topFiles = options.topFiles ?? 24\n const perFile = options.symbolsPerFile ?? 18\n const ranked = index.files\n .filter((f) => f.symbols.length > 0)\n .map((f) => ({ file: f, score: scoreFile(f) }))\n .sort((a, b) => b.score - a.score || a.file.path.localeCompare(b.file.path))\n .slice(0, topFiles)\n\n return ranked.map(({ file, score }) => ({\n path: file.path,\n score,\n symbols: file.symbols.slice(0, perFile).map((s) => ({\n name: s.name,\n kind: s.kind,\n line: s.line,\n signature: s.signature,\n })),\n }))\n}\n\n/** Render the ranked map as markdown, hard-truncated to maxChars. */\nexport function renderRepoMap(entries: RepoMapEntry[], options: RepoMapOptions = {}): string {\n const maxChars = options.maxChars ?? 3200\n const lines: string[] = ['# repo map']\n let totalSymbols = 0\n for (const e of entries) {\n totalSymbols += e.symbols.length\n lines.push(`## ${e.path} (${e.symbols.length})`)\n for (const s of e.symbols) {\n const label = s.signature || s.name\n lines.push(` ${s.kind} ${label} :${s.line}`)\n }\n }\n let text = lines.join('\\n')\n if (text.length > maxChars) {\n text = `${text.slice(0, maxChars)}\\n… truncated`\n }\n return totalSymbols > 0 ? text : ''\n}","/** Model-visible tools: code_index, code_symbols, code_search. */\n\nimport { defineTool, type JsonValue } from '@deepseek-ai/dsh-tools'\nimport path from 'node:path'\nimport { buildIndexWithCache, findRepoRoot } from './buildIndex.js'\nimport { renderHit, searchSymbols } from './search.js'\nimport { rankRepoMap, renderRepoMap } from './repomap.js'\nimport { getConfig, indexOptions } from './config.js'\nimport { cacheKeyForRoot } from './store.js'\nimport type { RepoIndex } from './types.js'\n\n/** Minimal structural types for the harness surfaces we touch. */\ninterface ToolCwdContext {\n agent?: {\n session?: { header?: { cwd?: string } }\n }\n}\ntype ToolRunExec = ToolCwdContext & { signal?: AbortSignal }\n\ninterface TextBlock {\n type: 'text'\n text: string\n}\n\nexport interface IndexCache {\n get(root: string, force?: boolean): Promise<RepoIndex>\n invalidate(): void\n}\n\n/** Retain completed indexes briefly while still coalescing concurrent refreshes. */\nexport function createIndexCache(\n load: (root: string) => Promise<RepoIndex>,\n ttlMs = 60_000,\n now: () => number = Date.now,\n): IndexCache {\n interface CompletedEntry {\n index: RepoIndex\n at: number\n epoch: number\n }\n interface LoadEntry {\n promise: Promise<RepoIndex>\n epoch: number\n }\n\n const completed = new Map<string, CompletedEntry>()\n const inFlight = new Map<string, LoadEntry>()\n let epoch = 0\n\n function startLoad(key: string, root: string, previous?: Promise<RepoIndex>): Promise<RepoIndex> {\n const loadEpoch = epoch\n const begin = previous\n ? previous.catch(() => undefined).then(() => load(root))\n : load(root)\n const promise = begin\n .then((index) => {\n if (loadEpoch === epoch) {\n completed.delete(key)\n completed.set(key, { index, at: now(), epoch: loadEpoch })\n while (completed.size > 16) completed.delete(completed.keys().next().value!)\n }\n return index\n })\n .finally(() => {\n if (inFlight.get(key)?.promise === promise) inFlight.delete(key)\n })\n inFlight.set(key, { promise, epoch: loadEpoch })\n return promise\n }\n\n return {\n get(root, force = false) {\n const resolvedRoot = path.resolve(root)\n const key = cacheKeyForRoot(resolvedRoot)\n const running = inFlight.get(key)\n if (running) {\n if (running.epoch === epoch && !force) return running.promise\n return startLoad(key, resolvedRoot, running.promise)\n }\n\n if (!force) {\n const cached = completed.get(key)\n if (cached && cached.epoch === epoch && now() - cached.at < ttlMs) {\n completed.delete(key)\n completed.set(key, cached)\n return Promise.resolve(cached.index)\n }\n if (cached) completed.delete(key)\n } else {\n completed.delete(key)\n }\n return startLoad(key, resolvedRoot)\n },\n invalidate() {\n epoch++\n completed.clear()\n },\n }\n}\n\nconst indexCache = createIndexCache((root) => buildIndexWithCache(root, indexOptions()))\n\nexport function getIndex(root: string, force = false): Promise<RepoIndex> {\n return indexCache.get(root, force)\n}\n\nexport function invalidateIndexCache(): void {\n indexCache.invalidate()\n}\n\nasync function resolveRoot(arg: string | undefined, exec: ToolRunExec): Promise<string> {\n const cwd = exec.agent?.session?.header?.cwd\n const base = arg ?? cwd ?? process.cwd()\n const root = await findRepoRoot(base)\n if (!root) throw new Error(`no git repository found from ${path.resolve(base)}`)\n return root\n}\n\nexport const tools = [\n defineTool({\n name: 'code_index',\n description:\n 'Manage the semantic repo index: status or (re)build it for the current workspace. Auto-builds the first time it is queried. Returns file/symbol counts and the index location.',\n parameters: {\n action: {\n type: 'string',\n enum: ['status', 'build'],\n description: '\"status\" (default) reports without forcing a rebuild; \"build\" forces a fresh scan.',\n },\n repoRoot: {\n type: 'string',\n description:\n 'Optional absolute repo path. Defaults to the workspace root of the current session.',\n },\n },\n output: {\n schema: { type: 'string' },\n render: (_args, value: string): TextBlock[] => [{ type: 'text', text: value }],\n },\n async execute(args: { action?: string; repoRoot?: string }, exec: ToolRunExec): Promise<string> {\n try {\n const root = await resolveRoot(args.repoRoot, exec)\n const index = await getIndex(root, args.action === 'build')\n const total = index.files.reduce((n, f) => n + f.symbols.length, 0)\n const langs = new Set(index.files.map((f) => f.lang))\n return [\n `repo: ${root}`,\n `files indexed: ${index.files.length}`,\n `symbols: ${total}`,\n `languages: ${[...langs].join(', ')}`,\n index.files.length === 0 ? 'no supported files found' : 'index up to date',\n ].join('\\n')\n } catch (error) {\n return `code_index: ${(error as Error).message ?? String(error)}`\n }\n },\n }),\n\n defineTool({\n name: 'code_symbols',\n description:\n 'List symbols (functions, classes, interfaces, types, methods, variables) in the current repo. Filter by name substring, file path substring, or symbol kind. Results are exported-first, alphabetically ordered.',\n parameters: {\n query: {\n type: 'string',\n description: 'Substring of the symbol name to match (case-insensitive). Omit to list all.',\n },\n file: {\n type: 'string',\n description: 'Substring of the repo-relative file path to match, e.g. \"src/core\".',\n },\n kind: {\n type: 'string',\n enum: ['function', 'method', 'class', 'interface', 'type', 'enum', 'variable', 'field'],\n description: 'Only return symbols of this kind.',\n },\n exportedOnly: {\n type: 'boolean',\n description: 'Only exported (module-level public) symbols.',\n },\n limit: {\n type: 'number',\n description: 'Max rows (default 50).',\n },\n repoRoot: {\n type: 'string',\n description: 'Optional absolute repo path; defaults to the session workspace root.',\n },\n },\n output: {\n schema: { type: 'array' },\n render: (_args, value: JsonValue[]): TextBlock[] =>\n value.map((v) => ({\n type: 'text' as const,\n text: renderHit(v as unknown as Parameters<typeof renderHit>[0]),\n })),\n },\n async execute(\n args: {\n query?: string\n file?: string\n kind?: 'function' | 'method' | 'class' | 'interface' | 'type' | 'enum' | 'variable' | 'field'\n exportedOnly?: boolean\n limit?: number\n repoRoot?: string\n },\n exec: ToolRunExec,\n ): Promise<JsonValue[]> {\n const root = await resolveRoot(args.repoRoot, exec)\n const index = await getIndex(root)\n const hits = searchSymbols(\n index,\n { query: args.query, file: args.file, kind: args.kind, exportedOnly: args.exportedOnly },\n args.limit ?? 50,\n )\n return hits as unknown as JsonValue[]\n },\n }),\n\n defineTool({\n name: 'code_search',\n description:\n 'Ranked symbol search over the repo index: exact > prefix > substring name matches, exported symbols first. Results carry a relevance score and file:line, so the model can locate definitions quickly.',\n parameters: {\n query: {\n type: 'string',\n required: true,\n description: 'Symbol name (or fragment) to find.',\n },\n limit: {\n type: 'number',\n description: 'Max hits (default 20).',\n },\n repoRoot: {\n type: 'string',\n description: 'Optional absolute repo path; defaults to the session workspace root.',\n },\n },\n output: {\n schema: { type: 'array' },\n render: (_args, value: JsonValue[]): TextBlock[] =>\n value.map((v) => ({\n type: 'text' as const,\n text: renderHit(v as unknown as Parameters<typeof renderHit>[0]),\n })),\n },\n async execute(\n args: { query: string; limit?: number; repoRoot?: string },\n exec: ToolRunExec,\n ): Promise<JsonValue[]> {\n const root = await resolveRoot(args.repoRoot, exec)\n const index = await getIndex(root)\n const hits = searchSymbols(index, { query: args.query }, args.limit ?? 20)\n return hits as unknown as JsonValue[]\n },\n }),\n\n defineTool({\n name: 'code_map',\n description:\n 'Return a bounded, ranked map of the current repo (top files by symbol density, with their key symbols and lines). The model can call this once per session to build an internal model of the codebase before browsing files.',\n parameters: {\n repoRoot: {\n type: 'string',\n description: 'Optional absolute repo path; defaults to the session workspace root.',\n },\n },\n output: {\n schema: { type: 'string' },\n render: (_args, value: string): TextBlock[] => [{ type: 'text', text: value }],\n },\n async execute(args: { repoRoot?: string }, exec: ToolRunExec): Promise<string> {\n try {\n const root = await resolveRoot(args.repoRoot, exec)\n const index = await getIndex(root)\n const cfg = getConfig()\n const map = renderRepoMap(\n rankRepoMap(index, { topFiles: cfg.mapTopFiles }),\n { maxChars: cfg.mapMaxChars },\n )\n if (!map) return 'no indexable symbols found in this repo'\n return map\n } catch (error) {\n return `code_index: ${(error as Error).message ?? String(error)}`\n }\n },\n }),\n]\n","/** Plugin configuration: merged once at apply time, read wherever needed. */\n\nimport type { IndexOptions } from './types.js'\n\nexport interface PluginConfig {\n /** Extra directories to exclude from indexing (appended to defaults). */\n excludeDirs?: string[]\n /** Max files in the ranked repo map (code_map / auto section). */\n mapTopFiles?: number\n /** Hard char cap for rendered maps. */\n mapMaxChars?: number\n /** Set false to disable the auto-injected system section. */\n autoInject?: boolean\n}\n\ninterface EffectiveConfig {\n excludeDirs: string[]\n mapTopFiles: number\n mapMaxChars: number\n autoInject: boolean\n}\n\nconst DEFAULTS: EffectiveConfig = {\n excludeDirs: [],\n mapTopFiles: 24,\n mapMaxChars: 3200,\n autoInject: true,\n}\n\nconst state: { current: EffectiveConfig } = { current: { ...DEFAULTS } }\n\n/** Merge a plugin-provided partial config over the defaults (idempotent). */\nexport function applyConfig(partial?: PluginConfig): void {\n state.current = {\n ...DEFAULTS,\n ...(partial ?? {}),\n excludeDirs: [...DEFAULTS.excludeDirs, ...(partial?.excludeDirs ?? [])],\n }\n // Coerce obviously wrong inputs.\n if (!Number.isFinite(state.current.mapTopFiles) || state.current.mapTopFiles < 1) {\n state.current.mapTopFiles = DEFAULTS.mapTopFiles\n }\n if (!Number.isFinite(state.current.mapMaxChars) || state.current.mapMaxChars < 200) {\n state.current.mapMaxChars = DEFAULTS.mapMaxChars\n }\n}\n\nexport function getConfig(): Readonly<EffectiveConfig> {\n return state.current\n}\n\n/** Map the effective config onto the index pipeline options. */\nexport function indexOptions(): IndexOptions {\n return { excludeDirs: state.current.excludeDirs }\n}","/**\n * dsh-code-index — DeepSeek Harness bundle entry.\n *\n * Registers four model-visible tools (code_index / code_symbols /\n * code_search / code_map) backed by a tree-sitter symbol index, and\n * injects a bounded auto-updating repo map for the default workspace\n * into the system prompt.\n */\n\ntype Disposer = void | (() => void)\n\n/** Minimal structural Context; the real @deepseek-ai/cordis type is a\n * runtime dependency we intentionally do not import in the bundle entry. */\ninterface MinimalContext {\n effect(fn: () => Disposer): void\n tools: { register(t: unknown): () => void }\n systemPrompt: {\n section(section: {\n name: string\n order: number\n text: string | ((context: unknown) => string)\n }): () => void\n }\n}\n\nexport const name = 'dsh-code-index'\n\n// Public API surface (consumable by other bundles / tests).\nexport { buildIndex, buildIndexWithCache, findRepoRoot } from './buildIndex.js'\nexport { extractSymbols, languageForFile, parseFileToSymbols } from './extract.js'\nexport { scanRepo, DEFAULT_EXCLUDED_DIRS, SUPPORTED_EXTS } from './scan.js'\nexport { loadIndex, saveIndex, defaultCachePath, CACHE_DIR_NAME } from './store.js'\nexport { symbolCount } from './types.js'\nexport type { RepoIndex, IndexedFile, SymbolInfo, SymbolKind, IndexOptions } from './types.js'\nexport { searchSymbols, renderHit } from './search.js'\nexport { rankRepoMap, renderRepoMap, scoreFile } from './repomap.js'\nexport { tools } from './tools.js'\n\nimport { getIndex, invalidateIndexCache, tools } from './tools.js'\nimport { findRepoRoot } from './buildIndex.js'\nimport { rankRepoMap, renderRepoMap } from './repomap.js'\nimport { symbolCount } from './types.js'\nimport { applyConfig, getConfig, type PluginConfig } from './config.js'\n\nexport const inject = ['tools', 'systemPrompt'] as const\n\n/** TTL for the auto-injected repo map (seconds). */\nconst MAP_TTL_MS = 60_000\n\nexport function apply(ctx: MinimalContext, pluginConfig?: PluginConfig) {\n applyConfig(pluginConfig)\n invalidateIndexCache()\n ctx.effect(() => {\n const disposers: Array<() => void> = []\n console.log('[dsh-code-index] plugin loaded')\n for (const tool of tools) {\n disposers.push(ctx.tools.register(tool))\n console.log(`[dsh-code-index] registered tool: ${tool.name}`)\n }\n\n // Auto-inject a bounded repo map for the DEFAULT workspace (the dsh\n // launch directory, per the harness docs). Multi-workspace web sessions\n // should rely on the `code_map` tool, which resolves the per-session cwd.\n let cached: { root: string; at: number; text: string } | null = null\n\n async function warmMap(): Promise<void> {\n const now = Date.now()\n const cfg = getConfig()\n try {\n const root = await findRepoRoot(process.cwd())\n if (!root) {\n cached = { root: '', at: now, text: '' }\n return\n }\n const index = await getIndex(root)\n const text = renderRepoMap(\n rankRepoMap(index, { topFiles: cfg.mapTopFiles }),\n { maxChars: cfg.mapMaxChars },\n )\n const stats = symbolCount(index)\n cached = {\n root: index.root,\n at: Date.now(),\n text: text ? `${text}\\n\\n(summary: ${index.files.length} files, ${stats} symbols)` : '',\n }\n } catch {\n cached = { root: '', at: now, text: '' } // never let injection fail the boot\n }\n }\n\n // Warm eagerly at load so the first assembly already has the map.\n void warmMap()\n\n if (getConfig().autoInject) {\n disposers.push(ctx.systemPrompt.section({\n name: 'code-index:repo-map',\n order: 60, // before tool guidance (100–199), after persona (0)\n text: () => {\n const now = Date.now()\n if (cached && now - cached.at < MAP_TTL_MS) return cached.text\n void warmMap()\n return cached?.text ?? ''\n },\n }))\n }\n\n return () => {\n const errors: unknown[] = []\n for (const dispose of disposers.reverse()) {\n try {\n dispose()\n } catch (error) {\n errors.push(error)\n }\n }\n console.log('[dsh-code-index] plugin unloaded')\n if (errors.length > 0) throw new AggregateError(errors, 'failed to unload dsh-code-index')\n }\n })\n}\n"],"mappings":";AAEA,SAAS,YAAAA,WAAU,QAAAC,aAAY;AAC/B,OAAOC,WAA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ACjC,cAAM,OAAO;AAAA,UACX,YAAY,OAAO,EAAE,UAAU,IAAI,YAAY,CAAC;AAAA,UAChD,EAAE,UAAU,IAAI,YAAY;AAAA,QAC9B;AACA,cAAM,QAAQ,YAAY,KAAK;AAC/B,iBAAS;AAAA,UACP,MAAM,MAAM;AAAA,UACZ,IAAI,KAAK,IAAI;AAAA,UACb,MAAM,OAAO,GAAG,IAAI;AAAA;AAAA,YAAiB,MAAM,MAAM,MAAM,WAAW,KAAK,cAAc;AAAA,QACvF;AAAA,MACF,QAAQ;AACN,iBAAS,EAAE,MAAM,IAAI,IAAI,KAAK,MAAM,GAAG;AAAA,MACzC;AAAA,IACF;AAGA,SAAK,QAAQ;AAEb,QAAI,UAAU,EAAE,YAAY;AAC1B,gBAAU,KAAK,IAAI,aAAa,QAAQ;AAAA,QACtC,MAAM;AAAA,QACN,OAAO;AAAA;AAAA,QACP,MAAM,MAAM;AACV,gBAAM,MAAM,KAAK,IAAI;AACrB,cAAI,UAAU,MAAM,OAAO,KAAK,WAAY,QAAO,OAAO;AAC1D,eAAK,QAAQ;AACb,iBAAO,QAAQ,QAAQ;AAAA,QACzB;AAAA,MACF,CAAC,CAAC;AAAA,IACJ;AAEA,WAAO,MAAM;AACX,YAAM,SAAoB,CAAC;AAC3B,iBAAW,WAAW,UAAU,QAAQ,GAAG;AACzC,YAAI;AACF,kBAAQ;AAAA,QACV,SAAS,OAAO;AACd,iBAAO,KAAK,KAAK;AAAA,QACnB;AAAA,MACF;AACA,cAAQ,IAAI,kCAAkC;AAC9C,UAAI,OAAO,SAAS,EAAG,OAAM,IAAI,eAAe,QAAQ,iCAAiC;AAAA,IAC3F;AAAA,EACF,CAAC;AACH;","names":["readFile","stat","path","require","name","path","readFile","path","readFile","path","stat","name","path","path"]}
1
+ {"version":3,"sources":["../src/buildIndex.ts","../src/extract.ts","../src/scan.ts","../src/store.ts","../src/types.ts","../src/search.ts","../src/repomap.ts","../src/tools.ts","../src/config.ts","../src/index.ts"],"sourcesContent":["/** Build a RepoIndex for a workspace: scan -> extract -> persist. */\r\n\r\nimport { readFile, stat } from 'node:fs/promises'\r\nimport path from 'node:path'\r\nimport { extractAll, languageForFile } from './extract.js'\r\nimport { scanRepo, DEFAULT_EXCLUDED_DIRS } from './scan.js'\r\nimport {\r\n cacheKeyForRoot,\r\n defaultCachePath,\r\n legacyCachePath,\r\n loadIndex,\r\n saveIndex,\r\n} from './store.js'\r\nimport type { IndexOptions, IndexedFile, RepoIndex } from './types.js'\r\n\r\n/**\r\n * Full build: scan + extract every supported file. Existing per-file\r\n * extraction is reused when `previous` holds an identical mtime for the\r\n * same rel path (incremental refresh), so touched files alone re-parse.\r\n */\r\nexport async function buildIndex(\r\n root: string,\r\n options: IndexOptions = {},\r\n previous: RepoIndex | null = null,\r\n): Promise<RepoIndex> {\r\n const scanned = await scanRepo(root, options)\r\n\r\n // Index stale/current state from the previous run by rel path.\r\n const prevByPath = new Map((previous?.files ?? []).map((f) => [f.path, f]))\r\n const prevMtime = new Map((previous?.files ?? []).map((f) => [f.path, f.mtimeMs]))\r\n\r\n const files: IndexedFile[] = []\r\n const BATCH = 8\r\n for (let i = 0; i < scanned.length; i += BATCH) {\r\n const batch = scanned.slice(i, i + BATCH)\r\n const rows = await Promise.all(\r\n batch.map(async (f) => {\r\n const lang = languageForFile(f.abs)\r\n if (!lang) return null\r\n if (prevMtime.get(f.rel) === f.mtimeMs) {\r\n const cached = prevByPath.get(f.rel)!\r\n return {\r\n ...cached,\r\n mtimeMs: f.mtimeMs,\r\n symbols: cached.symbols.map((symbol) => ({ ...symbol, file: f.rel })),\r\n }\r\n }\r\n let code: string\r\n try {\r\n code = await readFile(f.abs, 'utf8')\r\n } catch {\r\n return null\r\n }\r\n const { symbols, imports } = await extractAll(code, lang)\r\n // Backfill the repo-relative path: the extractor is file-agnostic and\r\n // leaves SymbolInfo.file empty, but search/render depend on it.\r\n return {\r\n path: f.rel,\r\n lang,\r\n mtimeMs: f.mtimeMs,\r\n symbols: symbols.map((s) => ({ ...s, file: f.rel })),\r\n imports,\r\n } satisfies IndexedFile\r\n }),\r\n )\r\n for (const f of rows) {\r\n if (f) files.push(f)\r\n }\r\n }\r\n\r\n return {\r\n root,\r\n generatedAt: Date.now(),\r\n files,\r\n excludedDirs: [...DEFAULT_EXCLUDED_DIRS, ...(options.excludeDirs ?? [])],\r\n }\r\n}\r\n\r\n/** Convenience wrapper: evolve an on-disk cache if `root` exists. */\r\nexport async function buildIndexWithCache(\r\n root: string,\r\n options: IndexOptions = {},\r\n cacheDir?: string,\r\n): Promise<RepoIndex> {\r\n const cachePath = defaultCachePath(root, cacheDir)\r\n let prev = await loadIndex(cachePath)\r\n let loadedLegacy = false\r\n if (!prev) {\r\n const oldPath = legacyCachePath(root, cacheDir)\r\n if (oldPath !== cachePath) {\r\n prev = await loadIndex(oldPath)\r\n loadedLegacy = prev !== null\r\n }\r\n }\r\n const reusable = prev && cacheKeyForRoot(prev.root) === cacheKeyForRoot(root) ? prev : null\r\n const fresh = await buildIndex(root, options, reusable)\r\n if (prev && indexesEqual(prev, fresh)) {\r\n if (loadedLegacy) await saveIndex(cachePath, fresh)\r\n return loadedLegacy ? fresh : prev\r\n }\r\n await saveIndex(cachePath, fresh)\r\n return fresh\r\n}\r\n\r\nfunction indexesEqual(left: RepoIndex, right: RepoIndex): boolean {\r\n if (cacheKeyForRoot(left.root) !== cacheKeyForRoot(right.root)) return false\r\n if (left.files.length !== right.files.length) return false\r\n if (left.excludedDirs.length !== right.excludedDirs.length) return false\r\n if (left.excludedDirs.some((value, index) => value !== right.excludedDirs[index])) return false\r\n\r\n return left.files.every((file, fileIndex) => {\r\n const other = right.files[fileIndex]\r\n if (!other || file.path !== other.path || file.lang !== other.lang || file.mtimeMs !== other.mtimeMs) {\r\n return false\r\n }\r\n if (file.symbols.length !== other.symbols.length) return false\r\n return file.symbols.every((symbol, symbolIndex) => {\r\n const candidate = other.symbols[symbolIndex]\r\n return candidate !== undefined\r\n && symbol.name === candidate.name\r\n && symbol.kind === candidate.kind\r\n && symbol.file === candidate.file\r\n && symbol.line === candidate.line\r\n && symbol.endLine === candidate.endLine\r\n && symbol.exported === candidate.exported\r\n && symbol.signature === candidate.signature\r\n })\r\n })\r\n}\r\n\r\n/**\r\n * Locate the git repo root for a path by walking up to the nearest `.git`\r\n * directory. Bounded walk (max `maxLevels` levels); returns `null` when no\r\n * repo marker is found — callers must NOT index an untagged directory\r\n * (the fs root is the classic footgun: indexing `C:\\` by accident).\r\n */\r\nexport async function findRepoRoot(startDir: string, maxLevels = 12): Promise<string | null> {\r\n let dir = path.resolve(startDir)\r\n for (let level = 0; level < maxLevels; level++) {\r\n try {\r\n // stat() accepts BOTH a `.git` directory (normal repos) and a `.git`\r\n // file (worktrees / submodules) — readFile only handled the file form.\r\n await stat(path.join(dir, '.git'))\r\n return dir\r\n } catch {\r\n // not a repo here — keep walking\r\n }\r\n const parent = path.dirname(dir)\r\n if (parent === dir) return null\r\n dir = parent\r\n }\r\n return null\r\n}\r\n","/**\r\n * tree-sitter symbol extraction.\r\n *\r\n * Parses a source text with a per-language grammar (web-tree-sitter WASM,\r\n * static grammars from tree-sitter-wasms) and returns flat SymbolInfo rows.\r\n *\r\n * NOTE on the dependency pin: web-tree-sitter must stay at ^0.20.x — newer\r\n * releases expect dylinked grammar wasm, while tree-sitter-wasms ships\r\n * static builds. Verified working pair: web-tree-sitter@0.20.8 + tree-sitter-wasms@0.1.13.\r\n */\r\n\r\nimport { readFile } from 'node:fs/promises'\r\nimport { createRequire } from 'node:module'\r\nimport path from 'node:path'\r\nimport Parser from 'web-tree-sitter'\r\nimport type { SymbolInfo, SymbolKind } from './types.js'\r\n\r\nconst require = createRequire(import.meta.url)\r\n// web-tree-sitter@0.20.8 is CJS `export = Parser`; default-interop gives the class directly.\r\n\r\nexport type LanguageId = 'typescript' | 'javascript' | 'python' | 'go' | 'rust' | 'java'\r\n\r\nconst WASM_DIR = path.dirname(require.resolve('tree-sitter-wasms/out/tree-sitter-typescript.wasm'))\r\n\r\nconst GRAMMAR_NAMES: Record<LanguageId, string> = {\r\n typescript: 'tree-sitter-typescript',\r\n javascript: 'tree-sitter-javascript',\r\n python: 'tree-sitter-python',\r\n go: 'tree-sitter-go',\r\n rust: 'tree-sitter-rust',\r\n java: 'tree-sitter-java',\r\n}\r\n\r\nconst EXT_TO_LANG: Record<string, LanguageId> = {\r\n '.ts': 'typescript',\r\n '.tsx': 'typescript',\r\n '.mts': 'typescript',\r\n '.cts': 'typescript',\r\n '.js': 'javascript',\r\n '.jsx': 'javascript',\r\n '.mjs': 'javascript',\r\n '.cjs': 'javascript',\r\n '.py': 'python',\r\n '.pyi': 'python',\r\n '.go': 'go',\r\n '.rs': 'rust',\r\n '.java': 'java',\r\n}\r\n\r\nexport function languageForFile(filePath: string): LanguageId | null {\r\n const ext = path.extname(filePath).toLowerCase()\r\n return EXT_TO_LANG[ext] ?? null\r\n}\r\n\r\n/** Kind of a capture per query. */\r\ntype CaptureDef = { kind: SymbolKind; exported?: boolean }\r\n\r\n// Query definitions per language. Captures bind to the DECLARATION node\r\n// (capture OUTSIDE the pattern: `(function_declaration) @function` — the\r\n// 0.20 query parser rejects a capture sitting directly after the node type\r\n// inside the parens). Names/signatures/export come from node fields.\r\nconst QUERIES: Record<LanguageId, string> = {\r\n typescript: `\r\n (function_declaration) @function\r\n (generator_function_declaration) @function\r\n (method_definition) @method\r\n (class_declaration) @class\r\n (interface_declaration) @interface\r\n (type_alias_declaration) @type\r\n (enum_declaration) @enum\r\n (variable_declarator) @variable\r\n (public_field_definition) @field\r\n (abstract_class_declaration) @class\r\n `,\r\n // JS shares the same query surface; type-related patterns simply never match.\r\n javascript: `\r\n (function_declaration) @function\r\n (generator_function_declaration) @function\r\n (method_definition) @method\r\n (class_declaration) @class\r\n (variable_declarator) @variable\r\n `,\r\n python: `\r\n (function_definition) @function\r\n (class_definition) @class\r\n `,\r\n go: `\r\n (function_declaration) @function\r\n (method_declaration) @method\r\n (type_spec) @type\r\n `,\r\n rust: `\r\n (function_item) @function\r\n (function_signature_item) @method\r\n (struct_item) @class\r\n (enum_item) @enum\r\n (trait_item) @interface\r\n `,\r\n java: `\r\n (class_declaration) @class\r\n (interface_declaration) @interface\r\n (enum_declaration) @enum\r\n (method_declaration) @method\r\n (constructor_declaration) @method\r\n `,\r\n}\r\n\r\nconst CAPTURE_KINDS: Record<string, CaptureDef> = {\r\n function: { kind: 'function' },\r\n method: { kind: 'method' },\r\n class: { kind: 'class' },\r\n interface: { kind: 'interface' },\r\n type: { kind: 'type' },\r\n enum: { kind: 'enum' },\r\n variable: { kind: 'variable' },\r\n field: { kind: 'field' },\r\n}\r\n\r\n// Import statements per language. Whole statements are captured; the module\r\n// specifier is read from node fields in code (string quoting, dotted vs\r\n// relative vs URL-style syntax differ per grammar). CommonJS require() is out\r\n// of scope — the ES import surface covers the modern plugin ecosystem.\r\nconst IMPORT_QUERIES: Record<LanguageId, string> = {\r\n typescript: `\r\n (import_statement) @import\r\n (export_statement) @reexport\r\n `,\r\n javascript: `\r\n (import_statement) @import\r\n (export_statement) @reexport\r\n `,\r\n python: `\r\n (import_from_statement) @import\r\n (import_statement) @import\r\n `,\r\n go: `\r\n (import_spec) @import\r\n `,\r\n rust: `\r\n (use_declaration) @use\r\n `,\r\n java: `\r\n (import_declaration) @import\r\n `,\r\n}\r\n\r\nlet parserPromise: Promise<Parser> | null = null\r\n\r\nasync function getParser(): Promise<Parser> {\r\n if (!parserPromise) {\r\n parserPromise = (async () => {\r\n const wasm = path.join(path.dirname(require.resolve('web-tree-sitter')), 'tree-sitter.wasm')\r\n await Parser.init({ locateFile: () => wasm })\r\n const p = new Parser()\r\n return p\r\n })()\r\n }\r\n return parserPromise\r\n}\r\n\r\nconst languageCache = new Map<LanguageId, Promise<Parser.Language>>()\r\n\r\nfunction getLanguage(id: LanguageId): Promise<Parser.Language> {\r\n let entry = languageCache.get(id)\r\n if (!entry) {\r\n entry = getParser().then(async () => {\r\n const grammarPath = path.join(WASM_DIR, `${GRAMMAR_NAMES[id]}.wasm`)\r\n const bytes = await readFile(grammarPath)\r\n const lang = await Parser.Language.load(bytes)\r\n // Precompile queries per language to catch authoring errors early.\r\n const q = lang.query(QUERIES[id])\r\n q.delete()\r\n const iq = lang.query(IMPORT_QUERIES[id])\r\n iq.delete()\r\n return lang\r\n })\r\n languageCache.set(id, entry)\r\n }\r\n return entry\r\n}\r\n\r\n/**\r\n * Extract symbols and raw import specifiers from source text of the given\r\n * language, from a single parse. Returns rows ordered by file line. Never\r\n * throws for parse errors — a failed parse yields empty lists (the caller\r\n * logs and continues).\r\n */\r\nexport interface ExtractedFile {\r\n symbols: SymbolInfo[]\r\n /** Raw module specifiers, e.g. './util', 'node:fs', './utils' (py). */\r\n imports: string[]\r\n}\r\n\r\nexport async function extractAll(code: string, id: LanguageId): Promise<ExtractedFile> {\r\n const lang = await getLanguage(id)\r\n const parser = await getParser()\r\n parser.setLanguage(lang)\r\n const tree = parser.parse(code)\r\n try {\r\n const symbols: SymbolInfo[] = []\r\n const symbolQuery = lang.query(QUERIES[id])\r\n try {\r\n const captures = symbolQuery.captures(tree.rootNode)\r\n for (const cap of captures) {\r\n const def = CAPTURE_KINDS[cap.name]\r\n if (!def) continue\r\n const node = cap.node\r\n // tree-sitter queries match at any depth; without this check the\r\n // variable_declarator pattern would also capture function-body\r\n // locals — pure index noise.\r\n if (def.kind === 'variable' && !isModuleLevelVariable(node)) continue\r\n const name = nameOf(node)\r\n if (!name) continue\r\n symbols.push({\r\n name,\r\n kind: kindFor(id, node, def.kind),\r\n file: '', // set by the caller (extractor is file-agnostic)\r\n line: node.startPosition.row + 1,\r\n endLine: node.endPosition.row + 1,\r\n exported: isExported(id, node),\r\n signature: signatureFor(node),\r\n })\r\n }\r\n } finally {\r\n symbolQuery.delete()\r\n }\r\n\r\n const imports: string[] = []\r\n const importQuery = lang.query(IMPORT_QUERIES[id])\r\n try {\r\n for (const cap of importQuery.captures(tree.rootNode)) {\r\n const spec = specifierOf(id, cap.node)\r\n if (spec) imports.push(spec)\r\n }\r\n } finally {\r\n importQuery.delete()\r\n }\r\n\r\n symbols.sort((a, b) => a.line - b.line)\r\n return { symbols, imports }\r\n } finally {\r\n tree.delete()\r\n }\r\n}\r\n\r\n/** Symbols only — see extractAll for the combined parse. */\r\nexport async function extractSymbols(code: string, id: LanguageId): Promise<SymbolInfo[]> {\r\n return (await extractAll(code, id)).symbols\r\n}\r\n\r\n/** The declared name of a declaration node, via its `name` field. */\r\nfunction nameOf(node: Parser.SyntaxNode): string {\r\n const field = node.childForFieldName?.('name')\r\n if (field) return field.text.trim()\r\n // e.g. an anonymous default export — skip those.\r\n return ''\r\n}\r\n\r\n/** Read the raw module specifier out of a captured import statement. */\r\nfunction specifierOf(id: LanguageId, node: Parser.SyntaxNode): string | null {\r\n switch (node.type) {\r\n case 'import_statement':\r\n // ts/js: `import … from './x'` (source); python: `import a.b` (name)\r\n if (id === 'python') return dottedToPath(node.childForFieldName('name')?.text)\r\n return stripQuotes(node.childForFieldName('source')?.text)\r\n case 'export_statement':\r\n // ts/js re-export: `export … from './x'`; plain exports have no source\r\n return stripQuotes(node.childForFieldName('source')?.text)\r\n case 'import_from_statement': {\r\n // python: `from .utils import x` / `from mypkg.core import Thing`\r\n const raw = node.childForFieldName('module_name')?.text\r\n if (raw == null) return null\r\n return raw.startsWith('.') ? pythonRelative(raw) : dottedToPath(raw)\r\n }\r\n case 'import_spec': // go: `import \"example.com/foo/util\"`\r\n return stripQuotes(node.childForFieldName('path')?.text)\r\n case 'use_declaration': // rust: `use crate::a::b::{c, d}`\r\n return rustUsePath(node.childForFieldName('argument')?.text)\r\n case 'import_declaration': // java: `import com.example.Thing;`\r\n return dottedToPath(node.namedChildren[0]?.text)\r\n default:\r\n return null\r\n }\r\n}\r\n\r\n/**\r\n * Rust use paths: 'crate::a::b' is root-relative, 'super::x' is parent-module\r\n * ('../x'), 'self::x' is current ('./x'); everything else (std, external\r\n * crates) stays root-relative and simply won't resolve in-repo. Use-lists\r\n * ('a::b::{c,d}') contribute their base path.\r\n */\r\nfunction rustUsePath(text: string | undefined | null): string | null {\r\n if (!text) return null\r\n const base = text.split('{')[0].trim()\r\n if (!base) return null\r\n const parts = base.split('::').filter(Boolean)\r\n if (parts[0] === 'crate') parts.shift()\r\n return parts.map((p) => (p === 'super' ? '..' : p === 'self' ? '.' : p)).join('/')\r\n}\r\n\r\nfunction stripQuotes(text: string | undefined | null): string | null {\r\n if (text == null || text.length < 2) return null\r\n const first = text[0]\r\n const last = text[text.length - 1]\r\n if ((first === \"'\" && last === \"'\") || (first === '\"' && last === '\"')) {\r\n return text.slice(1, -1)\r\n }\r\n return null\r\n}\r\n\r\n/** 'os.path' → 'os/path' — dotted module path to repo-relative-ish path. */\r\nfunction dottedToPath(text: string | undefined | null): string | null {\r\n if (!text) return null\r\n return text.trim().replace(/\\./g, '/')\r\n}\r\n\r\n/** '.utils' → './utils', '..pkg.mod' → '../pkg/mod' — python relative import. */\r\nfunction pythonRelative(raw: string): string {\r\n const dots = raw.match(/^\\.+/)?.[0].length ?? 0\r\n const rest = raw.slice(dots).replace(/\\./g, '/')\r\n const prefix = dots === 1 ? './' : '../'.repeat(dots - 1)\r\n return prefix + rest\r\n}\r\n\r\n/** Best-effort declaration signature: `name` + parameter list, if any. */\r\nfunction signatureFor(node: Parser.SyntaxNode): string {\r\n const name = nameOf(node)\r\n // Field first (go method_declaration has both a receiver and a parameters\r\n // parameter_list — the field picks the right one), type fallback otherwise.\r\n const params =\r\n node.childForFieldName?.('parameters') ??\r\n node.namedChildren.find(\r\n (c) =>\r\n c.type === 'formal_parameters' ||\r\n c.type === 'method_parameters' ||\r\n c.type === 'parameters' ||\r\n c.type === 'parameter_list',\r\n )\r\n if (params) {\r\n return `${name}${collapseSpace(params.text)}`\r\n }\r\n const first = node.namedChildren[0]\r\n return first ? collapseSpace(first.text) : name\r\n}\r\n\r\n/**\r\n * Signatures must stay one line: repo-map rows are budgeted per line, and a\r\n * multi-line parameter list would both wrap the format and burn chars.\r\n */\r\nfunction collapseSpace(text: string): string {\r\n return text\r\n .replace(/\\s+/g, ' ')\r\n .replace(/\\( /g, '(')\r\n .replace(/ \\)/g, ')')\r\n .replace(/ ,/g, ',')\r\n .replace(/,\\)/g, ')')\r\n .trim()\r\n}\r\n\r\n/**\r\n * A variable is indexable only at module level: its declaration must sit\r\n * directly inside the program (or the export_statement wrapping it). Anything\r\n * deeper — function bodies, blocks, for-of heads — is a local with no\r\n * navigation value.\r\n */\r\nfunction isModuleLevelVariable(node: Parser.SyntaxNode): boolean {\r\n const declaration = node.parent // variable_declaration | lexical_declaration\r\n const container = declaration?.parent // program | export_statement | …\r\n return container?.type === 'program' || container?.type === 'export_statement'\r\n}\r\n\r\n/**\r\n * A symbol is exported when walking up from it reaches an export_statement\r\n * before any function or class body — only module-level declarations count.\r\n * A method inside `export class` must NOT inherit the class's export, and a\r\n * function nested inside an exported function is not exported either.\r\n */\r\nfunction isExported(id: LanguageId, node: Parser.SyntaxNode): boolean {\r\n if (id === 'python') {\r\n // Python has no export syntax: a def/class directly under the module is\r\n // importable, anything nested (methods, inner functions) is not a\r\n // module-level symbol.\r\n return node.parent?.type === 'module'\r\n }\r\n if (id === 'go') {\r\n // Go exports by capitalisation, not by keyword.\r\n const name = nameOf(node)\r\n return !!name && /^[A-Z]/.test(name)\r\n }\r\n if (id === 'rust') {\r\n // `pub` = exported; `pub(crate)` & friends are crate-local, not public.\r\n return node.namedChildren.some(\r\n (c) => c.type === 'visibility_modifier' && c.text === 'pub',\r\n )\r\n }\r\n if (id === 'java') {\r\n // Interface members are implicitly public.\r\n if (node.parent?.type === 'interface_body') return true\r\n return node.namedChildren.some((c) => c.type === 'modifiers' && /\\bpublic\\b/.test(c.text))\r\n }\r\n for (let parent = node.parent; parent; parent = parent.parent) {\r\n if (parent.type === 'export_statement') return true\r\n if (parent.type === 'statement_block' || parent.type === 'class_body') return false\r\n if (parent.type === 'program') return false\r\n }\r\n return false\r\n}\r\n\r\n/**\r\n * Language quirks the query syntax can't express:\r\n * - python: no distinct method node — a def directly in a class body is one\r\n * - go: a type_spec is a class (struct) or interface by its type child\r\n * - rust: function_item directly in an impl body is a method\r\n */\r\nfunction kindFor(id: LanguageId, node: Parser.SyntaxNode, kind: SymbolKind): SymbolKind {\r\n if (id === 'python' && kind === 'function') {\r\n const inClassBody = node.parent?.type === 'block' && node.parent?.parent?.type === 'class_definition'\r\n if (inClassBody) return 'method'\r\n }\r\n if (id === 'go' && node.type === 'type_spec') {\r\n const type = node.childForFieldName('type')?.type\r\n if (type === 'struct_type') return 'class'\r\n if (type === 'interface_type') return 'interface'\r\n return 'type'\r\n }\r\n if (id === 'rust' && node.type === 'function_item') {\r\n const inImpl = node.parent?.type === 'declaration_list' && node.parent?.parent?.type === 'impl_item'\r\n if (inImpl) return 'method'\r\n }\r\n return kind\r\n}\r\n\r\n/** Compile a symbol query for a code sample (used by tests). */\r\nexport async function parseFileToSymbols(\r\n filePath: string,\r\n repoRoot: string,\r\n code?: string,\r\n): Promise<SymbolInfo[]> {\r\n const lang = languageForFile(filePath)\r\n if (!lang) return []\r\n const text = code ?? (await readFile(filePath, 'utf8'))\r\n const rows = await extractSymbols(text, lang)\r\n const rel = path.relative(repoRoot, filePath).split(path.sep).join('/')\r\n return rows.map((r) => ({ ...r, file: rel }))\r\n}","/** Workspace file discovery with dir exclusions and mtime tracking. */\r\n\r\nimport { readdir, stat } from 'node:fs/promises'\r\nimport path from 'node:path'\r\nimport type { IndexOptions } from './types.js'\r\n\r\nexport const DEFAULT_EXCLUDED_DIRS = [\r\n 'node_modules',\r\n '.git',\r\n '.idea',\r\n '.vscode',\r\n 'dist',\r\n 'build',\r\n 'out',\r\n 'coverage',\r\n '.next',\r\n '.nuxt',\r\n '.cache',\r\n 'target',\r\n 'vendor',\r\n '.dsh-code-index',\r\n]\r\n\r\n/** Language-agnostic source extensions we index. */\r\nexport const SUPPORTED_EXTS = new Set([\r\n '.ts',\r\n '.tsx',\r\n '.mts',\r\n '.cts',\r\n '.js',\r\n '.jsx',\r\n '.mjs',\r\n '.cjs',\r\n '.py',\r\n '.pyi',\r\n '.go',\r\n '.rs',\r\n '.java',\r\n])\r\n\r\nexport interface ScannedFile {\r\n /** Absolute path on disk. */\r\n abs: string\r\n /** Repo-relative path (forward-slash). */\r\n rel: string\r\n mtimeMs: number\r\n}\r\n\r\n/**\r\n * Recursively walk `root` and return indexed files, skipping excluded dir\r\n * components at any depth. Uses readdir with `withFileTypes` so we never\r\n * stat every entry; mtime comes from a targeted stat per candidate file.\r\n */\r\nexport async function scanRepo(\r\n root: string,\r\n options: IndexOptions = {},\r\n): Promise<ScannedFile[]> {\r\n const excluded = new Set([...DEFAULT_EXCLUDED_DIRS, ...(options.excludeDirs ?? [])])\r\n const results: ScannedFile[] = []\r\n const queue: Array<[string, string]> = [[root, '']] // [absDir, relDir]\r\n\r\n while (queue.length) {\r\n const [absDir, relDir] = queue.pop()!\r\n let entries\r\n try {\r\n entries = await readdir(absDir, { withFileTypes: true })\r\n } catch {\r\n continue // unreadable dir: skip into the void\r\n }\r\n for (const entry of entries) {\r\n const abs = path.join(absDir, entry.name)\r\n const rel = relDir ? `${relDir}/${entry.name}` : entry.name\r\n if (entry.isDirectory()) {\r\n if (excluded.has(entry.name)) continue\r\n queue.push([abs, rel])\r\n } else if (entry.isFile() && SUPPORTED_EXTS.has(path.extname(entry.name).toLowerCase())) {\r\n try {\r\n const st = await stat(abs)\r\n results.push({ abs, rel, mtimeMs: st.mtimeMs })\r\n } catch {\r\n // race: file deleted mid-scan — ignore\r\n }\r\n }\r\n }\r\n }\r\n\r\n results.sort((a, b) => a.rel.localeCompare(b.rel))\r\n return results\r\n}","/** On-disk JSON cache for RepoIndex, keyed by repo root. */\r\n\r\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\r\nimport path from 'node:path'\r\nimport { createHash, randomUUID } from 'node:crypto'\r\nimport type { RepoIndex } from './types.js'\r\n\r\nexport const CACHE_DIR_NAME = '.dsh-code-index'\r\n\r\n/** Stable root identity for cache hashing, including Windows case aliases. */\r\nexport function cacheKeyForRoot(root: string): string {\r\n const resolved = path.resolve(root)\r\n return process.platform === 'win32' ? resolved.toLowerCase() : resolved\r\n}\r\n\r\n/** Default cache location: `<repoRoot>/.dsh-code-index/index.json`. */\r\nexport function defaultCachePath(root: string, cacheDir?: string): string {\r\n const dir = cacheDir ?? path.join(root, CACHE_DIR_NAME)\r\n const hash = createHash('sha1').update(cacheKeyForRoot(root)).digest('hex').slice(0, 12)\r\n return path.join(dir, `${hash}.json`)\r\n}\r\n\r\n/** Cache filename used before Windows root casing was canonicalized. */\r\nexport function legacyCachePath(root: string, cacheDir?: string): string {\r\n const dir = cacheDir ?? path.join(root, CACHE_DIR_NAME)\r\n const hash = createHash('sha1').update(root).digest('hex').slice(0, 12)\r\n return path.join(dir, `${hash}.json`)\r\n}\r\n\r\nexport async function loadIndex(cachePath: string): Promise<RepoIndex | null> {\r\n try {\r\n const raw = await readFile(cachePath, 'utf8')\r\n const parsed = JSON.parse(raw) as RepoIndex\r\n if (!parsed || typeof parsed.root !== 'string' || !Array.isArray(parsed.files)) return null\r\n return healSymbolFiles(parsed)\r\n } catch {\r\n return null // missing or corrupt cache == no cache\r\n }\r\n}\r\n\r\n/**\r\n * Self-heal caches written before the per-symbol file backfill (the\r\n * \"SymbolInfo.file is always set\" invariant). Empty `file` fields are derived\r\n * from the containing IndexedFile path on load, so any consumer of loadIndex\r\n * sees consistent rows — and the next save persists the healed form.\r\n */\r\nexport function healSymbolFiles(index: RepoIndex): RepoIndex {\r\n for (const file of index.files) {\r\n for (const symbol of file.symbols) {\r\n if (!symbol.file) symbol.file = file.path\r\n }\r\n }\r\n return index\r\n}\r\n\r\nexport async function saveIndex(cachePath: string, index: RepoIndex): Promise<void> {\r\n await mkdir(path.dirname(cachePath), { recursive: true })\r\n const temporaryPath = `${cachePath}.${process.pid}.${randomUUID()}.tmp`\r\n try {\r\n await writeFile(temporaryPath, JSON.stringify(index, null, 2), { encoding: 'utf8', flag: 'wx' })\r\n await rename(temporaryPath, cachePath)\r\n } finally {\r\n await rm(temporaryPath, { force: true })\r\n }\r\n}\r\n","/** Shared data model for dsh-code-index. */\r\n\r\nexport type SymbolKind =\r\n | 'function'\r\n | 'method'\r\n | 'class'\r\n | 'interface'\r\n | 'type'\r\n | 'enum'\r\n | 'variable'\r\n | 'field'\r\n | 'import'\r\n | 'module'\r\n\r\nexport interface SymbolInfo {\r\n /** Symbol name (identifier / type id / member name). */\r\n name: string\r\n kind: SymbolKind\r\n /** Repo-relative path of the containing file, always forward-slash. */\r\n file: string\r\n /** 1-based start line. */\r\n line: number\r\n /** 1-based end line (inclusive). */\r\n endLine: number\r\n /** True when the symbol is exported at module level (export .. / export default). */\r\n exported: boolean\r\n /** Short human-readable signature, e.g. `greet(name: string)` — empty when n/a. */\r\n signature: string\r\n}\r\n\r\nexport interface IndexedFile {\r\n /** Repo-relative path (forward-slash). */\r\n path: string\r\n lang: string\r\n /** fs mtime of the source file at index time (milliseconds). */\r\n mtimeMs: number\r\n symbols: SymbolInfo[]\r\n /** Raw import specifiers found in this file ('./util', 'mypkg/core', …).\r\n * Optional because caches written before reference ranking lack it. */\r\n imports?: string[]\r\n}\r\n\r\nexport interface RepoIndex {\r\n /** Absolute source root this index describes. */\r\n root: string\r\n /** Unix ms when the index was generated. */\r\n generatedAt: number\r\n files: IndexedFile[]\r\n excludedDirs: string[]\r\n}\r\n\r\nexport function symbolCount(index: RepoIndex): number {\r\n return index.files.reduce((n, f) => n + f.symbols.length, 0)\r\n}\r\n\r\n/** Optional config consumed by the index build pipeline. */\r\nexport interface IndexOptions {\r\n /** Extra directories to exclude, appended to the defaults. */\r\n excludeDirs?: string[]\r\n /** Minimum mtime delta (ms) that forces a re-extract in refresh mode. */\r\n staleToleranceMs?: number\r\n}","/** Pure search / filter logic over a RepoIndex — unit-testable, no IO. */\r\n\r\nimport type { RepoIndex, SymbolInfo, SymbolKind } from './types.js'\r\n\r\nexport interface SymbolFilter {\r\n query?: string\r\n file?: string\r\n kind?: SymbolKind\r\n exportedOnly?: boolean\r\n}\r\n\r\nexport interface RankedHit extends SymbolInfo {\r\n /** 0..1 relevance. 1 = exact name match; lower = fuzzier. */\r\n score: number\r\n}\r\n\r\nfunction matchScore(name: string, query: string): number {\r\n const q = query.toLowerCase()\r\n const n = name.toLowerCase()\r\n if (n === q) return 1\r\n if (n.startsWith(q)) return 0.8\r\n if (n.includes(q)) return 0.5\r\n if (q.length >= 3 && isSubsequence(q, n)) return 0.3\r\n return 0\r\n}\r\n\r\n/**\r\n * Every query char appears in the name, in order — 'cfgldr' finds\r\n * 'configLoader'. Gated to 3+ chars so short queries don't match everything.\r\n */\r\nfunction isSubsequence(query: string, name: string): boolean {\r\n let i = 0\r\n for (const ch of name) {\r\n if (ch === query[i]) i++\r\n if (i === query.length) return true\r\n }\r\n return false\r\n}\r\n\r\n/** Filter symbols by file/kind/export, then score by name against query (if any). */\r\nexport function searchSymbols(\r\n index: RepoIndex,\r\n filter: SymbolFilter,\r\n limit = 50,\r\n): RankedHit[] {\r\n const q = (filter.query ?? '').trim()\r\n const filePat = filter.file?.trim().toLowerCase()\r\n const hits: RankedHit[] = []\r\n\r\n for (const file of index.files) {\r\n if (filePat && !file.path.toLowerCase().includes(filePat)) continue\r\n for (const sym of file.symbols) {\r\n if (filter.kind && sym.kind !== filter.kind) continue\r\n if (filter.exportedOnly && !sym.exported) continue\r\n const score = q ? matchScore(sym.name, q) : 0.4\r\n if (q && score === 0) continue\r\n hits.push({ ...sym, score })\r\n }\r\n }\r\n\r\n // Export boost, then relevance, then stable name order.\r\n hits.sort((a, b) => {\r\n const ab =\r\n Number(b.exported) - Number(a.exported) ||\r\n b.score - a.score ||\r\n a.name.localeCompare(b.name) ||\r\n a.file.localeCompare(b.file)\r\n return ab\r\n })\r\n return hits.slice(0, limit)\r\n}\r\n\r\n/** Neat one-line rendering of a hit for terminal/chat output. */\r\nexport function renderHit(hit: RankedHit): string {\r\n const exportMark = hit.exported ? 'export ' : ''\r\n const sig = hit.signature || hit.name\r\n const score = hit.score < 1 ? ` [${hit.score.toFixed(2)}]` : ''\r\n return `${exportMark}${hit.kind} ${sig}${score} — ${hit.file}:${hit.line}`\r\n}","/**\r\n * Bounded, ranked repo map generation — the \"aider-style\" overview the model\r\n * can turn to before browsing files. Pure logic, no IO.\r\n */\r\n\r\nimport path from 'node:path'\r\nimport { SUPPORTED_EXTS } from './scan.js'\r\nimport type { IndexedFile, RepoIndex, SymbolInfo, SymbolKind } from './types.js'\r\n\r\n/** Higher-weight symbols pull their file up the map. */\r\nexport const KIND_WEIGHT: Record<SymbolKind, number> = {\r\n class: 1.0,\r\n interface: 1.0,\r\n type: 0.8,\r\n function: 0.8,\r\n method: 0.7,\r\n enum: 0.9,\r\n variable: 0.25,\r\n field: 0.2,\r\n import: 0.05,\r\n module: 0.3,\r\n}\r\n\r\nexport interface RepoMapOptions {\r\n /** Max files to include (default 24). */\r\n topFiles?: number\r\n /** Max symbols per file (default 18). */\r\n symbolsPerFile?: number\r\n /** Hard cap on rendered characters (default 3200). */\r\n maxChars?: number\r\n}\r\n\r\nexport interface RepoMapEntry {\r\n path: string\r\n score: number\r\n symbols: Array<{ name: string; kind: SymbolKind; line: number; signature: string }>\r\n}\r\n\r\n/**\r\n * Paths that look like tests. A map led by test files reads as noise: tests\r\n * reference an API, they rarely explain it — and symbol density actively\r\n * favours them (many small functions), so they need an explicit damper.\r\n */\r\nconst TEST_PATH_RE =\r\n /(^|\\/)(tests?|__tests__)(\\/|$)|\\.(?:spec|test)\\.[cm]?[jt]sx?$|(^|\\/)(?:test_[^/]+\\.py|[^/]+_test\\.(?:py|go))$/\r\n\r\n/** Density-aware file score: weighted symbols minus bloat; test paths damped. */\r\nexport function scoreFile(file: IndexedFile): number {\r\n let score = 0\r\n for (const sym of file.symbols) {\r\n score += KIND_WEIGHT[sym.kind] ?? 0.3\r\n if (sym.exported) score += 0.3\r\n }\r\n score /= 1 + file.symbols.length * 0.04\r\n if (TEST_PATH_RE.test(file.path)) score *= 0.2\r\n return score\r\n}\r\n\r\n/** Rank files, take the top slice, cap per-file symbols. */\r\nexport function rankRepoMap(index: RepoIndex, options: RepoMapOptions = {}): RepoMapEntry[] {\r\n const topFiles = options.topFiles ?? 24\r\n const perFile = options.symbolsPerFile ?? 18\r\n const refs = countReferences(index.files)\r\n const ranked = index.files\r\n .filter((f) => f.symbols.length > 0)\r\n .map((f) => ({\r\n file: f,\r\n score: scoreFile(f) + REF_WEIGHT * (refs.get(f.path) ?? 0),\r\n }))\r\n .sort((a, b) => b.score - a.score || a.file.path.localeCompare(b.file.path))\r\n .slice(0, topFiles)\r\n\r\n return ranked.map(({ file, score }) => ({\r\n path: file.path,\r\n score,\r\n symbols: file.symbols.slice(0, perFile).map((s) => ({\r\n name: s.name,\r\n kind: s.kind,\r\n line: s.line,\r\n signature: s.signature,\r\n })),\r\n }))\r\n}\r\n\r\n/** How much one in-repo import is worth in map score. */\r\nconst REF_WEIGHT = 0.5\r\n\r\n/**\r\n * Count in-repo references: how many OTHER indexed files import each file.\r\n * Self-imports don't count; each (importer, target) pair counts once.\r\n */\r\nexport function countReferences(files: IndexedFile[]): Map<string, number> {\r\n const fileSet = new Set(files.map((f) => f.path))\r\n const counts = new Map<string, number>()\r\n for (const file of files) {\r\n const targets = new Set<string>()\r\n for (const spec of file.imports ?? []) {\r\n const target = resolveImport(spec, file.path, fileSet)\r\n if (target && target !== file.path) targets.add(target)\r\n }\r\n for (const target of targets) {\r\n counts.set(target, (counts.get(target) ?? 0) + 1)\r\n }\r\n }\r\n return counts\r\n}\r\n\r\n/**\r\n * Resolve a raw import specifier against the indexed file set; returns the\r\n * repo-relative target path or null. Relative specifiers resolve against the\r\n * importing file; absolute ones against the repo root — with a suffix\r\n * fallback so Go module paths and Java package names match their in-repo\r\n * location without reading go.mod / package-info.\r\n */\r\nexport function resolveImport(spec: string, fromPath: string, fileSet: Set<string>): string | null {\r\n if (!spec) return null\r\n if (spec.startsWith('./') || spec.startsWith('../')) {\r\n const base = path.posix.normalize(path.posix.join(path.posix.dirname(fromPath), spec))\r\n return candidateFor(base, fileSet)\r\n }\r\n const segments = spec.split('/').filter(Boolean)\r\n for (let skip = 0; skip < segments.length; skip++) {\r\n const hit = candidateFor(segments.slice(skip).join('/'), fileSet)\r\n if (hit) return hit\r\n }\r\n return null\r\n}\r\n\r\n/** Extension and index-file candidates for a specifier base path. */\r\nfunction candidateFor(base: string, fileSet: Set<string>): string | null {\r\n for (const ext of SUPPORTED_EXTS) {\r\n if (fileSet.has(`${base}${ext}`)) return `${base}${ext}`\r\n }\r\n for (const ext of SUPPORTED_EXTS) {\r\n if (fileSet.has(`${base}/index${ext}`)) return `${base}/index${ext}`\r\n if (fileSet.has(`${base}/__init__${ext}`)) return `${base}/__init__${ext}`\r\n }\r\n return null\r\n}\r\n\r\n/** Render the ranked map as markdown, hard-truncated to maxChars. */\r\nexport function renderRepoMap(entries: RepoMapEntry[], options: RepoMapOptions = {}): string {\r\n const maxChars = options.maxChars ?? 3200\r\n const lines: string[] = ['# repo map']\r\n let totalSymbols = 0\r\n for (const e of entries) {\r\n totalSymbols += e.symbols.length\r\n lines.push(`## ${e.path} (${e.symbols.length})`)\r\n for (const s of e.symbols) {\r\n const label = s.signature || s.name\r\n lines.push(` ${s.kind} ${label} :${s.line}`)\r\n }\r\n }\r\n let text = lines.join('\\n')\r\n if (text.length > maxChars) {\r\n text = `${text.slice(0, maxChars)}\\n… truncated`\r\n }\r\n return totalSymbols > 0 ? text : ''\r\n}","/** Model-visible tools: code_index, code_symbols, code_search. */\r\n\r\nimport { defineTool, type JsonValue } from '@deepseek-ai/dsh-tools'\r\nimport path from 'node:path'\r\nimport { buildIndexWithCache, findRepoRoot } from './buildIndex.js'\r\nimport { renderHit, searchSymbols } from './search.js'\r\nimport { rankRepoMap, renderRepoMap } from './repomap.js'\r\nimport { getConfig, indexOptions } from './config.js'\r\nimport { cacheKeyForRoot } from './store.js'\r\nimport type { RepoIndex } from './types.js'\r\n\r\n/** Minimal structural types for the harness surfaces we touch. */\r\ninterface ToolCwdContext {\r\n agent?: {\r\n session?: { header?: { cwd?: string } }\r\n }\r\n}\r\ntype ToolRunExec = ToolCwdContext & { signal?: AbortSignal }\r\n\r\ninterface TextBlock {\r\n type: 'text'\r\n text: string\r\n}\r\n\r\nexport interface IndexCache {\r\n get(root: string, force?: boolean): Promise<RepoIndex>\r\n invalidate(): void\r\n}\r\n\r\n/** Retain completed indexes briefly while still coalescing concurrent refreshes. */\r\nexport function createIndexCache(\r\n load: (root: string) => Promise<RepoIndex>,\r\n ttlMs = 60_000,\r\n now: () => number = Date.now,\r\n): IndexCache {\r\n interface CompletedEntry {\r\n index: RepoIndex\r\n at: number\r\n epoch: number\r\n }\r\n interface LoadEntry {\r\n promise: Promise<RepoIndex>\r\n epoch: number\r\n }\r\n\r\n const completed = new Map<string, CompletedEntry>()\r\n const inFlight = new Map<string, LoadEntry>()\r\n let epoch = 0\r\n\r\n function startLoad(key: string, root: string, previous?: Promise<RepoIndex>): Promise<RepoIndex> {\r\n const loadEpoch = epoch\r\n const begin = previous\r\n ? previous.catch(() => undefined).then(() => load(root))\r\n : load(root)\r\n const promise = begin\r\n .then((index) => {\r\n if (loadEpoch === epoch) {\r\n completed.delete(key)\r\n completed.set(key, { index, at: now(), epoch: loadEpoch })\r\n while (completed.size > 16) completed.delete(completed.keys().next().value!)\r\n }\r\n return index\r\n })\r\n .finally(() => {\r\n if (inFlight.get(key)?.promise === promise) inFlight.delete(key)\r\n })\r\n inFlight.set(key, { promise, epoch: loadEpoch })\r\n return promise\r\n }\r\n\r\n return {\r\n get(root, force = false) {\r\n const resolvedRoot = path.resolve(root)\r\n const key = cacheKeyForRoot(resolvedRoot)\r\n const running = inFlight.get(key)\r\n if (running) {\r\n if (running.epoch === epoch && !force) return running.promise\r\n return startLoad(key, resolvedRoot, running.promise)\r\n }\r\n\r\n if (!force) {\r\n const cached = completed.get(key)\r\n if (cached && cached.epoch === epoch && now() - cached.at < ttlMs) {\r\n completed.delete(key)\r\n completed.set(key, cached)\r\n return Promise.resolve(cached.index)\r\n }\r\n if (cached) completed.delete(key)\r\n } else {\r\n completed.delete(key)\r\n }\r\n return startLoad(key, resolvedRoot)\r\n },\r\n invalidate() {\r\n epoch++\r\n completed.clear()\r\n },\r\n }\r\n}\r\n\r\nconst indexCache = createIndexCache((root) => buildIndexWithCache(root, indexOptions()))\r\n\r\nexport function getIndex(root: string, force = false): Promise<RepoIndex> {\r\n return indexCache.get(root, force)\r\n}\r\n\r\nexport function invalidateIndexCache(): void {\r\n indexCache.invalidate()\r\n}\r\n\r\nasync function resolveRoot(arg: string | undefined, exec: ToolRunExec): Promise<string> {\r\n const cwd = exec.agent?.session?.header?.cwd\r\n const base = arg ?? cwd ?? process.cwd()\r\n const root = await findRepoRoot(base)\r\n if (!root) throw new Error(`no git repository found from ${path.resolve(base)}`)\r\n return root\r\n}\r\n\r\nexport const tools = [\r\n defineTool({\r\n name: 'code_index',\r\n description:\r\n 'Manage the semantic repo index: status or (re)build it for the current workspace. Auto-builds the first time it is queried. Returns file/symbol counts and the index location.',\r\n parameters: {\r\n action: {\r\n type: 'string',\r\n enum: ['status', 'build'],\r\n description: '\"status\" (default) reports without forcing a rebuild; \"build\" forces a fresh scan.',\r\n },\r\n repoRoot: {\r\n type: 'string',\r\n description:\r\n 'Optional absolute repo path. Defaults to the workspace root of the current session.',\r\n },\r\n },\r\n output: {\r\n schema: { type: 'string' },\r\n render: (_args, value: string): TextBlock[] => [{ type: 'text', text: value }],\r\n },\r\n async execute(args: { action?: string; repoRoot?: string }, exec: ToolRunExec): Promise<string> {\r\n try {\r\n const root = await resolveRoot(args.repoRoot, exec)\r\n const index = await getIndex(root, args.action === 'build')\r\n const total = index.files.reduce((n, f) => n + f.symbols.length, 0)\r\n const langs = new Set(index.files.map((f) => f.lang))\r\n return [\r\n `repo: ${root}`,\r\n `files indexed: ${index.files.length}`,\r\n `symbols: ${total}`,\r\n `languages: ${[...langs].join(', ')}`,\r\n index.files.length === 0 ? 'no supported files found' : 'index up to date',\r\n ].join('\\n')\r\n } catch (error) {\r\n return `code_index: ${(error as Error).message ?? String(error)}`\r\n }\r\n },\r\n }),\r\n\r\n defineTool({\r\n name: 'code_symbols',\r\n description:\r\n 'List symbols (functions, classes, interfaces, types, methods, variables) in the current repo. Filter by name substring, file path substring, or symbol kind. Results are exported-first, alphabetically ordered.',\r\n parameters: {\r\n query: {\r\n type: 'string',\r\n description: 'Substring of the symbol name to match (case-insensitive). Omit to list all.',\r\n },\r\n file: {\r\n type: 'string',\r\n description: 'Substring of the repo-relative file path to match, e.g. \"src/core\".',\r\n },\r\n kind: {\r\n type: 'string',\r\n enum: ['function', 'method', 'class', 'interface', 'type', 'enum', 'variable', 'field'],\r\n description: 'Only return symbols of this kind.',\r\n },\r\n exportedOnly: {\r\n type: 'boolean',\r\n description: 'Only exported (module-level public) symbols.',\r\n },\r\n limit: {\r\n type: 'number',\r\n description: 'Max rows (default 50).',\r\n },\r\n repoRoot: {\r\n type: 'string',\r\n description: 'Optional absolute repo path; defaults to the session workspace root.',\r\n },\r\n },\r\n output: {\r\n schema: { type: 'array' },\r\n render: (_args, value: JsonValue[]): TextBlock[] =>\r\n value.map((v) => ({\r\n type: 'text' as const,\r\n text: renderHit(v as unknown as Parameters<typeof renderHit>[0]),\r\n })),\r\n },\r\n async execute(\r\n args: {\r\n query?: string\r\n file?: string\r\n kind?: 'function' | 'method' | 'class' | 'interface' | 'type' | 'enum' | 'variable' | 'field'\r\n exportedOnly?: boolean\r\n limit?: number\r\n repoRoot?: string\r\n },\r\n exec: ToolRunExec,\r\n ): Promise<JsonValue[]> {\r\n const root = await resolveRoot(args.repoRoot, exec)\r\n const index = await getIndex(root)\r\n const hits = searchSymbols(\r\n index,\r\n { query: args.query, file: args.file, kind: args.kind, exportedOnly: args.exportedOnly },\r\n args.limit ?? 50,\r\n )\r\n return hits as unknown as JsonValue[]\r\n },\r\n }),\r\n\r\n defineTool({\r\n name: 'code_search',\r\n description:\r\n 'Ranked symbol search over the repo index: exact > prefix > substring name matches, exported symbols first. Results carry a relevance score and file:line, so the model can locate definitions quickly.',\r\n parameters: {\r\n query: {\r\n type: 'string',\r\n required: true,\r\n description: 'Symbol name (or fragment) to find.',\r\n },\r\n limit: {\r\n type: 'number',\r\n description: 'Max hits (default 20).',\r\n },\r\n repoRoot: {\r\n type: 'string',\r\n description: 'Optional absolute repo path; defaults to the session workspace root.',\r\n },\r\n },\r\n output: {\r\n schema: { type: 'array' },\r\n render: (_args, value: JsonValue[]): TextBlock[] =>\r\n value.map((v) => ({\r\n type: 'text' as const,\r\n text: renderHit(v as unknown as Parameters<typeof renderHit>[0]),\r\n })),\r\n },\r\n async execute(\r\n args: { query: string; limit?: number; repoRoot?: string },\r\n exec: ToolRunExec,\r\n ): Promise<JsonValue[]> {\r\n const root = await resolveRoot(args.repoRoot, exec)\r\n const index = await getIndex(root)\r\n const hits = searchSymbols(index, { query: args.query }, args.limit ?? 20)\r\n return hits as unknown as JsonValue[]\r\n },\r\n }),\r\n\r\n defineTool({\r\n name: 'code_map',\r\n description:\r\n 'Return a bounded, ranked map of the current repo (top files by symbol density, with their key symbols and lines). The model can call this once per session to build an internal model of the codebase before browsing files.',\r\n parameters: {\r\n repoRoot: {\r\n type: 'string',\r\n description: 'Optional absolute repo path; defaults to the session workspace root.',\r\n },\r\n },\r\n output: {\r\n schema: { type: 'string' },\r\n render: (_args, value: string): TextBlock[] => [{ type: 'text', text: value }],\r\n },\r\n async execute(args: { repoRoot?: string }, exec: ToolRunExec): Promise<string> {\r\n try {\r\n const root = await resolveRoot(args.repoRoot, exec)\r\n const index = await getIndex(root)\r\n const cfg = getConfig()\r\n const map = renderRepoMap(\r\n rankRepoMap(index, { topFiles: cfg.mapTopFiles }),\r\n { maxChars: cfg.mapMaxChars },\r\n )\r\n if (!map) return 'no indexable symbols found in this repo'\r\n return map\r\n } catch (error) {\r\n return `code_index: ${(error as Error).message ?? String(error)}`\r\n }\r\n },\r\n }),\r\n]\r\n","/** Plugin configuration: merged once at apply time, read wherever needed. */\r\n\r\nimport type { IndexOptions } from './types.js'\r\n\r\nexport interface PluginConfig {\r\n /** Extra directories to exclude from indexing (appended to defaults). */\r\n excludeDirs?: string[]\r\n /** Max files in the ranked repo map (code_map / auto section). */\r\n mapTopFiles?: number\r\n /** Hard char cap for rendered maps. */\r\n mapMaxChars?: number\r\n /** Refresh interval for the auto-injected map (ms, min 1000). */\r\n mapTtlMs?: number\r\n /** Set false to disable the auto-injected system section. */\r\n autoInject?: boolean\r\n}\r\n\r\ninterface EffectiveConfig {\r\n excludeDirs: string[]\r\n mapTopFiles: number\r\n mapMaxChars: number\r\n mapTtlMs: number\r\n autoInject: boolean\r\n}\r\n\r\nconst DEFAULTS: EffectiveConfig = {\r\n excludeDirs: [],\r\n mapTopFiles: 24,\r\n mapMaxChars: 3200,\r\n mapTtlMs: 60_000,\r\n autoInject: true,\r\n}\r\n\r\nconst state: { current: EffectiveConfig } = { current: { ...DEFAULTS } }\r\n\r\n/** Merge a plugin-provided partial config over the defaults (idempotent). */\r\nexport function applyConfig(partial?: PluginConfig): void {\r\n state.current = {\r\n ...DEFAULTS,\r\n ...(partial ?? {}),\r\n excludeDirs: [...DEFAULTS.excludeDirs, ...(partial?.excludeDirs ?? [])],\r\n }\r\n // Coerce obviously wrong inputs.\r\n if (!Number.isFinite(state.current.mapTopFiles) || state.current.mapTopFiles < 1) {\r\n state.current.mapTopFiles = DEFAULTS.mapTopFiles\r\n }\r\n if (!Number.isFinite(state.current.mapMaxChars) || state.current.mapMaxChars < 200) {\r\n state.current.mapMaxChars = DEFAULTS.mapMaxChars\r\n }\r\n if (!Number.isFinite(state.current.mapTtlMs) || state.current.mapTtlMs < 1_000) {\r\n state.current.mapTtlMs = DEFAULTS.mapTtlMs\r\n }\r\n}\r\n\r\nexport function getConfig(): Readonly<EffectiveConfig> {\r\n return state.current\r\n}\r\n\r\n/** Map the effective config onto the index pipeline options. */\r\nexport function indexOptions(): IndexOptions {\r\n return { excludeDirs: state.current.excludeDirs }\r\n}","/**\r\n * dsh-code-index — DeepSeek Harness bundle entry.\r\n *\r\n * Registers four model-visible tools (code_index / code_symbols /\r\n * code_search / code_map) backed by a tree-sitter symbol index, and\r\n * injects a bounded auto-updating repo map for the default workspace\r\n * into the system prompt.\r\n */\r\n\r\ntype Disposer = void | (() => void)\r\n\r\n/** Minimal structural Context; the real @deepseek-ai/cordis type is a\r\n * runtime dependency we intentionally do not import in the bundle entry. */\r\ninterface MinimalContext {\r\n effect(fn: () => Disposer): void\r\n tools: { register(t: unknown): () => void }\r\n systemPrompt: {\r\n section(section: {\r\n name: string\r\n order: number\r\n text: string | ((context: unknown) => string)\r\n }): () => void\r\n }\r\n}\r\n\r\nexport const name = 'dsh-code-index'\r\n\r\n// Public API surface (consumable by other bundles / tests).\r\nexport { buildIndex, buildIndexWithCache, findRepoRoot } from './buildIndex.js'\r\nexport { extractSymbols, extractAll, languageForFile, parseFileToSymbols } from './extract.js'\r\nexport { scanRepo, DEFAULT_EXCLUDED_DIRS, SUPPORTED_EXTS } from './scan.js'\r\nexport { loadIndex, saveIndex, defaultCachePath, CACHE_DIR_NAME } from './store.js'\r\nexport { symbolCount } from './types.js'\r\nexport type { RepoIndex, IndexedFile, SymbolInfo, SymbolKind, IndexOptions } from './types.js'\r\nexport { searchSymbols, renderHit } from './search.js'\r\nexport { rankRepoMap, renderRepoMap, scoreFile } from './repomap.js'\r\nexport { tools } from './tools.js'\r\n\r\nimport { getIndex, invalidateIndexCache, tools } from './tools.js'\r\nimport { findRepoRoot } from './buildIndex.js'\r\nimport { rankRepoMap, renderRepoMap } from './repomap.js'\r\nimport { symbolCount } from './types.js'\r\nimport { applyConfig, getConfig, type PluginConfig } from './config.js'\r\n\r\nexport const inject = ['tools', 'systemPrompt'] as const\r\n\r\nexport function apply(ctx: MinimalContext, pluginConfig?: PluginConfig) {\r\n applyConfig(pluginConfig)\r\n invalidateIndexCache()\r\n ctx.effect(() => {\r\n const disposers: Array<() => void> = []\r\n console.log('[dsh-code-index] plugin loaded')\r\n for (const tool of tools) {\r\n disposers.push(ctx.tools.register(tool))\r\n console.log(`[dsh-code-index] registered tool: ${tool.name}`)\r\n }\r\n\r\n // Auto-inject a bounded repo map for the DEFAULT workspace (the dsh\r\n // launch directory, per the harness docs). Multi-workspace web sessions\r\n // should rely on the `code_map` tool, which resolves the per-session cwd.\r\n let cached: { root: string; at: number; text: string } | null = null\r\n\r\n async function warmMap(): Promise<void> {\r\n const now = Date.now()\r\n const cfg = getConfig()\r\n try {\r\n const root = await findRepoRoot(process.cwd())\r\n if (!root) {\r\n cached = { root: '', at: now, text: '' }\r\n return\r\n }\r\n const index = await getIndex(root)\r\n const text = renderRepoMap(\r\n rankRepoMap(index, { topFiles: cfg.mapTopFiles }),\r\n { maxChars: cfg.mapMaxChars },\r\n )\r\n const stats = symbolCount(index)\r\n cached = {\r\n root: index.root,\r\n at: Date.now(),\r\n text: text ? `${text}\\n\\n(summary: ${index.files.length} files, ${stats} symbols)` : '',\r\n }\r\n } catch {\r\n cached = { root: '', at: now, text: '' } // never let injection fail the boot\r\n }\r\n }\r\n\r\n // Warm eagerly at load so the first assembly already has the map.\r\n void warmMap()\r\n\r\n if (getConfig().autoInject) {\r\n disposers.push(ctx.systemPrompt.section({\r\n name: 'code-index:repo-map',\r\n order: 60, // before tool guidance (100–199), after persona (0)\r\n text: () => {\r\n const now = Date.now()\r\n if (cached && now - cached.at < getConfig().mapTtlMs) return cached.text\r\n void warmMap()\r\n return cached?.text ?? ''\r\n },\r\n }))\r\n }\r\n\r\n return () => {\r\n const errors: unknown[] = []\r\n for (const dispose of disposers.reverse()) {\r\n try {\r\n dispose()\r\n } catch (error) {\r\n errors.push(error)\r\n }\r\n }\r\n console.log('[dsh-code-index] plugin unloaded')\r\n if (errors.length > 0) throw new AggregateError(errors, 'failed to unload dsh-code-index')\r\n }\r\n })\r\n}\r\n"],"mappings":";AAEA,SAAS,YAAAA,WAAU,QAAAC,aAAY;AAC/B,OAA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Q,IAAI,kCAAkC;AAC9C,UAAI,OAAO,SAAS,EAAG,OAAM,IAAI,eAAe,QAAQ,iCAAiC;AAAA,IAC3F;AAAA,EACF,CAAC;AACH;","names":["readFile","stat","path","require","name","path","readFile","path","readFile","path","stat","name","path","path","path","path"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-code-index",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Semantic repo index for DeepSeek Harness — tree-sitter symbol index, code search, and a bounded ranked repo map injected into agent context.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,9 +40,20 @@
40
40
  "vitest": "^4.1.8"
41
41
  },
42
42
  "license": "MIT",
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "https://github.com/lemonxiny55/dsh-code-index.git"
49
+ },
50
+ "homepage": "https://github.com/lemonxiny55/dsh-code-index",
51
+ "bugs": {
52
+ "url": "https://github.com/lemonxiny55/dsh-code-index/issues"
53
+ },
43
54
  "dependencies": {
44
55
  "@deepseek-ai/dsh-tools": "0.1.0-rc.8",
45
56
  "tree-sitter-wasms": "^0.1.13",
46
57
  "web-tree-sitter": "^0.20.8"
47
58
  }
48
- }
59
+ }