@ninjaxtools/slopdex 0.3.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/.agents/skills/slopdex/SKILL.md +178 -0
- package/LICENSE +21 -0
- package/README.md +181 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +1691 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +213 -0
- package/dist/index.js +1413 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
- package/scripts/install-opencode-skill.mjs +11 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/code-index.ts","../src/errors.ts","../src/git/repository.ts","../src/parser/callable-parser.ts","../src/utils.ts","../src/source-policy.ts","../src/storage/database.ts","../src/search/cross-search.ts","../src/embeddings/openai.ts","../src/embeddings/http.ts","../src/embeddings/jina.ts","../src/index.ts"],"sourcesContent":["import { lstat, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { CodeIndexError, GitDivergenceError } from \"./errors.js\";\nimport { GitRepository, type GitChange, type GitTreeEntry } from \"./git/repository.js\";\nimport { parseCallables } from \"./parser/callable-parser.js\";\nimport { SourcePolicy } from \"./source-policy.js\";\nimport { IndexDatabase, type PreparedCallable, type PreparedFile } from \"./storage/database.js\";\nimport type {\n CodeIndexOptions,\n CrossSearchSourceFilter,\n EmbeddingProfile,\n IndexStatus,\n IndexedFunction,\n SimilarityResult,\n SimilaritySearchOptions,\n UpdateFilesOptions,\n UpdateFromGitOptions,\n UpdateStats,\n} from \"./types.js\";\nimport { assertPositiveInteger, chunk, normalizeEmbeddingVector, normalizeRelativePath, sha256, throwIfAborted } from \"./utils.js\";\n\nconst DEFAULT_MAX_FILE_SIZE = 1024 * 1024;\nconst DEFAULT_BATCH_SIZE = 32;\n\nexport class CodeIndex {\n public readonly rootDir: string;\n public readonly indexPath: string;\n public readonly provider;\n readonly #database: IndexDatabase;\n readonly #policy: SourcePolicy;\n readonly #maxFileSize: number;\n readonly #embeddingBatchSize: number;\n readonly #git: GitRepository;\n readonly #onWarning: (message: string) => void;\n\n public constructor(options: CodeIndexOptions) {\n this.rootDir = path.resolve(options.rootDir);\n this.indexPath = path.resolve(options.indexPath ?? path.join(this.rootDir, \".slopdex\", \"index.sqlite\"));\n this.provider = options.provider;\n const profile = normalizeProfile(options.provider.profile);\n assertPositiveInteger(profile.dimensions, \"embedding dimensions\");\n this.#database = new IndexDatabase(this.indexPath, this.rootDir, profile, options.readOnly ?? false);\n this.#policy = new SourcePolicy(options.include, options.exclude);\n this.#maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n this.#embeddingBatchSize = options.embeddingBatchSize ?? DEFAULT_BATCH_SIZE;\n this.#onWarning = options.onWarning ?? console.warn;\n assertPositiveInteger(this.#maxFileSize, \"maxFileSize\");\n assertPositiveInteger(this.#embeddingBatchSize, \"embeddingBatchSize\");\n this.#git = new GitRepository(this.rootDir);\n }\n\n public close(): void {\n this.#database.close();\n }\n\n public status(): IndexStatus {\n return this.#database.status();\n }\n\n public allFunctions(): IndexedFunction[] {\n return this.#database.allFunctions();\n }\n\n public async updateFiles(options: UpdateFilesOptions): Promise<UpdateStats> {\n const normalizedRenames = (options.renames ?? []).map(({ from, to }) => ({\n from: normalizeRelativePath(this.rootDir, from),\n to: normalizeRelativePath(this.rootDir, to),\n }));\n validateRenames(normalizedRenames);\n const upsertPaths = [...new Set((options.upsert ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];\n const deletePaths = [...new Set((options.delete ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];\n const renameMap = new Map(\n normalizedRenames.map(({ from, to }) => [to, from]),\n );\n for (const target of renameMap.keys()) {\n if (!upsertPaths.includes(target)) upsertPaths.push(target);\n }\n\n const prepared: PreparedFile[] = [];\n for (const relativePath of upsertPaths) {\n throwIfAborted(options.signal);\n if (!this.#policy.includes(relativePath)) throw new CodeIndexError(`Unsupported or excluded source file: ${relativePath}`);\n const absolutePath = path.join(this.rootDir, relativePath);\n const info = await lstat(absolutePath);\n if (info.isSymbolicLink()) throw new CodeIndexError(`Symbolic links are not supported: ${relativePath}`);\n if (!info.isFile()) throw new CodeIndexError(`Not a regular file: ${relativePath}`);\n if (info.size > this.#maxFileSize) throw new CodeIndexError(`File exceeds maxFileSize: ${relativePath}`);\n const content = await readFile(absolutePath);\n const renameSource = renameMap.get(relativePath);\n const originalPath = renameSource ? this.#database.previousPath(renameSource) ?? renameSource : undefined;\n prepared.push(this.#prepareFile(relativePath, content, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n ...(originalPath ? { previousPath: originalPath } : {}),\n ...(renameSource ? { replacePath: renameSource } : {}),\n }));\n }\n await this.#attachEmbeddings(prepared, options.signal);\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: [...deletePaths, ...renameMap.values()],\n });\n }\n\n public async updateFromGit(options: UpdateFromGitOptions = {}): Promise<UpdateStats> {\n throwIfAborted(options.signal);\n await this.#git.assertRepository();\n const relativeIndexPath = path.relative(this.rootDir, this.indexPath).replaceAll(path.sep, \"/\");\n const indexArtifacts = relativeIndexPath && !relativeIndexPath.startsWith(\"../\")\n ? [relativeIndexPath, `${relativeIndexPath}-shm`, `${relativeIndexPath}-wal`, `${relativeIndexPath}-journal`]\n : [];\n await this.#git.assertCleanWorkingTree(indexArtifacts);\n const target = await this.#git.resolveCommit(options.target ?? \"HEAD\");\n const checkpoint = this.#database.getCheckpoint();\n let rebuild = checkpoint === null;\n if (checkpoint && !(await this.#git.isAncestor(checkpoint, target))) {\n if (!options.rebuildOnDivergence) throw new GitDivergenceError(checkpoint, target);\n rebuild = true;\n }\n\n const tree = await this.#git.listTree(target);\n const workingFiles = this.#database.getWorkingTreeFiles();\n const changes = rebuild || !checkpoint ? [] : await this.#git.diff(checkpoint, target);\n const upserts = new Map<string, { entry: GitTreeEntry; previousPath?: string }>();\n const deletes = new Set<string>();\n if (rebuild) {\n for (const existing of this.#database.allFilePaths()) deletes.add(existing);\n for (const entry of tree.values()) {\n if (this.#policy.includes(entry.path) && entry.size <= this.#maxFileSize) upserts.set(entry.path, { entry });\n }\n } else {\n this.#classifyGitChanges(changes, tree, upserts, deletes);\n for (const { path: dirtyPath } of workingFiles) {\n const entry = tree.get(dirtyPath);\n if (entry && this.#policy.includes(dirtyPath) && entry.size <= this.#maxFileSize) upserts.set(dirtyPath, { entry });\n else deletes.add(dirtyPath);\n }\n const eligibleTargetPaths = new Set(\n [...tree.values()]\n .filter((entry) => this.#policy.includes(entry.path) && entry.size <= this.#maxFileSize)\n .map((entry) => entry.path),\n );\n const indexedPaths = new Set(this.#database.allFilePaths());\n for (const targetPath of eligibleTargetPaths) {\n if (!indexedPaths.has(targetPath) && !upserts.has(targetPath)) {\n upserts.set(targetPath, { entry: tree.get(targetPath)! });\n }\n }\n for (const indexedPath of indexedPaths) {\n if (!eligibleTargetPaths.has(indexedPath)) deletes.add(indexedPath);\n }\n }\n\n if (!rebuild && checkpoint === target && upserts.size === 0 && deletes.size === 0) return emptyStats(checkpoint);\n\n const prepared: PreparedFile[] = [];\n for (const { entry, previousPath } of upserts.values()) {\n throwIfAborted(options.signal);\n const content = await this.#git.readBlob(entry.oid);\n if (content.byteLength > this.#maxFileSize) {\n deletes.add(entry.path);\n continue;\n }\n prepared.push(this.#prepareFile(entry.path, content, {\n blobOid: entry.oid,\n sourceMode: \"git\",\n indexedCommit: target,\n ...(previousPath ? { replacePath: previousPath } : {}),\n }));\n }\n await this.#attachEmbeddings(prepared, options.signal);\n const resolvedAgain = await this.#git.resolveCommit(options.target ?? \"HEAD\");\n if (resolvedAgain !== target) throw new CodeIndexError(\"Target Git ref changed while indexing; retry the update.\");\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: [...deletes],\n checkpoint: target,\n expectedCheckpoint: checkpoint,\n });\n }\n\n #classifyGitChanges(\n changes: readonly GitChange[],\n tree: ReadonlyMap<string, GitTreeEntry>,\n upserts: Map<string, { entry: GitTreeEntry; previousPath?: string }>,\n deletes: Set<string>,\n ): void {\n for (const change of changes) {\n if (change.status === \"D\") {\n deletes.add(change.path);\n continue;\n }\n if (change.status === \"R\") {\n deletes.add(change.oldPath);\n const entry = tree.get(change.path);\n if (entry && this.#policy.includes(change.path) && entry.size <= this.#maxFileSize) {\n upserts.set(change.path, { entry, previousPath: change.oldPath });\n }\n continue;\n }\n const entry = tree.get(change.path);\n if (entry && this.#policy.includes(change.path) && entry.size <= this.#maxFileSize) upserts.set(change.path, { entry });\n else deletes.add(change.path);\n }\n }\n\n #prepareFile(\n relativePath: string,\n buffer: Buffer,\n provenance: Pick<PreparedFile, \"blobOid\" | \"sourceMode\" | \"indexedCommit\" | \"previousPath\" | \"replacePath\">,\n ): PreparedFile {\n const content = buffer.toString(\"utf8\");\n const callables = parseCallables(relativePath, content, this.#onWarning) as PreparedCallable[];\n const language = callables[0]?.language ?? path.extname(relativePath).slice(1);\n return {\n path: relativePath,\n contentHash: sha256(content),\n blobOid: provenance.blobOid,\n sourceMode: provenance.sourceMode,\n indexedCommit: provenance.indexedCommit,\n language,\n byteSize: buffer.byteLength,\n ...(provenance.previousPath ? { previousPath: provenance.previousPath } : {}),\n ...(provenance.replacePath ? { replacePath: provenance.replacePath } : {}),\n callables,\n };\n }\n\n async #attachEmbeddings(files: PreparedFile[], signal?: AbortSignal): Promise<void> {\n const profile = JSON.stringify(normalizeProfile(this.provider.profile));\n const unique = new Map<string, PreparedCallable[]>();\n for (const file of files) {\n for (const callable of file.callables) {\n callable.embeddingKey = sha256(`${profile}\\0${callable.embeddingInput}`);\n const values = unique.get(callable.embeddingKey) ?? [];\n values.push(callable);\n unique.set(callable.embeddingKey, values);\n }\n }\n const existing = this.#database.getEmbeddingKeys([...unique.keys()]);\n const missing = [...unique.entries()].filter(([key]) => !existing.has(key));\n for (const batch of chunk(missing, this.#embeddingBatchSize)) {\n throwIfAborted(signal);\n const vectors = await this.provider.embedDocuments(batch.map(([, callables]) => callables[0]!.embeddingInput), signal ? { signal } : undefined);\n if (vectors.length !== batch.length) throw new CodeIndexError(\"Embedding provider returned an unexpected number of vectors.\");\n vectors.forEach((vector, index) => {\n const converted = normalizeEmbeddingVector(vector, this.provider.profile.dimensions);\n for (const callable of batch[index]![1]) callable.vector = converted;\n });\n }\n }\n\n public async similaritySearch(options: SimilaritySearchOptions): Promise<SimilarityResult[]> {\n if (!options.query.trim()) throw new CodeIndexError(\"query must not be empty.\");\n const limit = options.limit ?? 10;\n assertPositiveInteger(limit, \"limit\");\n throwIfAborted(options.signal);\n const vector = await this.provider.embedQuery(options.query, options.signal ? { signal: options.signal } : undefined);\n return this.searchByVector(vector, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n });\n }\n\n public similarToFunction(functionId: number, options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n }): SimilarityResult[] {\n const vector = this.#database.vectorForFunction(functionId);\n return this.#database.searchVector(vector, {\n limit: options.limit,\n minSimilarity: options.minSimilarity,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n excludeId: functionId,\n });\n }\n\n public vectorForFunction(functionId: number): number[] {\n return this.#database.vectorForFunction(functionId);\n }\n\n public searchByVector(vector: readonly number[], options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n }): SimilarityResult[] {\n return this.#database.searchVector(normalizeEmbeddingVector(vector, this.provider.profile.dimensions), options);\n }\n\n public async sourceFunctions(filter: CrossSearchSourceFilter): Promise<IndexedFunction[]> {\n const functions = filter.type === \"all\" ? this.allFunctions() : await this.#functionsAddedSince(filter.commit);\n if (!filter.path) return functions;\n const sourcePath = normalizeRelativePath(this.rootDir, filter.path);\n return functions.filter((callable) => callable.path === sourcePath || callable.path.startsWith(`${sourcePath}/`));\n }\n\n async #functionsAddedSince(baseRef: string): Promise<IndexedFunction[]> {\n await this.#git.assertRepository();\n const checkpoint = this.#database.getCheckpoint();\n if (!checkpoint) throw new CodeIndexError(\"added-since requires an index with a Git checkpoint.\");\n const base = await this.#git.resolveCommit(baseRef);\n if (!(await this.#git.isAncestor(base, checkpoint))) {\n throw new GitDivergenceError(base, checkpoint);\n }\n\n const changes = await this.#git.diff(base, checkpoint);\n const baseTree = await this.#git.listTree(base);\n const comparisonPaths = new Map<string, string | null>();\n for (const change of changes) {\n if (change.status === \"D\") continue;\n if (change.status === \"R\") comparisonPaths.set(change.path, change.oldPath);\n else if (change.status === \"A\" || change.status === \"C\") comparisonPaths.set(change.path, null);\n else comparisonPaths.set(change.path, change.path);\n }\n for (const dirtyFile of this.#database.getWorkingTreeFiles()) {\n if (!comparisonPaths.has(dirtyFile.path)) {\n comparisonPaths.set(dirtyFile.path, dirtyFile.previousPath ?? dirtyFile.path);\n }\n }\n\n const current = this.#database.functionsForPaths([...comparisonPaths.keys()]);\n const baseFunctionsByCurrentPath = new Map<string, ReturnType<typeof parseCallables>>();\n for (const [currentPath, basePath] of comparisonPaths) {\n if (!basePath) {\n baseFunctionsByCurrentPath.set(currentPath, []);\n continue;\n }\n const entry = baseTree.get(basePath);\n if (!entry) {\n baseFunctionsByCurrentPath.set(currentPath, []);\n continue;\n }\n const content = (await this.#git.readBlob(entry.oid)).toString(\"utf8\");\n baseFunctionsByCurrentPath.set(currentPath, parseCallables(basePath, content, this.#onWarning));\n }\n const currentByPath = groupBy(current, (callable) => callable.path);\n const addedIds = new Set<number>();\n for (const [currentPath, currentFunctions] of currentByPath) {\n for (const id of addedFunctionIds(currentFunctions, baseFunctionsByCurrentPath.get(currentPath) ?? [])) {\n addedIds.add(id);\n }\n }\n return current.filter((callable) => addedIds.has(callable.id));\n }\n}\n\nfunction addedFunctionIds(\n current: readonly IndexedFunction[],\n base: readonly Pick<IndexedFunction, \"qualifiedName\" | \"kind\" | \"sourceHash\">[],\n): number[] {\n const currentGroups = groupBy(current, (callable) => `${callable.qualifiedName}\\0${callable.kind}`);\n const baseGroups = groupBy(base, (callable) => `${callable.qualifiedName}\\0${callable.kind}`);\n const added: number[] = [];\n for (const [key, currentGroup] of currentGroups) {\n const baseGroup = baseGroups.get(key) ?? [];\n const unmatchedBase = new Set(baseGroup.map((_, index) => index));\n const unmatchedCurrent = new Set(currentGroup.map((_, index) => index));\n for (let currentIndex = 0; currentIndex < currentGroup.length; currentIndex += 1) {\n const exactBaseIndex = [...unmatchedBase].find(\n (baseIndex) => baseGroup[baseIndex]!.sourceHash === currentGroup[currentIndex]!.sourceHash,\n );\n if (exactBaseIndex !== undefined) {\n unmatchedBase.delete(exactBaseIndex);\n unmatchedCurrent.delete(currentIndex);\n }\n }\n for (const currentIndex of unmatchedCurrent) {\n const baseIndex = unmatchedBase.values().next().value as number | undefined;\n if (baseIndex === undefined) added.push(currentGroup[currentIndex]!.id);\n else unmatchedBase.delete(baseIndex);\n }\n }\n return added;\n}\n\nfunction normalizeProfile(profile: EmbeddingProfile): Required<EmbeddingProfile> {\n return {\n provider: profile.provider,\n model: profile.model,\n dimensions: profile.dimensions,\n strategyVersion: profile.strategyVersion ?? \"callable-v1\",\n };\n}\n\nfunction emptyStats(checkpoint: string | null): UpdateStats {\n return {\n filesUpdated: 0,\n filesDeleted: 0,\n functionsAdded: 0,\n functionsUpdated: 0,\n functionsDeleted: 0,\n embeddingsCreated: 0,\n checkpoint,\n };\n}\n\nfunction validateRenames(renames: readonly { from: string; to: string }[]): void {\n const sources = new Set(renames.map((rename) => rename.from));\n const targets = new Set(renames.map((rename) => rename.to));\n if (sources.size !== renames.length || targets.size !== renames.length) {\n throw new CodeIndexError(\"Rename sources and targets must be unique.\");\n }\n if ([...sources].some((source) => targets.has(source))) {\n throw new CodeIndexError(\"Chained or cyclic renames must be applied in separate updates.\");\n }\n}\n\nfunction groupBy<T>(values: readonly T[], keyFor: (value: T) => string): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n for (const value of values) {\n const key = keyFor(value);\n const group = groups.get(key) ?? [];\n group.push(value);\n groups.set(key, group);\n }\n return groups;\n}\n","export class CodeIndexError extends Error {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CodeIndexError\";\n }\n}\n\nexport class GitDivergenceError extends CodeIndexError {\n public constructor(checkpoint: string, target: string) {\n super(`Stored Git checkpoint ${checkpoint} is not an ancestor of ${target}; rebuild the index.`);\n this.name = \"GitDivergenceError\";\n }\n}\n\nexport class IncompatibleIndexError extends CodeIndexError {\n public constructor(message: string) {\n super(message);\n this.name = \"IncompatibleIndexError\";\n }\n}\n","import { spawn } from \"node:child_process\";\nimport path from \"node:path\";\n\nimport { CodeIndexError } from \"../errors.js\";\n\nexport type GitChange =\n | { status: \"A\" | \"M\" | \"D\" | \"T\"; path: string }\n | { status: \"R\" | \"C\"; oldPath: string; path: string };\n\nexport interface GitTreeEntry {\n path: string;\n oid: string;\n mode: string;\n size: number;\n}\n\nexport class GitRepository {\n public constructor(public readonly rootDir: string) {}\n\n async #run(args: readonly string[], allowExitOne = false): Promise<{ stdout: Buffer; code: number }> {\n return await new Promise((resolve, reject) => {\n const child = spawn(\"git\", [\"-C\", this.rootDir, ...args], { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n child.stdout.on(\"data\", (value: Buffer) => stdout.push(value));\n child.stderr.on(\"data\", (value: Buffer) => stderr.push(value));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => {\n const exitCode = code ?? -1;\n if (exitCode === 0 || (allowExitOne && exitCode === 1)) {\n resolve({ stdout: Buffer.concat(stdout), code: exitCode });\n return;\n }\n reject(new CodeIndexError(`Git command failed: ${Buffer.concat(stderr).toString(\"utf8\").trim()}`));\n });\n });\n }\n\n public async assertRepository(): Promise<void> {\n const result = await this.#run([\"rev-parse\", \"--is-inside-work-tree\"]);\n if (result.stdout.toString(\"utf8\").trim() !== \"true\") {\n throw new CodeIndexError(`${this.rootDir} is not a Git worktree.`);\n }\n const topLevel = (await this.#run([\"rev-parse\", \"--show-toplevel\"])).stdout.toString(\"utf8\").trim();\n if (path.resolve(topLevel) !== path.resolve(this.rootDir)) {\n throw new CodeIndexError(`rootDir must be the Git worktree root: ${topLevel}`);\n }\n }\n\n public async assertCleanWorkingTree(excludePaths: readonly string[] = []): Promise<void> {\n const pathspecs = [\".\", ...excludePaths.map((filePath) => `:(top,literal,exclude)${filePath}`)];\n const result = await this.#run([\n \"status\",\n \"--porcelain=v1\",\n \"-z\",\n \"--untracked-files=all\",\n \"--ignore-submodules=none\",\n \"--\",\n ...pathspecs,\n ]);\n if (result.stdout.length > 0) {\n throw new CodeIndexError(\"Cannot update from Git: the working tree has uncommitted changes. Commit or stash them first.\");\n }\n }\n\n public async resolveCommit(ref: string): Promise<string> {\n const result = await this.#run([\"rev-parse\", \"--verify\", \"--end-of-options\", `${ref}^{commit}`]);\n const oid = result.stdout.toString(\"ascii\").trim();\n if (!/^[0-9a-f]{40,64}$/.test(oid)) throw new CodeIndexError(`Could not resolve Git commit: ${ref}`);\n return oid;\n }\n\n public async isAncestor(ancestor: string, descendant: string): Promise<boolean> {\n const result = await this.#run([\"merge-base\", \"--is-ancestor\", ancestor, descendant], true);\n return result.code === 0;\n }\n\n public async listTree(commit: string): Promise<Map<string, GitTreeEntry>> {\n const result = await this.#run([\"ls-tree\", \"-r\", \"-z\", \"-l\", \"--full-tree\", commit, \"--\"]);\n const entries = new Map<string, GitTreeEntry>();\n for (const record of splitNull(result.stdout)) {\n const tab = record.indexOf(\"\\t\");\n if (tab < 0) continue;\n const [mode, type, oid, sizeText] = record.slice(0, tab).trim().split(/\\s+/);\n const filePath = record.slice(tab + 1);\n const size = Number(sizeText);\n if ((mode === \"100644\" || mode === \"100755\") && type === \"blob\" && oid && Number.isSafeInteger(size)) {\n entries.set(filePath, { path: filePath, oid, mode, size });\n }\n }\n return entries;\n }\n\n public async readBlob(oid: string): Promise<Buffer> {\n return (await this.#run([\"cat-file\", \"blob\", oid])).stdout;\n }\n\n public async diff(base: string, target: string): Promise<GitChange[]> {\n const result = await this.#run([\"diff\", \"--name-status\", \"-z\", \"--find-renames\", `${base}..${target}`, \"--\"]);\n const values = splitNull(result.stdout);\n const changes: GitChange[] = [];\n for (let index = 0; index < values.length;) {\n const rawStatus = values[index++];\n if (!rawStatus) continue;\n const status = rawStatus[0];\n if (status === \"R\" || status === \"C\") {\n const oldPath = values[index++];\n const filePath = values[index++];\n if (oldPath && filePath) changes.push({ status, oldPath, path: filePath });\n } else if (status === \"A\" || status === \"M\" || status === \"D\" || status === \"T\") {\n const filePath = values[index++];\n if (filePath) changes.push({ status, path: filePath });\n } else {\n throw new CodeIndexError(`Unsupported Git diff status: ${rawStatus}`);\n }\n }\n return changes;\n }\n}\n\nfunction splitNull(buffer: Buffer): string[] {\n const value = buffer.toString(\"utf8\");\n const parts = value.split(\"\\0\");\n if (parts.at(-1) === \"\") parts.pop();\n return parts;\n}\n","import path from \"node:path\";\n\nimport Parser from \"tree-sitter\";\nimport JavaScript from \"tree-sitter-javascript\";\nimport TypeScript from \"tree-sitter-typescript\";\n\nimport { CodeIndexError } from \"../errors.js\";\nimport type { CallableKind, ParsedCallable, SupportedLanguage } from \"../types.js\";\nimport { sha256 } from \"../utils.js\";\n\ninterface CallableCandidate {\n node: Parser.SyntaxNode;\n name: string;\n kind: CallableKind;\n scope: readonly string[];\n}\n\nconst parsers = new Map<SupportedLanguage, Parser>();\n\nexport function languageForPath(filePath: string): SupportedLanguage | null {\n switch (path.extname(filePath).toLowerCase()) {\n case \".ts\":\n case \".mts\":\n case \".cts\":\n return \"typescript\";\n case \".tsx\":\n return \"tsx\";\n case \".js\":\n case \".mjs\":\n case \".cjs\":\n return \"javascript\";\n case \".jsx\":\n return \"jsx\";\n default:\n return null;\n }\n}\n\nfunction getParser(language: SupportedLanguage): Parser {\n const existing = parsers.get(language);\n if (existing) return existing;\n\n const parser = new Parser();\n if (language === \"typescript\") parser.setLanguage(TypeScript.typescript);\n else if (language === \"tsx\") parser.setLanguage(TypeScript.tsx);\n else parser.setLanguage(JavaScript);\n parsers.set(language, parser);\n return parser;\n}\n\nfunction parseTree(parser: Parser, content: string, relativePath: string): Parser.Tree {\n try {\n return parser.parse(content, undefined, { bufferSize: Buffer.byteLength(content) + 1 });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CodeIndexError(`Cannot index ${relativePath}: tree-sitter failed: ${message}`, { cause: error });\n }\n}\n\nfunction maskSyntax(value: string, replacement: string): string {\n return replacement + value.slice(replacement.length).replace(/[^\\r\\n]/g, \" \");\n}\n\nfunction recoverUnsupportedTypeScriptSyntax(\n parser: Parser,\n tree: Parser.Tree,\n content: string,\n relativePath: string,\n): Parser.Tree | null {\n const errors: Parser.SyntaxNode[] = [];\n const collectErrors = (node: Parser.SyntaxNode): void => {\n if (node.isError || node.isMissing) errors.push(node);\n for (const child of node.children) collectErrors(child);\n };\n collectErrors(tree.rootNode);\n\n if (errors.length === 0) return null;\n\n let recoveredContent = content;\n let changed = false;\n const taggedTemplateTypeArguments = new Map<number, Parser.SyntaxNode>();\n for (const error of errors) {\n const parent = error.parent;\n if (error.isMissing\n && error.type === \"!\"\n && parent?.type === \"type_arguments\"\n && /^\\s*`/.test(content.slice(parent.endIndex))) {\n taggedTemplateTypeArguments.set(parent.startIndex, parent);\n }\n }\n for (const node of [...taggedTemplateTypeArguments.values()].toSorted((left, right) => right.startIndex - left.startIndex)) {\n const value = recoveredContent.slice(node.startIndex, node.endIndex);\n recoveredContent = `${recoveredContent.slice(0, node.startIndex)}${value.replace(/[^\\r\\n]/g, \" \")}${recoveredContent.slice(node.endIndex)}`;\n changed = true;\n }\n\n for (const node of errors.filter((candidate) => {\n const parent = candidate.parent;\n return !candidate.isMissing\n && candidate.type === \"ERROR\"\n && candidate.text === \"type\"\n && parent?.type === \"export_statement\"\n && content.slice(parent.startIndex, candidate.startIndex).trim() === \"export\"\n && /^\\s*\\*/.test(content.slice(candidate.endIndex, parent.endIndex));\n }).toSorted((left, right) => right.startIndex - left.startIndex)) {\n recoveredContent = `${recoveredContent.slice(0, node.startIndex)} ${recoveredContent.slice(node.endIndex)}`;\n changed = true;\n }\n\n recoveredContent = recoveredContent.replace(\n /\\bimport\\s*\\(\\s*([\"'])(?:\\\\.|(?!\\1)[^\\\\])*\\1\\s*\\)/g,\n (value) => {\n changed = true;\n return maskSyntax(value, \"X\");\n },\n );\n if (!changed) return null;\n\n const recoveredTree = parseTree(parser, recoveredContent, relativePath);\n return recoveredTree.rootNode.hasError ? null : recoveredTree;\n}\n\nfunction textFor(content: string, node: Parser.SyntaxNode): string {\n return content.slice(node.startIndex, node.endIndex);\n}\n\nfunction fieldText(content: string, node: Parser.SyntaxNode, field: string): string | null {\n const child = node.childForFieldName(field);\n return child ? textFor(content, child) : null;\n}\n\nfunction callableKind(node: Parser.SyntaxNode, name: string): CallableKind {\n if (name === \"constructor\") return \"constructor\";\n if (node.type.includes(\"generator\") || /^\\s*(?:async\\s+)?\\*/.test(node.text)) return \"generator\";\n return node.type === \"method_definition\" ? \"method\" : \"function\";\n}\n\nfunction bindingName(content: string, node: Parser.SyntaxNode): string | null {\n const nameNode = node.childForFieldName(\"name\");\n if (!nameNode || ![\"identifier\", \"property_identifier\", \"private_property_identifier\"].includes(nameNode.type)) {\n return null;\n }\n return textFor(content, nameNode).replace(/^#/, \"\");\n}\n\nfunction assignmentName(content: string, node: Parser.SyntaxNode): string | null {\n const left = node.childForFieldName(\"left\");\n if (!left) return null;\n const value = textFor(content, left).trim();\n const match = value.match(/(?:^|[.#])([A-Za-z_$][\\w$]*)$/);\n return match?.[1] ?? null;\n}\n\nfunction objectScopeName(content: string, node: Parser.SyntaxNode): string | null {\n const parent = node.parent;\n if (!parent) return null;\n if (parent.type === \"variable_declarator\" && parent.childForFieldName(\"value\")?.id === node.id) {\n return bindingName(content, parent);\n }\n if (parent.type === \"pair\" && parent.childForFieldName(\"value\")?.id === node.id) {\n return fieldText(content, parent, \"key\")?.replace(/[\"']/g, \"\") ?? null;\n }\n if (parent.type === \"assignment_expression\" && parent.childForFieldName(\"right\")?.id === node.id) {\n return assignmentName(content, parent);\n }\n return null;\n}\n\nfunction walk(\n node: Parser.SyntaxNode,\n content: string,\n scope: readonly string[],\n candidates: CallableCandidate[],\n): void {\n if (node.type === \"class_declaration\" || node.type === \"class\") {\n const name = fieldText(content, node, \"name\") ?? objectScopeName(content, node);\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if (node.type === \"internal_module\" || node.type === \"module\") {\n const name = fieldText(content, node, \"name\")?.replace(/[\"']/g, \"\");\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if (node.type === \"object\") {\n const name = objectScopeName(content, node);\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if ([\"function_declaration\", \"generator_function_declaration\"].includes(node.type)) {\n const name = fieldText(content, node, \"name\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n }\n return;\n }\n\n if (node.type === \"method_definition\") {\n const name = fieldText(content, node, \"name\")?.replace(/^#/, \"\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n }\n return;\n }\n\n if (node.type === \"public_field_definition\" || node.type === \"field_definition\") {\n const name = (fieldText(content, node, \"name\") ?? fieldText(content, node, \"property\"))?.replace(/^#/, \"\");\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n const kind = callableKind(value, name) === \"generator\" ? \"generator\" : \"method\";\n candidates.push({ node: value, name, kind, scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"variable_declarator\") {\n const name = bindingName(content, node);\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"pair\") {\n const name = fieldText(content, node, \"key\")?.replace(/[\"']/g, \"\");\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"assignment_expression\") {\n const name = assignmentName(content, node);\n const value = node.childForFieldName(\"right\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if ([\"function_expression\", \"generator_function\"].includes(node.type)) {\n const name = fieldText(content, node, \"name\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n for (const child of node.namedChildren) walk(child, content, scope, candidates);\n}\n\nfunction signatureFor(content: string, node: Parser.SyntaxNode, name: string): string | null {\n const parameters = node.childForFieldName(\"parameters\");\n if (!parameters) return name;\n const returnType = node.childForFieldName(\"return_type\");\n return `${name}${textFor(content, parameters)}${returnType ? textFor(content, returnType) : \"\"}`;\n}\n\nexport function parseCallables(\n relativePath: string,\n content: string,\n onWarning: (message: string) => void = console.warn,\n): ParsedCallable[] {\n const language = languageForPath(relativePath);\n if (!language) return [];\n\n const parser = getParser(language);\n const parsedTree = parseTree(parser, content, relativePath);\n const tree = parsedTree.rootNode.hasError\n ? recoverUnsupportedTypeScriptSyntax(parser, parsedTree, content, relativePath) ?? parsedTree\n : parsedTree;\n if (tree.rootNode.hasError) {\n onWarning(`Cannot fully parse ${relativePath}: tree-sitter reported syntax errors; indexing recoverable callables only.`);\n }\n\n const candidates: CallableCandidate[] = [];\n walk(tree.rootNode, content, [], candidates);\n candidates.sort((left, right) => left.node.startIndex - right.node.startIndex);\n\n const occurrences = new Map<string, number>();\n return candidates.map(({ node, name, kind, scope }) => {\n const qualifiedName = [...scope, name].join(\".\");\n const baseIdentity = `${relativePath}\\0${qualifiedName}\\0${kind}`;\n const occurrence = occurrences.get(baseIdentity) ?? 0;\n occurrences.set(baseIdentity, occurrence + 1);\n const identityKey = sha256(`${baseIdentity}\\0${occurrence}`);\n const source = textFor(content, node);\n const signature = signatureFor(content, node, name);\n const embeddingInput = [\n `language: ${language}`,\n `kind: ${kind}`,\n `symbol: ${qualifiedName}`,\n signature ? `signature: ${signature}` : null,\n \"source:\",\n source,\n ].filter((value): value is string => value !== null).join(\"\\n\");\n\n return {\n path: relativePath,\n language,\n kind,\n name,\n qualifiedName,\n signature,\n identityKey,\n startLine: node.startPosition.row + 1,\n startColumn: node.startPosition.column + 1,\n endLine: node.endPosition.row + 1,\n endColumn: node.endPosition.column + 1,\n source,\n sourceHash: sha256(source),\n embeddingInput,\n };\n });\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { CodeIndexError } from \"./errors.js\";\n\nexport function sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function normalizeRelativePath(rootDir: string, inputPath: string): string {\n const absolute = path.resolve(rootDir, inputPath);\n const relative = path.relative(rootDir, absolute);\n if (relative === \"\" || relative === \".\") {\n throw new CodeIndexError(`Expected a file path, received repository root: ${inputPath}`);\n }\n if (relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {\n throw new CodeIndexError(`Path escapes repository root: ${inputPath}`);\n }\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function throwIfAborted(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nexport function chunk<T>(values: readonly T[], size: number): T[][] {\n const batches: T[][] = [];\n for (let index = 0; index < values.length; index += size) {\n batches.push(values.slice(index, index + size));\n }\n return batches;\n}\n\nexport function assertPositiveInteger(value: number, name: string): void {\n if (!Number.isInteger(value) || value < 1) {\n throw new CodeIndexError(`${name} must be a positive integer.`);\n }\n}\n\nexport function normalizeEmbeddingVector(value: unknown, dimensions: number): number[] {\n if (!Array.isArray(value) || value.length !== dimensions) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n const converted: number[] = [];\n for (const component of value) {\n if (typeof component !== \"number\" || !Number.isFinite(component)) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n const normalized = Math.fround(component);\n if (!Number.isFinite(normalized)) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n converted.push(normalized);\n }\n if (!converted.some((component) => component !== 0)) {\n throw new CodeIndexError(\"Embedding vector must not be all zeroes.\");\n }\n return converted;\n}\n","import path from \"node:path\";\n\nimport { languageForPath } from \"./parser/callable-parser.js\";\n\nconst DEFAULT_EXCLUDED_SEGMENTS = new Set([\n \".git\",\n \".slopdex\",\n \"node_modules\",\n \"dist\",\n \"build\",\n \"coverage\",\n \"vendor\",\n \"generated\",\n]);\n\nexport class SourcePolicy {\n readonly #include: readonly string[];\n readonly #exclude: readonly string[];\n\n public constructor(include: readonly string[] = [], exclude: readonly string[] = []) {\n this.#include = include;\n this.#exclude = exclude;\n }\n\n public includes(relativePath: string): boolean {\n const normalized = relativePath.replaceAll(\"\\\\\", \"/\");\n if (!languageForPath(normalized)) return false;\n if (normalized.split(\"/\").some((segment) => DEFAULT_EXCLUDED_SEGMENTS.has(segment))) return false;\n if (this.#exclude.some((pattern) => path.matchesGlob(normalized, pattern))) return false;\n return this.#include.length === 0 || this.#include.some((pattern) => path.matchesGlob(normalized, pattern));\n }\n}\n","import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\n\nimport * as sqliteVec from \"sqlite-vec\";\n\nimport { CodeIndexError, IncompatibleIndexError } from \"../errors.js\";\nimport type {\n EmbeddingProfile,\n IndexStatus,\n IndexedFunction,\n ParsedCallable,\n SourceMode,\n UpdateStats,\n} from \"../types.js\";\n\nconst SCHEMA_VERSION = \"1\";\n\nexport interface PreparedCallable extends ParsedCallable {\n embeddingKey: string;\n vector?: readonly number[];\n}\n\nexport interface PreparedFile {\n path: string;\n contentHash: string;\n blobOid: string | null;\n sourceMode: SourceMode;\n indexedCommit: string | null;\n language: string;\n byteSize: number;\n previousPath?: string;\n replacePath?: string;\n callables: PreparedCallable[];\n}\n\ninterface FunctionRow {\n id: number;\n path: string;\n language: IndexedFunction[\"language\"];\n kind: IndexedFunction[\"kind\"];\n name: string;\n qualified_name: string;\n signature: string | null;\n identity_key: string;\n start_line: number;\n start_column: number;\n end_line: number;\n end_column: number;\n source: string;\n source_hash: string;\n embedding_input: string;\n first_seen_commit: string | null;\n last_seen_commit: string | null;\n source_mode: SourceMode;\n embedding_id: number;\n}\n\nexport class IndexDatabase {\n readonly #db: DatabaseSync;\n readonly #rootDir: string;\n readonly #indexPath: string;\n readonly #profile: Required<EmbeddingProfile>;\n\n public constructor(indexPath: string, rootDir: string, profile: Required<EmbeddingProfile>, readOnly = false) {\n if (!readOnly) mkdirSync(path.dirname(indexPath), { recursive: true });\n this.#indexPath = indexPath;\n this.#rootDir = rootDir;\n this.#profile = profile;\n this.#db = new DatabaseSync(indexPath, { allowExtension: true, readOnly });\n sqliteVec.load(this.#db);\n this.#db.enableLoadExtension(false);\n if (readOnly) {\n this.#db.exec(\"PRAGMA foreign_keys=ON\");\n } else {\n this.#db.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON;\");\n this.#migrate();\n }\n this.#validateMetadata(readOnly);\n }\n\n public close(): void {\n this.#db.close();\n }\n\n #migrate(): void {\n this.#db.exec(`\n CREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS files (\n path TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n blob_oid TEXT,\n source_mode TEXT NOT NULL CHECK(source_mode IN ('git', 'working-tree')),\n indexed_commit TEXT,\n previous_path TEXT,\n language TEXT NOT NULL,\n byte_size INTEGER NOT NULL\n );\n CREATE TABLE IF NOT EXISTS embeddings (\n id INTEGER PRIMARY KEY,\n embedding_key TEXT NOT NULL UNIQUE,\n vector BLOB NOT NULL\n );\n CREATE TABLE IF NOT EXISTS functions (\n id INTEGER PRIMARY KEY,\n path TEXT NOT NULL REFERENCES files(path) ON DELETE CASCADE ON UPDATE CASCADE,\n language TEXT NOT NULL,\n kind TEXT NOT NULL,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL,\n signature TEXT,\n identity_key TEXT NOT NULL UNIQUE,\n start_line INTEGER NOT NULL,\n start_column INTEGER NOT NULL,\n end_line INTEGER NOT NULL,\n end_column INTEGER NOT NULL,\n source TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n embedding_input TEXT NOT NULL,\n first_seen_commit TEXT,\n last_seen_commit TEXT,\n source_mode TEXT NOT NULL CHECK(source_mode IN ('git', 'working-tree')),\n embedding_id INTEGER NOT NULL REFERENCES embeddings(id)\n );\n CREATE INDEX IF NOT EXISTS functions_path ON functions(path);\n CREATE INDEX IF NOT EXISTS functions_embedding ON functions(embedding_id);\n `);\n const fileColumns = this.#db.prepare(\"PRAGMA table_info(files)\").all() as Array<{ name: string }>;\n if (!fileColumns.some((column) => column.name === \"previous_path\")) {\n this.#db.exec(\"ALTER TABLE files ADD COLUMN previous_path TEXT\");\n }\n }\n\n #metadata(key: string): string | null {\n const row = this.#db.prepare(\"SELECT value FROM metadata WHERE key = ?\").get(key) as { value: string } | undefined;\n return row?.value ?? null;\n }\n\n #setMetadata(key: string, value: string): void {\n this.#db.prepare(`\n INSERT INTO metadata(key, value) VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n `).run(key, value);\n }\n\n #validateMetadata(readOnly: boolean): void {\n const schemaVersion = this.#metadata(\"schema_version\");\n if (readOnly && !schemaVersion) throw new IncompatibleIndexError(\"Target file is not a slopdex index.\");\n if (schemaVersion && schemaVersion !== SCHEMA_VERSION) {\n throw new IncompatibleIndexError(`Unsupported index schema version ${schemaVersion}.`);\n }\n const storedRoot = this.#metadata(\"root_dir\");\n if (readOnly && !storedRoot) throw new IncompatibleIndexError(\"Target index has no repository identity.\");\n if (storedRoot && path.resolve(storedRoot) !== this.#rootDir) {\n throw new IncompatibleIndexError(`Index belongs to ${storedRoot}, not ${this.#rootDir}.`);\n }\n const profileJson = JSON.stringify(this.#profile);\n const storedProfile = this.#metadata(\"embedding_profile\");\n if (readOnly && !storedProfile) throw new IncompatibleIndexError(\"Target index has no embedding profile.\");\n if (storedProfile && storedProfile !== profileJson) {\n throw new IncompatibleIndexError(\"Embedding provider, model, dimensions, or strategy differs from this index.\");\n }\n if (readOnly) return;\n this.#transaction(() => {\n this.#setMetadata(\"schema_version\", SCHEMA_VERSION);\n this.#setMetadata(\"root_dir\", this.#rootDir);\n this.#setMetadata(\"embedding_profile\", profileJson);\n if (!this.#metadata(\"generation\")) this.#setMetadata(\"generation\", \"0\");\n });\n }\n\n #transaction<T>(operation: () => T): T {\n this.#db.exec(\"BEGIN IMMEDIATE\");\n try {\n const result = operation();\n this.#db.exec(\"COMMIT\");\n return result;\n } catch (error) {\n this.#db.exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n public getCheckpoint(): string | null {\n return this.#metadata(\"git_checkpoint\");\n }\n\n public getGeneration(): number {\n return Number(this.#metadata(\"generation\") ?? 0);\n }\n\n public getWorkingTreeFiles(): Array<{ path: string; previousPath: string | null }> {\n return this.#db.prepare(`\n SELECT path, previous_path AS previousPath\n FROM files WHERE source_mode = 'working-tree' ORDER BY path\n `).all() as Array<{ path: string; previousPath: string | null }>;\n }\n\n public getEmbeddingKeys(keys: readonly string[]): Set<string> {\n const found = new Set<string>();\n const statement = this.#db.prepare(\"SELECT 1 FROM embeddings WHERE embedding_key = ?\");\n for (const key of keys) {\n if (statement.get(key)) found.add(key);\n }\n return found;\n }\n\n public applyUpdate(options: {\n files: readonly PreparedFile[];\n deletePaths: readonly string[];\n checkpoint?: string;\n expectedCheckpoint?: string | null;\n }): UpdateStats {\n return this.#transaction(() => {\n if (options.expectedCheckpoint !== undefined && this.getCheckpoint() !== options.expectedCheckpoint) {\n throw new CodeIndexError(\"Git checkpoint changed while the update was being prepared.\");\n }\n\n const stats: UpdateStats = {\n filesUpdated: options.files.length,\n filesDeleted: 0,\n functionsAdded: 0,\n functionsUpdated: 0,\n functionsDeleted: 0,\n embeddingsCreated: 0,\n checkpoint: options.checkpoint ?? this.getCheckpoint(),\n };\n\n const deleteFile = this.#db.prepare(\"DELETE FROM files WHERE path = ?\");\n const countFunctions = this.#db.prepare(\"SELECT COUNT(*) AS count FROM functions WHERE path = ?\");\n const uniqueDeletes = new Set(options.deletePaths);\n for (const file of options.files) {\n uniqueDeletes.delete(file.path);\n if (file.previousPath) uniqueDeletes.delete(file.previousPath);\n if (file.replacePath) uniqueDeletes.delete(file.replacePath);\n }\n for (const filePath of uniqueDeletes) {\n const count = Number((countFunctions.get(filePath) as { count: number }).count);\n const result = deleteFile.run(filePath);\n if (result.changes > 0) {\n stats.filesDeleted += 1;\n stats.functionsDeleted += count;\n }\n }\n\n for (const file of options.files) this.#replaceFile(file, stats);\n\n this.#db.exec(\"DELETE FROM embeddings WHERE id NOT IN (SELECT DISTINCT embedding_id FROM functions)\");\n const generation = this.getGeneration() + 1;\n this.#setMetadata(\"generation\", String(generation));\n if (options.checkpoint) this.#setMetadata(\"git_checkpoint\", options.checkpoint);\n return stats;\n });\n }\n\n #replaceFile(file: PreparedFile, stats: UpdateStats): void {\n const sourcePath = file.replacePath ?? file.previousPath ?? file.path;\n const oldRows = this.#rowsForPath(sourcePath);\n const existingFile = this.#db.prepare(\"SELECT previous_path FROM files WHERE path = ?\").get(sourcePath) as\n | { previous_path: string | null }\n | undefined;\n const oldMatches = reconcileFunctions(file.callables, oldRows);\n\n if (sourcePath !== file.path) {\n this.#db.prepare(\"DELETE FROM files WHERE path = ?\").run(sourcePath);\n } else {\n this.#db.prepare(\"DELETE FROM files WHERE path = ?\").run(file.path);\n }\n this.#db.prepare(`\n INSERT INTO files(path, content_hash, blob_oid, source_mode, indexed_commit, previous_path, language, byte_size)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n file.path,\n file.contentHash,\n file.blobOid,\n file.sourceMode,\n file.indexedCommit,\n file.sourceMode === \"working-tree\" ? file.previousPath ?? existingFile?.previous_path ?? null : null,\n file.language,\n file.byteSize,\n );\n\n const usedIds = new Set<number>();\n const orderedCallables = [\n ...file.callables.filter((callable) => oldMatches.has(callable)),\n ...file.callables.filter((callable) => !oldMatches.has(callable)),\n ];\n for (const callable of orderedCallables) {\n if (callable.vector) {\n const result = this.#db.prepare(\"INSERT OR IGNORE INTO embeddings(embedding_key, vector) VALUES (?, ?)\")\n .run(callable.embeddingKey, vectorBuffer(callable.vector));\n stats.embeddingsCreated += Number(result.changes);\n }\n const embedding = this.#db.prepare(\"SELECT id FROM embeddings WHERE embedding_key = ?\").get(callable.embeddingKey) as { id: number } | undefined;\n if (!embedding) throw new CodeIndexError(`Missing embedding for ${callable.qualifiedName}.`);\n\n const old = oldMatches.get(callable);\n if (old) usedIds.add(old.id);\n const firstSeenCommit = old?.first_seen_commit ?? file.indexedCommit;\n this.#db.prepare(`\n INSERT INTO functions(\n id, path, language, kind, name, qualified_name, signature, identity_key,\n start_line, start_column, end_line, end_column, source, source_hash,\n embedding_input, first_seen_commit, last_seen_commit, source_mode, embedding_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n old?.id ?? null,\n file.path,\n callable.language,\n callable.kind,\n callable.name,\n callable.qualifiedName,\n callable.signature,\n callable.identityKey,\n callable.startLine,\n callable.startColumn,\n callable.endLine,\n callable.endColumn,\n callable.source,\n callable.sourceHash,\n callable.embeddingInput,\n firstSeenCommit,\n file.indexedCommit,\n file.sourceMode,\n embedding.id,\n );\n if (old) stats.functionsUpdated += 1;\n else stats.functionsAdded += 1;\n }\n stats.functionsDeleted += oldRows.length - usedIds.size;\n }\n\n #rowsForPath(filePath: string): FunctionRow[] {\n return this.#db.prepare(\"SELECT * FROM functions WHERE path = ? ORDER BY start_line, start_column, id\").all(filePath) as unknown as FunctionRow[];\n }\n\n public allFunctions(): IndexedFunction[] {\n return (this.#db.prepare(\"SELECT * FROM functions ORDER BY path, start_line, start_column, id\").all() as unknown as FunctionRow[])\n .map(toIndexedFunction);\n }\n\n public allFilePaths(): string[] {\n return (this.#db.prepare(\"SELECT path FROM files ORDER BY path\").all() as Array<{ path: string }>).map((row) => row.path);\n }\n\n public previousPath(filePath: string): string | null {\n const row = this.#db.prepare(\"SELECT previous_path FROM files WHERE path = ?\").get(filePath) as\n | { previous_path: string | null }\n | undefined;\n return row?.previous_path ?? null;\n }\n\n public functionsForPaths(paths: readonly string[]): IndexedFunction[] {\n const results: IndexedFunction[] = [];\n for (const filePath of paths) results.push(...this.#rowsForPath(filePath).map(toIndexedFunction));\n return results;\n }\n\n public searchVector(vector: readonly number[], options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludeId?: number;\n }): Array<{ function: IndexedFunction; similarity: number }> {\n const rows = this.#db.prepare(`\n SELECT f.*, 1.0 - vec_distance_cosine(e.vector, ?) AS similarity\n FROM functions f\n JOIN embeddings e ON e.id = f.embedding_id\n WHERE (? IS NULL OR f.id != ?)\n AND (1.0 - vec_distance_cosine(e.vector, ?)) >= ?\n AND (? IS NULL OR (1.0 - vec_distance_cosine(e.vector, ?)) <= ?)\n ORDER BY similarity DESC, f.id ASC\n LIMIT ?\n `).all(\n vectorBuffer(vector),\n options.excludeId ?? null,\n options.excludeId ?? null,\n vectorBuffer(vector),\n options.minSimilarity,\n options.maxSimilarity ?? null,\n vectorBuffer(vector),\n options.maxSimilarity ?? null,\n options.limit,\n ) as unknown as Array<FunctionRow & { similarity: number }>;\n return rows.map((row) => ({ function: toIndexedFunction(row), similarity: row.similarity }));\n }\n\n public vectorForFunction(id: number): number[] {\n const row = this.#db.prepare(`\n SELECT e.vector FROM functions f JOIN embeddings e ON e.id = f.embedding_id WHERE f.id = ?\n `).get(id) as { vector: Uint8Array } | undefined;\n if (!row) throw new CodeIndexError(`Function ${id} does not exist.`);\n return Array.from(new Float32Array(row.vector.buffer, row.vector.byteOffset, row.vector.byteLength / 4));\n }\n\n public status(): IndexStatus {\n const functionCount = Number((this.#db.prepare(\"SELECT COUNT(*) AS count FROM functions\").get() as { count: number }).count);\n const fileCount = Number((this.#db.prepare(\"SELECT COUNT(*) AS count FROM files\").get() as { count: number }).count);\n return {\n rootDir: this.#rootDir,\n indexPath: this.#indexPath,\n functionCount,\n fileCount,\n generation: this.getGeneration(),\n gitCheckpoint: this.getCheckpoint(),\n embeddingProfile: this.#profile,\n };\n }\n}\n\nfunction vectorBuffer(vector: readonly number[]): Uint8Array {\n const values = Float32Array.from(vector);\n return new Uint8Array(values.buffer);\n}\n\nfunction toIndexedFunction(row: FunctionRow): IndexedFunction {\n return {\n id: row.id,\n path: row.path,\n language: row.language,\n kind: row.kind,\n name: row.name,\n qualifiedName: row.qualified_name,\n signature: row.signature,\n identityKey: row.identity_key,\n startLine: row.start_line,\n startColumn: row.start_column,\n endLine: row.end_line,\n endColumn: row.end_column,\n source: row.source,\n sourceHash: row.source_hash,\n embeddingInput: row.embedding_input,\n firstSeenCommit: row.first_seen_commit,\n lastSeenCommit: row.last_seen_commit,\n sourceMode: row.source_mode,\n embeddingId: row.embedding_id,\n };\n}\n\nfunction reconcileFunctions(\n current: readonly PreparedCallable[],\n previous: readonly FunctionRow[],\n): Map<PreparedCallable, FunctionRow> {\n const matches = new Map<PreparedCallable, FunctionRow>();\n const keys = new Set([\n ...current.map((callable) => `${callable.qualifiedName}\\0${callable.kind}`),\n ...previous.map((callable) => `${callable.qualified_name}\\0${callable.kind}`),\n ]);\n for (const key of keys) {\n const currentGroup = current.filter((callable) => `${callable.qualifiedName}\\0${callable.kind}` === key);\n const previousGroup = previous.filter((callable) => `${callable.qualified_name}\\0${callable.kind}` === key);\n const unmatchedPrevious = new Set(previousGroup);\n const unmatchedCurrent = new Set(currentGroup);\n for (const callable of currentGroup) {\n const exact = [...unmatchedPrevious].find((old) => old.source_hash === callable.sourceHash);\n if (exact) {\n matches.set(callable, exact);\n unmatchedPrevious.delete(exact);\n unmatchedCurrent.delete(callable);\n }\n }\n for (const callable of unmatchedCurrent) {\n const old = unmatchedPrevious.values().next().value as FunctionRow | undefined;\n if (!old) break;\n matches.set(callable, old);\n unmatchedPrevious.delete(old);\n }\n }\n return matches;\n}\n","import { IncompatibleIndexError } from \"../errors.js\";\nimport type { CrossSearchOptions, CrossSearchResult } from \"../types.js\";\nimport { assertPositiveInteger, throwIfAborted } from \"../utils.js\";\n\nexport async function* crossSearch(options: CrossSearchOptions): AsyncGenerator<CrossSearchResult> {\n const target = options.target ?? options.source;\n const sourceProfile = JSON.stringify(options.source.status().embeddingProfile);\n const targetProfile = JSON.stringify(target.status().embeddingProfile);\n if (sourceProfile !== targetProfile) {\n throw new IncompatibleIndexError(\"Cross-search requires identical embedding profiles.\");\n }\n\n const limit = options.limitPerFunction ?? 5;\n assertPositiveInteger(limit, \"limitPerFunction\");\n const sourceFunctions = await options.source.sourceFunctions(options.sourceFilter ?? { type: \"all\" });\n const sameIndex = target.indexPath === options.source.indexPath;\n const seenPairs = new Set<string>();\n for (let index = 0; index < sourceFunctions.length; index += 1) {\n throwIfAborted(options.signal);\n const source = sourceFunctions[index]!;\n const vector = options.source.vectorForFunction(source.id);\n const candidates = sameIndex\n ? options.source.similarToFunction(source.id, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n })\n : target.searchByVector(vector, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n });\n const matches = sameIndex && !options.includeSymmetricDuplicates\n ? candidates.filter((match) => {\n const pair = source.id < match.function.id\n ? `${source.id}:${match.function.id}`\n : `${match.function.id}:${source.id}`;\n if (seenPairs.has(pair)) return false;\n seenPairs.add(pair);\n return true;\n })\n : candidates;\n if (matches.length > 0) yield { source, matches };\n options.onProgress?.({ completed: index + 1, total: sourceFunctions.length });\n }\n}\n","import { Tiktoken } from \"js-tiktoken/lite\";\nimport cl100kBase from \"js-tiktoken/ranks/cl100k_base\";\n\nimport type { EmbeddingProvider } from \"../types.js\";\nimport { requestEmbeddings } from \"./http.js\";\n\nconst MAX_INPUT_TOKENS = 8192;\nlet tokenizer: Tiktoken | undefined;\n\nfunction truncateInput(input: string): string {\n tokenizer ??= new Tiktoken(cl100kBase);\n const tokens = tokenizer.encode(input);\n return tokens.length <= MAX_INPUT_TOKENS ? input : tokenizer.decode(tokens.slice(0, MAX_INPUT_TOKENS));\n}\n\nexport interface OpenAIEmbeddingProviderOptions {\n apiKey?: string;\n model?: string;\n dimensions?: number;\n baseUrl?: string;\n}\n\nexport class OpenAIEmbeddingProvider implements EmbeddingProvider {\n public readonly profile;\n readonly #apiKey: string;\n readonly #url: string;\n\n public constructor(options: OpenAIEmbeddingProviderOptions = {}) {\n this.#apiKey = options.apiKey ?? process.env.OPENAI_API_KEY ?? \"\";\n if (!this.#apiKey) throw new Error(\"OPENAI_API_KEY is required.\");\n const model = options.model ?? \"text-embedding-3-small\";\n const dimensions = options.dimensions ?? 1536;\n if (!Number.isInteger(dimensions) || dimensions < 1) throw new Error(\"dimensions must be a positive integer.\");\n this.profile = { provider: \"openai\", model, dimensions, strategyVersion: \"callable-v1\" } as const;\n this.#url = `${(options.baseUrl ?? \"https://api.openai.com/v1\").replace(/\\/$/, \"\")}/embeddings`;\n }\n\n public embedDocuments(inputs: readonly string[], options?: { signal?: AbortSignal }): Promise<number[][]> {\n if (inputs.length === 0) return Promise.resolve([]);\n return this.#embed(inputs, options?.signal);\n }\n\n public async embedQuery(input: string, options?: { signal?: AbortSignal }): Promise<number[]> {\n return (await this.#embed([input], options?.signal))[0]!;\n }\n\n #embed(inputs: readonly string[], signal?: AbortSignal): Promise<number[][]> {\n return requestEmbeddings({\n url: this.#url,\n apiKey: this.#apiKey,\n body: {\n model: this.profile.model,\n dimensions: this.profile.dimensions,\n encoding_format: \"float\",\n input: inputs.map(truncateInput),\n },\n expectedCount: inputs.length,\n dimensions: this.profile.dimensions,\n ...(signal ? { signal } : {}),\n });\n }\n}\n","import { CodeIndexError } from \"../errors.js\";\nimport { normalizeEmbeddingVector } from \"../utils.js\";\n\ninterface EmbeddingResponse {\n data?: Array<{ index?: number; embedding?: number[] }>;\n}\n\nexport async function requestEmbeddings(options: {\n url: string;\n apiKey: string;\n body: Record<string, unknown>;\n expectedCount: number;\n dimensions: number;\n signal?: AbortSignal;\n}): Promise<number[][]> {\n let lastError: unknown;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n const response = await fetch(options.url, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${options.apiKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(options.body),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) {\n const detail = (await response.text()).slice(0, 500);\n const error = new CodeIndexError(`Embedding request failed (${response.status}): ${detail}`);\n if (response.status !== 429 && response.status < 500) throw error;\n lastError = error;\n } else {\n const payload = await response.json() as EmbeddingResponse;\n if (!Array.isArray(payload.data) || payload.data.length !== options.expectedCount) {\n throw new CodeIndexError(\"Embedding provider returned an unexpected number of vectors.\");\n }\n const indexes = payload.data.map((item) => item.index);\n if (indexes.some((index) => !Number.isInteger(index))\n || new Set(indexes).size !== options.expectedCount\n || indexes.some((index) => index! < 0 || index! >= options.expectedCount)) {\n throw new CodeIndexError(\"Embedding provider returned invalid vector indexes.\");\n }\n const ordered = new Array<{ index?: number; embedding?: number[] }>(options.expectedCount);\n for (const item of payload.data) ordered[item.index!] = item;\n try {\n return ordered.map((item) => normalizeEmbeddingVector(item.embedding, options.dimensions));\n } catch {\n throw new CodeIndexError(\"Embedding provider returned a malformed vector.\");\n }\n }\n } catch (error) {\n if (options.signal?.aborted) throw error;\n lastError = error;\n if (error instanceof CodeIndexError && !/\\((429|5\\d\\d)\\)/.test(error.message)) throw error;\n }\n await new Promise((resolve) => setTimeout(resolve, 250 * 2 ** attempt));\n }\n throw new CodeIndexError(\"Embedding request failed after three attempts.\", { cause: lastError });\n}\n","import type { EmbeddingProvider } from \"../types.js\";\nimport { requestEmbeddings } from \"./http.js\";\n\nexport interface JinaEmbeddingProviderOptions {\n apiKey?: string;\n model?: string;\n dimensions?: number;\n baseUrl?: string;\n}\n\nexport class JinaEmbeddingProvider implements EmbeddingProvider {\n public readonly profile;\n readonly #apiKey: string;\n readonly #url: string;\n\n public constructor(options: JinaEmbeddingProviderOptions = {}) {\n this.#apiKey = options.apiKey ?? process.env.JINA_API_KEY ?? \"\";\n if (!this.#apiKey) throw new Error(\"JINA_API_KEY is required.\");\n const model = options.model ?? \"jina-embeddings-v4\";\n const dimensions = options.dimensions ?? 1024;\n if (!Number.isInteger(dimensions) || dimensions < 1) throw new Error(\"dimensions must be a positive integer.\");\n this.profile = {\n provider: \"jina\",\n model,\n dimensions,\n strategyVersion: \"callable-v1:code-query-passage\",\n } as const;\n this.#url = options.baseUrl ?? \"https://api.jina.ai/v1/embeddings\";\n }\n\n public embedDocuments(inputs: readonly string[], options?: { signal?: AbortSignal }): Promise<number[][]> {\n if (inputs.length === 0) return Promise.resolve([]);\n return this.#embed(inputs, \"code.passage\", options?.signal);\n }\n\n public async embedQuery(input: string, options?: { signal?: AbortSignal }): Promise<number[]> {\n return (await this.#embed([input], \"code.query\", options?.signal))[0]!;\n }\n\n #embed(inputs: readonly string[], task: \"code.passage\" | \"code.query\", signal?: AbortSignal): Promise<number[][]> {\n return requestEmbeddings({\n url: this.#url,\n apiKey: this.#apiKey,\n body: {\n model: this.profile.model,\n dimensions: this.profile.dimensions,\n embedding_type: \"float\",\n truncate: true,\n task,\n input: inputs,\n },\n expectedCount: inputs.length,\n dimensions: this.profile.dimensions,\n ...(signal ? { signal } : {}),\n });\n }\n}\n","export { CodeIndex } from \"./code-index.js\";\nexport { crossSearch } from \"./search/cross-search.js\";\nexport { OpenAIEmbeddingProvider } from \"./embeddings/openai.js\";\nexport type { OpenAIEmbeddingProviderOptions } from \"./embeddings/openai.js\";\nexport { JinaEmbeddingProvider } from \"./embeddings/jina.js\";\nexport type { JinaEmbeddingProviderOptions } from \"./embeddings/jina.js\";\nexport { CodeIndexError, GitDivergenceError, IncompatibleIndexError } from \"./errors.js\";\nexport type * from \"./types.js\";\n\nimport { CodeIndex } from \"./code-index.js\";\nimport { crossSearch } from \"./search/cross-search.js\";\nimport type {\n CodeIndexOptions,\n CrossSearchOptions,\n SimilaritySearchOptions,\n UpdateFilesOptions,\n UpdateFromGitOptions,\n} from \"./types.js\";\n\nexport function openCodeIndex(options: CodeIndexOptions): CodeIndex {\n return new CodeIndex(options);\n}\n\nexport function updateFiles(index: CodeIndex, options: UpdateFilesOptions) {\n return index.updateFiles(options);\n}\n\nexport function updateFromGit(index: CodeIndex, options?: UpdateFromGitOptions) {\n return index.updateFromGit(options);\n}\n\nexport function similaritySearch(index: CodeIndex, options: SimilaritySearchOptions) {\n return index.similaritySearch(options);\n}\n\nexport function crossSearchFunctions(options: CrossSearchOptions) {\n return crossSearch(options);\n}\n"],"mappings":";AAAA,SAAS,OAAO,gBAAgB;AAChC,OAAOA,WAAU;;;ACDV,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACjC,YAAY,SAAiB,SAAwB;AAC1D,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,qBAAN,cAA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B,SAA6B;AAChE,SAAO,YAAY,OAAO;AAC5B;","names":["path","path","path","path","path","path","path","path","path","path","entry"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ninjaxtools/slopdex",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Callable-level semantic indexing, search, and duplicate discovery for TypeScript and JavaScript codebases",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"bin": {
|
|
16
|
+
"slopdex": "dist/cli.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
".agents/skills/slopdex/SKILL.md",
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md",
|
|
22
|
+
"scripts/install-opencode-skill.mjs"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=24.0.0"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsup",
|
|
29
|
+
"dev": "tsx src/cli.ts",
|
|
30
|
+
"typecheck": "tsc --noEmit",
|
|
31
|
+
"test": "vitest",
|
|
32
|
+
"test:run": "vitest run",
|
|
33
|
+
"smoke": "node scripts/smoke.mjs",
|
|
34
|
+
"install:skill:opencode": "node scripts/install-opencode-skill.mjs",
|
|
35
|
+
"publish:minor": "npm version minor && npm publish --access public",
|
|
36
|
+
"prepack": "npm run build && npm run smoke",
|
|
37
|
+
"check": "npm run typecheck && npm run test:run && npm run build && npm run smoke"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"install": "^0.13.0",
|
|
41
|
+
"js-tiktoken": "^1.0.21",
|
|
42
|
+
"sqlite-vec": "^0.1.9",
|
|
43
|
+
"tree-sitter": "^0.21.1",
|
|
44
|
+
"tree-sitter-javascript": "^0.23.1",
|
|
45
|
+
"tree-sitter-typescript": "^0.23.2"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "^24.0.0",
|
|
49
|
+
"tsup": "^8.5.0",
|
|
50
|
+
"tsx": "^4.20.0",
|
|
51
|
+
"typescript": "^5.9.0",
|
|
52
|
+
"vitest": "^3.2.0"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { copyFile, mkdir } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const source = path.resolve(import.meta.dirname, "..", ".agents", "skills", "slopdex", "SKILL.md");
|
|
6
|
+
const destinationDirectory = path.join(homedir(), ".config", "opencode", "skills", "slopdex");
|
|
7
|
+
const destination = path.join(destinationDirectory, "SKILL.md");
|
|
8
|
+
|
|
9
|
+
await mkdir(destinationDirectory, { recursive: true });
|
|
10
|
+
await copyFile(source, destination);
|
|
11
|
+
process.stdout.write(`Installed Slopdex skill to ${destination}\n`);
|