opencode-codebase-index 0.9.0 → 0.11.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/README.md +4 -2
- package/dist/cli.cjs +78 -28
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +78 -28
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +244 -113
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +244 -113
- package/dist/index.js.map +1 -1
- package/native/codebase-index-native.darwin-arm64.node +0 -0
- package/native/codebase-index-native.darwin-x64.node +0 -0
- package/native/codebase-index-native.linux-arm64-gnu.node +0 -0
- package/native/codebase-index-native.linux-x64-gnu.node +0 -0
- package/native/codebase-index-native.win32-x64-msvc.node +0 -0
- package/package.json +3 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/ignore/index.js","../node_modules/eventemitter3/index.js","../src/index.ts","../src/config/constants.ts","../src/config/defaults.ts","../src/config/env-substitution.ts","../src/config/validators.ts","../src/config/schema.ts","../src/config/merger.ts","../src/config/paths.ts","../src/git/index.ts","../src/git/refs.ts","../src/config/rebase.ts","../src/utils/paths.ts","../node_modules/chokidar/index.js","../node_modules/readdirp/index.js","../node_modules/chokidar/handler.js","../src/watcher/file-watcher.ts","../src/utils/files.ts","../src/watcher/git-head-watcher.ts","../src/watcher/index.ts","../src/tools/index.ts","../src/indexer/index.ts","../node_modules/eventemitter3/index.mjs","../node_modules/p-timeout/index.js","../node_modules/p-queue/dist/lower-bound.js","../node_modules/p-queue/dist/priority-queue.js","../node_modules/p-queue/dist/index.js","../node_modules/is-network-error/index.js","../node_modules/p-retry/index.js","../src/embeddings/detector.ts","../src/embeddings/provider-types.ts","../src/utils/url-validation.ts","../src/embeddings/providers/custom.ts","../src/embeddings/providers/github-copilot.ts","../src/embeddings/providers/google.ts","../src/embeddings/providers/ollama.ts","../src/embeddings/providers/openai.ts","../src/embeddings/provider.ts","../src/rerank/index.ts","../src/utils/cost.ts","../src/utils/logger.ts","../src/native/index.ts","../src/tools/utils.ts","../src/tools/knowledge-base-paths.ts","../src/tools/config-state.ts","../src/commands/loader.ts","../src/routing-hints-patterns.ts","../src/routing-hints.ts"],"sourcesContent":["// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\nconst REGEX_TEST_BLANK_LINE = /^\\s+$/\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst REGEX_TEST_INVALID_PATH = /^\\.{0,2}\\/|^\\.{1,2}$/\n\nconst REGEX_TEST_TRAILING_SLASH = /\\/$/\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g\n\nconst RETURN_FALSE = () => false\n\n// Sanitize the range of a regular expression\n// The cases are complicated, see test cases for details\nconst sanitizeRange = range => range.replace(\n REGEX_REGEXP_RANGE,\n (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)\n ? match\n // Invalid range (out of order) which is ok for gitignore rules but\n // fatal for JavaScript regular expression, so eliminate it.\n : EMPTY\n)\n\n// See fixtures #59\nconst cleanRangeBackSlash = slashes => {\n const {length} = slashes\n return slashes.slice(0, length - length % 2)\n}\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\nconst REPLACERS = [\n\n [\n // Remove BOM\n // TODO:\n // Other similar zero-width characters?\n /^\\uFEFF/,\n () => EMPTY\n ],\n\n // > Trailing spaces are ignored unless they are quoted with backslash (\"\\\")\n [\n // (a\\ ) -> (a )\n // (a ) -> (a)\n // (a ) -> (a)\n // (a \\ ) -> (a )\n /((?:\\\\\\\\)*?)(\\\\?\\s+)$/,\n (_, m1, m2) => m1 + (\n m2.indexOf('\\\\') === 0\n ? SPACE\n : EMPTY\n )\n ],\n\n // Replace (\\ ) with ' '\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n /(\\\\+?)\\s/g,\n (_, m1) => {\n const {length} = m1\n return m1.slice(0, length - length % 2) + SPACE\n }\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^'\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/'\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*\\\\\\*\\\\\\*\\\\\\//,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n /^(?=[^^])/,\n function startingReplacer () {\n // If has a slash `/` at the beginning or middle\n return !/\\/(?!$)/.test(this)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n ? '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder\n : '\\\\/.+'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n }\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE\n ],\n\n [\n // > The range notation, e.g. [a-zA-Z],\n // > can be used to match one of the characters in a range.\n\n // `\\` is escaped by step 3\n /(\\\\)?\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE\n // '\\\\[bar]' -> '\\\\\\\\[bar\\\\]'\n ? `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}`\n : close === ']'\n ? endEscape.length % 2 === 0\n // A normal case, and it is a range notation\n // '[bar]'\n // '[bar\\\\\\\\]'\n ? `[${sanitizeRange(range)}${endEscape}]`\n // Invalid range notaton\n // '[bar\\\\]' -> '[bar\\\\\\\\]'\n : '[]'\n : '[]'\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n /(?:[^*])$/,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n match => /\\/$/.test(match)\n // foo/ will not match 'foo'\n ? `${match}$`\n // foo matches 'foo' and 'foo/'\n : `${match}(?=$|\\\\/$)`\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\\\\\*$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst TRAILING_WILD_CARD_REPLACERS = {\n [MODE_IGNORE] (_, p1) {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n },\n\n [MODE_CHECK_IGNORE] (_, p1) {\n // When doing `git check-ignore`\n const prefix = p1\n // '\\\\\\/':\n // 'abc/*' DOES match 'abc/' !\n ? `${p1}[^/]*`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n }\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => REPLACERS.reduce(\n (prev, [matcher, replacer]) =>\n prev.replace(matcher, replacer.bind(pattern)),\n pattern\n)\n\nconst isString = subject => typeof subject === 'string'\n\n// > A blank line matches no files, so it can serve as a separator for readability.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_TEST_BLANK_LINE.test(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\n // > A line starting with # serves as a comment.\n && pattern.indexOf('#') !== 0\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = this.regexPrefix.replace(\n REGEX_REPLACE_TRAILING_WILDCARD,\n\n // It does not need to bind pattern\n TRAILING_WILD_CARD_REPLACERS[mode]\n )\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n let negative = false\n let body = pattern\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body.indexOf('!') === 0) {\n negative = true\n body = body.substr(1)\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n if (checkPattern(pattern.pattern)) {\n const rule = createRule(pattern, this._ignoreCase)\n this._added = true\n this._rules.push(rule)\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n return this._added\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - checkUnignored `boolean` whether should check if the path is unignored,\n // setting `checkUnignored` to `false` could reduce additional\n // path matching.\n // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult} true if a file is ignored\n test (path, checkUnignored, mode) {\n let ignored = false\n let unignored = false\n let matchedRule\n\n this._rules.forEach(rule => {\n const {negative} = rule\n\n // | ignored : unignored\n // -------- | ---------------------------------------\n // negative | 0:0 | 0:1 | 1:0 | 1:1\n // -------- | ------- | ------- | ------- | --------\n // 0 | TEST | TEST | SKIP | X\n // 1 | TESTIF | SKIP | TEST | X\n\n // - SKIP: always skip\n // - TEST: always test\n // - TESTIF: only test if checkUnignored\n // - X: that never happen\n if (\n unignored === negative && ignored !== unignored\n || negative && !ignored && !unignored && !checkUnignored\n ) {\n return\n }\n\n const matched = rule[mode].test(path)\n\n if (!matched) {\n return\n }\n\n ignored = !negative\n unignored = negative\n\n matchedRule = negative\n ? UNDEFINED\n : rule\n })\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\nconst isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path)\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache, checkUnignored, slices) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache, checkUnignored, slices)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (!REGEX_TEST_TRAILING_SLASH.test(path)) {\n return this.test(path)\n }\n\n const slices = path.split(SLASH).filter(Boolean)\n slices.pop()\n\n if (slices.length) {\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n this._testCache,\n true,\n slices\n )\n\n if (parent.ignored) {\n return parent\n }\n }\n\n return this._rules.test(path, false, MODE_CHECK_IGNORE)\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache,\n\n // Whether should check if the path is unignored\n checkUnignored,\n\n // The path slices\n slices\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n if (!slices) {\n // path/to/a.js\n // ['path', 'to', 'a.js']\n slices = path.split(SLASH).filter(Boolean)\n }\n\n slices.pop()\n\n // If the path has no parent directory, just test it\n if (!slices.length) {\n return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n cache,\n checkUnignored,\n slices\n )\n\n // If the path contains a parent directory, check the parent first\n return cache[path] = parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache, false).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache, true)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import type { Plugin } from \"@opencode-ai/plugin\";\nimport * as path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport { parseConfig } from \"./config/schema.js\";\nimport { loadMergedConfig } from \"./config/merger.js\";\nimport { createWatcherWithIndexer } from \"./watcher/index.js\";\nimport {\n codebase_search,\n codebase_peek,\n index_codebase,\n index_status,\n index_health_check,\n index_metrics,\n index_logs,\n find_similar,\n call_graph,\n implementation_lookup,\n add_knowledge_base,\n list_knowledge_bases,\n remove_knowledge_base,\n getSharedIndexer,\n initializeTools,\n} from \"./tools/index.js\";\nimport { loadCommandsFromDirectory } from \"./commands/loader.js\";\nimport { RoutingHintController } from \"./routing-hints.js\";\nimport { hasProjectMarker } from \"./utils/files.js\";\nimport type { CombinedWatcher } from \"./watcher/index.js\";\n\nlet activeWatcher: CombinedWatcher | null = null;\n\nfunction replaceActiveWatcher(nextWatcher: CombinedWatcher | null): void {\n activeWatcher?.stop();\n activeWatcher = nextWatcher;\n}\n\nfunction getCommandsDir(): string {\n let currentDir = process.cwd();\n \n if (typeof import.meta !== \"undefined\" && import.meta.url) {\n currentDir = path.dirname(fileURLToPath(import.meta.url));\n }\n \n return path.join(currentDir, \"..\", \"commands\");\n}\n\nconst plugin: Plugin = async ({ directory }) => {\n try {\n const projectRoot = directory;\n const rawConfig = loadMergedConfig(projectRoot);\n const config = parseConfig(rawConfig);\n\n initializeTools(projectRoot, config);\n\n const indexer = getSharedIndexer();\n const routingHints = config.search.routingHints\n ? new RoutingHintController(() => indexer.getStatus())\n : null;\n\n const isValidProject = !config.indexing.requireProjectMarker || hasProjectMarker(projectRoot);\n\n if (!isValidProject) {\n console.warn(\n `[codebase-index] Skipping file watching and auto-indexing: no project marker found in \"${projectRoot}\". ` +\n `Set \"indexing.requireProjectMarker\": false in config to override.`\n );\n }\n\n if (config.indexing.autoIndex && isValidProject) {\n indexer.initialize().then(() => {\n indexer.index().catch(() => {});\n }).catch(() => {});\n }\n\n if (config.indexing.watchFiles && isValidProject) {\n replaceActiveWatcher(createWatcherWithIndexer(getSharedIndexer, projectRoot, config));\n } else {\n replaceActiveWatcher(null);\n }\n\n return {\n tool: {\n codebase_search,\n codebase_peek,\n index_codebase,\n index_status,\n index_health_check,\n index_metrics,\n index_logs,\n find_similar,\n call_graph,\n implementation_lookup,\n add_knowledge_base,\n list_knowledge_bases,\n remove_knowledge_base,\n },\n\n async \"chat.message\"(input, output) {\n routingHints?.observeUserMessage(input.sessionID, output.parts);\n },\n\n async \"experimental.chat.system.transform\"(input, output) {\n const hints = await routingHints?.getSystemHints(input.sessionID) ?? [];\n output.system.push(...hints);\n },\n\n async \"tool.execute.after\"(input) {\n routingHints?.markToolUsed(input.sessionID, input.tool);\n },\n\n async config(cfg) {\n cfg.command = cfg.command ?? {};\n\n const commandsDir = getCommandsDir();\n const commands = loadCommandsFromDirectory(commandsDir);\n\n for (const [name, definition] of commands) {\n cfg.command[name] = definition;\n }\n },\n };\n } catch (error) {\n console.error(\"[codebase-index] Failed to initialize plugin:\", error);\n // Return a plugin with no tools to prevent opencode from crashing\n return {\n tool: undefined,\n async config() {},\n };\n }\n};\n\nexport default plugin;\n","export const DEFAULT_INCLUDE = [\n \"**/*.{ts,tsx,js,jsx,mjs,cjs}\",\n \"**/*.{py,pyi}\",\n \"**/*.{go,rs,java,kt,scala}\",\n \"**/*.{c,cpp,cc,h,hpp}\",\n \"**/*.{rb,php,inc,swift}\",\n \"**/*.{cls,trigger}\",\n \"**/*.{vue,svelte,astro}\",\n \"**/*.{sql,graphql,proto}\",\n \"**/*.{yaml,yml,toml}\",\n \"**/*.{md,mdx}\",\n \"**/*.{sh,bash,zsh}\",\n \"**/*.{txt,html,htm}\",\n \"**/*.zig\",\n \"**/*.gd\",\n];\n\nexport const DEFAULT_EXCLUDE = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/*build*/**\",\n \"**/*.min.js\",\n \"**/*.bundle.js\",\n \"**/vendor/**\",\n \"**/__pycache__/**\",\n \"**/target/**\",\n \"**/coverage/**\",\n \"**/.next/**\",\n \"**/.nuxt/**\",\n \"**/.opencode/**\",\n \"**/.*\",\n \"**/.*/**\",\n];\n\nexport const EMBEDDING_MODELS = {\n \"google\": {\n // `text-embedding-004` is DEPRECATED - https://ai.google.dev/gemini-api/docs/deprecations\n \"text-embedding-005\": {\n provider: \"google\",\n model: \"text-embedding-005\",\n dimensions: 768,\n maxTokens: 2048,\n costPer1MTokens: 0.025,\n taskAble: false,\n // Note: on reality, this model allows for task-specific embeddings. See: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/embeddings/task-types\n },\n \"gemini-embedding-001\": {\n provider: \"google\",\n model: \"gemini-embedding-001\",\n // Native output is 3072D, but we use Matryoshka truncation via outputDimensionality\n // to reduce to 1536D for better storage/search efficiency with minimal quality loss.\n // Google recommends 768, 1536, or 3072. See: https://ai.google.dev/gemini-api/docs/embeddings\n dimensions: 1536,\n maxTokens: 2048,\n costPer1MTokens: 0.15,\n taskAble: true,\n },\n },\n \"openai\": {\n \"text-embedding-3-small\": {\n provider: \"openai\",\n model: \"text-embedding-3-small\",\n dimensions: 1536,\n maxTokens: 8191,\n costPer1MTokens: 0.02,\n },\n \"text-embedding-3-large\": {\n provider: \"openai\",\n model: \"text-embedding-3-large\",\n dimensions: 3072,\n maxTokens: 8191,\n costPer1MTokens: 0.13,\n },\n },\n \"ollama\": {\n \"nomic-embed-text\": {\n provider: \"ollama\",\n model: \"nomic-embed-text\",\n dimensions: 768,\n maxTokens: 2048,\n costPer1MTokens: 0.00,\n },\n \"mxbai-embed-large\": {\n provider: \"ollama\",\n model: \"mxbai-embed-large\",\n dimensions: 1024,\n maxTokens: 512,\n costPer1MTokens: 0.00,\n },\n },\n \"github-copilot\": {\n \"text-embedding-3-small\": {\n provider: \"github-copilot\",\n model: \"text-embedding-3-small\",\n dimensions: 1536,\n maxTokens: 8191,\n costPer1MTokens: 0.00,\n },\n },\n} as const;\n\nexport const DEFAULT_PROVIDER_MODELS = {\n \"github-copilot\": \"text-embedding-3-small\",\n \"openai\": \"text-embedding-3-small\",\n \"google\": \"gemini-embedding-001\",\n \"ollama\": \"nomic-embed-text\",\n} as const;\n\nexport const AUTO_DETECT_PROVIDER_ORDER = [\n \"ollama\",\n \"github-copilot\",\n \"openai\",\n \"google\",\n] as const;\n","import type {\n DebugConfig,\n IndexingConfig,\n RerankerProvider,\n SearchConfig,\n} from \"./schema.js\";\n\nexport function getDefaultIndexingConfig(): IndexingConfig {\n return {\n autoIndex: false,\n watchFiles: true,\n maxFileSize: 1048576,\n maxChunksPerFile: 100,\n semanticOnly: false,\n retries: 3,\n retryDelayMs: 1000,\n autoGc: true,\n gcIntervalDays: 7,\n gcOrphanThreshold: 100,\n requireProjectMarker: true,\n maxDepth: 5,\n maxFilesPerDirectory: 100,\n fallbackToTextOnMaxChunks: true,\n };\n}\n\nexport function getDefaultSearchConfig(): SearchConfig {\n return {\n maxResults: 20,\n minScore: 0.1,\n includeContext: true,\n hybridWeight: 0.5,\n fusionStrategy: \"rrf\",\n rrfK: 60,\n rerankTopN: 20,\n contextLines: 0,\n routingHints: true,\n };\n}\n\nexport function getDefaultRerankerBaseUrl(provider: RerankerProvider): string {\n switch (provider) {\n case \"cohere\":\n return \"https://api.cohere.ai/v1\";\n case \"jina\":\n return \"https://api.jina.ai/v1\";\n case \"custom\":\n return \"\";\n }\n}\n\nexport function getDefaultDebugConfig(): DebugConfig {\n return {\n enabled: false,\n logLevel: \"info\",\n logSearch: true,\n logEmbedding: true,\n logCache: true,\n logGc: true,\n logBranch: true,\n metrics: true,\n };\n}\n","const ENV_REFERENCE_PATTERN = /^\\{env:([A-Z_][A-Z0-9_]*)\\}$/;\nconst ENV_REFERENCE_LIKE_PATTERN = /\\{env:[^}]+\\}/;\n\nexport function substituteEnvString(value: string, keyPath: string): string {\n const match = value.match(ENV_REFERENCE_PATTERN);\n\n if (!match) {\n if (ENV_REFERENCE_LIKE_PATTERN.test(value)) {\n throw new Error(\n `Invalid environment variable reference at '${keyPath}'. ` +\n \"Expected the entire string to match '{env:VAR_NAME}' with VAR_NAME matching [A-Z_][A-Z0-9_]*.\"\n );\n }\n\n return value;\n }\n\n const variableName = match[1];\n const envValue = process.env[variableName];\n\n if (envValue === undefined) {\n throw new Error(`Missing environment variable '${variableName}' referenced by config at '${keyPath}'.`);\n }\n\n return envValue;\n}\n\nexport function substituteEnvReferences(raw: unknown, keyPath = \"$root\"): unknown {\n if (typeof raw === \"string\") {\n return substituteEnvString(raw, keyPath);\n }\n\n if (Array.isArray(raw)) {\n return raw.map((item, index) => substituteEnvReferences(item, `${keyPath}[${index}]`));\n }\n\n if (raw && typeof raw === \"object\") {\n return Object.fromEntries(\n Object.entries(raw).map(([key, value]) => [key, substituteEnvReferences(value, `${keyPath}.${key}`)])\n );\n }\n\n return raw;\n}\n","import type {\n EmbeddingProvider,\n IndexScope,\n LogLevel,\n ProviderModels,\n RerankerProvider,\n SearchConfig,\n} from \"./schema.js\";\n\nimport { EMBEDDING_MODELS } from \"./constants.js\";\nimport { substituteEnvString } from \"./env-substitution.js\";\n\nconst VALID_SCOPES: IndexScope[] = [\"project\", \"global\"];\nconst VALID_LOG_LEVELS: LogLevel[] = [\"error\", \"warn\", \"info\", \"debug\"];\n\nexport function isValidFusionStrategy(value: unknown): value is SearchConfig[\"fusionStrategy\"] {\n return value === \"weighted\" || value === \"rrf\";\n}\n\nexport function isValidRerankerProvider(value: unknown): value is RerankerProvider {\n return value === \"cohere\" || value === \"jina\" || value === \"custom\";\n}\n\nexport function isValidProvider(value: unknown): value is EmbeddingProvider {\n return typeof value === \"string\" && Object.keys(EMBEDDING_MODELS).includes(value);\n}\n\nexport function isValidModel<P extends EmbeddingProvider>(\n value: unknown,\n provider: P\n): value is ProviderModels[P] {\n return typeof value === \"string\" && Object.keys(EMBEDDING_MODELS[provider]).includes(value);\n}\n\nexport function isValidScope(value: unknown): value is IndexScope {\n return typeof value === \"string\" && VALID_SCOPES.includes(value as IndexScope);\n}\n\nexport function isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every(item => typeof item === \"string\");\n}\n\nexport function getResolvedString(value: unknown, keyPath: string): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n return substituteEnvString(value, keyPath);\n}\n\nexport function getResolvedStringArray(value: unknown, keyPath: string): string[] | undefined {\n if (!isStringArray(value)) {\n return undefined;\n }\n\n return value.map((item, index) => substituteEnvString(item, `${keyPath}[${index}]`));\n}\n\nexport function isValidLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && VALID_LOG_LEVELS.includes(value as LogLevel);\n}\n","// Config schema without zod dependency to avoid version conflicts with OpenCode SDK\n\nimport { AUTO_DETECT_PROVIDER_ORDER, DEFAULT_INCLUDE, DEFAULT_EXCLUDE, EMBEDDING_MODELS, DEFAULT_PROVIDER_MODELS } from \"./constants.js\";\nimport {\n getDefaultDebugConfig,\n getDefaultIndexingConfig,\n getDefaultRerankerBaseUrl,\n getDefaultSearchConfig,\n} from \"./defaults.js\";\nimport {\n getResolvedString,\n getResolvedStringArray,\n isStringArray,\n isValidFusionStrategy,\n isValidLogLevel,\n isValidModel,\n isValidProvider,\n isValidRerankerProvider,\n isValidScope,\n} from \"./validators.js\";\n\nexport { isValidModel } from \"./validators.js\";\n\nexport type IndexScope = \"project\" | \"global\";\n\nexport interface IndexingConfig {\n autoIndex: boolean;\n watchFiles: boolean;\n maxFileSize: number;\n maxChunksPerFile: number;\n semanticOnly: boolean;\n retries: number;\n retryDelayMs: number;\n autoGc: boolean;\n gcIntervalDays: number;\n gcOrphanThreshold: number;\n /**\n * When true (default), requires a project marker (.git, package.json, Cargo.toml, etc.)\n * to be present before enabling file watching and auto-indexing.\n */\n requireProjectMarker: boolean;\n /**\n * Max directory traversal depth. -1 = unlimited, 0 = only files in the root dir,\n * 1 = one level of subdirectories, etc. Default: 5\n */\n maxDepth: number;\n /**\n * Max number of files to index per directory. Always picks the smallest files first.\n * Default: 100\n */\n maxFilesPerDirectory: number;\n /**\n * When a file hits maxChunksPerFile, fallback to text-based (chunk_by_lines) parsing\n * instead of skipping the rest of the file. Default: true\n */\n fallbackToTextOnMaxChunks: boolean;\n}\n\nexport interface SearchConfig {\n maxResults: number;\n minScore: number;\n includeContext: boolean;\n hybridWeight: number;\n fusionStrategy: \"weighted\" | \"rrf\";\n rrfK: number;\n rerankTopN: number;\n contextLines: number;\n routingHints: boolean;\n}\n\nexport type RerankerProvider = \"cohere\" | \"jina\" | \"custom\";\n\nexport interface RerankerConfig {\n /** Whether to enable reranking. Default: false */\n enabled: boolean;\n /** Provider shortcut for hosted rerank APIs. Use 'custom' to provide only baseUrl. */\n provider: RerankerProvider;\n /** Model name for reranking */\n model: string;\n /** Base URL of the rerank API endpoint */\n baseUrl: string;\n /** API key for the rerank service */\n apiKey?: string;\n /** Number of top documents to rerank */\n topN: number;\n /** Request timeout in milliseconds */\n timeoutMs: number;\n}\n\nexport type LogLevel = \"error\" | \"warn\" | \"info\" | \"debug\";\n\nexport interface DebugConfig {\n enabled: boolean;\n logLevel: LogLevel;\n logSearch: boolean;\n logEmbedding: boolean;\n logCache: boolean;\n logGc: boolean;\n logBranch: boolean;\n metrics: boolean;\n}\n\nexport interface CustomProviderConfig {\n /** Base URL of the OpenAI-compatible embeddings API. The path /embeddings is appended automatically (e.g. \"http://localhost:11434/v1\", \"https://api.example.com/v1\") */\n baseUrl: string;\n /** Model name to send in the API request (e.g. \"nomic-embed-text\") */\n model: string;\n /** Vector dimensions the model produces (e.g. 768 for nomic-embed-text) */\n dimensions: number;\n /** Optional API key for authenticated endpoints */\n apiKey?: string;\n /** Max tokens per input text (default: 8192) */\n maxTokens?: number;\n /** Request timeout in milliseconds (default: 30000) */\n timeoutMs?: number;\n /** Max concurrent embedding requests (default: 3). Increase for local servers like llama.cpp or vLLM. */\n concurrency?: number;\n /** Minimum delay between requests in milliseconds (default: 1000). Set to 0 for local servers. */\n requestIntervalMs?: number;\n maxBatchSize?: number;\n max_batch_size?: number;\n}\n\nexport interface CodebaseIndexConfig {\n embeddingProvider: EmbeddingProvider | 'custom' | 'auto';\n embeddingModel?: EmbeddingModelName;\n /** Configuration for custom OpenAI-compatible embedding providers (required when embeddingProvider is 'custom') */\n customProvider?: CustomProviderConfig;\n scope: IndexScope;\n indexing?: Partial<IndexingConfig>;\n search?: Partial<SearchConfig>;\n debug?: Partial<DebugConfig>;\n /** Reranking configuration for improving search result quality */\n reranker?: Partial<RerankerConfig>;\n /** External directories to index as knowledge bases (absolute or relative paths) */\n knowledgeBases?: string[];\n /** Override the default include patterns (replaces defaults) */\n include: string[];\n /** Override the default exclude patterns (replaces defaults) */\n exclude: string[];\n /** Additional file patterns to include (extends defaults) */\n additionalInclude?: string[];\n}\n\nexport type ParsedCodebaseIndexConfig = CodebaseIndexConfig & {\n indexing: IndexingConfig;\n search: SearchConfig;\n debug: DebugConfig;\n reranker?: RerankerConfig;\n knowledgeBases: string[];\n additionalInclude: string[];\n};\n\nexport function parseConfig(raw: unknown): ParsedCodebaseIndexConfig {\n const input = (raw && typeof raw === \"object\" ? raw : {}) as Record<string, unknown>;\n const embeddingProviderValue = getResolvedString(input.embeddingProvider, \"$root.embeddingProvider\");\n const scopeValue = getResolvedString(input.scope, \"$root.scope\");\n const includeValue = getResolvedStringArray(input.include, \"$root.include\");\n const excludeValue = getResolvedStringArray(input.exclude, \"$root.exclude\");\n\n const defaultIndexing = getDefaultIndexingConfig();\n const defaultSearch = getDefaultSearchConfig();\n const defaultDebug = getDefaultDebugConfig();\n\n const rawIndexing = (input.indexing && typeof input.indexing === \"object\" ? input.indexing : {}) as Record<string, unknown>;\n const indexing: IndexingConfig = {\n autoIndex: typeof rawIndexing.autoIndex === \"boolean\" ? rawIndexing.autoIndex : defaultIndexing.autoIndex,\n watchFiles: typeof rawIndexing.watchFiles === \"boolean\" ? rawIndexing.watchFiles : defaultIndexing.watchFiles,\n maxFileSize: typeof rawIndexing.maxFileSize === \"number\" ? rawIndexing.maxFileSize : defaultIndexing.maxFileSize,\n maxChunksPerFile: typeof rawIndexing.maxChunksPerFile === \"number\" ? Math.max(1, rawIndexing.maxChunksPerFile) : defaultIndexing.maxChunksPerFile,\n semanticOnly: typeof rawIndexing.semanticOnly === \"boolean\" ? rawIndexing.semanticOnly : defaultIndexing.semanticOnly,\n retries: typeof rawIndexing.retries === \"number\" ? rawIndexing.retries : defaultIndexing.retries,\n retryDelayMs: typeof rawIndexing.retryDelayMs === \"number\" ? rawIndexing.retryDelayMs : defaultIndexing.retryDelayMs,\n autoGc: typeof rawIndexing.autoGc === \"boolean\" ? rawIndexing.autoGc : defaultIndexing.autoGc,\n gcIntervalDays: typeof rawIndexing.gcIntervalDays === \"number\" ? Math.max(1, rawIndexing.gcIntervalDays) : defaultIndexing.gcIntervalDays,\n gcOrphanThreshold: typeof rawIndexing.gcOrphanThreshold === \"number\" ? Math.max(0, rawIndexing.gcOrphanThreshold) : defaultIndexing.gcOrphanThreshold,\n requireProjectMarker: typeof rawIndexing.requireProjectMarker === \"boolean\" ? rawIndexing.requireProjectMarker : defaultIndexing.requireProjectMarker,\n maxDepth: typeof rawIndexing.maxDepth === \"number\" ? (rawIndexing.maxDepth < -1 ? -1 : rawIndexing.maxDepth) : defaultIndexing.maxDepth,\n maxFilesPerDirectory: typeof rawIndexing.maxFilesPerDirectory === \"number\" ? Math.max(1, rawIndexing.maxFilesPerDirectory) : defaultIndexing.maxFilesPerDirectory,\n fallbackToTextOnMaxChunks: typeof rawIndexing.fallbackToTextOnMaxChunks === \"boolean\" ? rawIndexing.fallbackToTextOnMaxChunks : defaultIndexing.fallbackToTextOnMaxChunks,\n };\n\n const rawSearch = (input.search && typeof input.search === \"object\" ? input.search : {}) as Record<string, unknown>;\n const search: SearchConfig = {\n maxResults: typeof rawSearch.maxResults === \"number\" ? rawSearch.maxResults : defaultSearch.maxResults,\n minScore: typeof rawSearch.minScore === \"number\" ? rawSearch.minScore : defaultSearch.minScore,\n includeContext: typeof rawSearch.includeContext === \"boolean\" ? rawSearch.includeContext : defaultSearch.includeContext,\n hybridWeight: typeof rawSearch.hybridWeight === \"number\" ? Math.min(1, Math.max(0, rawSearch.hybridWeight)) : defaultSearch.hybridWeight,\n fusionStrategy: isValidFusionStrategy(rawSearch.fusionStrategy) ? rawSearch.fusionStrategy : defaultSearch.fusionStrategy,\n rrfK: typeof rawSearch.rrfK === \"number\" ? Math.max(1, Math.floor(rawSearch.rrfK)) : defaultSearch.rrfK,\n rerankTopN: typeof rawSearch.rerankTopN === \"number\" ? Math.min(200, Math.max(0, Math.floor(rawSearch.rerankTopN))) : defaultSearch.rerankTopN,\n contextLines: typeof rawSearch.contextLines === \"number\" ? Math.min(50, Math.max(0, rawSearch.contextLines)) : defaultSearch.contextLines,\n routingHints: typeof rawSearch.routingHints === \"boolean\" ? rawSearch.routingHints : defaultSearch.routingHints,\n };\n\n const rawDebug = (input.debug && typeof input.debug === \"object\" ? input.debug : {}) as Record<string, unknown>;\n const debug: DebugConfig = {\n enabled: typeof rawDebug.enabled === \"boolean\" ? rawDebug.enabled : defaultDebug.enabled,\n logLevel: isValidLogLevel(rawDebug.logLevel) ? rawDebug.logLevel : defaultDebug.logLevel,\n logSearch: typeof rawDebug.logSearch === \"boolean\" ? rawDebug.logSearch : defaultDebug.logSearch,\n logEmbedding: typeof rawDebug.logEmbedding === \"boolean\" ? rawDebug.logEmbedding : defaultDebug.logEmbedding,\n logCache: typeof rawDebug.logCache === \"boolean\" ? rawDebug.logCache : defaultDebug.logCache,\n logGc: typeof rawDebug.logGc === \"boolean\" ? rawDebug.logGc : defaultDebug.logGc,\n logBranch: typeof rawDebug.logBranch === \"boolean\" ? rawDebug.logBranch : defaultDebug.logBranch,\n metrics: typeof rawDebug.metrics === \"boolean\" ? rawDebug.metrics : defaultDebug.metrics,\n };\n\n const rawKnowledgeBases = input.knowledgeBases;\n const knowledgeBases: string[] = isStringArray(rawKnowledgeBases)\n ? rawKnowledgeBases.filter(p => typeof p === \"string\" && p.trim().length > 0).map(p => p.trim())\n : [];\n\n const rawAdditionalInclude = input.additionalInclude;\n const additionalInclude: string[] = isStringArray(rawAdditionalInclude)\n ? rawAdditionalInclude\n .filter(p => typeof p === \"string\" && p.trim().length > 0)\n .map(p => p.trim())\n : [];\n\n let embeddingProvider: EmbeddingProvider | 'custom' | 'auto';\n let embeddingModel: EmbeddingModelName | undefined;\n let customProvider: CustomProviderConfig | undefined;\n let reranker: RerankerConfig | undefined;\n if (embeddingProviderValue === 'custom') {\n embeddingProvider = 'custom';\n const rawCustom = (input.customProvider && typeof input.customProvider === 'object' ? input.customProvider : null) as Record<string, unknown> | null;\n const baseUrlValue = getResolvedString(rawCustom?.baseUrl, \"$root.customProvider.baseUrl\");\n const modelValue = getResolvedString(rawCustom?.model, \"$root.customProvider.model\");\n const apiKeyValue = getResolvedString(rawCustom?.apiKey, \"$root.customProvider.apiKey\");\n if (rawCustom && typeof baseUrlValue === 'string' && baseUrlValue.trim().length > 0 && typeof modelValue === 'string' && modelValue.trim().length > 0 && typeof rawCustom.dimensions === 'number' && Number.isInteger(rawCustom.dimensions) && rawCustom.dimensions > 0) {\n customProvider = {\n baseUrl: baseUrlValue.trim().replace(/\\/+$/, ''),\n model: modelValue,\n dimensions: rawCustom.dimensions,\n apiKey: apiKeyValue,\n maxTokens: typeof rawCustom.maxTokens === 'number' ? rawCustom.maxTokens : undefined,\n timeoutMs: typeof rawCustom.timeoutMs === 'number' ? Math.max(1000, rawCustom.timeoutMs) : undefined,\n concurrency: typeof rawCustom.concurrency === 'number' ? Math.max(1, Math.floor(rawCustom.concurrency)) : undefined,\n requestIntervalMs: typeof rawCustom.requestIntervalMs === 'number' ? Math.max(0, Math.floor(rawCustom.requestIntervalMs)) : undefined,\n maxBatchSize: typeof rawCustom.maxBatchSize === 'number'\n ? Math.max(1, Math.floor(rawCustom.maxBatchSize))\n : typeof rawCustom.max_batch_size === 'number'\n ? Math.max(1, Math.floor(rawCustom.max_batch_size))\n : undefined,\n };\n // Warn if baseUrl doesn't end with an API version path like /v1.\n // Note: using console.warn here because Logger isn't initialized yet at config parse time.\n if (!/\\/v\\d+\\/?$/.test(customProvider.baseUrl)) {\n console.warn(\n `[codebase-index] Warning: customProvider.baseUrl (\"${customProvider.baseUrl}\") does not end with an API version path like /v1. ` +\n `The plugin appends /embeddings automatically, so the full URL will be \"${customProvider.baseUrl}/embeddings\". ` +\n `If your provider expects /v1/embeddings, set baseUrl to \"${customProvider.baseUrl}/v1\".`\n );\n }\n } else {\n throw new Error(\n \"embeddingProvider is 'custom' but customProvider config is missing or invalid. \" +\n \"Required fields: baseUrl (string), model (string), dimensions (positive integer).\"\n );\n }\n } else if (isValidProvider(embeddingProviderValue)) {\n embeddingProvider = embeddingProviderValue;\n const rawEmbeddingModel = input.embeddingModel;\n if (typeof rawEmbeddingModel === \"string\") {\n const embeddingModelValue = getResolvedString(rawEmbeddingModel, \"$root.embeddingModel\");\n if (embeddingModelValue) {\n embeddingModel = isValidModel(embeddingModelValue, embeddingProvider) ? embeddingModelValue : DEFAULT_PROVIDER_MODELS[embeddingProvider];\n }\n } else if (rawEmbeddingModel) {\n embeddingModel = DEFAULT_PROVIDER_MODELS[embeddingProvider];\n }\n } else {\n embeddingProvider = 'auto';\n }\n\n const rawReranker = (input.reranker && typeof input.reranker === \"object\"\n ? input.reranker\n : {}) as Record<string, unknown>;\n const rerankerEnabled = typeof rawReranker.enabled === \"boolean\" ? rawReranker.enabled : false;\n if (rerankerEnabled) {\n const provider = isValidRerankerProvider(rawReranker.provider) ? rawReranker.provider : \"custom\";\n const model = getResolvedString(rawReranker.model, \"$root.reranker.model\");\n if (!model || model.trim().length === 0) {\n throw new Error(\"reranker is enabled but reranker.model is missing or invalid.\");\n }\n\n const configuredBaseUrl = getResolvedString(rawReranker.baseUrl, \"$root.reranker.baseUrl\");\n const baseUrl = configuredBaseUrl?.trim() || getDefaultRerankerBaseUrl(provider);\n if (baseUrl.length === 0) {\n throw new Error(\"reranker is enabled but reranker.baseUrl is missing or invalid for provider 'custom'.\");\n }\n\n const apiKey = getResolvedString(rawReranker.apiKey, \"$root.reranker.apiKey\");\n if ((provider === \"cohere\" || provider === \"jina\") && (!apiKey || apiKey.trim().length === 0)) {\n throw new Error(`reranker provider '${provider}' requires reranker.apiKey when enabled.`);\n }\n\n reranker = {\n enabled: true,\n provider,\n model: model.trim(),\n baseUrl: baseUrl.replace(/\\/+$/, \"\"),\n apiKey: apiKey?.trim() || undefined,\n topN: typeof rawReranker.topN === \"number\" ? Math.min(50, Math.max(1, Math.floor(rawReranker.topN))) : 15,\n timeoutMs: typeof rawReranker.timeoutMs === \"number\" ? Math.max(1000, Math.floor(rawReranker.timeoutMs)) : 10000,\n };\n }\n\n return {\n embeddingProvider,\n embeddingModel,\n customProvider,\n scope: isValidScope(scopeValue) ? scopeValue : \"project\",\n include: includeValue ?? DEFAULT_INCLUDE,\n exclude: excludeValue ?? DEFAULT_EXCLUDE,\n additionalInclude,\n indexing,\n search,\n debug,\n reranker,\n knowledgeBases,\n };\n}\n\nexport function getDefaultModelForProvider(provider: EmbeddingProvider): EmbeddingModelInfo {\n const models = EMBEDDING_MODELS[provider];\n const providerDefault = DEFAULT_PROVIDER_MODELS[provider];\n return models[providerDefault as keyof typeof models];\n}\n\n/**\n * Built-in embedding providers derived from the static EMBEDDING_MODELS catalog.\n * 'custom' is intentionally excluded from this union because it has no static model\n * catalog — its model/dimensions/config are entirely user-defined at runtime via\n * CustomProviderConfig. Code that handles all providers uses `EmbeddingProvider | 'custom'`.\n */\nexport type EmbeddingProvider = keyof typeof EMBEDDING_MODELS;\n\nexport const availableProviders: EmbeddingProvider[] = Object.keys(EMBEDDING_MODELS) as EmbeddingProvider[];\n\nexport const autoDetectProviders: EmbeddingProvider[] = AUTO_DETECT_PROVIDER_ORDER.filter(\n (provider): provider is EmbeddingProvider => provider in EMBEDDING_MODELS,\n);\n\nexport type ProviderModels = {\n [P in keyof typeof EMBEDDING_MODELS]: keyof (typeof EMBEDDING_MODELS)[P]\n}\n\nexport type EmbeddingModelName = ProviderModels[keyof ProviderModels];\n\nexport type EmbeddingProviderModelInfo = {\n [P in EmbeddingProvider]: (typeof EMBEDDING_MODELS)[P][keyof (typeof EMBEDDING_MODELS)[P]]\n}\n\n\n/** Shared fields across all embedding model types (built-in and custom) */\nexport interface BaseModelInfo {\n model: string;\n dimensions: number;\n maxTokens: number;\n costPer1MTokens: number;\n}\n\nexport type EmbeddingModelInfo = EmbeddingProviderModelInfo[EmbeddingProvider];\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { resolveProjectConfigPath } from \"./paths.js\";\nimport { resolveInheritedKnowledgeBaseEntries } from \"./rebase.js\";\n\nconst PROJECT_OVERRIDE_KEYS = [\n \"embeddingProvider\",\n \"customProvider\",\n \"embeddingModel\",\n \"reranker\",\n \"include\",\n \"exclude\",\n \"indexing\",\n \"search\",\n \"debug\",\n \"scope\",\n] as const;\n\nconst MERGE_ARRAY_KEYS = [\"knowledgeBases\", \"additionalInclude\"] as const;\n\ntype ProjectOverrideKey = (typeof PROJECT_OVERRIDE_KEYS)[number];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\nfunction applyProjectOverride(\n merged: Record<string, unknown>,\n normalizedProjectConfig: Record<string, unknown>,\n globalConfig: Record<string, unknown>,\n key: ProjectOverrideKey,\n): void {\n if (key in normalizedProjectConfig) {\n merged[key] = normalizedProjectConfig[key];\n return;\n }\n\n if (key in globalConfig) {\n merged[key] = globalConfig[key];\n }\n}\n\nfunction mergeUniqueStringArray(values: unknown[]): string[] {\n return [...new Set(values.map((value) => String(value).trim()))];\n}\n\nfunction normalizeKnowledgeBasePath(value: unknown): string {\n let normalized = path.normalize(String(value).trim());\n const root = path.parse(normalized).root;\n\n while (normalized.length > root.length && /[\\\\/]$/.test(normalized)) {\n normalized = normalized.slice(0, -1);\n }\n\n return normalized;\n}\n\nfunction mergeKnowledgeBasePaths(values: unknown[]): string[] {\n return [...new Set(values.map((value) => normalizeKnowledgeBasePath(value)).filter((value) => value.length > 0))];\n}\n\nfunction validateConfigLayerShape(rawConfig: unknown, filePath: string): Record<string, unknown> {\n if (!isRecord(rawConfig)) {\n throw new Error(`Config file ${filePath} must contain a JSON object at the root.`);\n }\n\n if (rawConfig.knowledgeBases !== undefined && !isStringArray(rawConfig.knowledgeBases)) {\n throw new Error(`Config file ${filePath} field 'knowledgeBases' must be an array of strings.`);\n }\n if (rawConfig.additionalInclude !== undefined && !isStringArray(rawConfig.additionalInclude)) {\n throw new Error(`Config file ${filePath} field 'additionalInclude' must be an array of strings.`);\n }\n if (rawConfig.include !== undefined && !isStringArray(rawConfig.include)) {\n throw new Error(`Config file ${filePath} field 'include' must be an array of strings.`);\n }\n if (rawConfig.exclude !== undefined && !isStringArray(rawConfig.exclude)) {\n throw new Error(`Config file ${filePath} field 'exclude' must be an array of strings.`);\n }\n\n for (const section of [\"customProvider\", \"indexing\", \"search\", \"debug\", \"reranker\"] as const) {\n const value = rawConfig[section];\n if (value !== undefined && !isRecord(value)) {\n throw new Error(`Config file ${filePath} field '${section}' must be an object.`);\n }\n }\n\n return rawConfig;\n}\n\nfunction loadJsonFile(filePath: string): unknown {\n if (!existsSync(filePath)) {\n return null;\n }\n\n try {\n const content = readFileSync(filePath, \"utf-8\");\n return validateConfigLayerShape(JSON.parse(content), filePath);\n } catch (error: unknown) {\n if (error instanceof Error && error.message.startsWith(\"Config file \")) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load config file ${filePath}: ${message}`);\n }\n\n return null;\n}\n\nexport function materializeLocalProjectConfig(projectRoot: string, config: unknown): string {\n const localConfigPath = path.join(projectRoot, \".opencode\", \"codebase-index.json\");\n mkdirSync(path.dirname(localConfigPath), { recursive: true });\n writeFileSync(localConfigPath, JSON.stringify(config, null, 2), \"utf-8\");\n return localConfigPath;\n}\n\nexport function loadProjectConfigLayer(projectRoot: string): Record<string, unknown> {\n const projectConfigPath = resolveProjectConfigPath(projectRoot);\n const projectConfig = loadJsonFile(projectConfigPath) as Record<string, unknown> | null;\n\n if (!projectConfig) {\n return {};\n }\n\n const normalizedConfig: Record<string, unknown> = { ...projectConfig };\n const projectConfigBaseDir = path.dirname(path.dirname(projectConfigPath));\n\n if (Array.isArray(normalizedConfig.knowledgeBases)) {\n normalizedConfig.knowledgeBases = resolveInheritedKnowledgeBaseEntries(\n normalizedConfig.knowledgeBases,\n projectConfigBaseDir,\n projectRoot,\n );\n }\n\n return normalizedConfig;\n}\n\n/**\n * Loads and merges global and project configs.\n * \n * Merge rules:\n * - Global config is the base\n * - For most fields: project overrides global if set, otherwise load global (fallback)\n * - For knowledgeBases: merge arrays (union, deduplicated)\n * - For additionalInclude: merge arrays (union, deduplicated)\n * - For include/exclude: project overrides global if set, otherwise load global\n */\nexport function loadMergedConfig(projectRoot: string): unknown {\n const globalConfigPath = os.homedir() + \"/.config/opencode/codebase-index.json\";\n const projectConfigPath = resolveProjectConfigPath(projectRoot);\n let globalConfig: Record<string, unknown> | null = null;\n let globalConfigError: Error | null = null;\n\n try {\n globalConfig = loadJsonFile(globalConfigPath) as Record<string, unknown> | null;\n } catch (error: unknown) {\n globalConfigError = error instanceof Error ? error : new Error(String(error));\n }\n\n const projectConfig = loadJsonFile(projectConfigPath) as Record<string, unknown> | null;\n const normalizedProjectConfig = loadProjectConfigLayer(projectRoot);\n\n if (globalConfigError) {\n if (!projectConfig) {\n throw globalConfigError;\n }\n globalConfig = null;\n }\n\n if (!globalConfig && !projectConfig) {\n return {};\n }\n\n if (!projectConfig && globalConfig) {\n return globalConfig;\n }\n\n if (!globalConfig && projectConfig) {\n return normalizedProjectConfig;\n }\n\n if (!globalConfig || !projectConfig) {\n return globalConfig ?? normalizedProjectConfig;\n }\n\n\n const merged: Record<string, unknown> = { ...globalConfig };\n\n for (const key of PROJECT_OVERRIDE_KEYS) {\n applyProjectOverride(merged, normalizedProjectConfig, globalConfig, key);\n }\n\n // For other config sections: project overrides if set, otherwise use global\n if (projectConfig) {\n for (const key of Object.keys(projectConfig)) {\n if (\n PROJECT_OVERRIDE_KEYS.includes(key as ProjectOverrideKey) ||\n MERGE_ARRAY_KEYS.includes(key as (typeof MERGE_ARRAY_KEYS)[number])\n ) {\n continue; // Already handled above\n }\n merged[key] = normalizedProjectConfig[key];\n }\n }\n\n // For knowledgeBases: merge arrays (union, deduplicated)\n const globalKbs = globalConfig && Array.isArray(globalConfig.knowledgeBases) ? globalConfig.knowledgeBases : [];\n const projectKbs = projectConfig\n ? (Array.isArray(normalizedProjectConfig.knowledgeBases) ? normalizedProjectConfig.knowledgeBases as string[] : [])\n : [];\n const allKbs = [...globalKbs, ...projectKbs];\n merged.knowledgeBases = mergeKnowledgeBasePaths(allKbs);\n\n // For additionalInclude: merge arrays (union, deduplicated)\n const globalAdditional = globalConfig && Array.isArray(globalConfig.additionalInclude) ? globalConfig.additionalInclude : [];\n const projectAdditional = projectConfig && Array.isArray(projectConfig.additionalInclude) ? projectConfig.additionalInclude : [];\n const allAdditional = [...globalAdditional, ...projectAdditional];\n merged.additionalInclude = mergeUniqueStringArray(allAdditional);\n\n return merged;\n}\n","import { existsSync } from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { resolveWorktreeMainRepoRoot } from \"../git/index.js\";\n\nconst PROJECT_CONFIG_RELATIVE_PATH = path.join(\".opencode\", \"codebase-index.json\");\nconst PROJECT_INDEX_RELATIVE_PATH = path.join(\".opencode\", \"index\");\n\nfunction resolveWorktreeFallbackPath(projectRoot: string, relativePath: string): string | null {\n const mainRepoRoot = resolveWorktreeMainRepoRoot(projectRoot);\n if (!mainRepoRoot) {\n return null;\n }\n\n const fallbackPath = path.join(mainRepoRoot, relativePath);\n return existsSync(fallbackPath) ? fallbackPath : null;\n}\n\nfunction hasProjectConfig(projectRoot: string): boolean {\n return existsSync(path.join(projectRoot, PROJECT_CONFIG_RELATIVE_PATH));\n}\n\nexport function getGlobalIndexPath(): string {\n return path.join(os.homedir(), \".opencode\", \"global-index\");\n}\n\nexport function resolveProjectConfigPath(projectRoot: string): string {\n const localConfigPath = path.join(projectRoot, PROJECT_CONFIG_RELATIVE_PATH);\n if (existsSync(localConfigPath)) {\n return localConfigPath;\n }\n\n return resolveWorktreeFallbackPath(projectRoot, PROJECT_CONFIG_RELATIVE_PATH) ?? localConfigPath;\n}\n\nexport function resolveWritableProjectConfigPath(projectRoot: string): string {\n return path.join(projectRoot, PROJECT_CONFIG_RELATIVE_PATH);\n}\n\nexport function resolveProjectIndexPath(projectRoot: string, scope: \"project\" | \"global\"): string {\n if (scope === \"global\") {\n return getGlobalIndexPath();\n }\n\n const localIndexPath = path.join(projectRoot, PROJECT_INDEX_RELATIVE_PATH);\n if (existsSync(localIndexPath)) {\n return localIndexPath;\n }\n\n if (hasProjectConfig(projectRoot)) {\n return localIndexPath;\n }\n\n return resolveWorktreeFallbackPath(projectRoot, PROJECT_INDEX_RELATIVE_PATH) ?? localIndexPath;\n}\n","import { existsSync, readFileSync, statSync } from \"fs\";\nimport * as path from \"path\";\nimport { collectBranchRefs, readPackedRefs, resolveCommonGitDir, tryResolveRefCommit } from \"./refs.js\";\n\nexport function resolveWorktreeMainRepoRoot(repoRoot: string): string | null {\n const gitDir = resolveGitDir(repoRoot);\n if (!gitDir) {\n return null;\n }\n\n const commonGitDir = resolveCommonGitDir(gitDir);\n if (commonGitDir === gitDir || path.basename(commonGitDir) !== \".git\") {\n return null;\n }\n\n const mainRepoRoot = path.dirname(commonGitDir);\n if (!existsSync(mainRepoRoot)) {\n return null;\n }\n\n return path.resolve(mainRepoRoot) === path.resolve(repoRoot) ? null : mainRepoRoot;\n}\n\n/**\n * Resolves the actual git directory path.\n * \n * In a normal repo, `.git` is a directory containing HEAD, refs, etc.\n * In a worktree, `.git` is a file containing `gitdir: /path/to/actual/git/dir`.\n * \n * @returns The resolved git directory path, or null if not a git repo\n */\nexport function resolveGitDir(repoRoot: string): string | null {\n const gitPath = path.join(repoRoot, \".git\");\n \n if (!existsSync(gitPath)) {\n return null;\n }\n \n try {\n const stat = statSync(gitPath);\n \n if (stat.isDirectory()) {\n return gitPath;\n }\n \n if (stat.isFile()) {\n const content = readFileSync(gitPath, \"utf-8\").trim();\n const match = content.match(/^gitdir:\\s*(.+)$/);\n if (match) {\n const gitdir = match[1];\n // Handle relative paths\n const resolvedPath = path.isAbsolute(gitdir)\n ? gitdir\n : path.resolve(repoRoot, gitdir);\n \n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n }\n }\n } catch {\n // Ignore errors (permission issues, etc.)\n }\n \n return null;\n}\n\nexport function isGitRepo(dir: string): boolean {\n return resolveGitDir(dir) !== null;\n}\n\nexport function getCurrentBranch(repoRoot: string): string | null {\n const gitDir = resolveGitDir(repoRoot);\n if (!gitDir) {\n return null;\n }\n \n const headPath = path.join(gitDir, \"HEAD\");\n \n if (!existsSync(headPath)) {\n return null;\n }\n\n try {\n const headContent = readFileSync(headPath, \"utf-8\").trim();\n \n const match = headContent.match(/^ref: refs\\/heads\\/(.+)$/);\n if (match) {\n return match[1];\n }\n\n if (/^[0-9a-f]{40}$/i.test(headContent)) {\n return headContent.slice(0, 7);\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport function getCurrentCommit(repoRoot: string): string | null {\n const gitDir = resolveGitDir(repoRoot);\n if (!gitDir) {\n return null;\n }\n const refStoreDir = resolveCommonGitDir(gitDir);\n\n const headPath = path.join(gitDir, \"HEAD\");\n if (!existsSync(headPath)) {\n return null;\n }\n\n try {\n const headContent = readFileSync(headPath, \"utf-8\").trim();\n\n if (/^[0-9a-f]{40}$/i.test(headContent)) {\n return headContent;\n }\n\n const refMatch = headContent.match(/^ref:\\s*(.+)$/);\n if (!refMatch) {\n return null;\n }\n\n return tryResolveRefCommit(refStoreDir, refMatch[1]);\n } catch {\n return null;\n }\n}\n\nexport function getBaseBranch(repoRoot: string): string {\n const gitDir = resolveGitDir(repoRoot);\n const refStoreDir = gitDir ? resolveCommonGitDir(gitDir) : null;\n const candidates = [\"main\", \"master\", \"develop\", \"trunk\"];\n \n if (refStoreDir) {\n for (const candidate of candidates) {\n const refPath = path.join(refStoreDir, \"refs\", \"heads\", candidate);\n if (existsSync(refPath)) {\n return candidate;\n }\n\n const packedRefs = readPackedRefs(refStoreDir);\n if (packedRefs.some((line) => line.endsWith(` refs/heads/${candidate}`))) {\n return candidate;\n }\n }\n }\n\n return getCurrentBranch(repoRoot) ?? \"main\";\n}\n\nexport function getAllBranches(repoRoot: string): string[] {\n const branchSet = new Set<string>();\n const gitDir = resolveGitDir(repoRoot);\n const refStoreDir = gitDir ? resolveCommonGitDir(gitDir) : null;\n \n if (!refStoreDir) {\n return [];\n }\n \n const refsPath = path.join(refStoreDir, \"refs\", \"heads\");\n \n if (!existsSync(refsPath)) {\n return [];\n }\n\n const looseBranches: string[] = [];\n collectBranchRefs(looseBranches, refsPath);\n for (const branch of looseBranches) {\n branchSet.add(branch);\n }\n\n const packedRefs = readPackedRefs(refStoreDir);\n for (const line of packedRefs) {\n const splitIndex = line.indexOf(\" \");\n if (splitIndex <= 0) {\n continue;\n }\n\n const ref = line.slice(splitIndex + 1).trim();\n const prefix = \"refs/heads/\";\n if (ref.startsWith(prefix)) {\n branchSet.add(ref.slice(prefix.length));\n }\n }\n\n return Array.from(branchSet).sort();\n}\n\nexport function getBranchOrDefault(repoRoot: string): string {\n if (!isGitRepo(repoRoot)) {\n return \"default\";\n }\n \n return getCurrentBranch(repoRoot) ?? \"default\";\n}\n\nexport function getHeadPath(repoRoot: string): string {\n const gitDir = resolveGitDir(repoRoot);\n if (gitDir) {\n return path.join(gitDir, \"HEAD\");\n }\n return path.join(repoRoot, \".git\", \"HEAD\");\n}\n","import { existsSync, readFileSync, readdirSync, statSync } from \"fs\";\nimport * as path from \"path\";\n\nexport function readPackedRefs(gitDir: string): string[] {\n const packedRefsPath = path.join(gitDir, \"packed-refs\");\n if (!existsSync(packedRefsPath)) {\n return [];\n }\n\n try {\n return readFileSync(packedRefsPath, \"utf-8\")\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\") && !line.startsWith(\"^\"));\n } catch {\n return [];\n }\n}\n\nexport function resolveCommonGitDir(gitDir: string): string {\n const commonDirPath = path.join(gitDir, \"commondir\");\n if (!existsSync(commonDirPath)) {\n return gitDir;\n }\n\n try {\n const raw = readFileSync(commonDirPath, \"utf-8\").trim();\n if (!raw) {\n return gitDir;\n }\n\n const resolved = path.isAbsolute(raw) ? raw : path.resolve(gitDir, raw);\n if (existsSync(resolved)) {\n return resolved;\n }\n } catch {\n return gitDir;\n }\n\n return gitDir;\n}\n\nexport function tryResolveRefCommit(gitDir: string, refPath: string): string | null {\n const looseRefPath = path.join(gitDir, refPath);\n if (existsSync(looseRefPath)) {\n try {\n const value = readFileSync(looseRefPath, \"utf-8\").trim();\n if (/^[0-9a-f]{40}$/i.test(value)) {\n return value;\n }\n } catch {\n return null;\n }\n }\n\n const packedRefs = readPackedRefs(gitDir);\n for (const line of packedRefs) {\n const splitIndex = line.indexOf(\" \");\n if (splitIndex <= 0) {\n continue;\n }\n\n const commit = line.slice(0, splitIndex).trim();\n const packedRef = line.slice(splitIndex + 1).trim();\n if (packedRef === refPath && /^[0-9a-f]{40}$/i.test(commit)) {\n return commit;\n }\n }\n\n return null;\n}\n\nexport function collectBranchRefs(branches: string[], baseDir: string, prefix = \"\"): void {\n if (!existsSync(baseDir)) {\n return;\n }\n\n try {\n const entries = readdirSync(baseDir);\n for (const entry of entries) {\n const nextPath = path.join(baseDir, entry);\n const nextPrefix = prefix ? `${prefix}/${entry}` : entry;\n const stat = statSync(nextPath);\n if (stat.isDirectory()) {\n collectBranchRefs(branches, nextPath, nextPrefix);\n } else if (stat.isFile()) {\n branches.push(nextPrefix);\n }\n }\n } catch {\n return;\n }\n}\n","import * as path from \"path\";\n\nimport { normalizePathSeparators } from \"../utils/paths.js\";\n\n\nfunction isWithinRoot(rootDir: string, targetPath: string): boolean {\n const relativePath = path.relative(rootDir, targetPath);\n return relativePath === \"\" || (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath));\n}\n\nexport function rebasePathEntries(\n values: unknown,\n fromDir: string,\n toDir: string,\n): string[] {\n if (!Array.isArray(values)) {\n return [];\n }\n\n return values\n .filter((value): value is string => typeof value === \"string\")\n .map((value) => {\n const trimmed = value.trim();\n if (!trimmed || path.isAbsolute(trimmed)) {\n return trimmed;\n }\n\n return normalizePathSeparators(path.normalize(path.relative(toDir, path.resolve(fromDir, trimmed))));\n })\n .filter(Boolean);\n}\n\nexport function resolveInheritedKnowledgeBaseEntries(\n values: unknown,\n sourceRoot: string,\n targetRoot: string,\n): string[] {\n if (!Array.isArray(values)) {\n return [];\n }\n\n return values\n .filter((value): value is string => typeof value === \"string\")\n .map((value) => {\n const trimmed = value.trim();\n if (!trimmed) {\n return trimmed;\n }\n\n if (path.isAbsolute(trimmed)) {\n if (isWithinRoot(sourceRoot, trimmed)) {\n return normalizePathSeparators(path.normalize(path.relative(sourceRoot, trimmed) || \".\"));\n }\n\n return path.normalize(trimmed);\n }\n\n const resolvedFromSource = path.resolve(sourceRoot, trimmed);\n if (isWithinRoot(sourceRoot, resolvedFromSource)) {\n return normalizePathSeparators(path.normalize(trimmed));\n }\n\n return normalizePathSeparators(path.normalize(path.relative(targetRoot, resolvedFromSource)));\n })\n .filter(Boolean);\n}\n","import * as path from \"path\";\n\nexport function normalizePathSeparators(value: string): string {\n return value.replace(/\\\\/g, \"/\");\n}\n\nexport function isHiddenPathSegment(part: string): boolean {\n return part.startsWith(\".\") && part !== \".\" && part !== \"..\";\n}\n\nexport function isBuildPathSegment(part: string): boolean {\n return part.toLowerCase().includes(\"build\");\n}\n\nexport function hasFilteredPathSegment(relativePath: string, separator: string = path.sep): boolean {\n return relativePath.split(separator).some(\n (part) => isHiddenPathSegment(part) || isBuildPathSegment(part)\n );\n}\n","/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */\nimport { EventEmitter } from 'node:events';\nimport { stat as statcb, Stats } from 'node:fs';\nimport { readdir, stat } from 'node:fs/promises';\nimport * as sp from 'node:path';\nimport { readdirp, ReaddirpStream } from 'readdirp';\nimport { EMPTY_FN, EVENTS as EV, isIBMi, isWindows, NodeFsHandler, STR_CLOSE, STR_END, } from './handler.js';\nconst SLASH = '/';\nconst SLASH_SLASH = '//';\nconst ONE_DOT = '.';\nconst TWO_DOTS = '..';\nconst STRING_TYPE = 'string';\nconst BACK_SLASH_RE = /\\\\/g;\nconst DOUBLE_SLASH_RE = /\\/\\//g;\nconst DOT_RE = /\\..*\\.(sw[px])$|~$|\\.subl.*\\.tmp/;\nconst REPLACER_RE = /^\\.[/\\\\]/;\nfunction arrify(item) {\n return Array.isArray(item) ? item : [item];\n}\nconst isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);\nfunction createPattern(matcher) {\n if (typeof matcher === 'function')\n return matcher;\n if (typeof matcher === 'string')\n return (string) => matcher === string;\n if (matcher instanceof RegExp)\n return (string) => matcher.test(string);\n if (typeof matcher === 'object' && matcher !== null) {\n return (string) => {\n if (matcher.path === string)\n return true;\n if (matcher.recursive) {\n const relative = sp.relative(matcher.path, string);\n if (!relative) {\n return false;\n }\n return !relative.startsWith('..') && !sp.isAbsolute(relative);\n }\n return false;\n };\n }\n return () => false;\n}\nfunction normalizePath(path) {\n if (typeof path !== 'string')\n throw new Error('string expected');\n path = sp.normalize(path);\n path = path.replace(/\\\\/g, '/');\n let prepend = false;\n if (path.startsWith('//'))\n prepend = true;\n path = path.replace(DOUBLE_SLASH_RE, '/');\n if (prepend)\n path = '/' + path;\n return path;\n}\nfunction matchPatterns(patterns, testString, stats) {\n const path = normalizePath(testString);\n for (let index = 0; index < patterns.length; index++) {\n const pattern = patterns[index];\n if (pattern(path, stats)) {\n return true;\n }\n }\n return false;\n}\nfunction anymatch(matchers, testString) {\n if (matchers == null) {\n throw new TypeError('anymatch: specify first argument');\n }\n // Early cache for matchers.\n const matchersArray = arrify(matchers);\n const patterns = matchersArray.map((matcher) => createPattern(matcher));\n if (testString == null) {\n return (testString, stats) => {\n return matchPatterns(patterns, testString, stats);\n };\n }\n return matchPatterns(patterns, testString);\n}\nconst unifyPaths = (paths_) => {\n const paths = arrify(paths_).flat();\n if (!paths.every((p) => typeof p === STRING_TYPE)) {\n throw new TypeError(`Non-string provided as watch path: ${paths}`);\n }\n return paths.map(normalizePathToUnix);\n};\n// If SLASH_SLASH occurs at the beginning of path, it is not replaced\n// because \"//StoragePC/DrivePool/Movies\" is a valid network path\nconst toUnix = (string) => {\n let str = string.replace(BACK_SLASH_RE, SLASH);\n let prepend = false;\n if (str.startsWith(SLASH_SLASH)) {\n prepend = true;\n }\n str = str.replace(DOUBLE_SLASH_RE, SLASH);\n if (prepend) {\n str = SLASH + str;\n }\n return str;\n};\n// Our version of upath.normalize\n// TODO: this is not equal to path-normalize module - investigate why\nconst normalizePathToUnix = (path) => toUnix(sp.normalize(toUnix(path)));\n// TODO: refactor\nconst normalizeIgnored = (cwd = '') => (path) => {\n if (typeof path === 'string') {\n return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));\n }\n else {\n return path;\n }\n};\nconst getAbsolutePath = (path, cwd) => {\n if (sp.isAbsolute(path)) {\n return path;\n }\n return sp.join(cwd, path);\n};\nconst EMPTY_SET = Object.freeze(new Set());\n/**\n * Directory entry.\n */\nclass DirEntry {\n path;\n _removeWatcher;\n items;\n constructor(dir, removeWatcher) {\n this.path = dir;\n this._removeWatcher = removeWatcher;\n this.items = new Set();\n }\n add(item) {\n const { items } = this;\n if (!items)\n return;\n if (item !== ONE_DOT && item !== TWO_DOTS)\n items.add(item);\n }\n async remove(item) {\n const { items } = this;\n if (!items)\n return;\n items.delete(item);\n if (items.size > 0)\n return;\n const dir = this.path;\n try {\n await readdir(dir);\n }\n catch (err) {\n if (this._removeWatcher) {\n this._removeWatcher(sp.dirname(dir), sp.basename(dir));\n }\n }\n }\n has(item) {\n const { items } = this;\n if (!items)\n return;\n return items.has(item);\n }\n getChildren() {\n const { items } = this;\n if (!items)\n return [];\n return [...items.values()];\n }\n dispose() {\n this.items.clear();\n this.path = '';\n this._removeWatcher = EMPTY_FN;\n this.items = EMPTY_SET;\n Object.freeze(this);\n }\n}\nconst STAT_METHOD_F = 'stat';\nconst STAT_METHOD_L = 'lstat';\nexport class WatchHelper {\n fsw;\n path;\n watchPath;\n fullWatchPath;\n dirParts;\n followSymlinks;\n statMethod;\n constructor(path, follow, fsw) {\n this.fsw = fsw;\n const watchPath = path;\n this.path = path = path.replace(REPLACER_RE, '');\n this.watchPath = watchPath;\n this.fullWatchPath = sp.resolve(watchPath);\n this.dirParts = [];\n this.dirParts.forEach((parts) => {\n if (parts.length > 1)\n parts.pop();\n });\n this.followSymlinks = follow;\n this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;\n }\n entryPath(entry) {\n return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));\n }\n filterPath(entry) {\n const { stats } = entry;\n if (stats && stats.isSymbolicLink())\n return this.filterDir(entry);\n const resolvedPath = this.entryPath(entry);\n // TODO: what if stats is undefined? remove !\n return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);\n }\n filterDir(entry) {\n return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);\n }\n}\n/**\n * Watches files & directories for changes. Emitted events:\n * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`\n *\n * new FSWatcher()\n * .add(directories)\n * .on('add', path => log('File', path, 'was added'))\n */\nexport class FSWatcher extends EventEmitter {\n closed;\n options;\n _closers;\n _ignoredPaths;\n _throttled;\n _streams;\n _symlinkPaths;\n _watched;\n _pendingWrites;\n _pendingUnlinks;\n _readyCount;\n _emitReady;\n _closePromise;\n _userIgnored;\n _readyEmitted;\n _emitRaw;\n _boundRemove;\n _nodeFsHandler;\n // Not indenting methods for history sake; for now.\n constructor(_opts = {}) {\n super();\n this.closed = false;\n this._closers = new Map();\n this._ignoredPaths = new Set();\n this._throttled = new Map();\n this._streams = new Set();\n this._symlinkPaths = new Map();\n this._watched = new Map();\n this._pendingWrites = new Map();\n this._pendingUnlinks = new Map();\n this._readyCount = 0;\n this._readyEmitted = false;\n const awf = _opts.awaitWriteFinish;\n const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };\n const opts = {\n // Defaults\n persistent: true,\n ignoreInitial: false,\n ignorePermissionErrors: false,\n interval: 100,\n binaryInterval: 300,\n followSymlinks: true,\n usePolling: false,\n // useAsync: false,\n atomic: true, // NOTE: overwritten later (depends on usePolling)\n ..._opts,\n // Change format\n ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),\n awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,\n };\n // Always default to polling on IBM i because fs.watch() is not available on IBM i.\n if (isIBMi)\n opts.usePolling = true;\n // Editor atomic write normalization enabled by default with fs.watch\n if (opts.atomic === undefined)\n opts.atomic = !opts.usePolling;\n // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;\n // Global override. Useful for developers, who need to force polling for all\n // instances of chokidar, regardless of usage / dependency depth\n const envPoll = process.env.CHOKIDAR_USEPOLLING;\n if (envPoll !== undefined) {\n const envLower = envPoll.toLowerCase();\n if (envLower === 'false' || envLower === '0')\n opts.usePolling = false;\n else if (envLower === 'true' || envLower === '1')\n opts.usePolling = true;\n else\n opts.usePolling = !!envLower;\n }\n const envInterval = process.env.CHOKIDAR_INTERVAL;\n if (envInterval)\n opts.interval = Number.parseInt(envInterval, 10);\n // This is done to emit ready only once, but each 'add' will increase that?\n let readyCalls = 0;\n this._emitReady = () => {\n readyCalls++;\n if (readyCalls >= this._readyCount) {\n this._emitReady = EMPTY_FN;\n this._readyEmitted = true;\n // use process.nextTick to allow time for listener to be bound\n process.nextTick(() => this.emit(EV.READY));\n }\n };\n this._emitRaw = (...args) => this.emit(EV.RAW, ...args);\n this._boundRemove = this._remove.bind(this);\n this.options = opts;\n this._nodeFsHandler = new NodeFsHandler(this);\n // You’re frozen when your heart’s not open.\n Object.freeze(opts);\n }\n _addIgnoredPath(matcher) {\n if (isMatcherObject(matcher)) {\n // return early if we already have a deeply equal matcher object\n for (const ignored of this._ignoredPaths) {\n if (isMatcherObject(ignored) &&\n ignored.path === matcher.path &&\n ignored.recursive === matcher.recursive) {\n return;\n }\n }\n }\n this._ignoredPaths.add(matcher);\n }\n _removeIgnoredPath(matcher) {\n this._ignoredPaths.delete(matcher);\n // now find any matcher objects with the matcher as path\n if (typeof matcher === 'string') {\n for (const ignored of this._ignoredPaths) {\n // TODO (43081j): make this more efficient.\n // probably just make a `this._ignoredDirectories` or some\n // such thing.\n if (isMatcherObject(ignored) && ignored.path === matcher) {\n this._ignoredPaths.delete(ignored);\n }\n }\n }\n }\n // Public methods\n /**\n * Adds paths to be watched on an existing FSWatcher instance.\n * @param paths_ file or file list. Other arguments are unused\n */\n add(paths_, _origAdd, _internal) {\n const { cwd } = this.options;\n this.closed = false;\n this._closePromise = undefined;\n let paths = unifyPaths(paths_);\n if (cwd) {\n paths = paths.map((path) => {\n const absPath = getAbsolutePath(path, cwd);\n // Check `path` instead of `absPath` because the cwd portion can't be a glob\n return absPath;\n });\n }\n paths.forEach((path) => {\n this._removeIgnoredPath(path);\n });\n this._userIgnored = undefined;\n if (!this._readyCount)\n this._readyCount = 0;\n this._readyCount += paths.length;\n Promise.all(paths.map(async (path) => {\n const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);\n if (res)\n this._emitReady();\n return res;\n })).then((results) => {\n if (this.closed)\n return;\n results.forEach((item) => {\n if (item)\n this.add(sp.dirname(item), sp.basename(_origAdd || item));\n });\n });\n return this;\n }\n /**\n * Close watchers or start ignoring events from specified paths.\n */\n unwatch(paths_) {\n if (this.closed)\n return this;\n const paths = unifyPaths(paths_);\n const { cwd } = this.options;\n paths.forEach((path) => {\n // convert to absolute path unless relative path already matches\n if (!sp.isAbsolute(path) && !this._closers.has(path)) {\n if (cwd)\n path = sp.join(cwd, path);\n path = sp.resolve(path);\n }\n this._closePath(path);\n this._addIgnoredPath(path);\n if (this._watched.has(path)) {\n this._addIgnoredPath({\n path,\n recursive: true,\n });\n }\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = undefined;\n });\n return this;\n }\n /**\n * Close watchers and remove all listeners from watched paths.\n */\n close() {\n if (this._closePromise) {\n return this._closePromise;\n }\n this.closed = true;\n // Memory management.\n this.removeAllListeners();\n const closers = [];\n this._closers.forEach((closerList) => closerList.forEach((closer) => {\n const promise = closer();\n if (promise instanceof Promise)\n closers.push(promise);\n }));\n this._streams.forEach((stream) => stream.destroy());\n this._userIgnored = undefined;\n this._readyCount = 0;\n this._readyEmitted = false;\n this._watched.forEach((dirent) => dirent.dispose());\n this._closers.clear();\n this._watched.clear();\n this._streams.clear();\n this._symlinkPaths.clear();\n this._throttled.clear();\n this._closePromise = closers.length\n ? Promise.all(closers).then(() => undefined)\n : Promise.resolve();\n return this._closePromise;\n }\n /**\n * Expose list of watched paths\n * @returns for chaining\n */\n getWatched() {\n const watchList = {};\n this._watched.forEach((entry, dir) => {\n const key = this.options.cwd ? sp.relative(this.options.cwd, dir) : dir;\n const index = key || ONE_DOT;\n watchList[index] = entry.getChildren().sort();\n });\n return watchList;\n }\n emitWithAll(event, args) {\n this.emit(event, ...args);\n if (event !== EV.ERROR)\n this.emit(EV.ALL, event, ...args);\n }\n // Common helpers\n // --------------\n /**\n * Normalize and emit events.\n * Calling _emit DOES NOT MEAN emit() would be called!\n * @param event Type of event\n * @param path File or directory path\n * @param stats arguments to be passed with event\n * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n async _emit(event, path, stats) {\n if (this.closed)\n return;\n const opts = this.options;\n if (isWindows)\n path = sp.normalize(path);\n if (opts.cwd)\n path = sp.relative(opts.cwd, path);\n const args = [path];\n if (stats != null)\n args.push(stats);\n const awf = opts.awaitWriteFinish;\n let pw;\n if (awf && (pw = this._pendingWrites.get(path))) {\n pw.lastChange = new Date();\n return this;\n }\n if (opts.atomic) {\n if (event === EV.UNLINK) {\n this._pendingUnlinks.set(path, [event, ...args]);\n setTimeout(() => {\n this._pendingUnlinks.forEach((entry, path) => {\n this.emit(...entry);\n this.emit(EV.ALL, ...entry);\n this._pendingUnlinks.delete(path);\n });\n }, typeof opts.atomic === 'number' ? opts.atomic : 100);\n return this;\n }\n if (event === EV.ADD && this._pendingUnlinks.has(path)) {\n event = EV.CHANGE;\n this._pendingUnlinks.delete(path);\n }\n }\n if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) {\n const awfEmit = (err, stats) => {\n if (err) {\n event = EV.ERROR;\n args[0] = err;\n this.emitWithAll(event, args);\n }\n else if (stats) {\n // if stats doesn't exist the file must have been deleted\n if (args.length > 1) {\n args[1] = stats;\n }\n else {\n args.push(stats);\n }\n this.emitWithAll(event, args);\n }\n };\n this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);\n return this;\n }\n if (event === EV.CHANGE) {\n const isThrottled = !this._throttle(EV.CHANGE, path, 50);\n if (isThrottled)\n return this;\n }\n if (opts.alwaysStat &&\n stats === undefined &&\n (event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)) {\n const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;\n let stats;\n try {\n stats = await stat(fullPath);\n }\n catch (err) {\n // do nothing\n }\n // Suppress event when fs_stat fails, to avoid sending undefined 'stat'\n if (!stats || this.closed)\n return;\n args.push(stats);\n }\n this.emitWithAll(event, args);\n return this;\n }\n /**\n * Common handler for errors\n * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n _handleError(error) {\n const code = error && error.code;\n if (error &&\n code !== 'ENOENT' &&\n code !== 'ENOTDIR' &&\n (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {\n this.emit(EV.ERROR, error);\n }\n return error || this.closed;\n }\n /**\n * Helper utility for throttling\n * @param actionType type being throttled\n * @param path being acted upon\n * @param timeout duration of time to suppress duplicate actions\n * @returns tracking object or false if action should be suppressed\n */\n _throttle(actionType, path, timeout) {\n if (!this._throttled.has(actionType)) {\n this._throttled.set(actionType, new Map());\n }\n const action = this._throttled.get(actionType);\n if (!action)\n throw new Error('invalid throttle');\n const actionPath = action.get(path);\n if (actionPath) {\n actionPath.count++;\n return false;\n }\n // eslint-disable-next-line prefer-const\n let timeoutObject;\n const clear = () => {\n const item = action.get(path);\n const count = item ? item.count : 0;\n action.delete(path);\n clearTimeout(timeoutObject);\n if (item)\n clearTimeout(item.timeoutObject);\n return count;\n };\n timeoutObject = setTimeout(clear, timeout);\n const thr = { timeoutObject, clear, count: 0 };\n action.set(path, thr);\n return thr;\n }\n _incrReadyCount() {\n return this._readyCount++;\n }\n /**\n * Awaits write operation to finish.\n * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.\n * @param path being acted upon\n * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished\n * @param event\n * @param awfEmit Callback to be called when ready for event to be emitted.\n */\n _awaitWriteFinish(path, threshold, event, awfEmit) {\n const awf = this.options.awaitWriteFinish;\n if (typeof awf !== 'object')\n return;\n const pollInterval = awf.pollInterval;\n let timeoutHandler;\n let fullPath = path;\n if (this.options.cwd && !sp.isAbsolute(path)) {\n fullPath = sp.join(this.options.cwd, path);\n }\n const now = new Date();\n const writes = this._pendingWrites;\n function awaitWriteFinishFn(prevStat) {\n statcb(fullPath, (err, curStat) => {\n if (err || !writes.has(path)) {\n if (err && err.code !== 'ENOENT')\n awfEmit(err);\n return;\n }\n const now = Number(new Date());\n if (prevStat && curStat.size !== prevStat.size) {\n writes.get(path).lastChange = now;\n }\n const pw = writes.get(path);\n const df = now - pw.lastChange;\n if (df >= threshold) {\n writes.delete(path);\n awfEmit(undefined, curStat);\n }\n else {\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);\n }\n });\n }\n if (!writes.has(path)) {\n writes.set(path, {\n lastChange: now,\n cancelWait: () => {\n writes.delete(path);\n clearTimeout(timeoutHandler);\n return event;\n },\n });\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);\n }\n }\n /**\n * Determines whether user has asked to ignore this path.\n */\n _isIgnored(path, stats) {\n if (this.options.atomic && DOT_RE.test(path))\n return true;\n if (!this._userIgnored) {\n const { cwd } = this.options;\n const ign = this.options.ignored;\n const ignored = (ign || []).map(normalizeIgnored(cwd));\n const ignoredPaths = [...this._ignoredPaths];\n const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];\n this._userIgnored = anymatch(list, undefined);\n }\n return this._userIgnored(path, stats);\n }\n _isntIgnored(path, stat) {\n return !this._isIgnored(path, stat);\n }\n /**\n * Provides a set of common helpers and properties relating to symlink handling.\n * @param path file or directory pattern being watched\n */\n _getWatchHelpers(path) {\n return new WatchHelper(path, this.options.followSymlinks, this);\n }\n // Directory helpers\n // -----------------\n /**\n * Provides directory tracking objects\n * @param directory path of the directory\n */\n _getWatchedDir(directory) {\n const dir = sp.resolve(directory);\n if (!this._watched.has(dir))\n this._watched.set(dir, new DirEntry(dir, this._boundRemove));\n return this._watched.get(dir);\n }\n // File helpers\n // ------------\n /**\n * Check for read permissions: https://stackoverflow.com/a/11781404/1358405\n */\n _hasReadPermissions(stats) {\n if (this.options.ignorePermissionErrors)\n return true;\n return Boolean(Number(stats.mode) & 0o400);\n }\n /**\n * Handles emitting unlink events for\n * files and directories, and via recursion, for\n * files and directories within directories that are unlinked\n * @param directory within which the following item is located\n * @param item base path of item/directory\n */\n _remove(directory, item, isDirectory) {\n // if what is being deleted is a directory, get that directory's paths\n // for recursive deleting and cleaning of watched object\n // if it is not a directory, nestedDirectoryChildren will be empty array\n const path = sp.join(directory, item);\n const fullPath = sp.resolve(path);\n isDirectory =\n isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);\n // prevent duplicate handling in case of arriving here nearly simultaneously\n // via multiple paths (such as _handleFile and _handleDir)\n if (!this._throttle('remove', path, 100))\n return;\n // if the only watched file is removed, watch for its return\n if (!isDirectory && this._watched.size === 1) {\n this.add(directory, item, true);\n }\n // This will create a new entry in the watched object in either case\n // so we got to do the directory check beforehand\n const wp = this._getWatchedDir(path);\n const nestedDirectoryChildren = wp.getChildren();\n // Recursively remove children directories / files.\n nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));\n // Check if item was on the watched list and remove it\n const parent = this._getWatchedDir(directory);\n const wasTracked = parent.has(item);\n parent.remove(item);\n // Fixes issue #1042 -> Relative paths were detected and added as symlinks\n // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),\n // but never removed from the map in case the path was deleted.\n // This leads to an incorrect state if the path was recreated:\n // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553\n if (this._symlinkPaths.has(fullPath)) {\n this._symlinkPaths.delete(fullPath);\n }\n // If we wait for this file to be fully written, cancel the wait.\n let relPath = path;\n if (this.options.cwd)\n relPath = sp.relative(this.options.cwd, path);\n if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {\n const event = this._pendingWrites.get(relPath).cancelWait();\n if (event === EV.ADD)\n return;\n }\n // The Entry will either be a directory that just got removed\n // or a bogus entry to a file, in either case we have to remove it\n this._watched.delete(path);\n this._watched.delete(fullPath);\n const eventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK;\n if (wasTracked && !this._isIgnored(path))\n this._emit(eventName, path);\n // Avoid conflicts if we later create another file with the same name\n this._closePath(path);\n }\n /**\n * Closes all watchers for a path\n */\n _closePath(path) {\n this._closeFile(path);\n const dir = sp.dirname(path);\n this._getWatchedDir(dir).remove(sp.basename(path));\n }\n /**\n * Closes only file-specific watchers\n */\n _closeFile(path) {\n const closers = this._closers.get(path);\n if (!closers)\n return;\n closers.forEach((closer) => closer());\n this._closers.delete(path);\n }\n _addPathCloser(path, closer) {\n if (!closer)\n return;\n let list = this._closers.get(path);\n if (!list) {\n list = [];\n this._closers.set(path, list);\n }\n list.push(closer);\n }\n _readdirp(root, opts) {\n if (this.closed)\n return;\n const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };\n let stream = readdirp(root, options);\n this._streams.add(stream);\n stream.once(STR_CLOSE, () => {\n stream = undefined;\n });\n stream.once(STR_END, () => {\n if (stream) {\n this._streams.delete(stream);\n stream = undefined;\n }\n });\n return stream;\n }\n}\n/**\n * Instantiates watcher with paths to be tracked.\n * @param paths file / directory paths\n * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others\n * @returns an instance of FSWatcher for chaining.\n * @example\n * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });\n * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })\n */\nexport function watch(paths, options = {}) {\n const watcher = new FSWatcher(options);\n watcher.add(paths);\n return watcher;\n}\nexport default { watch: watch, FSWatcher: FSWatcher };\n","import { lstat, readdir, realpath, stat } from 'node:fs/promises';\nimport { join as pjoin, relative as prelative, resolve as presolve, sep as psep } from 'node:path';\nimport { Readable } from 'node:stream';\nexport const EntryTypes = {\n FILE_TYPE: 'files',\n DIR_TYPE: 'directories',\n FILE_DIR_TYPE: 'files_directories',\n EVERYTHING_TYPE: 'all',\n};\nconst defaultOptions = {\n root: '.',\n fileFilter: (_entryInfo) => true,\n directoryFilter: (_entryInfo) => true,\n type: EntryTypes.FILE_TYPE,\n lstat: false,\n depth: 2147483648,\n alwaysStat: false,\n highWaterMark: 4096,\n};\nObject.freeze(defaultOptions);\nconst RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';\nconst NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);\nconst ALL_TYPES = [\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n];\nconst DIR_TYPES = new Set([\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n]);\nconst FILE_TYPES = new Set([\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n]);\nconst isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);\nconst wantBigintFsStats = process.platform === 'win32';\nconst emptyFn = (_entryInfo) => true;\nconst normalizeFilter = (filter) => {\n if (filter === undefined)\n return emptyFn;\n if (typeof filter === 'function')\n return filter;\n if (typeof filter === 'string') {\n const fl = filter.trim();\n return (entry) => entry.basename === fl;\n }\n if (Array.isArray(filter)) {\n const trItems = filter.map((item) => item.trim());\n return (entry) => trItems.some((f) => entry.basename === f);\n }\n return emptyFn;\n};\n/** Readable readdir stream, emitting new files as they're being listed. */\nexport class ReaddirpStream extends Readable {\n parents;\n reading;\n parent;\n _stat;\n _maxDepth;\n _wantsDir;\n _wantsFile;\n _wantsEverything;\n _root;\n _isDirent;\n _statsProp;\n _rdOptions;\n _fileFilter;\n _directoryFilter;\n constructor(options = {}) {\n super({\n objectMode: true,\n autoDestroy: true,\n highWaterMark: options.highWaterMark,\n });\n const opts = { ...defaultOptions, ...options };\n const { root, type } = opts;\n this._fileFilter = normalizeFilter(opts.fileFilter);\n this._directoryFilter = normalizeFilter(opts.directoryFilter);\n const statMethod = opts.lstat ? lstat : stat;\n // Use bigint stats if it's windows and stat() supports options (node 10+).\n if (wantBigintFsStats) {\n this._stat = (path) => statMethod(path, { bigint: true });\n }\n else {\n this._stat = statMethod;\n }\n this._maxDepth =\n opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;\n this._wantsDir = type ? DIR_TYPES.has(type) : false;\n this._wantsFile = type ? FILE_TYPES.has(type) : false;\n this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;\n this._root = presolve(root);\n this._isDirent = !opts.alwaysStat;\n this._statsProp = this._isDirent ? 'dirent' : 'stats';\n this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };\n // Launch stream with one parent, the root dir.\n this.parents = [this._exploreDir(root, 1)];\n this.reading = false;\n this.parent = undefined;\n }\n async _read(batch) {\n if (this.reading)\n return;\n this.reading = true;\n try {\n while (!this.destroyed && batch > 0) {\n const par = this.parent;\n const fil = par && par.files;\n if (fil && fil.length > 0) {\n const { path, depth } = par;\n const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));\n const awaited = await Promise.all(slice);\n for (const entry of awaited) {\n if (!entry)\n continue;\n if (this.destroyed)\n return;\n const entryType = await this._getEntryType(entry);\n if (entryType === 'directory' && this._directoryFilter(entry)) {\n if (depth <= this._maxDepth) {\n this.parents.push(this._exploreDir(entry.fullPath, depth + 1));\n }\n if (this._wantsDir) {\n this.push(entry);\n batch--;\n }\n }\n else if ((entryType === 'file' || this._includeAsFile(entry)) &&\n this._fileFilter(entry)) {\n if (this._wantsFile) {\n this.push(entry);\n batch--;\n }\n }\n }\n }\n else {\n const parent = this.parents.pop();\n if (!parent) {\n this.push(null);\n break;\n }\n this.parent = await parent;\n if (this.destroyed)\n return;\n }\n }\n }\n catch (error) {\n this.destroy(error);\n }\n finally {\n this.reading = false;\n }\n }\n async _exploreDir(path, depth) {\n let files;\n try {\n files = await readdir(path, this._rdOptions);\n }\n catch (error) {\n this._onError(error);\n }\n return { files, depth, path };\n }\n async _formatEntry(dirent, path) {\n let entry;\n const basename = this._isDirent ? dirent.name : dirent;\n try {\n const fullPath = presolve(pjoin(path, basename));\n entry = { path: prelative(this._root, fullPath), fullPath, basename };\n entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);\n }\n catch (err) {\n this._onError(err);\n return;\n }\n return entry;\n }\n _onError(err) {\n if (isNormalFlowError(err) && !this.destroyed) {\n this.emit('warn', err);\n }\n else {\n this.destroy(err);\n }\n }\n async _getEntryType(entry) {\n // entry may be undefined, because a warning or an error were emitted\n // and the statsProp is undefined\n if (!entry && this._statsProp in entry) {\n return '';\n }\n const stats = entry[this._statsProp];\n if (stats.isFile())\n return 'file';\n if (stats.isDirectory())\n return 'directory';\n if (stats && stats.isSymbolicLink()) {\n const full = entry.fullPath;\n try {\n const entryRealPath = await realpath(full);\n const entryRealPathStats = await lstat(entryRealPath);\n if (entryRealPathStats.isFile()) {\n return 'file';\n }\n if (entryRealPathStats.isDirectory()) {\n const len = entryRealPath.length;\n if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {\n const recursiveError = new Error(`Circular symlink detected: \"${full}\" points to \"${entryRealPath}\"`);\n // @ts-ignore\n recursiveError.code = RECURSIVE_ERROR_CODE;\n return this._onError(recursiveError);\n }\n return 'directory';\n }\n }\n catch (error) {\n this._onError(error);\n return '';\n }\n }\n }\n _includeAsFile(entry) {\n const stats = entry && entry[this._statsProp];\n return stats && this._wantsEverything && !stats.isDirectory();\n }\n}\n/**\n * Streaming version: Reads all files and directories in given root recursively.\n * Consumes ~constant small amount of RAM.\n * @param root Root directory\n * @param options Options to specify root (start directory), filters and recursion depth\n */\nexport function readdirp(root, options = {}) {\n // @ts-ignore\n let type = options.entryType || options.type;\n if (type === 'both')\n type = EntryTypes.FILE_DIR_TYPE; // backwards-compatibility\n if (type)\n options.type = type;\n if (!root) {\n throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');\n }\n else if (typeof root !== 'string') {\n throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');\n }\n else if (type && !ALL_TYPES.includes(type)) {\n throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);\n }\n options.root = root;\n return new ReaddirpStream(options);\n}\n/**\n * Promise version: Reads all files and directories in given root recursively.\n * Compared to streaming version, will consume a lot of RAM e.g. when 1 million files are listed.\n * @returns array of paths and their entry infos\n */\nexport function readdirpPromise(root, options = {}) {\n return new Promise((resolve, reject) => {\n const files = [];\n readdirp(root, options)\n .on('data', (entry) => files.push(entry))\n .on('end', () => resolve(files))\n .on('error', (error) => reject(error));\n });\n}\nexport default readdirp;\n","import { watch as fs_watch, unwatchFile, watchFile } from 'node:fs';\nimport { realpath as fsrealpath, lstat, open, stat } from 'node:fs/promises';\nimport { type as osType } from 'node:os';\nimport * as sp from 'node:path';\nexport const STR_DATA = 'data';\nexport const STR_END = 'end';\nexport const STR_CLOSE = 'close';\nexport const EMPTY_FN = () => { };\nexport const IDENTITY_FN = (val) => val;\nconst pl = process.platform;\nexport const isWindows = pl === 'win32';\nexport const isMacos = pl === 'darwin';\nexport const isLinux = pl === 'linux';\nexport const isFreeBSD = pl === 'freebsd';\nexport const isIBMi = osType() === 'OS400';\nexport const EVENTS = {\n ALL: 'all',\n READY: 'ready',\n ADD: 'add',\n CHANGE: 'change',\n ADD_DIR: 'addDir',\n UNLINK: 'unlink',\n UNLINK_DIR: 'unlinkDir',\n RAW: 'raw',\n ERROR: 'error',\n};\nconst EV = EVENTS;\nconst THROTTLE_MODE_WATCH = 'watch';\nconst statMethods = { lstat, stat };\nconst KEY_LISTENERS = 'listeners';\nconst KEY_ERR = 'errHandlers';\nconst KEY_RAW = 'rawEmitters';\nconst HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];\n// prettier-ignore\nconst binaryExtensions = new Set([\n '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',\n 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',\n 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',\n 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',\n 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',\n 'dtshd', 'dvb', 'dwg', 'dxf',\n 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',\n 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',\n 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',\n 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',\n 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',\n 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',\n 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',\n 'mobi', 'mov', 'movie', 'mp3',\n 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',\n 'nef', 'npx', 'numbers', 'nupkg',\n 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',\n 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',\n 'potx', 'ppa', 'ppam',\n 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',\n 'qt',\n 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',\n 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',\n 'stl', 'suo', 'sub', 'swf',\n 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',\n 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',\n 'viv', 'vob',\n 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',\n 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',\n 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',\n 'xmind', 'xpi', 'xpm', 'xwd', 'xz',\n 'z', 'zip', 'zipx',\n]);\nconst isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());\n// TODO: emit errors properly. Example: EMFILE on Macos.\nconst foreach = (val, fn) => {\n if (val instanceof Set) {\n val.forEach(fn);\n }\n else {\n fn(val);\n }\n};\nconst addAndConvert = (main, prop, item) => {\n let container = main[prop];\n if (!(container instanceof Set)) {\n main[prop] = container = new Set([container]);\n }\n container.add(item);\n};\nconst clearItem = (cont) => (key) => {\n const set = cont[key];\n if (set instanceof Set) {\n set.clear();\n }\n else {\n delete cont[key];\n }\n};\nconst delFromSet = (main, prop, item) => {\n const container = main[prop];\n if (container instanceof Set) {\n container.delete(item);\n }\n else if (container === item) {\n delete main[prop];\n }\n};\nconst isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);\nconst FsWatchInstances = new Map();\n/**\n * Instantiates the fs_watch interface\n * @param path to be watched\n * @param options to be passed to fs_watch\n * @param listener main event handler\n * @param errHandler emits info about errors\n * @param emitRaw emits raw event data\n * @returns {NativeFsWatcher}\n */\nfunction createFsWatchInstance(path, options, listener, errHandler, emitRaw) {\n const handleEvent = (rawEvent, evPath) => {\n listener(path);\n emitRaw(rawEvent, evPath, { watchedPath: path });\n // emit based on events occurring for files from a directory's watcher in\n // case the file's watcher misses it (and rely on throttling to de-dupe)\n if (evPath && path !== evPath) {\n fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));\n }\n };\n try {\n return fs_watch(path, {\n persistent: options.persistent,\n }, handleEvent);\n }\n catch (error) {\n errHandler(error);\n return undefined;\n }\n}\n/**\n * Helper for passing fs_watch event data to a collection of listeners\n * @param fullPath absolute path bound to fs_watch instance\n */\nconst fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {\n const cont = FsWatchInstances.get(fullPath);\n if (!cont)\n return;\n foreach(cont[listenerType], (listener) => {\n listener(val1, val2, val3);\n });\n};\n/**\n * Instantiates the fs_watch interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path\n * @param fullPath absolute path\n * @param options to be passed to fs_watch\n * @param handlers container for event listener functions\n */\nconst setFsWatchListener = (path, fullPath, options, handlers) => {\n const { listener, errHandler, rawEmitter } = handlers;\n let cont = FsWatchInstances.get(fullPath);\n let watcher;\n if (!options.persistent) {\n watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);\n if (!watcher)\n return;\n return watcher.close.bind(watcher);\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_ERR, errHandler);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here\n fsWatchBroadcast.bind(null, fullPath, KEY_RAW));\n if (!watcher)\n return;\n watcher.on(EV.ERROR, async (error) => {\n const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);\n if (cont)\n cont.watcherUnusable = true; // documented since Node 10.4.1\n // Workaround for https://github.com/joyent/node/issues/4337\n if (isWindows && error.code === 'EPERM') {\n try {\n const fd = await open(path, 'r');\n await fd.close();\n broadcastErr(error);\n }\n catch (err) {\n // do nothing\n }\n }\n else {\n broadcastErr(error);\n }\n });\n cont = {\n listeners: listener,\n errHandlers: errHandler,\n rawEmitters: rawEmitter,\n watcher,\n };\n FsWatchInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // removes this instance's listeners and closes the underlying fs_watch\n // instance if there are no more listeners left\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_ERR, errHandler);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n // Check to protect against issue gh-730.\n // if (cont.watcherUnusable) {\n cont.watcher.close();\n // }\n FsWatchInstances.delete(fullPath);\n HANDLER_KEYS.forEach(clearItem(cont));\n // @ts-ignore\n cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n// fs_watchFile helpers\n// object to hold per-process fs_watchFile instances\n// (may be shared across chokidar FSWatcher instances)\nconst FsWatchFileInstances = new Map();\n/**\n * Instantiates the fs_watchFile interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path to be watched\n * @param fullPath absolute path\n * @param options options to be passed to fs_watchFile\n * @param handlers container for event listener functions\n * @returns closer\n */\nconst setFsWatchFileListener = (path, fullPath, options, handlers) => {\n const { listener, rawEmitter } = handlers;\n let cont = FsWatchFileInstances.get(fullPath);\n // let listeners = new Set();\n // let rawEmitters = new Set();\n const copts = cont && cont.options;\n if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {\n // \"Upgrade\" the watcher to persistence or a quicker interval.\n // This creates some unlikely edge case issues if the user mixes\n // settings in a very weird way, but solving for those cases\n // doesn't seem worthwhile for the added complexity.\n // listeners = cont.listeners;\n // rawEmitters = cont.rawEmitters;\n unwatchFile(fullPath);\n cont = undefined;\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n // TODO\n // listeners.add(listener);\n // rawEmitters.add(rawEmitter);\n cont = {\n listeners: listener,\n rawEmitters: rawEmitter,\n options,\n watcher: watchFile(fullPath, options, (curr, prev) => {\n foreach(cont.rawEmitters, (rawEmitter) => {\n rawEmitter(EV.CHANGE, fullPath, { curr, prev });\n });\n const currmtime = curr.mtimeMs;\n if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {\n foreach(cont.listeners, (listener) => listener(path, curr));\n }\n }),\n };\n FsWatchFileInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // Removes this instance's listeners and closes the underlying fs_watchFile\n // instance if there are no more listeners left.\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n FsWatchFileInstances.delete(fullPath);\n unwatchFile(fullPath);\n cont.options = cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n/**\n * @mixin\n */\nexport class NodeFsHandler {\n fsw;\n _boundHandleError;\n constructor(fsW) {\n this.fsw = fsW;\n this._boundHandleError = (error) => fsW._handleError(error);\n }\n /**\n * Watch file for changes with fs_watchFile or fs_watch.\n * @param path to file or dir\n * @param listener on fs change\n * @returns closer for the watcher instance\n */\n _watchWithNodeFs(path, listener) {\n const opts = this.fsw.options;\n const directory = sp.dirname(path);\n const basename = sp.basename(path);\n const parent = this.fsw._getWatchedDir(directory);\n parent.add(basename);\n const absolutePath = sp.resolve(path);\n const options = {\n persistent: opts.persistent,\n };\n if (!listener)\n listener = EMPTY_FN;\n let closer;\n if (opts.usePolling) {\n const enableBin = opts.interval !== opts.binaryInterval;\n options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;\n closer = setFsWatchFileListener(path, absolutePath, options, {\n listener,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n else {\n closer = setFsWatchListener(path, absolutePath, options, {\n listener,\n errHandler: this._boundHandleError,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n return closer;\n }\n /**\n * Watch a file and emit add event if warranted.\n * @returns closer for the watcher instance\n */\n _handleFile(file, stats, initialAdd) {\n if (this.fsw.closed) {\n return;\n }\n const dirname = sp.dirname(file);\n const basename = sp.basename(file);\n const parent = this.fsw._getWatchedDir(dirname);\n // stats is always present\n let prevStats = stats;\n // if the file is already being watched, do nothing\n if (parent.has(basename))\n return;\n const listener = async (path, newStats) => {\n if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))\n return;\n if (!newStats || newStats.mtimeMs === 0) {\n try {\n const newStats = await stat(file);\n if (this.fsw.closed)\n return;\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {\n this.fsw._closeFile(path);\n prevStats = newStats;\n const closer = this._watchWithNodeFs(file, listener);\n if (closer)\n this.fsw._addPathCloser(path, closer);\n }\n else {\n prevStats = newStats;\n }\n }\n catch (error) {\n // Fix issues where mtime is null but file is still present\n this.fsw._remove(dirname, basename);\n }\n // add is about to be emitted if file not already tracked in parent\n }\n else if (parent.has(basename)) {\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n prevStats = newStats;\n }\n };\n // kick off the watcher\n const closer = this._watchWithNodeFs(file, listener);\n // emit an add event if we're supposed to\n if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {\n if (!this.fsw._throttle(EV.ADD, file, 0))\n return;\n this.fsw._emit(EV.ADD, file, stats);\n }\n return closer;\n }\n /**\n * Handle symlinks encountered while reading a dir.\n * @param entry returned by readdirp\n * @param directory path of dir being read\n * @param path of this item\n * @param item basename of this item\n * @returns true if no more processing is needed for this entry.\n */\n async _handleSymlink(entry, directory, path, item) {\n if (this.fsw.closed) {\n return;\n }\n const full = entry.fullPath;\n const dir = this.fsw._getWatchedDir(directory);\n if (!this.fsw.options.followSymlinks) {\n // watch symlink directly (don't follow) and detect changes\n this.fsw._incrReadyCount();\n let linkPath;\n try {\n linkPath = await fsrealpath(path);\n }\n catch (e) {\n this.fsw._emitReady();\n return true;\n }\n if (this.fsw.closed)\n return;\n if (dir.has(item)) {\n if (this.fsw._symlinkPaths.get(full) !== linkPath) {\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.CHANGE, path, entry.stats);\n }\n }\n else {\n dir.add(item);\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.ADD, path, entry.stats);\n }\n this.fsw._emitReady();\n return true;\n }\n // don't follow the same symlink more than once\n if (this.fsw._symlinkPaths.has(full)) {\n return true;\n }\n this.fsw._symlinkPaths.set(full, true);\n }\n _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {\n // Normalize the directory name on Windows\n directory = sp.join(directory, '');\n const throttleKey = target ? `${directory}:${target}` : directory;\n throttler = this.fsw._throttle('readdir', throttleKey, 1000);\n if (!throttler)\n return;\n const previous = this.fsw._getWatchedDir(wh.path);\n const current = new Set();\n let stream = this.fsw._readdirp(directory, {\n fileFilter: (entry) => wh.filterPath(entry),\n directoryFilter: (entry) => wh.filterDir(entry),\n });\n if (!stream)\n return;\n stream\n .on(STR_DATA, async (entry) => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const item = entry.path;\n let path = sp.join(directory, item);\n current.add(item);\n if (entry.stats.isSymbolicLink() &&\n (await this._handleSymlink(entry, directory, path, item))) {\n return;\n }\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n // Files that present in current directory snapshot\n // but absent in previous are added to watch list and\n // emit `add` event.\n if (item === target || (!target && !previous.has(item))) {\n this.fsw._incrReadyCount();\n // ensure relativeness of path is preserved in case of watcher reuse\n path = sp.join(dir, sp.relative(dir, path));\n this._addToNodeFs(path, initialAdd, wh, depth + 1);\n }\n })\n .on(EV.ERROR, this._boundHandleError);\n return new Promise((resolve, reject) => {\n if (!stream)\n return reject();\n stream.once(STR_END, () => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const wasThrottled = throttler ? throttler.clear() : false;\n resolve(undefined);\n // Files that absent in current directory snapshot\n // but present in previous emit `remove` event\n // and are removed from @watched[directory].\n previous\n .getChildren()\n .filter((item) => {\n return item !== directory && !current.has(item);\n })\n .forEach((item) => {\n this.fsw._remove(directory, item);\n });\n stream = undefined;\n // one more time for any missed in case changes came in extremely quickly\n if (wasThrottled)\n this._handleRead(directory, false, wh, target, dir, depth, throttler);\n });\n });\n }\n /**\n * Read directory to add / remove files from `@watched` list and re-read it on change.\n * @param dir fs path\n * @param stats\n * @param initialAdd\n * @param depth relative to user-supplied path\n * @param target child path targeted for watch\n * @param wh Common watch helpers for this path\n * @param realpath\n * @returns closer for the watcher instance.\n */\n async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {\n const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));\n const tracked = parentDir.has(sp.basename(dir));\n if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {\n this.fsw._emit(EV.ADD_DIR, dir, stats);\n }\n // ensure dir is tracked (harmless if redundant)\n parentDir.add(sp.basename(dir));\n this.fsw._getWatchedDir(dir);\n let throttler;\n let closer;\n const oDepth = this.fsw.options.depth;\n if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {\n if (!target) {\n await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);\n if (this.fsw.closed)\n return;\n }\n closer = this._watchWithNodeFs(dir, (dirPath, stats) => {\n // if current directory is removed, do nothing\n if (stats && stats.mtimeMs === 0)\n return;\n this._handleRead(dirPath, false, wh, target, dir, depth, throttler);\n });\n }\n return closer;\n }\n /**\n * Handle added file, directory, or glob pattern.\n * Delegates call to _handleFile / _handleDir after checks.\n * @param path to file or ir\n * @param initialAdd was the file added at watch instantiation?\n * @param priorWh depth relative to user-supplied path\n * @param depth Child path actually targeted for watch\n * @param target Child path actually targeted for watch\n */\n async _addToNodeFs(path, initialAdd, priorWh, depth, target) {\n const ready = this.fsw._emitReady;\n if (this.fsw._isIgnored(path) || this.fsw.closed) {\n ready();\n return false;\n }\n const wh = this.fsw._getWatchHelpers(path);\n if (priorWh) {\n wh.filterPath = (entry) => priorWh.filterPath(entry);\n wh.filterDir = (entry) => priorWh.filterDir(entry);\n }\n // evaluate what is at the path we're being asked to watch\n try {\n const stats = await statMethods[wh.statMethod](wh.watchPath);\n if (this.fsw.closed)\n return;\n if (this.fsw._isIgnored(wh.watchPath, stats)) {\n ready();\n return false;\n }\n const follow = this.fsw.options.followSymlinks;\n let closer;\n if (stats.isDirectory()) {\n const absPath = sp.resolve(path);\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (absPath !== targetPath && targetPath !== undefined) {\n this.fsw._symlinkPaths.set(absPath, targetPath);\n }\n }\n else if (stats.isSymbolicLink()) {\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n const parent = sp.dirname(wh.watchPath);\n this.fsw._getWatchedDir(parent).add(wh.watchPath);\n this.fsw._emit(EV.ADD, wh.watchPath, stats);\n closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (targetPath !== undefined) {\n this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);\n }\n }\n else {\n closer = this._handleFile(wh.watchPath, stats, initialAdd);\n }\n ready();\n if (closer)\n this.fsw._addPathCloser(path, closer);\n return false;\n }\n catch (error) {\n if (this.fsw._handleError(error)) {\n ready();\n return path;\n }\n }\n }\n}\n","import chokidar, { FSWatcher } from \"chokidar\";\nimport * as path from \"path\";\n\nimport type { CodebaseIndexConfig } from \"../config/schema.js\";\nimport { createIgnoreFilter, shouldIncludeFile } from \"../utils/files.js\";\nimport { hasFilteredPathSegment } from \"../utils/paths.js\";\n\nexport type FileChangeType = \"add\" | \"change\" | \"unlink\";\n\nexport interface FileChange {\n type: FileChangeType;\n path: string;\n}\n\nexport type ChangeHandler = (changes: FileChange[]) => Promise<void>;\n\nexport class FileWatcher {\n private watcher: FSWatcher | null = null;\n private projectRoot: string;\n private config: CodebaseIndexConfig;\n private pendingChanges: Map<string, FileChangeType> = new Map();\n private debounceTimer: NodeJS.Timeout | null = null;\n private debounceMs = 1000;\n private onChanges: ChangeHandler | null = null;\n\n constructor(projectRoot: string, config: CodebaseIndexConfig) {\n this.projectRoot = projectRoot;\n this.config = config;\n }\n\n start(handler: ChangeHandler): void {\n if (this.watcher) {\n return;\n }\n\n this.onChanges = handler;\n const ignoreFilter = createIgnoreFilter(this.projectRoot);\n\n this.watcher = chokidar.watch(this.projectRoot, {\n ignored: (filePath: string) => {\n const relativePath = path.relative(this.projectRoot, filePath);\n if (!relativePath) return false;\n\n if (hasFilteredPathSegment(relativePath, path.sep)) {\n return true;\n }\n\n if (ignoreFilter.ignores(relativePath)) {\n return true;\n }\n\n return false;\n },\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 300,\n pollInterval: 100,\n },\n });\n\n this.watcher.on(\"add\", (filePath) => this.handleChange(\"add\", filePath));\n this.watcher.on(\"change\", (filePath) => this.handleChange(\"change\", filePath));\n this.watcher.on(\"unlink\", (filePath) => this.handleChange(\"unlink\", filePath));\n }\n\n private handleChange(type: FileChangeType, filePath: string): void {\n const includePatterns = [...this.config.include, ...(this.config.additionalInclude ?? [])];\n if (\n !shouldIncludeFile(\n filePath,\n this.projectRoot,\n includePatterns,\n this.config.exclude,\n createIgnoreFilter(this.projectRoot)\n )\n ) {\n return;\n }\n\n this.pendingChanges.set(filePath, type);\n this.scheduleFlush();\n }\n\n private scheduleFlush(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n }\n\n this.debounceTimer = setTimeout(() => {\n this.flush();\n }, this.debounceMs);\n }\n\n private async flush(): Promise<void> {\n if (this.pendingChanges.size === 0 || !this.onChanges) {\n return;\n }\n\n const changes: FileChange[] = Array.from(this.pendingChanges.entries()).map(\n ([path, type]) => ({ path, type })\n );\n\n this.pendingChanges.clear();\n\n try {\n await this.onChanges(changes);\n } catch (error) {\n console.error(\"Error handling file changes:\", error);\n }\n }\n\n stop(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n\n if (this.watcher) {\n this.watcher.close();\n this.watcher = null;\n }\n\n this.pendingChanges.clear();\n this.onChanges = null;\n }\n\n isRunning(): boolean {\n return this.watcher !== null;\n }\n}\n","import ignore, { Ignore } from \"ignore\";\nimport { existsSync, readFileSync, promises as fsPromises } from \"fs\";\nimport * as path from \"path\";\n\nimport { hasFilteredPathSegment, isBuildPathSegment, isHiddenPathSegment } from \"./paths.js\";\n\nconst PROJECT_MARKERS = [\n \".git\",\n \"package.json\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"setup.py\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n \"pom.xml\",\n \"build.gradle\",\n \"CMakeLists.txt\",\n \"Makefile\",\n \".opencode\",\n];\n\nexport function hasProjectMarker(projectRoot: string): boolean {\n for (const marker of PROJECT_MARKERS) {\n if (existsSync(path.join(projectRoot, marker))) {\n return true;\n }\n }\n return false;\n}\n\nexport interface SkippedFile {\n path: string;\n reason: \"too_large\" | \"excluded\" | \"gitignore\" | \"no_match\";\n}\n\nexport interface CollectFilesResult {\n files: Array<{ path: string; size: number }>;\n skipped: SkippedFile[];\n}\n\nexport function createIgnoreFilter(projectRoot: string): Ignore {\n const ig = ignore();\n\n const defaultIgnores = [\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \".nuxt\",\n \"coverage\",\n \"__pycache__\",\n \"target\",\n \"vendor\",\n \".opencode\",\n \".*\",\n \"**/.*\",\n \"**/.*/**\",\n \"**/*build*/**\",\n ];\n\n ig.add(defaultIgnores);\n\n const gitignorePath = path.join(projectRoot, \".gitignore\");\n if (existsSync(gitignorePath)) {\n const gitignoreContent = readFileSync(gitignorePath, \"utf-8\");\n ig.add(gitignoreContent);\n }\n\n return ig;\n}\n\nexport function shouldIncludeFile(\n filePath: string,\n projectRoot: string,\n includePatterns: string[],\n excludePatterns: string[],\n ignoreFilter: Ignore\n): boolean {\n const relativePath = path.relative(projectRoot, filePath);\n\n if (hasFilteredPathSegment(relativePath, path.sep)) {\n return false;\n }\n\n if (ignoreFilter.ignores(relativePath)) {\n return false;\n }\n\n for (const pattern of excludePatterns) {\n if (matchGlob(relativePath, pattern)) {\n return false;\n }\n }\n\n for (const pattern of includePatterns) {\n if (matchGlob(relativePath, pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction matchGlob(filePath: string, pattern: string): boolean {\n if (pattern.startsWith(\"**/\")) {\n const withoutPrefix = pattern.slice(3);\n if (withoutPrefix && matchGlob(filePath, withoutPrefix)) {\n return true;\n }\n }\n\n const escapedPattern = pattern.replace(/[.+^$()|[\\]\\\\]/g, \"\\\\$&\");\n\n let regexPattern = escapedPattern\n .replace(/\\*\\*/g, \"<<<DOUBLESTAR>>>\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/<<<DOUBLESTAR>>>/g, \".*\")\n .replace(/\\?/g, \".\")\n .replace(/\\{([^}]+)\\}/g, (_, p1) => `(${p1.split(\",\").join(\"|\")})`);\n\n // **/*.js → matches both root \"file.js\" and nested \"dir/file.js\"\n if (regexPattern.startsWith(\".*/\")) {\n regexPattern = `(.*\\\\/)?${regexPattern.slice(3)}`;\n }\n\n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(filePath);\n}\n\nexport interface WalkOptions {\n maxDepth: number;\n maxFilesPerDirectory: number;\n}\n\nexport async function* walkDirectory(\n dir: string,\n projectRoot: string,\n includePatterns: string[],\n excludePatterns: string[],\n ignoreFilter: Ignore,\n maxFileSize: number,\n skipped: SkippedFile[],\n options: WalkOptions,\n currentDepth: number = 0\n): AsyncGenerator<{ path: string; size: number }> {\n const entries = await fsPromises.readdir(dir, { withFileTypes: true });\n\n const filesInDir: Array<{ path: string; size: number }> = [];\n const subdirs: Array<{ fullPath: string; relativePath: string }> = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = path.relative(projectRoot, fullPath);\n\n if (isHiddenPathSegment(entry.name)) {\n if (entry.isDirectory()) {\n skipped.push({ path: relativePath, reason: \"excluded\" });\n }\n continue;\n }\n\n if (entry.isDirectory() && isBuildPathSegment(entry.name)) {\n skipped.push({ path: relativePath, reason: \"excluded\" });\n continue;\n }\n\n if (ignoreFilter.ignores(relativePath)) {\n if (entry.isFile()) {\n skipped.push({ path: relativePath, reason: \"gitignore\" });\n }\n continue;\n }\n\n if (entry.isDirectory()) {\n subdirs.push({ fullPath, relativePath });\n } else if (entry.isFile()) {\n const stat = await fsPromises.stat(fullPath);\n\n if (stat.size > maxFileSize) {\n skipped.push({ path: relativePath, reason: \"too_large\" });\n continue;\n }\n\n for (const pattern of excludePatterns) {\n if (matchGlob(relativePath, pattern)) {\n skipped.push({ path: relativePath, reason: \"excluded\" });\n continue;\n }\n }\n\n let matched = false;\n for (const pattern of includePatterns) {\n if (matchGlob(relativePath, pattern)) {\n matched = true;\n break;\n }\n }\n\n if (matched) {\n filesInDir.push({ path: fullPath, size: stat.size });\n }\n }\n }\n\n filesInDir.sort((a, b) => a.size - b.size);\n const limitedFiles = filesInDir.slice(0, options.maxFilesPerDirectory);\n for (const f of limitedFiles) {\n yield f;\n }\n for (let i = options.maxFilesPerDirectory; i < filesInDir.length; i++) {\n skipped.push({ path: path.relative(projectRoot, filesInDir[i].path), reason: \"excluded\" });\n }\n\n const canRecurse = options.maxDepth === -1 || currentDepth < options.maxDepth;\n if (canRecurse) {\n for (const sub of subdirs) {\n yield* walkDirectory(\n sub.fullPath,\n projectRoot,\n includePatterns,\n excludePatterns,\n ignoreFilter,\n maxFileSize,\n skipped,\n options,\n currentDepth + 1\n );\n }\n }\n}\n\nexport async function collectFiles(\n projectRoot: string,\n includePatterns: string[],\n excludePatterns: string[],\n maxFileSize: number,\n additionalRoots?: string[],\n walkOptions?: WalkOptions\n): Promise<CollectFilesResult> {\n const opts: WalkOptions = walkOptions ?? { maxDepth: 5, maxFilesPerDirectory: 100 };\n const ignoreFilter = createIgnoreFilter(projectRoot);\n const files: Array<{ path: string; size: number }> = [];\n const skipped: SkippedFile[] = [];\n\n for await (const file of walkDirectory(\n projectRoot,\n projectRoot,\n includePatterns,\n excludePatterns,\n ignoreFilter,\n maxFileSize,\n skipped,\n opts,\n 0\n )) {\n files.push(file);\n }\n\n if (additionalRoots && additionalRoots.length > 0) {\n const normalizedRoots = new Set<string>();\n for (const kbRoot of additionalRoots) {\n const resolved = path.normalize(\n path.isAbsolute(kbRoot) ? kbRoot : path.resolve(projectRoot, kbRoot)\n );\n normalizedRoots.add(resolved);\n }\n\n for (const resolvedKbRoot of normalizedRoots) {\n try {\n const stat = await fsPromises.stat(resolvedKbRoot);\n if (!stat.isDirectory()) {\n skipped.push({ path: resolvedKbRoot, reason: \"excluded\" });\n continue;\n }\n const kbIgnoreFilter = createIgnoreFilter(resolvedKbRoot);\n for await (const file of walkDirectory(\n resolvedKbRoot,\n resolvedKbRoot,\n includePatterns,\n excludePatterns,\n kbIgnoreFilter,\n maxFileSize,\n skipped,\n opts,\n 0\n )) {\n files.push(file);\n }\n } catch {\n skipped.push({ path: resolvedKbRoot, reason: \"excluded\" });\n }\n }\n }\n\n return { files, skipped };\n}\n","import chokidar, { FSWatcher } from \"chokidar\";\nimport * as path from \"path\";\n\nimport { getCurrentBranch, getHeadPath, isGitRepo } from \"../git/index.js\";\n\nexport type BranchChangeHandler = (oldBranch: string | null, newBranch: string) => Promise<void>;\n\n/**\n * Watches .git/HEAD for branch changes.\n * When HEAD changes (branch switch, checkout), triggers callback with old and new branch.\n */\nexport class GitHeadWatcher {\n private watcher: FSWatcher | null = null;\n private projectRoot: string;\n private currentBranch: string | null = null;\n private onBranchChange: BranchChangeHandler | null = null;\n private debounceTimer: NodeJS.Timeout | null = null;\n private debounceMs = 100; // Short debounce for git operations\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n start(handler: BranchChangeHandler): void {\n if (this.watcher) {\n return;\n }\n\n if (!isGitRepo(this.projectRoot)) {\n return; // Not a git repo, nothing to watch\n }\n\n this.onBranchChange = handler;\n this.currentBranch = getCurrentBranch(this.projectRoot);\n\n const headPath = getHeadPath(this.projectRoot);\n\n // Also watch refs/heads for when branches are updated\n const refsPath = path.join(this.projectRoot, \".git\", \"refs\", \"heads\");\n\n this.watcher = chokidar.watch([headPath, refsPath], {\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 50,\n pollInterval: 10,\n },\n });\n\n this.watcher.on(\"change\", () => this.handleHeadChange());\n this.watcher.on(\"add\", () => this.handleHeadChange());\n }\n\n private handleHeadChange(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n }\n\n this.debounceTimer = setTimeout(() => {\n this.checkBranchChange();\n }, this.debounceMs);\n }\n\n private async checkBranchChange(): Promise<void> {\n const newBranch = getCurrentBranch(this.projectRoot);\n\n if (newBranch && newBranch !== this.currentBranch && this.onBranchChange) {\n const oldBranch = this.currentBranch;\n this.currentBranch = newBranch;\n\n try {\n await this.onBranchChange(oldBranch, newBranch);\n } catch (error) {\n console.error(\"Error handling branch change:\", error);\n }\n } else if (newBranch) {\n this.currentBranch = newBranch;\n }\n }\n\n getCurrentBranch(): string | null {\n return this.currentBranch;\n }\n\n stop(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n\n if (this.watcher) {\n this.watcher.close();\n this.watcher = null;\n }\n\n this.onBranchChange = null;\n }\n\n isRunning(): boolean {\n return this.watcher !== null;\n }\n}\n","import type { CodebaseIndexConfig } from \"../config/schema.js\";\nimport type { Indexer } from \"../indexer/index.js\";\nimport { isGitRepo } from \"../git/index.js\";\nimport { FileWatcher } from \"./file-watcher.js\";\nimport { GitHeadWatcher } from \"./git-head-watcher.js\";\n\nexport { FileWatcher } from \"./file-watcher.js\";\nexport type { ChangeHandler, FileChange, FileChangeType } from \"./file-watcher.js\";\nexport { GitHeadWatcher } from \"./git-head-watcher.js\";\nexport type { BranchChangeHandler } from \"./git-head-watcher.js\";\n\nexport interface CombinedWatcher {\n fileWatcher: FileWatcher;\n gitWatcher: GitHeadWatcher | null;\n stop(): void;\n}\n\nexport function createWatcherWithIndexer(\n getIndexer: () => Indexer,\n projectRoot: string,\n config: CodebaseIndexConfig\n): CombinedWatcher {\n const fileWatcher = new FileWatcher(projectRoot, config);\n\n fileWatcher.start(async (changes) => {\n const hasAddOrChange = changes.some(\n (c) => c.type === \"add\" || c.type === \"change\"\n );\n const hasDelete = changes.some((c) => c.type === \"unlink\");\n\n if (hasAddOrChange || hasDelete) {\n await getIndexer().index();\n }\n });\n\n let gitWatcher: GitHeadWatcher | null = null;\n \n if (isGitRepo(projectRoot)) {\n gitWatcher = new GitHeadWatcher(projectRoot);\n gitWatcher.start(async (oldBranch, newBranch) => {\n console.log(`Branch changed: ${oldBranch ?? \"(none)\"} -> ${newBranch}`);\n await getIndexer().index();\n });\n }\n\n return {\n fileWatcher,\n gitWatcher,\n stop() {\n fileWatcher.stop();\n gitWatcher?.stop();\n },\n };\n}\n","import { tool, type ToolDefinition } from \"@opencode-ai/plugin\";\n\nimport { parseConfig, type ParsedCodebaseIndexConfig } from \"../config/schema.js\";\nimport { Indexer } from \"../indexer/index.js\";\nimport { formatCostEstimate } from \"../utils/cost.js\";\nimport type { LogLevel } from \"../config/schema.js\";\nimport type { LogEntry } from \"../utils/logger.js\";\nimport {\n formatProgressTitle,\n formatIndexStats,\n formatStatus,\n calculatePercentage,\n formatCodebasePeek,\n formatDefinitionLookup,\n formatHealthCheck,\n formatLogs,\n formatSearchResults,\n} from \"./utils.js\";\nimport {\n findKnowledgeBasePathIndex,\n hasMatchingKnowledgeBasePath,\n resolveKnowledgeBasePath,\n} from \"./knowledge-base-paths.js\";\nimport { existsSync, realpathSync, statSync } from \"fs\";\nimport * as path from \"path\";\nimport { loadProjectConfigLayer, materializeLocalProjectConfig } from \"../config/merger.js\";\nimport { resolveWorktreeMainRepoRoot } from \"../git/index.js\";\nimport { getConfigPath, loadEditableConfig, loadRuntimeConfig, saveConfig } from \"./config-state.js\";\nimport * as os from \"os\";\n\nfunction ensureStringArray(value: unknown): string[] {\n return Array.isArray(value) ? (value as string[]) : [];\n}\n\nconst z = tool.schema;\n\nlet sharedIndexer: Indexer | null = null;\nlet sharedProjectRoot: string = \"\";\n\nexport function initializeTools(projectRoot: string, config: ParsedCodebaseIndexConfig): void {\n sharedProjectRoot = projectRoot;\n sharedIndexer = new Indexer(projectRoot, config);\n}\n\nexport function getSharedIndexer(): Indexer {\n return getIndexer();\n}\n\nfunction refreshIndexerFromConfig(): void {\n if (!sharedProjectRoot) {\n throw new Error(\"Codebase index tools not initialized. Plugin may not be loaded correctly.\");\n }\n\n sharedIndexer = new Indexer(sharedProjectRoot, parseConfig(loadRuntimeConfig(sharedProjectRoot)));\n}\n\nfunction shouldForceLocalizeProjectIndex(): boolean {\n const currentConfig = parseConfig(loadRuntimeConfig(sharedProjectRoot));\n if (currentConfig.scope !== \"project\") {\n return false;\n }\n\n const localIndexPath = path.join(sharedProjectRoot, \".opencode\", \"index\");\n const mainRepoRoot = resolveWorktreeMainRepoRoot(sharedProjectRoot);\n if (!mainRepoRoot) {\n return false;\n }\n\n const inheritedIndexPath = path.join(mainRepoRoot, \".opencode\", \"index\");\n return !existsSync(localIndexPath) && existsSync(inheritedIndexPath);\n}\n\nfunction getIndexer(): Indexer {\n if (!sharedIndexer) {\n throw new Error(\"Codebase index tools not initialized. Plugin may not be loaded correctly.\");\n }\n return sharedIndexer;\n}\n\nexport const codebase_peek: ToolDefinition = tool({\n description:\n \"Quick lookup of code locations by meaning. Returns only metadata (file, line, name, type) WITHOUT code content. Use this first to find WHERE code is, then use Read tool to examine specific files. Saves tokens by not returning full code blocks. Best for: discovery, navigation, finding multiple related locations.\",\n args: {\n query: z.string().describe(\"Natural language description of what code you're looking for.\"),\n limit: z.number().optional().default(10).describe(\"Maximum number of results to return\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py', 'rs')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils', 'lib')\"),\n chunkType: z.enum([\"function\", \"class\", \"method\", \"interface\", \"type\", \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\"]).optional().describe(\"Filter by code chunk type\"),\n },\n async execute(args) {\n const indexer = getIndexer();\n const results = await indexer.search(args.query, args.limit ?? 10, {\n fileType: args.fileType,\n directory: args.directory,\n chunkType: args.chunkType,\n metadataOnly: true,\n });\n\n return formatCodebasePeek(results);\n },\n});\n\nexport const index_codebase: ToolDefinition = tool({\n description:\n \"Index the codebase for semantic search. Creates vector embeddings of code chunks. Incremental - only re-indexes changed files (~50ms when nothing changed). Run before first codebase_search.\",\n args: {\n force: z.boolean().optional().default(false).describe(\"Force reindex even if already indexed\"),\n estimateOnly: z.boolean().optional().default(false).describe(\"Only show cost estimate without indexing\"),\n verbose: z.boolean().optional().default(false).describe(\"Show detailed info about skipped files and parsing failures\"),\n },\n async execute(args, context) {\n let indexer = getIndexer();\n\n if (args.estimateOnly) {\n const estimate = await indexer.estimateCost();\n return formatCostEstimate(estimate);\n }\n\n if (args.force) {\n if (shouldForceLocalizeProjectIndex()) {\n materializeLocalProjectConfig(sharedProjectRoot, loadProjectConfigLayer(sharedProjectRoot));\n refreshIndexerFromConfig();\n indexer = getIndexer();\n }\n await indexer.clearIndex();\n }\n\n const stats = await indexer.index((progress) => {\n context.metadata({\n title: formatProgressTitle(progress),\n metadata: {\n phase: progress.phase,\n filesProcessed: progress.filesProcessed,\n totalFiles: progress.totalFiles,\n chunksProcessed: progress.chunksProcessed,\n totalChunks: progress.totalChunks,\n percentage: calculatePercentage(progress),\n },\n });\n });\n return formatIndexStats(stats, args.verbose ?? false);\n },\n});\n\nexport const index_status: ToolDefinition = tool({\n description:\n \"Check the status of the codebase index. Shows whether the codebase is indexed, how many chunks are stored, and the embedding provider being used.\",\n args: {},\n async execute() {\n const indexer = getIndexer();\n const status = await indexer.getStatus();\n return formatStatus(status);\n },\n});\n\nexport const index_health_check: ToolDefinition = tool({\n description:\n \"Check index health and remove stale entries from deleted files. Run this to clean up the index after files have been deleted.\",\n args: {},\n async execute() {\n const indexer = getIndexer();\n const result = await indexer.healthCheck();\n\n return formatHealthCheck(result);\n },\n});\n\nexport const index_metrics: ToolDefinition = tool({\n description:\n \"Get metrics and performance statistics for the codebase index. Shows indexing stats, search timings, cache hit rates, and API usage. Requires debug.enabled=true and debug.metrics=true in config.\",\n args: {},\n async execute() {\n const indexer = getIndexer();\n const logger = indexer.getLogger();\n\n if (!logger.isEnabled()) {\n return \"Debug mode is disabled. Enable it in your config:\\n\\n```json\\n{\\n \\\"debug\\\": {\\n \\\"enabled\\\": true,\\n \\\"metrics\\\": true\\n }\\n}\\n```\";\n }\n\n if (!logger.isMetricsEnabled()) {\n return \"Metrics collection is disabled. Enable it in your config:\\n\\n```json\\n{\\n \\\"debug\\\": {\\n \\\"enabled\\\": true,\\n \\\"metrics\\\": true\\n }\\n}\\n```\";\n }\n\n return logger.formatMetrics();\n },\n});\n\nexport const index_logs: ToolDefinition = tool({\n description:\n \"Get recent debug logs from the codebase indexer. Shows timestamped log entries with level and category. Requires debug.enabled=true in config.\",\n args: {\n limit: z.number().optional().default(20).describe(\"Maximum number of log entries to return\"),\n category: z.enum([\"search\", \"embedding\", \"cache\", \"gc\", \"branch\", \"general\"]).optional().describe(\"Filter by log category\"),\n level: z.enum([\"error\", \"warn\", \"info\", \"debug\"]).optional().describe(\"Filter by minimum log level\"),\n },\n async execute(args) {\n const indexer = getIndexer();\n const logger = indexer.getLogger();\n\n if (!logger.isEnabled()) {\n return \"Debug mode is disabled. Enable it in your config:\\n\\n```json\\n{\\n \\\"debug\\\": {\\n \\\"enabled\\\": true\\n }\\n}\\n```\";\n }\n\n let logs: LogEntry[];\n if (args.category) {\n logs = logger.getLogsByCategory(args.category, args.limit);\n } else if (args.level) {\n logs = logger.getLogsByLevel(args.level as LogLevel, args.limit);\n } else {\n logs = logger.getLogs(args.limit);\n }\n\n return formatLogs(logs);\n },\n});\n\nexport const find_similar: ToolDefinition = tool({\n description:\n \"Find code similar to a given snippet. Use for duplicate detection, pattern discovery, or refactoring prep. Paste code and find semantically similar implementations elsewhere in the codebase.\",\n args: {\n code: z.string().describe(\"The code snippet to find similar code for\"),\n limit: z.number().optional().default(10).describe(\"Maximum number of results to return\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py', 'rs')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils', 'lib')\"),\n chunkType: z.enum([\"function\", \"class\", \"method\", \"interface\", \"type\", \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\"]).optional().describe(\"Filter by code chunk type\"),\n excludeFile: z.string().optional().describe(\"Exclude results from this file path (useful when searching for duplicates of code from a specific file)\"),\n },\n async execute(args) {\n const indexer = getIndexer();\n const results = await indexer.findSimilar(args.code, args.limit, {\n fileType: args.fileType,\n directory: args.directory,\n chunkType: args.chunkType,\n excludeFile: args.excludeFile,\n });\n\n if (results.length === 0) {\n return \"No similar code found. Try a different snippet or run index_codebase first.\";\n }\n\n return formatSearchResults(results);\n },\n});\n\nexport const codebase_search: ToolDefinition = tool({\n description:\n \"Search codebase by MEANING, not keywords. Returns full code content. Use when you need to see actual implementation. For just finding WHERE code is (saves ~90% tokens), use codebase_peek instead. For known identifiers like 'validateToken', use grep - it's faster.\",\n args: {\n query: z.string().describe(\"Natural language description of what code you're looking for. Describe behavior, not syntax.\"),\n limit: z.number().optional().default(5).describe(\"Maximum number of results to return\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py', 'rs')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils', 'lib')\"),\n chunkType: z.enum([\"function\", \"class\", \"method\", \"interface\", \"type\", \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\"]).optional().describe(\"Filter by code chunk type\"),\n contextLines: z.number().optional().describe(\"Number of extra lines to include before/after each match (default: 0)\"),\n },\n async execute(args) {\n const indexer = getIndexer();\n const results = await indexer.search(args.query, args.limit ?? 5, {\n fileType: args.fileType,\n directory: args.directory,\n chunkType: args.chunkType,\n contextLines: args.contextLines,\n });\n\n if (results.length === 0) {\n return \"No matching code found. Try a different query or run index_codebase first.\";\n }\n\n return formatSearchResults(results, \"score\");\n },\n});\n\nexport const implementation_lookup: ToolDefinition = tool({\n description:\n \"Jump to symbol definition. Find WHERE something is defined. \" +\n \"Returns the authoritative source location(s) for a function, class, method, type, or variable. \" +\n \"Prefers real implementation files over tests, docs, examples, and fixtures. \" +\n \"Use when you need the definition site, not all usages.\",\n args: {\n query: z.string().describe(\"Symbol name or natural language description (e.g., 'validateToken', 'where is the payment handler defined')\"),\n limit: z.number().optional().default(5).describe(\"Maximum number of results\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils')\"),\n },\n async execute(args) {\n const indexer = getIndexer();\n const results = await indexer.search(args.query, args.limit ?? 5, {\n fileType: args.fileType,\n directory: args.directory,\n definitionIntent: true,\n });\n return formatDefinitionLookup(results, args.query);\n },\n});\n\nexport const call_graph: ToolDefinition = tool({\n description:\n \"Query the call graph to find callers or callees of a function/method. Use to understand code flow and dependencies between functions.\",\n args: {\n name: z.string().describe(\"Function or method name to query\"),\n direction: z.enum([\"callers\", \"callees\"]).default(\"callers\").describe(\"Direction: 'callers' finds who calls this function, 'callees' finds what this function calls\"),\n symbolId: z.string().optional().describe(\"Symbol ID (required for 'callees' direction, returned by previous call_graph queries)\"),\n },\n async execute(args) {\n const indexer = getIndexer();\n if (args.direction === \"callees\") {\n if (!args.symbolId) {\n return \"Error: 'symbolId' is required when direction is 'callees'. First use direction='callers' to find the symbol ID.\";\n }\n const callees = await indexer.getCallees(args.symbolId);\n if (callees.length === 0) {\n return `No callees found for symbol ${args.symbolId}. The function may not call any other tracked functions.`;\n }\n const formatted = callees.map((e, i) =>\n `[${i + 1}] \\u2192 ${e.targetName} (${e.callType}) at line ${e.line}${e.isResolved ? ` [resolved: ${e.toSymbolId}]` : \" [unresolved]\"}`\n );\n return formatted.join(\"\\n\");\n }\n const callers = await indexer.getCallers(args.name);\n if (callers.length === 0) {\n return `No callers found for \"${args.name}\". It may not be called by any tracked function, or the index needs updating.`;\n }\n const formatted = callers.map((e, i) =>\n `[${i + 1}] \\u2190 from ${e.fromSymbolName ?? \"<unknown>\"} in ${e.fromSymbolFilePath ?? \"<unknown file>\"} [${e.fromSymbolId}] (${e.callType}) at line ${e.line}${e.isResolved ? \" [resolved]\" : \" [unresolved]\"}`\n );\n return formatted.join(\"\\n\");\n },\n});\n\nexport const add_knowledge_base: ToolDefinition = tool({\n description:\n \"Add a folder as a knowledge base to the semantic search index. \" +\n \"The folder will be indexed alongside the main project code. \" +\n \"Supports absolute paths or relative paths (relative to the project root).\",\n args: {\n path: z.string().describe(\"Path to the folder to add as a knowledge base (absolute or relative to project root)\"),\n },\n async execute(args) {\n const inputPath = args.path.trim();\n\n const normalizedPath = path.resolve(\n path.isAbsolute(inputPath)\n ? inputPath\n : resolveKnowledgeBasePath(inputPath, sharedProjectRoot)\n );\n\n if (!existsSync(normalizedPath)) {\n return `Error: Directory does not exist: ${normalizedPath}`;\n }\n\n // Resolve symlinks to get the real path for security checks only\n let realPath: string;\n try {\n realPath = realpathSync(normalizedPath);\n } catch {\n return `Error: Cannot resolve path: ${normalizedPath}`;\n }\n\n // Security: block sensitive system directories (check against real path to prevent symlink bypass)\n const blockedPrefixes = [\n \"/etc\",\n \"/proc\",\n \"/sys\",\n \"/dev\",\n \"/boot\",\n \"/root\",\n \"/var/run\",\n \"/var/log\",\n ];\n const homeDir = os.homedir();\n const sensitiveDotDirs = [\".ssh\", \".gnupg\", \".aws\", \".config/gcloud\", \".docker\", \".kube\"];\n\n for (const prefix of blockedPrefixes) {\n if (realPath === prefix || realPath.startsWith(prefix + \"/\")) {\n return `Error: Adding system directory as knowledge base is not allowed: ${normalizedPath}`;\n }\n }\n\n for (const dotDir of sensitiveDotDirs) {\n const sensitiveDir = path.join(homeDir, dotDir);\n if (realPath === sensitiveDir || realPath.startsWith(sensitiveDir + \"/\")) {\n return `Error: Adding sensitive directory as knowledge base is not allowed: ${normalizedPath}`;\n }\n }\n\n try {\n const stat = statSync(normalizedPath);\n if (!stat.isDirectory()) {\n return `Error: Path is not a directory: ${normalizedPath}`;\n }\n } catch (error) {\n return `Error: Cannot access directory: ${normalizedPath} - ${error instanceof Error ? error.message : String(error)}`;\n }\n\n const config = loadEditableConfig(sharedProjectRoot);\n const knowledgeBases: string[] = ensureStringArray(config.knowledgeBases);\n\n const alreadyExists = hasMatchingKnowledgeBasePath(knowledgeBases, normalizedPath, sharedProjectRoot);\n\n if (alreadyExists) {\n return `Knowledge base already configured: ${normalizedPath}`;\n }\n\n knowledgeBases.push(normalizedPath);\n config.knowledgeBases = knowledgeBases;\n saveConfig(sharedProjectRoot, config);\n refreshIndexerFromConfig();\n\n let result = `${normalizedPath}\\n`;\n result += `Total knowledge bases: ${knowledgeBases.length}\\n`;\n result += `Config saved to: ${getConfigPath(sharedProjectRoot)}\\n`;\n result += `\\nRun /index to rebuild the index with the new knowledge base.`;\n\n return result;\n },\n});\n\nexport const list_knowledge_bases: ToolDefinition = tool({\n description:\n \"List all configured knowledge base folders that are indexed alongside the main project.\",\n args: {},\n async execute() {\n const config = loadRuntimeConfig(sharedProjectRoot);\n const knowledgeBases: string[] = ensureStringArray(config.knowledgeBases);\n\n if (knowledgeBases.length === 0) {\n return \"No knowledge bases configured. Use add_knowledge_base to add folders.\";\n }\n\n let result = `Knowledge Bases (${knowledgeBases.length}):\\n\\n`;\n\n for (let i = 0; i < knowledgeBases.length; i++) {\n const kb = knowledgeBases[i];\n const resolvedPath = resolveKnowledgeBasePath(kb, sharedProjectRoot);\n const exists = existsSync(resolvedPath);\n\n result += `[${i + 1}] ${kb}\\n`;\n result += ` Resolved: ${resolvedPath}\\n`;\n result += ` Status: ${exists ? \"Exists\" : \"NOT FOUND\"}\\n`;\n if (exists) {\n try {\n const stat = statSync(resolvedPath);\n result += ` Type: ${stat.isDirectory() ? \"Directory\" : \"File\"}\\n`;\n } catch { /* ignore */ }\n }\n result += \"\\n\";\n }\n\n result += `Config file: ${getConfigPath(sharedProjectRoot)}`;\n return result;\n },\n});\n\nexport const remove_knowledge_base: ToolDefinition = tool({\n description:\n \"Remove a knowledge base folder from the semantic search index.\",\n args: {\n path: z.string().describe(\"Path of the knowledge base to remove (must match the configured path exactly)\"),\n },\n async execute(args) {\n const inputPath = args.path.trim();\n\n const config = loadEditableConfig(sharedProjectRoot);\n const knowledgeBases: string[] = ensureStringArray(config.knowledgeBases);\n\n if (knowledgeBases.length === 0) {\n return \"No knowledge bases configured.\";\n }\n\n const index = findKnowledgeBasePathIndex(knowledgeBases, inputPath, sharedProjectRoot);\n\n if (index === -1) {\n let result = `Knowledge base not found: ${inputPath}\\n\\n`;\n result += `Currently configured:\\n`;\n for (const kb of knowledgeBases) {\n result += ` - ${kb}\\n`;\n }\n return result;\n }\n\n const removed = knowledgeBases.splice(index, 1)[0];\n config.knowledgeBases = knowledgeBases;\n saveConfig(sharedProjectRoot, config);\n refreshIndexerFromConfig();\n\n let result = `Removed: ${removed}\\n\\n`;\n result += `Remaining knowledge bases: ${knowledgeBases.length}\\n`;\n result += `Config saved to: ${getConfigPath(sharedProjectRoot)}\\n`;\n result += `\\nRun /index to rebuild the index without the removed knowledge base.`;\n\n return result;\n },\n});\n","import { existsSync, readFileSync, writeFileSync, renameSync, unlinkSync, mkdirSync, promises as fsPromises } from \"fs\";\nimport * as path from \"path\";\nimport { performance } from \"perf_hooks\";\nimport PQueue from \"p-queue\";\nimport pRetry from \"p-retry\";\n\nimport { ParsedCodebaseIndexConfig, type RerankerConfig } from \"../config/schema.js\";\nimport { detectEmbeddingProvider, ConfiguredProviderInfo, tryDetectProvider, createCustomProviderInfo } from \"../embeddings/detector.js\";\nimport {\n createEmbeddingProvider,\n EmbeddingProviderInterface,\n CustomProviderNonRetryableError,\n} from \"../embeddings/provider.js\";\nimport { createReranker, RerankerInterface } from \"../rerank/index.js\";\nimport { collectFiles, SkippedFile } from \"../utils/files.js\";\nimport { createCostEstimate, CostEstimate } from \"../utils/cost.js\";\nimport { Logger, initializeLogger } from \"../utils/logger.js\";\nimport {\n VectorStore,\n InvertedIndex,\n Database,\n parseFiles,\n createEmbeddingTexts,\n generateChunkId,\n generateChunkHash,\n ChunkMetadata,\n ChunkData,\n createDynamicBatches,\n hashFile,\n hashContent,\n extractCalls,\n parseFileAsText,\n estimateTokens,\n} from \"../native/index.js\";\nimport type { SymbolData, CallEdgeData } from \"../native/index.js\";\nimport { getBranchOrDefault, getBaseBranch, isGitRepo } from \"../git/index.js\";\nimport { resolveProjectIndexPath } from \"../config/paths.js\";\n\nexport const CALL_GRAPH_LANGUAGES = new Set([\"typescript\", \"tsx\", \"javascript\", \"jsx\", \"python\", \"go\", \"rust\", \"php\", \"apex\", \"zig\", \"gdscript\", \"matlab\"]);\n// Languages whose identifiers are case-insensitive at the language level.\n// The Rust call_extractor lowercases callee names for these languages (except\n// constructors and imports), so same-file resolution in this file must use\n// the same normalization when looking up symbols by name. Keep this set in\n// sync with the matching branch in native/src/call_extractor.rs.\nexport const CASE_INSENSITIVE_LANGUAGES = new Set([\"apex\"]);\nexport const CALL_GRAPH_SYMBOL_CHUNK_TYPES = new Set([\n \"function_declaration\",\n \"function\",\n \"arrow_function\",\n \"method_definition\",\n \"class_declaration\",\n \"interface_declaration\",\n \"type_alias_declaration\",\n \"enum_declaration\",\n \"function_definition\",\n \"class_definition\",\n \"decorated_definition\",\n \"method_declaration\",\n \"type_declaration\",\n \"type_spec\",\n \"function_item\",\n \"impl_item\",\n \"struct_item\",\n \"enum_item\",\n \"trait_item\",\n \"mod_item\",\n \"trait_declaration\",\n \"trigger_declaration\",\n \"test_declaration\",\n \"struct_declaration\",\n \"union_declaration\",\n // GDScript declarations whose names participate in the call graph.\n // `function_definition` and `class_definition` are already in the set\n // above (shared with Python/C/Bash and Python, respectively).\n \"constructor_definition\",\n \"enum_definition\",\n \"signal_statement\",\n \"const_statement\",\n \"class_name_statement\",\n]);\n\nfunction float32ArrayToBuffer(arr: number[]): Buffer {\n const float32 = new Float32Array(arr);\n return Buffer.from(float32.buffer);\n}\n\nfunction bufferToFloat32Array(buf: Buffer): Float32Array {\n return new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);\n}\n\nfunction getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error && typeof error === \"object\" && \"message\" in error) {\n return String((error as { message: unknown }).message);\n }\n return String(error);\n}\n\nfunction isRateLimitError(error: unknown): boolean {\n const message = getErrorMessage(error);\n return message.includes(\"429\") || message.toLowerCase().includes(\"rate limit\") || message.toLowerCase().includes(\"too many requests\");\n}\n\nfunction getSafeEmbeddingChunkTokenLimit(provider: ConfiguredProviderInfo): number {\n const providerMaxTokens = provider.modelInfo.maxTokens;\n const maxChunkTokens = Math.max(256, Math.floor(providerMaxTokens * 0.75));\n return Math.min(2000, maxChunkTokens);\n}\n\nfunction getDynamicBatchOptions(provider: ConfiguredProviderInfo): { maxBatchTokens?: number; maxBatchItems?: number } {\n if (provider.provider === \"ollama\") {\n return {\n maxBatchTokens: provider.modelInfo.maxTokens,\n maxBatchItems: 1,\n };\n }\n\n return {};\n}\n\nfunction isSqliteCorruptionError(error: unknown): boolean {\n const message = getErrorMessage(error).toLowerCase();\n return message.includes(\"database disk image is malformed\")\n || message.includes(\"file is not a database\")\n || message.includes(\"database schema is corrupt\")\n || message.includes(\"sqlite_corrupt\");\n}\n\nexport interface IndexStats {\n totalFiles: number;\n totalChunks: number;\n indexedChunks: number;\n failedChunks: number;\n tokensUsed: number;\n durationMs: number;\n existingChunks: number;\n removedChunks: number;\n skippedFiles: SkippedFile[];\n parseFailures: string[];\n failedBatchesPath?: string;\n warning?: string;\n resetCorruptedIndex?: boolean;\n}\n\ninterface CorruptedIndexResetResult {\n warning: string;\n resetCorruptedIndex: true;\n}\n\nexport interface SearchResult {\n filePath: string;\n startLine: number;\n endLine: number;\n content: string;\n score: number;\n chunkType: string;\n name?: string;\n}\n\nexport interface HealthCheckResult {\n removed: number;\n filePaths: string[];\n gcOrphanEmbeddings: number;\n gcOrphanChunks: number;\n gcOrphanSymbols: number;\n gcOrphanCallEdges: number;\n warning?: string;\n resetCorruptedIndex?: boolean;\n}\n\nexport interface StatusResult {\n indexed: boolean;\n vectorCount: number;\n provider: string;\n model: string;\n indexPath: string;\n currentBranch: string;\n baseBranch: string;\n compatibility: IndexCompatibility | null;\n failedBatchesCount: number;\n failedBatchesPath?: string;\n warning?: string;\n}\n\nconst STARTUP_WARNING_METADATA_KEY = \"index.startupWarning\";\n\nexport interface IndexProgress {\n phase: \"scanning\" | \"parsing\" | \"embedding\" | \"storing\" | \"complete\";\n filesProcessed: number;\n totalFiles: number;\n chunksProcessed: number;\n totalChunks: number;\n currentFile?: string;\n}\n\nexport type ProgressCallback = (progress: IndexProgress) => void;\n\ninterface PendingChunk {\n id: string;\n texts: Array<{\n text: string;\n tokenCount: number;\n }>;\n storageText: string;\n content: string;\n contentHash: string;\n metadata: ChunkMetadata;\n}\n\ninterface PendingEmbeddingRequest {\n chunk: PendingChunk;\n partIndex: number;\n text: string;\n tokenCount: number;\n}\n\ninterface FailedBatch {\n chunks: PendingChunk[];\n error: string;\n attemptCount: number;\n lastAttempt: string;\n}\n\ninterface RetryableFailedChunk {\n chunk: PendingChunk;\n attemptCount: number;\n}\n\ninterface SerializedFailedBatch {\n chunks: unknown[];\n error: string;\n attemptCount: number;\n lastAttempt: string;\n}\n\ntype RankedCandidate = { id: string; score: number; metadata: ChunkMetadata };\n\ninterface RerankDocumentPayload {\n id: string;\n text: string;\n}\n\ntype ExternalRerankBand = \"implementation\" | \"documentation\" | \"test\" | \"other\";\n\ninterface HybridRankOptions {\n fusionStrategy: \"weighted\" | \"rrf\";\n rrfK: number;\n rerankTopN: number;\n limit: number;\n hybridWeight: number;\n}\n\ninterface SemanticRankOptions {\n rerankTopN: number;\n limit: number;\n prioritizeSourcePaths?: boolean;\n}\n\ninterface IndexMetadata {\n indexVersion: string;\n embeddingProvider: string;\n embeddingModel: string;\n embeddingDimensions: number;\n embeddingStrategyVersion: string;\n createdAt: string;\n updatedAt: string;\n}\n\nenum IncompatibilityCode {\n DIMENSION_MISMATCH = \"DIMENSION_MISMATCH\",\n MODEL_MISMATCH = \"MODEL_MISMATCH\",\n EMBEDDING_STRATEGY_MISMATCH = \"EMBEDDING_STRATEGY_MISMATCH\",\n}\n\ninterface IndexCompatibility {\n compatible: boolean;\n code?: IncompatibilityCode;\n reason?: string;\n storedMetadata?: IndexMetadata;\n}\n\nconst INDEX_METADATA_VERSION = \"1\";\nconst EMBEDDING_STRATEGY_VERSION = \"2\";\nconst RANKING_TOKEN_CACHE_LIMIT = 4096;\nconst RANK_HYBRID_CACHE_LIMIT = 256;\n\nfunction createPendingChunkStorageText(texts: PendingChunk[\"texts\"]): string {\n const primaryText = texts[0]?.text ?? \"\";\n if (texts.length <= 1) {\n return primaryText;\n }\n\n return `${primaryText}\\n\\n... [split into ${texts.length} parts for embedding]`;\n}\n\nfunction normalizePendingChunk(rawChunk: unknown, maxChunkTokens?: number): PendingChunk | null {\n if (!rawChunk || typeof rawChunk !== \"object\") {\n return null;\n }\n\n const chunk = rawChunk as {\n id?: unknown;\n text?: unknown;\n texts?: Array<{ text?: unknown; tokenCount?: unknown }>;\n storageText?: unknown;\n content?: unknown;\n contentHash?: unknown;\n metadata?: unknown;\n };\n\n if (typeof chunk.id !== \"string\" || typeof chunk.contentHash !== \"string\" || !chunk.metadata || typeof chunk.metadata !== \"object\") {\n return null;\n }\n\n const texts = Array.isArray(chunk.texts)\n ? chunk.texts\n .map((entry) => {\n if (!entry || typeof entry.text !== \"string\") {\n return null;\n }\n\n return {\n text: entry.text,\n tokenCount: typeof entry.tokenCount === \"number\" && Number.isFinite(entry.tokenCount)\n ? entry.tokenCount\n : estimateTokens(entry.text),\n };\n })\n .filter((entry): entry is PendingChunk[\"texts\"][number] => entry !== null)\n : [];\n\n if (texts.length === 0 && typeof chunk.text === \"string\") {\n if (typeof chunk.content === \"string\" && chunk.content.length > 0 && chunk.metadata && typeof chunk.metadata === \"object\") {\n const metadata = chunk.metadata as Partial<ChunkMetadata>;\n const rebuiltChunk = {\n content: chunk.content,\n startLine: typeof metadata.startLine === \"number\" ? metadata.startLine : 1,\n endLine: typeof metadata.endLine === \"number\" ? metadata.endLine : 1,\n chunkType: typeof metadata.chunkType === \"string\" ? metadata.chunkType : \"other\",\n name: typeof metadata.name === \"string\" ? metadata.name : undefined,\n language: typeof metadata.language === \"string\" ? metadata.language : \"text\",\n };\n const filePath = typeof metadata.filePath === \"string\" ? metadata.filePath : \"unknown\";\n texts.push(\n ...createEmbeddingTexts(rebuiltChunk, filePath, maxChunkTokens).map((text) => ({\n text,\n tokenCount: estimateTokens(text),\n }))\n );\n } else {\n texts.push({\n text: chunk.text,\n tokenCount: estimateTokens(chunk.text),\n });\n }\n }\n\n if (texts.length === 0) {\n return null;\n }\n\n return {\n id: chunk.id,\n texts,\n storageText: typeof chunk.storageText === \"string\" ? chunk.storageText : createPendingChunkStorageText(texts),\n content: typeof chunk.content === \"string\" ? chunk.content : \"\",\n contentHash: chunk.contentHash,\n metadata: chunk.metadata as ChunkMetadata,\n };\n}\n\nfunction getPendingChunkFilePath(rawChunk: unknown): string | null {\n if (!rawChunk || typeof rawChunk !== \"object\") {\n return null;\n }\n\n const chunk = rawChunk as { metadata?: unknown };\n if (!chunk.metadata || typeof chunk.metadata !== \"object\") {\n return null;\n }\n\n const metadata = chunk.metadata as { filePath?: unknown };\n return typeof metadata.filePath === \"string\" ? metadata.filePath : null;\n}\n\nfunction normalizeFailedBatch(batch: SerializedFailedBatch, maxChunkTokens?: number): FailedBatch | null {\n const chunks = batch.chunks\n .map((chunk) => normalizePendingChunk(chunk, maxChunkTokens))\n .filter((chunk): chunk is PendingChunk => chunk !== null);\n\n if (chunks.length === 0) {\n return null;\n }\n\n return {\n chunks,\n error: batch.error,\n attemptCount: batch.attemptCount,\n lastAttempt: batch.lastAttempt,\n } satisfies FailedBatch;\n}\n\nfunction createPendingEmbeddingRequests(chunks: PendingChunk[]): PendingEmbeddingRequest[] {\n return chunks.flatMap((chunk) =>\n chunk.texts.map((textPart, partIndex) => ({\n chunk,\n partIndex,\n text: textPart.text,\n tokenCount: textPart.tokenCount,\n }))\n );\n}\n\nfunction createPendingEmbeddingRequestBatches(\n chunks: PendingChunk[],\n options: { maxBatchTokens?: number; maxBatchItems?: number } = {}\n): PendingEmbeddingRequest[][] {\n return createDynamicBatches(createPendingEmbeddingRequests(chunks), options);\n}\n\nfunction getUniquePendingChunksFromRequests(requests: PendingEmbeddingRequest[]): PendingChunk[] {\n const uniqueChunks = new Map<string, PendingChunk>();\n for (const request of requests) {\n uniqueChunks.set(request.chunk.id, request.chunk);\n }\n return Array.from(uniqueChunks.values());\n}\n\nfunction coalesceFailedBatches(batches: FailedBatch[]): FailedBatch[] {\n const grouped = new Map<string, FailedBatch>();\n\n for (const batch of batches) {\n const key = `${batch.attemptCount}:${batch.lastAttempt}:${batch.error}`;\n const existing = grouped.get(key);\n if (!existing) {\n grouped.set(key, {\n ...batch,\n chunks: [...batch.chunks],\n });\n continue;\n }\n\n existing.chunks.push(...batch.chunks);\n }\n\n return Array.from(grouped.values());\n}\n\nfunction poolEmbeddingVectors(vectors: number[][], weights: number[]): number[] {\n const firstVector = vectors[0];\n if (!firstVector) {\n return [];\n }\n\n const pooled = new Array<number>(firstVector.length).fill(0);\n let totalWeight = 0;\n\n for (let index = 0; index < vectors.length; index++) {\n const vector = vectors[index];\n const weight = Math.max(1, weights[index] ?? 1);\n totalWeight += weight;\n\n for (let dimension = 0; dimension < vector.length; dimension++) {\n pooled[dimension] += vector[dimension] * weight;\n }\n }\n\n if (totalWeight === 0) {\n return firstVector;\n }\n\n return pooled.map((value) => value / totalWeight);\n}\n\nfunction hasAllEmbeddingParts(\n parts: Array<{ vector: number[]; tokenCount: number } | undefined>,\n expectedPartCount: number\n): boolean {\n if (parts.length !== expectedPartCount) {\n return false;\n }\n\n for (let index = 0; index < expectedPartCount; index++) {\n if (parts[index] === undefined) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isPathWithinRoot(filePath: string, rootPath: string): boolean {\n const normalizedFilePath = path.resolve(filePath);\n const normalizedRoot = path.resolve(rootPath);\n return normalizedFilePath === normalizedRoot || normalizedFilePath.startsWith(`${normalizedRoot}${path.sep}`);\n}\n\nconst rankingQueryTokenCache = new Map<string, Set<string>>();\nconst rankingNameTokenCache = new Map<string, Set<string>>();\nconst rankingPathTokenCache = new Map<string, Set<string>>();\nconst rankingTextTokenCache = new Map<string, Set<string>>();\nconst rankHybridResultsCache = new WeakMap<RankedCandidate[], WeakMap<RankedCandidate[], Map<string, RankedCandidate[]>>>();\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"for\", \"with\", \"from\", \"that\", \"this\", \"into\", \"using\", \"where\",\n \"what\", \"when\", \"why\", \"how\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\n \"find\", \"show\", \"get\", \"run\", \"use\", \"code\", \"function\", \"implementation\",\n \"retrieve\", \"results\", \"result\", \"search\", \"pipeline\", \"top\", \"in\", \"on\", \"of\",\n \"to\", \"by\", \"as\", \"or\", \"an\", \"a\",\n]);\n\nconst TEST_PATH_SEGMENTS = [\n \"tests/\",\n \"__tests__/\",\n \"/test/\",\n \"fixtures/\",\n \"benchmark\",\n \"README\",\n \"ARCHITECTURE\",\n \"docs/\",\n];\n\nconst IMPLEMENTATION_EXCLUDE_PATH_SEGMENTS = [\n \"tests/\",\n \"__tests__/\",\n \"/test/\",\n \"fixtures/\",\n \"benchmark\",\n \"readme\",\n \"architecture\",\n \"docs/\",\n \"examples/\",\n \"example/\",\n \".github/\",\n \"/scripts/\",\n \"/migrations/\",\n \"/generated/\",\n];\n\nconst SOURCE_INTENT_HINTS = new Set([\n \"implement\",\n \"implementation\",\n \"function\",\n \"method\",\n \"class\",\n \"logic\",\n \"algorithm\",\n \"pipeline\",\n \"indexer\",\n \"where\",\n]);\n\nconst DOC_TEST_INTENT_HINTS = new Set([\n \"test\",\n \"tests\",\n \"fixture\",\n \"fixtures\",\n \"benchmark\",\n \"readme\",\n \"docs\",\n \"documentation\",\n]);\n\nconst DOC_INTENT_HINTS = new Set([\n \"readme\",\n \"docs\",\n \"documentation\",\n \"guide\",\n \"usage\",\n]);\n\nfunction setBoundedCache(\n cache: Map<string, Set<string>>,\n key: string,\n value: Set<string>\n): void {\n if (cache.size >= RANKING_TOKEN_CACHE_LIMIT) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) {\n cache.delete(oldest);\n }\n }\n cache.set(key, value);\n}\n\nfunction tokenizeTextForRanking(text: string): Set<string> {\n if (!text) {\n return new Set<string>();\n }\n\n const lowered = text.toLowerCase();\n const cache = rankingQueryTokenCache.get(lowered) ?? rankingTextTokenCache.get(lowered);\n if (cache) {\n return cache;\n }\n\n const tokens = new Set(\n lowered\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter((token) => token.length > 1 && !STOPWORDS.has(token))\n );\n\n setBoundedCache(rankingQueryTokenCache, lowered, tokens);\n setBoundedCache(rankingTextTokenCache, lowered, tokens);\n return tokens;\n}\n\nfunction splitPathTokens(filePath: string): Set<string> {\n const lowered = filePath.toLowerCase();\n const cache = rankingPathTokenCache.get(lowered);\n if (cache) {\n return cache;\n }\n\n const normalized = lowered\n .replace(/[^a-z0-9/._-]/g, \" \")\n .split(/[/._-]+/)\n .filter((token) => token.length > 1);\n const tokens = new Set(normalized);\n setBoundedCache(rankingPathTokenCache, lowered, tokens);\n return tokens;\n}\n\nfunction splitNameTokens(name: string): Set<string> {\n if (!name) {\n return new Set<string>();\n }\n\n const lowered = name.toLowerCase();\n const cache = rankingNameTokenCache.get(lowered);\n if (cache) {\n return cache;\n }\n\n const tokens = new Set(\n lowered\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter((token) => token.length > 1)\n );\n setBoundedCache(rankingNameTokenCache, lowered, tokens);\n return tokens;\n}\n\nfunction chunkTypeBoost(chunkType: string): number {\n switch (chunkType) {\n case \"function\":\n case \"function_declaration\":\n case \"method\":\n case \"method_definition\":\n case \"class\":\n case \"class_declaration\":\n return 0.2;\n case \"interface\":\n case \"type\":\n case \"enum\":\n case \"struct\":\n case \"impl\":\n case \"trait\":\n case \"module\":\n return 0.1;\n default:\n return 0;\n }\n}\n\nfunction isTestOrDocPath(filePath: string): boolean {\n return TEST_PATH_SEGMENTS.some((segment) => filePath.includes(segment));\n}\n\nfunction isLikelyImplementationPath(filePath: string): boolean {\n const lowered = filePath.toLowerCase();\n if (IMPLEMENTATION_EXCLUDE_PATH_SEGMENTS.some((segment) => lowered.includes(segment))) {\n return false;\n }\n\n const ext = lowered.split(\".\").pop() ?? \"\";\n if ([\"md\", \"mdx\", \"txt\", \"rst\", \"adoc\", \"snap\", \"json\", \"yaml\", \"yml\", \"lock\"].includes(ext)) {\n return false;\n }\n\n return true;\n}\n\nfunction isDocumentationPath(filePath: string): boolean {\n const lowered = filePath.toLowerCase();\n const ext = lowered.split(\".\").pop() ?? \"\";\n return lowered.includes(\"readme\") || [\"md\", \"mdx\", \"rst\", \"adoc\", \"txt\"].includes(ext);\n}\n\nfunction classifyExternalRerankBand(\n candidate: RankedCandidate,\n preferSourcePaths: boolean,\n docIntent: boolean\n): ExternalRerankBand {\n const isDocOrTest = isTestOrDocPath(candidate.metadata.filePath);\n const isDocumentation = isDocumentationPath(candidate.metadata.filePath);\n const isImplementation = isLikelyImplementationPath(candidate.metadata.filePath) &&\n isImplementationChunkType(candidate.metadata.chunkType);\n\n if (preferSourcePaths) {\n if (isImplementation) return \"implementation\";\n if (isDocumentation) return \"documentation\";\n if (isDocOrTest) return \"test\";\n return \"other\";\n }\n\n if (docIntent) {\n if (isDocumentation) return \"documentation\";\n if (isImplementation) return \"implementation\";\n if (isDocOrTest) return \"test\";\n return \"other\";\n }\n\n if (isImplementation) return \"implementation\";\n if (isDocumentation) return \"documentation\";\n if (isDocOrTest) return \"test\";\n return \"other\";\n}\n\nfunction classifyQueryIntent(tokens: string[]): \"source\" | \"doc_test\" | \"neutral\" {\n const sourceIntentHits = tokens.filter((t) => SOURCE_INTENT_HINTS.has(t)).length;\n const docTestIntentHits = tokens.filter((t) => DOC_TEST_INTENT_HINTS.has(t)).length;\n\n if (sourceIntentHits === 0 && docTestIntentHits === 0) {\n return \"neutral\";\n }\n\n if (sourceIntentHits > docTestIntentHits) {\n return \"source\";\n }\n\n if (docTestIntentHits > sourceIntentHits) {\n return \"doc_test\";\n }\n\n return \"neutral\";\n}\n\nfunction classifyQueryIntentRaw(query: string): \"source\" | \"doc_test\" | \"neutral\" {\n const lowerQuery = query.toLowerCase();\n const docTestRawHits = Array.from(DOC_TEST_INTENT_HINTS).filter((hint) =>\n new RegExp(`\\\\b${hint}\\\\b`).test(lowerQuery)\n ).length;\n const sourceRawHits = [\n \"implement\",\n \"implementation\",\n \"implements\",\n \"function\",\n \"method\",\n \"class\",\n \"logic\",\n \"algorithm\",\n \"pipeline\",\n \"indexer\",\n ].filter((hint) => new RegExp(`\\\\b${hint}\\\\b`).test(lowerQuery)).length;\n\n if (docTestRawHits > sourceRawHits) {\n return \"doc_test\";\n }\n\n if (sourceRawHits > docTestRawHits && sourceRawHits > 0) {\n return \"source\";\n }\n\n const hasWhereIsPattern = /\\bwhere\\s+is\\b/.test(lowerQuery);\n const hasIdentifierHints = extractIdentifierHints(query).length > 0;\n if (hasWhereIsPattern && hasIdentifierHints && docTestRawHits === 0) {\n return \"source\";\n }\n\n const queryTokens = Array.from(tokenizeTextForRanking(query));\n return classifyQueryIntent(queryTokens);\n}\n\nfunction classifyDocIntent(tokens: string[]): \"docs\" | \"test\" | \"mixed\" | \"none\" {\n const docHits = tokens.filter((t) => DOC_INTENT_HINTS.has(t)).length;\n const testHits = tokens.filter((t) => [\"test\", \"tests\", \"fixture\", \"fixtures\", \"benchmark\"].includes(t)).length;\n\n if (docHits > 0 && testHits === 0) return \"docs\";\n if (testHits > 0 && docHits === 0) return \"test\";\n if (testHits > 0 || docHits > 0) return \"mixed\";\n return \"none\";\n}\n\nfunction isImplementationChunkType(chunkType: string): boolean {\n return [\n \"export_statement\",\n \"function\",\n \"function_declaration\",\n \"method\",\n \"method_definition\",\n \"class\",\n \"class_declaration\",\n \"interface\",\n \"type\",\n \"enum\",\n \"module\",\n ].includes(chunkType);\n}\n\nfunction extractIdentifierHints(query: string): string[] {\n const identifiers = query.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];\n return identifiers\n .filter((id) => id.length >= 3)\n .filter((id) => {\n const lower = id.toLowerCase();\n if (STOPWORDS.has(lower)) return false;\n return /[A-Z]/.test(id) || id.includes(\"_\") || id.endsWith(\"Results\") || id.endsWith(\"Result\");\n })\n .map((id) => id.toLowerCase());\n}\n\nfunction extractCodeTermHints(query: string): string[] {\n const terms = query.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];\n return terms\n .map((term) => term.toLowerCase())\n .filter((term) => term.length >= 3)\n .filter((term) => !STOPWORDS.has(term));\n}\n\nfunction normalizeIdentifierVariants(identifier: string): string[] {\n const lower = identifier.toLowerCase();\n const compact = lower.replace(/[^a-z0-9]/g, \"\");\n const snake = compact.replace(/([a-z])([A-Z])/g, \"$1_$2\").toLowerCase();\n const kebab = snake.replace(/_/g, \"-\");\n const variants = [lower, compact, snake, kebab].filter((value) => value.length > 0);\n return Array.from(new Set(variants));\n}\n\nfunction scoreIdentifierMatch(name: string | undefined, filePath: string, hints: string[]): number {\n const nameLower = (name ?? \"\").toLowerCase();\n const pathLower = filePath.toLowerCase();\n\n let best = 0;\n for (const hint of hints) {\n const variants = normalizeIdentifierVariants(hint);\n for (const variant of variants) {\n if (nameLower === variant) {\n best = Math.max(best, 1);\n } else if (nameLower.includes(variant)) {\n best = Math.max(best, 0.8);\n } else if (pathLower.includes(variant)) {\n best = Math.max(best, 0.6);\n }\n }\n }\n\n return best;\n}\n\nfunction extractPrimaryIdentifierQueryHint(query: string): string | null {\n const identifiers = extractIdentifierHints(query);\n if (identifiers.length > 0) {\n return identifiers[0] ?? null;\n }\n\n const codeTerms = extractCodeTermHints(query);\n const best = codeTerms.find((term) => term.length >= 6);\n return best ?? null;\n}\n\nconst FILE_PATH_HINT_EXTENSIONS = [\n \"ts\", \"tsx\", \"js\", \"jsx\", \"mjs\", \"cjs\", \"mts\", \"cts\",\n \"py\", \"rs\", \"go\", \"java\", \"kt\", \"kts\", \"swift\", \"rb\", \"php\",\n \"c\", \"h\", \"cc\", \"cpp\", \"cxx\", \"hpp\", \"cs\", \"scala\", \"lua\",\n \"sh\", \"bash\", \"zsh\", \"json\", \"yaml\", \"yml\", \"toml\",\n];\n\nconst FILE_PATH_HINT_SUFFIX_REGEX = new RegExp(\n \"\\\\s+\\\\bin\\\\s+[\\\"'`]?((?:\\\\.\\\\/)?(?:[A-Za-z0-9._-]+\\\\/)+[A-Za-z0-9._-]+\\\\.(?:\" +\n FILE_PATH_HINT_EXTENSIONS.join(\"|\") +\n \"))[\\\"'`]?[\\\\])}>.,;!?]*\\\\s*$\",\n \"i\"\n);\n\nfunction normalizeFilePathForHintMatch(filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\").toLowerCase().replace(/^\\.\\//, \"\");\n}\n\nfunction pathMatchesHint(filePath: string, hint: string): boolean {\n const normalizedPath = normalizeFilePathForHintMatch(filePath);\n const normalizedHint = normalizeFilePathForHintMatch(hint);\n\n return normalizedPath.endsWith(normalizedHint) ||\n normalizedPath.includes(`/${normalizedHint}`) ||\n normalizedPath.includes(normalizedHint);\n}\n\nexport function extractFilePathHint(query: string): string | null {\n const match = query.match(FILE_PATH_HINT_SUFFIX_REGEX);\n const rawPath = match?.[1];\n if (!rawPath) {\n return null;\n }\n\n return rawPath.replace(/^\\.\\//, \"\");\n}\n\nexport function stripFilePathHint(query: string): string {\n const stripped = query.replace(FILE_PATH_HINT_SUFFIX_REGEX, \"\").trim();\n return stripped.length > 0 ? stripped : query;\n}\n\nfunction buildDeterministicIdentifierPass(\n query: string,\n candidates: RankedCandidate[],\n limit: number,\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (!prioritizeSourcePaths) {\n return [];\n }\n\n const primary = extractPrimaryIdentifierQueryHint(query);\n if (!primary) {\n return [];\n }\n const filePathHint = extractFilePathHint(query);\n const primaryVariants = normalizeIdentifierVariants(primary);\n\n const hints = [primary, ...extractIdentifierHints(query), ...extractCodeTermHints(query)]\n .map((value) => value.toLowerCase())\n .filter((value, idx, arr) => value.length >= 3 && arr.indexOf(value) === idx)\n .slice(0, 8);\n\n const deterministic = candidates\n .filter((candidate) =>\n isLikelyImplementationPath(candidate.metadata.filePath) &&\n isImplementationChunkType(candidate.metadata.chunkType)\n )\n .map((candidate) => {\n const nameLower = (candidate.metadata.name ?? \"\").toLowerCase();\n const pathLower = candidate.metadata.filePath.toLowerCase();\n let maxMatch = 0;\n const nameMatchesPrimary = primaryVariants.some((variant) =>\n nameLower === variant || nameLower.replace(/[^a-z0-9]/g, \"\") === variant.replace(/[^a-z0-9]/g, \"\")\n );\n const pathMatchesFileHint = filePathHint ? pathMatchesHint(candidate.metadata.filePath, filePathHint) : false;\n\n for (const hint of hints) {\n const variants = normalizeIdentifierVariants(hint);\n for (const variant of variants) {\n if (nameLower === variant) {\n maxMatch = Math.max(maxMatch, 1);\n } else if (nameLower.includes(variant)) {\n maxMatch = Math.max(maxMatch, 0.85);\n } else if (pathLower.includes(variant)) {\n maxMatch = Math.max(maxMatch, 0.7);\n }\n }\n }\n\n if (pathMatchesFileHint && nameMatchesPrimary) {\n maxMatch = Math.max(maxMatch, 1);\n }\n\n return {\n candidate,\n maxMatch,\n pathMatchesFileHint,\n nameMatchesPrimary,\n };\n })\n .filter((entry) => entry.maxMatch >= 0.7)\n .sort((a, b) => {\n const aAnchored = a.pathMatchesFileHint && a.nameMatchesPrimary ? 1 : 0;\n const bAnchored = b.pathMatchesFileHint && b.nameMatchesPrimary ? 1 : 0;\n if (aAnchored !== bAnchored) return bAnchored - aAnchored;\n if (b.maxMatch !== a.maxMatch) return b.maxMatch - a.maxMatch;\n if (b.candidate.score !== a.candidate.score) return b.candidate.score - a.candidate.score;\n return a.candidate.id.localeCompare(b.candidate.id);\n })\n .slice(0, Math.max(limit * 2, 12));\n\n return deterministic.map((entry) => ({\n id: entry.candidate.id,\n score: entry.pathMatchesFileHint && entry.nameMatchesPrimary\n ? 0.995\n : Math.min(1, 0.9 + entry.maxMatch * 0.09),\n metadata: entry.candidate.metadata,\n }));\n}\n\nexport function fuseResultsWeighted(\n semanticResults: RankedCandidate[],\n keywordResults: RankedCandidate[],\n keywordWeight: number,\n limit: number\n): RankedCandidate[] {\n const semanticWeight = 1 - keywordWeight;\n const fusedScores = new Map<string, { score: number; metadata: ChunkMetadata }>();\n\n for (const r of semanticResults) {\n fusedScores.set(r.id, {\n score: r.score * semanticWeight,\n metadata: r.metadata,\n });\n }\n\n for (const r of keywordResults) {\n const existing = fusedScores.get(r.id);\n if (existing) {\n existing.score += r.score * keywordWeight;\n } else {\n fusedScores.set(r.id, {\n score: r.score * keywordWeight,\n metadata: r.metadata,\n });\n }\n }\n\n const results = Array.from(fusedScores.entries()).map(([id, data]) => ({\n id,\n score: data.score,\n metadata: data.metadata,\n }));\n\n results.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return results.slice(0, limit);\n}\n\nexport function fuseResultsRrf(\n semanticResults: RankedCandidate[],\n keywordResults: RankedCandidate[],\n rrfK: number,\n limit: number\n): RankedCandidate[] {\n const maxPossibleRaw = 2 / (rrfK + 1);\n const rankByIdSemantic = new Map<string, number>();\n const rankByIdKeyword = new Map<string, number>();\n const metadataById = new Map<string, ChunkMetadata>();\n\n semanticResults.forEach((result, index) => {\n rankByIdSemantic.set(result.id, index + 1);\n metadataById.set(result.id, result.metadata);\n });\n\n keywordResults.forEach((result, index) => {\n rankByIdKeyword.set(result.id, index + 1);\n if (!metadataById.has(result.id)) {\n metadataById.set(result.id, result.metadata);\n }\n });\n\n const allIds = new Set<string>([...rankByIdSemantic.keys(), ...rankByIdKeyword.keys()]);\n const fused: RankedCandidate[] = [];\n\n for (const id of allIds) {\n const semanticRank = rankByIdSemantic.get(id);\n const keywordRank = rankByIdKeyword.get(id);\n\n const semanticScore = semanticRank ? 1 / (rrfK + semanticRank) : 0;\n const keywordScore = keywordRank ? 1 / (rrfK + keywordRank) : 0;\n\n const metadata = metadataById.get(id);\n if (!metadata) continue;\n\n fused.push({\n id,\n score: maxPossibleRaw > 0 ? (semanticScore + keywordScore) / maxPossibleRaw : 0,\n metadata,\n });\n }\n\n fused.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return fused.slice(0, limit);\n}\n\nexport function rerankResults(\n query: string,\n candidates: RankedCandidate[],\n rerankTopN: number,\n options?: { prioritizeSourcePaths?: boolean }\n): RankedCandidate[] {\n if (rerankTopN <= 0 || candidates.length <= 1) {\n return candidates;\n }\n\n const topN = Math.min(rerankTopN, candidates.length);\n const queryTokens = tokenizeTextForRanking(query);\n if (queryTokens.size === 0) {\n return candidates;\n }\n\n const queryTokenList = Array.from(queryTokens);\n const docIntent = classifyDocIntent(queryTokenList);\n const preferSourcePaths = options?.prioritizeSourcePaths ?? classifyQueryIntentRaw(query) === \"source\";\n const identifierHints = extractIdentifierHints(query);\n\n const head = candidates.slice(0, topN).map((candidate, idx) => {\n const pathTokens = splitPathTokens(candidate.metadata.filePath);\n const nameTokens = splitNameTokens(candidate.metadata.name ?? \"\");\n const chunkTypeTokens = tokenizeTextForRanking(candidate.metadata.chunkType);\n let exactOrPrefixNameHits = 0;\n let pathOverlap = 0;\n let chunkTypeHits = 0;\n\n for (const token of queryTokenList) {\n if (nameTokens.has(token)) {\n exactOrPrefixNameHits += 1;\n } else {\n for (const nameToken of nameTokens) {\n if (nameToken.startsWith(token) || token.startsWith(nameToken)) {\n exactOrPrefixNameHits += 1;\n break;\n }\n }\n }\n\n if (pathTokens.has(token)) {\n pathOverlap += 1;\n }\n\n if (chunkTypeTokens.has(token)) {\n chunkTypeHits += 1;\n }\n }\n\n const likelyTestOrDoc = isTestOrDocPath(candidate.metadata.filePath);\n const lowerPath = candidate.metadata.filePath.toLowerCase();\n const lowerName = (candidate.metadata.name ?? \"\").toLowerCase();\n const hasIdentifierMatch = identifierHints.some((id) => lowerPath.includes(id) || lowerName.includes(id));\n\n const implementationPathBoost = preferSourcePaths && isLikelyImplementationPath(candidate.metadata.filePath) ? 0.08 : 0;\n const isReadmePath = candidate.metadata.filePath.toLowerCase().includes(\"readme\");\n const testDocPenalty = preferSourcePaths && likelyTestOrDoc ? 0.12 : 0;\n const readmeDocBoost = !preferSourcePaths && isReadmePath ? 0.08 : 0;\n const identifierBoost = hasIdentifierMatch ? 0.12 : 0;\n const tokenCoverage = queryTokenList.length > 0\n ? (exactOrPrefixNameHits + pathOverlap + chunkTypeHits) / queryTokenList.length\n : 0;\n const coverageBoost = Math.min(0.12, tokenCoverage * 0.06);\n\n const deterministicBoost =\n exactOrPrefixNameHits * 0.08 +\n pathOverlap * 0.03 +\n chunkTypeHits * 0.02 +\n coverageBoost +\n identifierBoost +\n implementationPathBoost -\n testDocPenalty +\n readmeDocBoost +\n chunkTypeBoost(candidate.metadata.chunkType);\n\n return {\n candidate,\n boostedScore: candidate.score + deterministicBoost,\n originalIndex: idx,\n hasIdentifierMatch,\n implementationChunk: isImplementationChunkType(candidate.metadata.chunkType),\n isLikelyImplementationPath: isLikelyImplementationPath(candidate.metadata.filePath),\n isTestOrDocPath: likelyTestOrDoc,\n isReadmePath,\n };\n });\n\n head.sort((a, b) => {\n if (b.boostedScore !== a.boostedScore) return b.boostedScore - a.boostedScore;\n if (b.candidate.score !== a.candidate.score) return b.candidate.score - a.candidate.score;\n if (a.originalIndex !== b.originalIndex) return a.originalIndex - b.originalIndex;\n return a.candidate.id.localeCompare(b.candidate.id);\n });\n\n if (preferSourcePaths) {\n head.sort((a, b) => {\n const aId = a.hasIdentifierMatch ? 1 : 0;\n const bId = b.hasIdentifierMatch ? 1 : 0;\n if (aId !== bId) return bId - aId;\n\n const aImpl = a.implementationChunk ? 1 : 0;\n const bImpl = b.implementationChunk ? 1 : 0;\n if (aImpl !== bImpl) return bImpl - aImpl;\n\n const aImplementationPath = a.isLikelyImplementationPath ? 1 : 0;\n const bImplementationPath = b.isLikelyImplementationPath ? 1 : 0;\n if (aImplementationPath !== bImplementationPath) return bImplementationPath - aImplementationPath;\n\n const aTestDoc = a.isTestOrDocPath ? 1 : 0;\n const bTestDoc = b.isTestOrDocPath ? 1 : 0;\n if (aTestDoc !== bTestDoc) return aTestDoc - bTestDoc;\n\n return 0;\n });\n } else if (docIntent === \"docs\") {\n head.sort((a, b) => {\n const aReadme = a.isReadmePath ? 1 : 0;\n const bReadme = b.isReadmePath ? 1 : 0;\n if (aReadme !== bReadme) return bReadme - aReadme;\n return 0;\n });\n }\n\n const shouldDiversify = !(preferSourcePaths && identifierHints.length > 0);\n const diversifiedHead = diversifyEntriesByFileAndSymbol(head, (entry) => entry.candidate, shouldDiversify);\n\n const tail = candidates.slice(topN);\n return [...diversifiedHead.map((entry) => entry.candidate), ...tail];\n}\n\nfunction diversifyEntriesByFileAndSymbol<T>(\n entries: T[],\n getCandidate: (entry: T) => RankedCandidate,\n enabled: boolean\n): T[] {\n if (!enabled || entries.length <= 2) {\n return entries;\n }\n\n const groups = new Map<string, T[]>();\n const groupOrder: string[] = [];\n\n for (const entry of entries) {\n const candidate = getCandidate(entry);\n const filePath = candidate.metadata.filePath;\n if (!groups.has(filePath)) {\n groups.set(filePath, []);\n groupOrder.push(filePath);\n }\n groups.get(filePath)?.push(entry);\n }\n\n const diversifiedGroups = groupOrder.map((filePath) => {\n const group = groups.get(filePath) ?? [];\n return diversifyGroupBySymbol(group, getCandidate);\n });\n\n const result: T[] = [];\n let added = true;\n let round = 0;\n while (added) {\n added = false;\n for (const group of diversifiedGroups) {\n const entry = group[round];\n if (entry !== undefined) {\n result.push(entry);\n added = true;\n }\n }\n round += 1;\n }\n\n return result;\n}\n\nfunction diversifyCandidatesByFile(candidates: RankedCandidate[], enabled: boolean): RankedCandidate[] {\n return diversifyEntriesByFileAndSymbol(candidates, (candidate) => candidate, enabled);\n}\n\nfunction diversifyGroupBySymbol<T>(\n entries: T[],\n getCandidate: (entry: T) => RankedCandidate\n): T[] {\n if (entries.length <= 2) {\n return entries;\n }\n\n const seenKeys = new Set<string>();\n const primary: T[] = [];\n const remainder: T[] = [];\n\n for (const entry of entries) {\n const key = buildDiversityKey(getCandidate(entry).metadata);\n if (!seenKeys.has(key)) {\n seenKeys.add(key);\n primary.push(entry);\n } else {\n remainder.push(entry);\n }\n }\n\n return [...primary, ...remainder];\n}\n\nfunction buildDiversityKey(metadata: ChunkMetadata): string {\n const normalizedPath = metadata.filePath.toLowerCase();\n const normalizedName = (metadata.name ?? \"\").trim().toLowerCase();\n if (normalizedName.length > 0) {\n return `${normalizedPath}#${normalizedName}`;\n }\n return normalizedPath;\n}\n\nexport function rankHybridResults(\n query: string,\n semanticResults: RankedCandidate[],\n keywordResults: RankedCandidate[],\n options: HybridRankOptions & { prioritizeSourcePaths?: boolean }\n): RankedCandidate[] {\n const prioritizeSourcePaths = options.prioritizeSourcePaths ?? classifyQueryIntentRaw(query) === \"source\";\n const cacheKey = `${query}\\u0001${options.fusionStrategy}|${options.rrfK}|${options.hybridWeight}|${options.rerankTopN}|${options.limit}|${prioritizeSourcePaths ? 1 : 0}`;\n\n let byKeyword = rankHybridResultsCache.get(semanticResults);\n if (!byKeyword) {\n byKeyword = new WeakMap<RankedCandidate[], Map<string, RankedCandidate[]>>();\n rankHybridResultsCache.set(semanticResults, byKeyword);\n }\n\n let bucket = byKeyword.get(keywordResults);\n if (!bucket) {\n bucket = new Map<string, RankedCandidate[]>();\n byKeyword.set(keywordResults, bucket);\n } else {\n const cached = bucket.get(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n const overfetchLimit = Math.max(options.limit * 4, options.limit);\n const fused = options.fusionStrategy === \"rrf\"\n ? fuseResultsRrf(semanticResults, keywordResults, options.rrfK, overfetchLimit)\n : fuseResultsWeighted(semanticResults, keywordResults, options.hybridWeight, overfetchLimit);\n\n const rerankPoolLimit = Math.max(overfetchLimit, options.rerankTopN * 3, options.limit * 6);\n const rerankPool = fused.slice(0, rerankPoolLimit);\n const ranked = rerankResults(query, rerankPool, options.rerankTopN, {\n prioritizeSourcePaths,\n });\n\n if (bucket.size >= RANK_HYBRID_CACHE_LIMIT) {\n const oldest = bucket.keys().next().value;\n if (oldest !== undefined) {\n bucket.delete(oldest);\n }\n }\n bucket.set(cacheKey, ranked);\n\n return ranked;\n}\n\nexport function rankSemanticOnlyResults(\n query: string,\n semanticResults: RankedCandidate[],\n options: SemanticRankOptions\n): RankedCandidate[] {\n const overfetchLimit = Math.max(options.limit * 4, options.limit);\n const bounded = semanticResults.slice(0, overfetchLimit);\n return rerankResults(query, bounded, options.rerankTopN, {\n prioritizeSourcePaths: options.prioritizeSourcePaths ?? false,\n });\n}\n\nfunction promoteIdentifierMatches(\n query: string,\n combined: RankedCandidate[],\n semanticCandidates: RankedCandidate[],\n keywordCandidates: RankedCandidate[],\n database?: Database,\n branchChunkIds?: Set<string> | null,\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (combined.length === 0) {\n return combined;\n }\n\n if (!prioritizeSourcePaths) {\n return combined;\n }\n\n const identifierHints = extractIdentifierHints(query);\n if (identifierHints.length === 0) {\n return combined;\n }\n\n const combinedById = new Map(combined.map((candidate) => [candidate.id, candidate]));\n const candidateUnion = new Map<string, RankedCandidate>();\n for (const candidate of semanticCandidates) {\n candidateUnion.set(candidate.id, candidate);\n }\n for (const candidate of keywordCandidates) {\n if (!candidateUnion.has(candidate.id)) {\n candidateUnion.set(candidate.id, candidate);\n }\n }\n\n if (database) {\n for (const identifier of identifierHints) {\n const symbols = database.getSymbolsByName(identifier);\n for (const symbol of symbols) {\n const chunks = database.getChunksByFile(symbol.filePath);\n for (const chunk of chunks) {\n if (branchChunkIds && !branchChunkIds.has(chunk.chunkId)) {\n continue;\n }\n\n const chunkType = ((chunk.nodeType ?? \"other\") as ChunkMetadata[\"chunkType\"]);\n if (!isImplementationChunkType(chunkType)) {\n continue;\n }\n\n if (!isLikelyImplementationPath(chunk.filePath)) {\n continue;\n }\n\n if (chunk.startLine > symbol.startLine || chunk.endLine < symbol.endLine) {\n continue;\n }\n\n const existing = combinedById.get(chunk.chunkId) ?? candidateUnion.get(chunk.chunkId);\n const metadata: ChunkMetadata = existing?.metadata ?? {\n filePath: chunk.filePath,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n chunkType,\n name: chunk.name ?? undefined,\n language: chunk.language,\n hash: chunk.contentHash,\n };\n\n const baselineScore = existing?.score ?? 0.5;\n candidateUnion.set(chunk.chunkId, {\n id: chunk.chunkId,\n score: Math.min(1, baselineScore + 0.5),\n metadata,\n });\n }\n }\n }\n }\n\n const promoted: RankedCandidate[] = [];\n for (const candidate of candidateUnion.values()) {\n const filePathLower = candidate.metadata.filePath.toLowerCase();\n const nameLower = (candidate.metadata.name ?? \"\").toLowerCase();\n const exactIdentifierMatch = identifierHints.some((hint) => nameLower === hint);\n const hasIdentifierMatch = exactIdentifierMatch || identifierHints.some((hint) =>\n nameLower.includes(hint) ||\n filePathLower.includes(hint)\n );\n\n if (!hasIdentifierMatch) {\n continue;\n }\n\n if (!isImplementationChunkType(candidate.metadata.chunkType)) {\n continue;\n }\n\n if (!isLikelyImplementationPath(candidate.metadata.filePath)) {\n continue;\n }\n\n const existing = combinedById.get(candidate.id) ?? candidate;\n const rescueBoost = exactIdentifierMatch ? 0.45 : 0.25;\n const boostedScore = Math.min(1, Math.max(existing.score, candidate.score) + rescueBoost);\n promoted.push({\n id: existing.id,\n score: boostedScore,\n metadata: existing.metadata,\n });\n }\n\n if (promoted.length === 0) {\n return combined;\n }\n\n promoted.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n\n const promotedIds = new Set(promoted.map((candidate) => candidate.id));\n const remainder = combined.filter((candidate) => !promotedIds.has(candidate.id));\n return [...promoted, ...remainder];\n}\n\nfunction buildSymbolDefinitionLane(\n query: string,\n database: Database,\n branchChunkIds: Set<string> | null,\n limit: number,\n fallbackCandidates: RankedCandidate[],\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (!prioritizeSourcePaths) {\n return [];\n }\n\n const identifierHints = extractIdentifierHints(query);\n const codeTermHints = extractCodeTermHints(query);\n if (identifierHints.length === 0 && codeTermHints.length === 0) {\n return [];\n }\n\n const symbolCandidates = new Map<string, RankedCandidate>();\n const filePathHint = extractFilePathHint(query);\n const primaryHint = extractPrimaryIdentifierQueryHint(query);\n\n const upsertChunkCandidate = (\n chunk: ReturnType<Database[\"getChunksByName\"]>[number],\n identifier: string,\n normalizedIdentifier: string,\n baseScore?: number\n ) => {\n if (branchChunkIds && !branchChunkIds.has(chunk.chunkId)) {\n return;\n }\n\n const chunkType = (chunk.nodeType ?? \"other\") as ChunkMetadata[\"chunkType\"];\n if (!isImplementationChunkType(chunkType)) {\n return;\n }\n\n if (!isLikelyImplementationPath(chunk.filePath)) {\n return;\n }\n\n const nameLower = (chunk.name ?? \"\").toLowerCase();\n const exactName =\n nameLower === identifier ||\n nameLower.replace(/_/g, \"\") === normalizedIdentifier;\n const base = baseScore ?? (exactName ? 0.99 : 0.88);\n\n const existing = symbolCandidates.get(chunk.chunkId);\n if (!existing || base > existing.score) {\n symbolCandidates.set(chunk.chunkId, {\n id: chunk.chunkId,\n score: base,\n metadata: {\n filePath: chunk.filePath,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n chunkType,\n name: chunk.name ?? undefined,\n language: chunk.language,\n hash: chunk.contentHash,\n },\n });\n }\n };\n\n const normalizedHints = identifierHints\n .flatMap((hint) => [\n hint,\n hint.replace(/_/g, \"\"),\n hint.replace(/_/g, \"-\")\n ])\n .filter((hint, idx, arr) => hint.length >= 3 && arr.indexOf(hint) === idx)\n .slice(0, 6);\n\n for (const identifier of normalizedHints) {\n const symbols = [\n ...database.getSymbolsByName(identifier),\n ...database.getSymbolsByNameCi(identifier),\n ];\n\n const chunksByName = [\n ...database.getChunksByName(identifier),\n ...database.getChunksByNameCi(identifier),\n ];\n\n const normalizedIdentifier = identifier.replace(/_/g, \"\");\n\n const dedupSymbols = new Map<string, typeof symbols[number]>();\n for (const symbol of symbols) {\n dedupSymbols.set(symbol.id, symbol);\n }\n\n for (const symbol of dedupSymbols.values()) {\n const chunks = database.getChunksByFile(symbol.filePath);\n for (const chunk of chunks) {\n if (chunk.startLine > symbol.startLine || chunk.endLine < symbol.endLine) {\n continue;\n }\n\n upsertChunkCandidate(chunk, identifier, normalizedIdentifier);\n }\n }\n\n const dedupChunksByName = new Map<string, typeof chunksByName[number]>();\n for (const chunk of chunksByName) {\n dedupChunksByName.set(chunk.chunkId, chunk);\n }\n\n for (const chunk of dedupChunksByName.values()) {\n upsertChunkCandidate(chunk, identifier, normalizedIdentifier);\n }\n }\n\n if (filePathHint && primaryHint) {\n const primaryChunks = [\n ...database.getChunksByName(primaryHint),\n ...database.getChunksByNameCi(primaryHint),\n ];\n const dedupPrimaryChunks = new Map<string, typeof primaryChunks[number]>();\n for (const chunk of primaryChunks) {\n dedupPrimaryChunks.set(chunk.chunkId, chunk);\n }\n\n for (const chunk of dedupPrimaryChunks.values()) {\n if (!pathMatchesHint(chunk.filePath, filePathHint)) {\n continue;\n }\n const normalizedPrimary = primaryHint.replace(/_/g, \"\");\n upsertChunkCandidate(chunk, primaryHint, normalizedPrimary, 1.0);\n }\n }\n\n const ranked = Array.from(symbolCandidates.values()).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n if (ranked.length === 0) {\n const implementationFallback = fallbackCandidates.filter((candidate) =>\n isImplementationChunkType(candidate.metadata.chunkType) &&\n isLikelyImplementationPath(candidate.metadata.filePath)\n );\n\n for (const candidate of implementationFallback) {\n const nameLower = (candidate.metadata.name ?? \"\").toLowerCase();\n const pathLower = candidate.metadata.filePath.toLowerCase();\n\n const exactHintMatch = normalizedHints.some((hint) => nameLower === hint || nameLower.replace(/_/g, \"\") === hint.replace(/_/g, \"\"));\n const tokenizedName = tokenizeTextForRanking(nameLower);\n const tokenHits = codeTermHints.filter((term) => tokenizedName.has(term) || pathLower.includes(term)).length;\n\n if (!exactHintMatch && tokenHits === 0) {\n continue;\n }\n\n const laneScore = exactHintMatch\n ? Math.min(1, Math.max(candidate.score, 0.97))\n : Math.min(0.95, Math.max(candidate.score, 0.82 + tokenHits * 0.03));\n symbolCandidates.set(candidate.id, {\n id: candidate.id,\n score: laneScore,\n metadata: candidate.metadata,\n });\n }\n\n if (symbolCandidates.size === 0) {\n const queryTokenSet = tokenizeTextForRanking(query);\n const rankedFallback = implementationFallback\n .map((candidate) => {\n const nameTokens = tokenizeTextForRanking(candidate.metadata.name ?? \"\");\n const pathTokens = splitPathTokens(candidate.metadata.filePath);\n let overlap = 0;\n for (const token of queryTokenSet) {\n if (nameTokens.has(token) || pathTokens.has(token)) {\n overlap += 1;\n }\n }\n const overlapScore = queryTokenSet.size > 0 ? overlap / queryTokenSet.size : 0;\n return {\n candidate,\n overlapScore,\n };\n })\n .filter((entry) => entry.overlapScore > 0)\n .sort((a, b) => b.overlapScore - a.overlapScore || b.candidate.score - a.candidate.score)\n .slice(0, Math.max(limit, 3));\n\n for (const entry of rankedFallback) {\n symbolCandidates.set(entry.candidate.id, {\n id: entry.candidate.id,\n score: Math.min(0.94, Math.max(entry.candidate.score, 0.8 + entry.overlapScore * 0.1)),\n metadata: entry.candidate.metadata,\n });\n }\n }\n }\n\n const withFallback = Array.from(symbolCandidates.values()).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return withFallback.slice(0, Math.max(limit * 2, limit));\n}\n\nfunction buildIdentifierDefinitionLane(\n query: string,\n candidates: RankedCandidate[],\n limit: number,\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (!prioritizeSourcePaths) {\n return [];\n }\n\n const primaryHint = extractPrimaryIdentifierQueryHint(query);\n if (!primaryHint) {\n return [];\n }\n\n const hints = [primaryHint, ...extractIdentifierHints(query), ...extractCodeTermHints(query)].slice(0, 8);\n const scored = candidates\n .filter((candidate) =>\n isLikelyImplementationPath(candidate.metadata.filePath) &&\n isImplementationChunkType(candidate.metadata.chunkType)\n )\n .map((candidate) => {\n const matchScore = scoreIdentifierMatch(candidate.metadata.name, candidate.metadata.filePath, hints);\n return {\n candidate,\n matchScore,\n };\n })\n .filter((entry) => entry.matchScore > 0)\n .sort((a, b) => {\n if (b.matchScore !== a.matchScore) return b.matchScore - a.matchScore;\n if (b.candidate.score !== a.candidate.score) return b.candidate.score - a.candidate.score;\n return a.candidate.id.localeCompare(b.candidate.id);\n })\n .slice(0, Math.max(limit * 2, 10));\n\n return scored.map((entry) => ({\n id: entry.candidate.id,\n score: Math.min(1, 0.9 + entry.matchScore * 0.09),\n metadata: entry.candidate.metadata,\n }));\n}\n\nexport function mergeTieredResults(\n symbolLane: RankedCandidate[],\n hybridLane: RankedCandidate[],\n limit: number\n): RankedCandidate[] {\n if (symbolLane.length === 0) {\n return hybridLane.slice(0, limit);\n }\n\n const out: RankedCandidate[] = [];\n const seen = new Set<string>();\n\n for (const candidate of symbolLane) {\n if (seen.has(candidate.id)) continue;\n out.push(candidate);\n seen.add(candidate.id);\n if (out.length >= limit) return out;\n }\n\n for (const candidate of hybridLane) {\n if (seen.has(candidate.id)) continue;\n out.push(candidate);\n seen.add(candidate.id);\n if (out.length >= limit) return out;\n }\n\n return out;\n}\n\nfunction matchesSearchFilters(\n candidate: RankedCandidate,\n options: {\n fileType?: string;\n directory?: string;\n chunkType?: string;\n } | undefined,\n minScore: number\n): boolean {\n if (candidate.score < minScore) return false;\n\n if (options?.fileType) {\n const ext = candidate.metadata.filePath.split(\".\").pop()?.toLowerCase();\n if (ext !== options.fileType.toLowerCase().replace(/^\\./, \"\")) return false;\n }\n\n if (options?.directory) {\n const normalizedDir = options.directory.replace(/^\\/|\\/$/g, \"\");\n if (!candidate.metadata.filePath.includes(`/${normalizedDir}/`) &&\n !candidate.metadata.filePath.includes(`${normalizedDir}/`)) return false;\n }\n\n if (options?.chunkType && candidate.metadata.chunkType !== options.chunkType) {\n return false;\n }\n\n return true;\n}\n\nfunction unionCandidates(\n semanticCandidates: RankedCandidate[],\n keywordCandidates: RankedCandidate[]\n): RankedCandidate[] {\n const byId = new Map<string, RankedCandidate>();\n for (const candidate of semanticCandidates) {\n byId.set(candidate.id, candidate);\n }\n for (const candidate of keywordCandidates) {\n const existing = byId.get(candidate.id);\n if (!existing || candidate.score > existing.score) {\n byId.set(candidate.id, candidate);\n }\n }\n return Array.from(byId.values());\n}\n\nexport class Indexer {\n private config: ParsedCodebaseIndexConfig;\n private projectRoot: string;\n private indexPath: string;\n private store: VectorStore | null = null;\n private invertedIndex: InvertedIndex | null = null;\n private database: Database | null = null;\n private provider: EmbeddingProviderInterface | null = null;\n private configuredProviderInfo: ConfiguredProviderInfo | null = null;\n private reranker: RerankerInterface | null = null;\n private fileHashCache: Map<string, string> = new Map();\n private fileHashCachePath: string = \"\";\n private failedBatchesPath: string = \"\";\n private currentBranch: string = \"default\";\n private baseBranch: string = \"main\";\n private logger: Logger;\n private queryEmbeddingCache: Map<string, { embedding: number[]; timestamp: number }> = new Map();\n private readonly maxQueryCacheSize = 100;\n private readonly queryCacheTtlMs = 5 * 60 * 1000;\n private readonly querySimilarityThreshold = 0.85;\n private indexCompatibility: IndexCompatibility | null = null;\n private indexingLockPath: string = \"\";\n\n constructor(projectRoot: string, config: ParsedCodebaseIndexConfig) {\n this.projectRoot = projectRoot;\n this.config = config;\n this.indexPath = this.getIndexPath();\n this.fileHashCachePath = path.join(this.indexPath, \"file-hashes.json\");\n this.failedBatchesPath = path.join(this.indexPath, \"failed-batches.json\");\n this.indexingLockPath = path.join(this.indexPath, \"indexing.lock\");\n this.logger = initializeLogger(config.debug);\n }\n\n private getIndexPath(): string {\n return resolveProjectIndexPath(this.projectRoot, this.config.scope);\n }\n\n private loadFileHashCache(): void {\n if (!existsSync(this.fileHashCachePath)) {\n return;\n }\n\n try {\n const data = readFileSync(this.fileHashCachePath, \"utf-8\");\n const parsed = JSON.parse(data);\n this.fileHashCache = new Map(Object.entries(parsed));\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.warn(\"Failed to load file hash cache, resetting cache state\", {\n fileHashCachePath: this.fileHashCachePath,\n error: message,\n });\n this.fileHashCache = new Map();\n }\n }\n\n private saveFileHashCache(): void {\n const obj: Record<string, string> = {};\n for (const [k, v] of this.fileHashCache) {\n obj[k] = v;\n }\n this.atomicWriteSync(this.fileHashCachePath, JSON.stringify(obj));\n }\n\n private atomicWriteSync(targetPath: string, data: string): void {\n const tempPath = `${targetPath}.tmp`;\n mkdirSync(path.dirname(targetPath), { recursive: true });\n writeFileSync(tempPath, data);\n renameSync(tempPath, targetPath);\n }\n\n private getScopedRoots(): string[] {\n const roots = new Set<string>([path.resolve(this.projectRoot)]);\n\n for (const kbRoot of this.config.knowledgeBases) {\n roots.add(path.resolve(this.projectRoot, kbRoot));\n }\n\n return Array.from(roots);\n }\n\n private getBranchCatalogKey(): string {\n const branchName = this.currentBranch || \"default\";\n if (this.config.scope !== \"global\") {\n return branchName;\n }\n\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `${projectHash}:${branchName}`;\n }\n\n private getLegacyBranchCatalogKey(): string {\n return this.currentBranch || \"default\";\n }\n\n private getLegacyMigrationMetadataKey(): string {\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `index.globalBranchMigration.${projectHash}`;\n }\n\n private getProjectEmbeddingStrategyMetadataKey(): string {\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `index.embeddingStrategyVersion.${projectHash}`;\n }\n\n private getProjectForceReembedMetadataKey(): string {\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `index.forceReembed.${projectHash}`;\n }\n\n private hasProjectForceReembedPending(): boolean {\n return this.config.scope === \"global\" && this.database?.getMetadata(this.getProjectForceReembedMetadataKey()) === \"true\";\n }\n\n private hasScopedIndexedData(): boolean {\n if (!this.store || this.config.scope !== \"global\") {\n return false;\n }\n\n if (this.hasProjectForceReembedPending()) {\n return false;\n }\n\n const roots = this.getScopedRoots();\n\n if (Array.from(this.fileHashCache.keys()).some((filePath) => this.isFileInCurrentScope(filePath, roots))) {\n return true;\n }\n\n if (this.loadSerializedFailedBatches().some((batch) =>\n batch.chunks.some((chunk) => {\n const filePath = getPendingChunkFilePath(chunk);\n return filePath !== null && this.isFileInCurrentScope(filePath, roots);\n })\n )) {\n return true;\n }\n\n if (!this.database) {\n return false;\n }\n\n if (this.getBranchCatalogKeys().some((branchKey) => {\n const branchChunkIds = this.database!.getBranchChunkIds(branchKey);\n if (branchChunkIds.length > 0) {\n return true;\n }\n\n return this.database!.getBranchSymbolIds(branchKey).length > 0;\n })) {\n return true;\n }\n\n const hasAnyBranchRows = this.database.getAllBranches().some((branchKey) => {\n const branchChunkIds = this.database!.getBranchChunkIds(branchKey);\n if (branchChunkIds.length > 0) {\n return true;\n }\n\n return this.database!.getBranchSymbolIds(branchKey).length > 0;\n });\n if (hasAnyBranchRows) {\n return false;\n }\n\n return this.store.getAllMetadata().some(({ metadata }) => this.isFileInCurrentScope(metadata.filePath, roots));\n }\n\n private loadStoredEmbeddingStrategyVersion(): string | null {\n if (!this.database) {\n return null;\n }\n\n if (this.hasProjectForceReembedPending()) {\n return null;\n }\n\n if (this.config.scope !== \"global\") {\n return this.database.getMetadata(\"index.embeddingStrategyVersion\") ?? \"1\";\n }\n\n const projectVersion = this.database.getMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n if (projectVersion) {\n return projectVersion;\n }\n\n const legacySharedVersion = this.database.getMetadata(\"index.embeddingStrategyVersion\");\n if (legacySharedVersion && this.hasScopedIndexedData()) {\n return legacySharedVersion;\n }\n\n return null;\n }\n\n private getBranchCatalogKeys(): string[] {\n const primary = this.getBranchCatalogKey();\n if (this.config.scope !== \"global\") {\n return [primary];\n }\n\n if (this.database?.getMetadata(this.getLegacyMigrationMetadataKey()) === \"done\") {\n return [primary];\n }\n\n const legacy = this.getLegacyBranchCatalogKey();\n return primary === legacy ? [primary] : [primary, legacy];\n }\n\n private getBranchCatalogCleanupKeys(): string[] {\n const primary = this.getBranchCatalogKey();\n if (this.config.scope !== \"global\") {\n return [primary];\n }\n\n const legacy = this.getLegacyBranchCatalogKey();\n return primary === legacy ? [primary] : [primary, legacy];\n }\n\n private getProjectLocalScopedOwnershipIds(roots: string[]): {\n chunkIds: Set<string>;\n symbolIds: Set<string>;\n } {\n const chunkIds = new Set<string>();\n const symbolIds = new Set<string>();\n if (!this.database) {\n return { chunkIds, symbolIds };\n }\n\n const projectRootPath = path.resolve(this.projectRoot);\n const projectLocalFilePaths = new Set<string>([\n ...Array.from(this.fileHashCache.keys()).filter(\n (filePath) => this.isFileInCurrentScope(filePath, roots) && isPathWithinRoot(filePath, projectRootPath)\n ),\n ...(this.store?.getAllMetadata() ?? [])\n .map(({ metadata }) => metadata.filePath)\n .filter(\n (filePath) => this.isFileInCurrentScope(filePath, roots) && isPathWithinRoot(filePath, projectRootPath)\n ),\n ]);\n\n for (const filePath of projectLocalFilePaths) {\n for (const chunk of this.database.getChunksByFile(filePath)) {\n chunkIds.add(chunk.chunkId);\n }\n\n for (const symbol of this.database.getSymbolsByFile(filePath)) {\n symbolIds.add(symbol.id);\n }\n }\n\n return { chunkIds, symbolIds };\n }\n\n private getProjectScopedBranchCatalogCleanupKeys(projectChunkIds: string[], projectSymbolIds: string[]): string[] {\n if (this.config.scope !== \"global\") {\n return this.getBranchCatalogCleanupKeys();\n }\n\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n const keys = new Set<string>();\n const projectChunkIdSet = new Set(projectChunkIds);\n const projectSymbolIdSet = new Set(projectSymbolIds);\n\n for (const branchKey of this.database?.getAllBranches() ?? []) {\n if (branchKey.startsWith(`${projectHash}:`)) {\n keys.add(branchKey);\n continue;\n }\n\n if (branchKey.includes(\":\")) {\n continue;\n }\n\n const referencesProjectChunks = this.database?.getBranchChunkIds(branchKey).some((chunkId) => projectChunkIdSet.has(chunkId)) ?? false;\n const referencesProjectSymbols = this.database?.getBranchSymbolIds(branchKey).some((symbolId) => projectSymbolIdSet.has(symbolId)) ?? false;\n if (referencesProjectChunks || referencesProjectSymbols) {\n keys.add(branchKey);\n }\n }\n\n for (const branchKey of this.getBranchCatalogCleanupKeys()) {\n keys.add(branchKey);\n }\n\n return Array.from(keys);\n }\n\n private isFileInCurrentScope(filePath: string, roots: string[]): boolean {\n return roots.some((root) => isPathWithinRoot(filePath, root));\n }\n\n private clearScopedFileHashCache(roots: string[]): void {\n for (const filePath of Array.from(this.fileHashCache.keys())) {\n if (this.isFileInCurrentScope(filePath, roots)) {\n this.fileHashCache.delete(filePath);\n }\n }\n this.saveFileHashCache();\n }\n\n private replaceScopedFileHashCache(currentFileHashes: Map<string, string>, roots: string[]): void {\n for (const filePath of Array.from(this.fileHashCache.keys())) {\n if (this.isFileInCurrentScope(filePath, roots)) {\n this.fileHashCache.delete(filePath);\n }\n }\n\n for (const [filePath, hash] of currentFileHashes) {\n this.fileHashCache.set(filePath, hash);\n }\n\n this.saveFileHashCache();\n }\n\n private partitionFailedBatches(roots: string[], maxChunkTokens?: number): { scoped: FailedBatch[]; retained: SerializedFailedBatch[] } {\n const scoped: FailedBatch[] = [];\n const retained: SerializedFailedBatch[] = [];\n\n for (const batch of this.loadSerializedFailedBatches()) {\n const scopedChunks = batch.chunks.filter((chunk) => {\n const filePath = getPendingChunkFilePath(chunk);\n return filePath !== null && this.isFileInCurrentScope(filePath, roots);\n });\n const retainedChunks = batch.chunks.filter((chunk) => {\n const filePath = getPendingChunkFilePath(chunk);\n return filePath === null || !this.isFileInCurrentScope(filePath, roots);\n });\n\n if (scopedChunks.length > 0) {\n const normalizedBatch = normalizeFailedBatch({ ...batch, chunks: scopedChunks }, maxChunkTokens);\n if (normalizedBatch) {\n scoped.push(normalizedBatch);\n }\n }\n\n if (retainedChunks.length > 0) {\n retained.push({ ...batch, chunks: retainedChunks });\n }\n }\n\n return { scoped, retained };\n }\n\n private clearScopedFailedBatches(roots: string[]): void {\n const { retained: retainedBatches } = this.partitionFailedBatches(roots);\n this.saveFailedBatches(retainedBatches);\n }\n\n private hasForeignScopedFileHashData(roots: string[]): boolean {\n return Array.from(this.fileHashCache.keys()).some((filePath) => !this.isFileInCurrentScope(filePath, roots));\n }\n\n private hasForeignScopedFailedBatches(roots: string[]): boolean {\n const { retained } = this.partitionFailedBatches(roots);\n return retained.length > 0;\n }\n\n private hasForeignScopedBranchData(): boolean {\n if (!this.database || this.config.scope !== \"global\") {\n return false;\n }\n\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n const roots = this.getScopedRoots();\n const { chunkIds: projectLocalChunkIds, symbolIds: projectLocalSymbolIds } = this.getProjectLocalScopedOwnershipIds(roots);\n\n return this.database.getAllBranches().some(\n (branchKey) => {\n const branchChunkIds = this.database!.getBranchChunkIds(branchKey);\n const branchSymbolIds = this.database!.getBranchSymbolIds(branchKey);\n const hasBranchData = branchChunkIds.length > 0 || branchSymbolIds.length > 0;\n if (!hasBranchData) {\n return false;\n }\n\n if (branchKey.startsWith(`${projectHash}:`)) {\n return false;\n }\n\n if (!branchKey.includes(\":\")) {\n const referencesCurrentProjectChunks = branchChunkIds.some((chunkId) => projectLocalChunkIds.has(chunkId));\n const referencesCurrentProjectSymbols = branchSymbolIds.some((symbolId) => projectLocalSymbolIds.has(symbolId));\n return !(referencesCurrentProjectChunks || referencesCurrentProjectSymbols);\n }\n\n return true;\n }\n );\n }\n\n private saveScopedFailedBatches(batches: FailedBatch[], roots: string[]): void {\n const { retained } = this.partitionFailedBatches(roots);\n this.saveFailedBatches([...retained, ...batches]);\n }\n\n private clearSharedIndexProjectData(\n store: VectorStore,\n invertedIndex: InvertedIndex,\n database: Database,\n roots: string[]\n ): { removedChunkIds: string[]; hasForeignData: boolean } {\n const allMetadata = store.getAllMetadata();\n const scopedEntries = allMetadata.filter(({ metadata }) => this.isFileInCurrentScope(metadata.filePath, roots));\n const filePaths = new Set<string>([\n ...Array.from(this.fileHashCache.keys()).filter((filePath) => this.isFileInCurrentScope(filePath, roots)),\n ...scopedEntries.map(({ metadata }) => metadata.filePath),\n ]);\n\n const projectRootPath = path.resolve(this.projectRoot);\n const projectLocalFilePaths = new Set<string>(\n Array.from(filePaths).filter((filePath) => isPathWithinRoot(filePath, projectRootPath))\n );\n\n const removedChunkIds = new Set<string>(scopedEntries.map(({ key }) => key));\n for (const filePath of filePaths) {\n for (const chunk of database.getChunksByFile(filePath)) {\n removedChunkIds.add(chunk.chunkId);\n }\n }\n const removedChunkIdList = Array.from(removedChunkIds);\n\n const projectLocalChunkIds = new Set<string>(\n scopedEntries\n .filter(({ metadata }) => isPathWithinRoot(metadata.filePath, projectRootPath))\n .map(({ key }) => key)\n );\n for (const filePath of projectLocalFilePaths) {\n for (const chunk of database.getChunksByFile(filePath)) {\n projectLocalChunkIds.add(chunk.chunkId);\n }\n }\n\n const symbolIds: string[] = [];\n const projectLocalSymbolIds = new Set<string>();\n for (const filePath of filePaths) {\n for (const symbol of database.getSymbolsByFile(filePath)) {\n symbolIds.push(symbol.id);\n if (projectLocalFilePaths.has(filePath)) {\n projectLocalSymbolIds.add(symbol.id);\n }\n }\n }\n\n for (const branchKey of this.getProjectScopedBranchCatalogCleanupKeys(Array.from(projectLocalChunkIds), Array.from(projectLocalSymbolIds))) {\n database.deleteBranchChunksForBranch(branchKey, removedChunkIdList);\n }\n const sharedChunkIds = new Set(database.getReferencedChunkIds(removedChunkIdList));\n const removableChunkIds = removedChunkIdList.filter((chunkId) => !sharedChunkIds.has(chunkId));\n\n if (removableChunkIds.length > 0) {\n this.rebuildVectorStoreExcludingChunkIds(store, database, removableChunkIds);\n for (const chunkId of removableChunkIds) {\n invertedIndex.removeChunk(chunkId);\n }\n }\n\n for (const branchKey of this.getProjectScopedBranchCatalogCleanupKeys(Array.from(projectLocalChunkIds), Array.from(projectLocalSymbolIds))) {\n database.deleteBranchSymbolsForBranch(branchKey, symbolIds);\n }\n const sharedSymbolIds = new Set(database.getReferencedSymbolIds(symbolIds));\n const removableSymbolIds = symbolIds.filter((symbolId) => !sharedSymbolIds.has(symbolId));\n\n database.clearCallEdgeTargetsForSymbols(removableSymbolIds);\n\n for (const filePath of filePaths) {\n const fileChunkIds = database.getChunksByFile(filePath).map((chunk) => chunk.chunkId);\n const fileSymbols = database.getSymbolsByFile(filePath);\n\n if (fileChunkIds.every((chunkId) => !sharedChunkIds.has(chunkId))) {\n database.deleteChunksByFile(filePath);\n }\n\n if (fileSymbols.every((symbol) => !sharedSymbolIds.has(symbol.id))) {\n database.deleteCallEdgesByFile(filePath);\n database.deleteSymbolsByFile(filePath);\n }\n }\n\n database.gcOrphanCallEdges();\n database.gcOrphanSymbols();\n database.gcOrphanEmbeddings();\n database.gcOrphanChunks();\n\n store.save();\n invertedIndex.save();\n\n return {\n removedChunkIds: removedChunkIdList,\n hasForeignData: allMetadata.some(({ metadata }) => !this.isFileInCurrentScope(metadata.filePath, roots)),\n };\n }\n\n private checkForInterruptedIndexing(): boolean {\n return existsSync(this.indexingLockPath);\n }\n\n private acquireIndexingLock(): void {\n const lockData = {\n startedAt: new Date().toISOString(),\n pid: process.pid,\n };\n writeFileSync(this.indexingLockPath, JSON.stringify(lockData));\n }\n\n private releaseIndexingLock(): void {\n if (existsSync(this.indexingLockPath)) {\n unlinkSync(this.indexingLockPath);\n }\n }\n\n private async recoverFromInterruptedIndexing(): Promise<void> {\n this.logger.warn(\"Detected interrupted indexing session, recovering...\");\n\n if (existsSync(this.fileHashCachePath)) {\n unlinkSync(this.fileHashCachePath);\n }\n\n await this.healthCheck();\n this.releaseIndexingLock();\n\n this.logger.info(\"Recovery complete, next index will re-process all files\");\n }\n\n private loadFailedBatches(maxChunkTokens?: number): FailedBatch[] {\n try {\n return this.loadSerializedFailedBatches()\n .map((batch) => normalizeFailedBatch(batch, maxChunkTokens))\n .filter((batch): batch is FailedBatch => batch !== null);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.warn(\"Failed to load failed batch state, skipping persisted retries\", {\n failedBatchesPath: this.failedBatchesPath,\n error: message,\n });\n return [];\n }\n }\n\n private loadSerializedFailedBatches(): SerializedFailedBatch[] {\n if (!existsSync(this.failedBatchesPath)) {\n return [];\n }\n\n const data = readFileSync(this.failedBatchesPath, \"utf-8\");\n const parsed = JSON.parse(data) as Array<{\n chunks?: unknown[];\n error?: unknown;\n attemptCount?: unknown;\n lastAttempt?: unknown;\n }>;\n\n return parsed\n .map((batch) => {\n const chunks = Array.isArray(batch.chunks) ? batch.chunks : [];\n if (chunks.length === 0) {\n return null;\n }\n\n return {\n chunks,\n error: typeof batch.error === \"string\" ? batch.error : \"Unknown embedding error\",\n attemptCount: typeof batch.attemptCount === \"number\" ? batch.attemptCount : 1,\n lastAttempt: typeof batch.lastAttempt === \"string\" ? batch.lastAttempt : new Date().toISOString(),\n } satisfies SerializedFailedBatch;\n })\n .filter((batch): batch is SerializedFailedBatch => batch !== null);\n }\n\n private saveFailedBatches(batches: SerializedFailedBatch[]): void {\n if (batches.length === 0) {\n if (existsSync(this.failedBatchesPath)) {\n try {\n unlinkSync(this.failedBatchesPath);\n } catch {\n // Ignore cleanup failures; stale diagnostics are best-effort only.\n }\n }\n return;\n }\n writeFileSync(this.failedBatchesPath, JSON.stringify(batches, null, 2));\n }\n\n private collectRetryableFailedChunks(\n currentFileHashes: Map<string, string>,\n unchangedFilePaths: Set<string>,\n maxChunkTokens?: number\n ): RetryableFailedChunk[] {\n const retryableById = new Map<string, RetryableFailedChunk>();\n\n for (const batch of this.loadFailedBatches(maxChunkTokens)) {\n for (const chunk of batch.chunks) {\n const filePath = chunk.metadata.filePath;\n if (!currentFileHashes.has(filePath)) {\n continue;\n }\n if (!unchangedFilePaths.has(filePath)) {\n continue;\n }\n\n const existing = retryableById.get(chunk.id);\n if (!existing || batch.attemptCount > existing.attemptCount) {\n retryableById.set(chunk.id, {\n chunk,\n attemptCount: batch.attemptCount,\n });\n }\n }\n }\n\n return Array.from(retryableById.values());\n }\n\n private getProviderRateLimits(provider: string): {\n concurrency: number;\n intervalMs: number;\n minRetryMs: number;\n maxRetryMs: number;\n } {\n switch (provider) {\n case \"github-copilot\":\n return { concurrency: 1, intervalMs: 4000, minRetryMs: 5000, maxRetryMs: 60000 };\n case \"openai\":\n return { concurrency: 3, intervalMs: 500, minRetryMs: 1000, maxRetryMs: 30000 };\n case \"google\":\n return { concurrency: 5, intervalMs: 200, minRetryMs: 1000, maxRetryMs: 30000 };\n case \"ollama\":\n return { concurrency: 5, intervalMs: 0, minRetryMs: 500, maxRetryMs: 5000 };\n case \"custom\": {\n // Custom providers allow user-configurable concurrency and request interval.\n // Defaults are conservative (3 concurrent, 1s interval) for cloud endpoints;\n // users running local servers should set concurrency higher and intervalMs to 0.\n const customConfig = this.config.customProvider;\n return {\n concurrency: customConfig?.concurrency ?? 3,\n intervalMs: customConfig?.requestIntervalMs ?? 1000,\n minRetryMs: 1000,\n maxRetryMs: 30000,\n };\n }\n default:\n return { concurrency: 3, intervalMs: 1000, minRetryMs: 1000, maxRetryMs: 30000 };\n }\n }\n\n private async rerankCandidatesWithApi(\n query: string,\n candidates: RankedCandidate[],\n options?: {\n definitionIntent?: boolean;\n hasIdentifierHints?: boolean;\n }\n ): Promise<RankedCandidate[]> {\n const reranker = this.config.reranker;\n if (!reranker || !reranker.enabled || candidates.length <= 1) {\n return candidates;\n }\n\n const queryTokens = Array.from(tokenizeTextForRanking(query));\n const preferSourcePaths = classifyQueryIntentRaw(query) === \"source\";\n const docIntent = classifyDocIntent(queryTokens) === \"docs\";\n\n if (options?.definitionIntent === true) {\n return candidates;\n }\n\n if (options?.hasIdentifierHints === true && preferSourcePaths && !docIntent) {\n return candidates;\n }\n\n const topN = Math.min(reranker.topN, candidates.length);\n const head = candidates.slice(0, topN);\n const tail = candidates.slice(topN);\n const grouped = new Map<ExternalRerankBand, RankedCandidate[]>([\n [\"implementation\", []],\n [\"documentation\", []],\n [\"test\", []],\n [\"other\", []],\n ]);\n\n for (const candidate of head) {\n const band = classifyExternalRerankBand(candidate, preferSourcePaths, docIntent);\n grouped.get(band)?.push(candidate);\n }\n\n const orderedBands: ExternalRerankBand[] = preferSourcePaths\n ? [\"implementation\", \"other\", \"documentation\", \"test\"]\n : docIntent\n ? [\"documentation\", \"implementation\", \"other\", \"test\"]\n : [\"implementation\", \"other\", \"documentation\", \"test\"];\n\n try {\n const rerankedHead: RankedCandidate[] = [];\n for (const band of orderedBands) {\n const bandCandidates = grouped.get(band) ?? [];\n if (bandCandidates.length <= 1) {\n rerankedHead.push(...bandCandidates);\n continue;\n }\n\n const documents = await Promise.all(\n bandCandidates.map(async (candidate) => ({\n id: candidate.id,\n text: await this.createRerankerDocumentText(candidate),\n }))\n );\n const rankedIds = await this.callExternalReranker(query, documents, reranker);\n if (rankedIds.length === 0) {\n rerankedHead.push(...bandCandidates);\n continue;\n }\n\n const order = new Map(rankedIds.map((id, index) => [id, index]));\n const bandReranked = [...bandCandidates].sort((a, b) => {\n const aRank = order.get(a.id) ?? Number.MAX_SAFE_INTEGER;\n const bRank = order.get(b.id) ?? Number.MAX_SAFE_INTEGER;\n if (aRank !== bRank) {\n return aRank - bRank;\n }\n if (b.score !== a.score) {\n return b.score - a.score;\n }\n return a.id.localeCompare(b.id);\n });\n const shouldDiversifyBand = !options?.hasIdentifierHints;\n rerankedHead.push(...diversifyCandidatesByFile(bandReranked, shouldDiversifyBand));\n }\n\n this.logger.search(\"debug\", \"Applied external reranker\", {\n provider: reranker.provider,\n model: reranker.model,\n candidateCount: head.length,\n bands: orderedBands,\n });\n\n return [...rerankedHead, ...tail];\n } catch (error) {\n this.logger.search(\"warn\", \"External reranker failed; using deterministic order\", {\n provider: reranker.provider,\n model: reranker.model,\n error: getErrorMessage(error),\n });\n return candidates;\n }\n }\n\n private async callExternalReranker(\n query: string,\n documents: RerankDocumentPayload[],\n reranker: RerankerConfig\n ): Promise<string[]> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (reranker.apiKey) {\n headers.Authorization = `Bearer ${reranker.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), reranker.timeoutMs);\n try {\n const response = await fetch(`${reranker.baseUrl}/rerank`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model: reranker.model,\n query,\n documents: documents.map((document) => document.text),\n top_n: documents.length,\n return_documents: false,\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Reranker API error: ${response.status} - ${await response.text()}`);\n }\n\n const body = await response.json() as {\n results?: Array<{ index?: number; relevance_score?: number }>;\n };\n if (!Array.isArray(body.results)) {\n throw new Error(\"Reranker API returned unexpected response format.\");\n }\n\n return body.results\n .map((result) => {\n const index = typeof result.index === \"number\" ? result.index : -1;\n return documents[index]?.id;\n })\n .filter((id): id is string => typeof id === \"string\");\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Reranker request timed out after ${reranker.timeoutMs}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async createRerankerDocumentText(candidate: RankedCandidate): Promise<string> {\n const parts = [\n `path: ${candidate.metadata.filePath}`,\n `chunk_type: ${candidate.metadata.chunkType}`,\n `language: ${candidate.metadata.language}`,\n `lines: ${candidate.metadata.startLine}-${candidate.metadata.endLine}`,\n ];\n\n if (candidate.metadata.name) {\n parts.push(`name: ${candidate.metadata.name}`);\n }\n\n const intent = isLikelyImplementationPath(candidate.metadata.filePath) ? \"implementation\" : \"doc_or_test\";\n parts.push(`intent_hint: ${intent}`);\n\n try {\n const fileContent = await fsPromises.readFile(candidate.metadata.filePath, \"utf-8\");\n const lines = fileContent.split(\"\\n\");\n const snippetStartLine = Math.max(1, candidate.metadata.startLine - 2);\n const snippetEndLine = Math.min(lines.length, candidate.metadata.endLine + 2);\n const snippet = lines.slice(snippetStartLine - 1, snippetEndLine).join(\"\\n\").trim();\n parts.push(\"snippet:\");\n parts.push(snippet.length > 0 ? snippet : \"[empty]\");\n } catch {\n parts.push(\"snippet:\");\n parts.push(\"[unavailable]\");\n }\n\n return parts.join(\"\\n\");\n }\n\n async initialize(): Promise<void> {\n if (this.config.embeddingProvider === 'custom') {\n if (!this.config.customProvider) {\n throw new Error(\"embeddingProvider is 'custom' but customProvider config is missing.\");\n }\n this.configuredProviderInfo = createCustomProviderInfo(this.config.customProvider);\n } else if (this.config.embeddingProvider === 'auto') {\n this.configuredProviderInfo = await tryDetectProvider();\n } else {\n this.configuredProviderInfo = await detectEmbeddingProvider(this.config.embeddingProvider, this.config.embeddingModel);\n }\n\n if (!this.configuredProviderInfo) {\n throw new Error(\n \"No embedding provider available. Configure GitHub Copilot, OpenAI, Google, Ollama, or a custom OpenAI-compatible endpoint.\"\n );\n }\n\n this.logger.info(\"Initializing indexer\", {\n provider: this.configuredProviderInfo.provider,\n model: this.configuredProviderInfo.modelInfo.model,\n scope: this.config.scope,\n rerankerEnabled: this.config.reranker?.enabled ?? false,\n });\n\n this.provider = createEmbeddingProvider(this.configuredProviderInfo);\n\n if (this.config.reranker?.enabled) {\n this.reranker = createReranker(this.config.reranker);\n if (this.reranker.isAvailable()) {\n this.logger.info(\"Reranker initialized\", {\n model: this.config.reranker.model,\n baseUrl: this.config.reranker.baseUrl,\n });\n }\n }\n\n await fsPromises.mkdir(this.indexPath, { recursive: true });\n\n // NOTE: Interrupted indexing recovery is deferred until after store,\n // invertedIndex, and database are initialized (see below). Running it here\n // would cause infinite recursion: recovery → healthCheck → ensureInitialized\n // → initialize (store not yet set) → recovery → ...\n\n const dimensions = this.configuredProviderInfo.modelInfo.dimensions;\n const storePath = path.join(this.indexPath, \"vectors\");\n this.store = new VectorStore(storePath, dimensions);\n\n const indexFilePath = path.join(this.indexPath, \"vectors.usearch\");\n if (existsSync(indexFilePath)) {\n this.store.load();\n }\n\n const invertedIndexPath = path.join(this.indexPath, \"inverted-index.json\");\n this.invertedIndex = new InvertedIndex(invertedIndexPath);\n try {\n this.invertedIndex.load();\n } catch {\n if (existsSync(invertedIndexPath)) {\n await fsPromises.unlink(invertedIndexPath);\n }\n this.invertedIndex = new InvertedIndex(invertedIndexPath);\n }\n\n const dbPath = path.join(this.indexPath, \"codebase.db\");\n let dbIsNew = !existsSync(dbPath);\n try {\n this.database = new Database(dbPath);\n } catch (error) {\n if (!(await this.tryResetCorruptedIndex(\"initializing index database\", error))) {\n throw error;\n }\n\n this.store = new VectorStore(storePath, dimensions);\n this.invertedIndex = new InvertedIndex(invertedIndexPath);\n this.database = new Database(dbPath);\n dbIsNew = true;\n }\n\n if (isGitRepo(this.projectRoot)) {\n this.currentBranch = getBranchOrDefault(this.projectRoot);\n this.baseBranch = getBaseBranch(this.projectRoot);\n this.logger.branch(\"info\", \"Detected git repository\", {\n currentBranch: this.currentBranch,\n baseBranch: this.baseBranch,\n });\n } else {\n this.currentBranch = \"default\";\n this.baseBranch = \"default\";\n this.logger.branch(\"debug\", \"Not a git repository, using default branch\");\n }\n\n // Recover from interrupted indexing AFTER store, invertedIndex, and database\n // are all initialized. healthCheck() calls ensureInitialized() which checks\n // these fields — if they're not set, it re-enters initialize() causing infinite\n // recursion and 70GB+ memory usage.\n if (this.checkForInterruptedIndexing()) {\n await this.recoverFromInterruptedIndexing();\n }\n\n if (dbIsNew && this.store.count() > 0) {\n this.migrateFromLegacyIndex();\n }\n\n this.loadFileHashCache();\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo);\n if (!this.indexCompatibility.compatible) {\n this.logger.warn(\"Index compatibility issue detected\", {\n reason: this.indexCompatibility.reason,\n storedMetadata: this.indexCompatibility.storedMetadata,\n configuredProviderInfo: this.configuredProviderInfo,\n });\n }\n\n // Auto-GC: Run garbage collection if enabled and interval has elapsed\n if (this.config.indexing.autoGc) {\n await this.maybeRunAutoGc();\n }\n }\n\n private async maybeRunAutoGc(): Promise<void> {\n if (!this.database) return;\n\n const lastGcTimestamp = this.database.getMetadata(\"lastGcTimestamp\");\n const now = Date.now();\n const intervalMs = this.config.indexing.gcIntervalDays * 24 * 60 * 60 * 1000;\n\n let shouldRunGc = false;\n if (!lastGcTimestamp) {\n // Never run GC before, run it now\n shouldRunGc = true;\n } else {\n const lastGcTime = parseInt(lastGcTimestamp, 10);\n if (!isNaN(lastGcTime) && now - lastGcTime > intervalMs) {\n shouldRunGc = true;\n }\n }\n\n if (shouldRunGc) {\n const result = await this.healthCheck();\n if (result.warning) {\n this.database.setMetadata(STARTUP_WARNING_METADATA_KEY, result.warning);\n } else {\n this.database.deleteMetadata(STARTUP_WARNING_METADATA_KEY);\n }\n this.database.setMetadata(\"lastGcTimestamp\", now.toString());\n }\n }\n\n private async maybeRunOrphanGc(): Promise<CorruptedIndexResetResult | null> {\n if (!this.database) return null;\n\n const stats = this.database.getStats();\n if (!stats) return null;\n\n const orphanCount = stats.embeddingCount - stats.chunkCount;\n if (orphanCount > this.config.indexing.gcOrphanThreshold) {\n try {\n this.database.gcOrphanEmbeddings();\n this.database.gcOrphanChunks();\n } catch (error) {\n if (await this.tryResetCorruptedIndex(\"running automatic orphan garbage collection\", error)) {\n return {\n resetCorruptedIndex: true,\n warning: this.getCorruptedIndexWarning(path.join(this.indexPath, \"codebase.db\")),\n };\n }\n throw error;\n }\n this.database.setMetadata(\"lastGcTimestamp\", Date.now().toString());\n }\n\n return null;\n }\n\n private rebuildVectorStoreExcludingChunkIds(\n store: VectorStore,\n database: Database,\n excludedChunkIds: Iterable<string>\n ): void {\n const excludedSet = new Set(excludedChunkIds);\n if (excludedSet.size === 0) {\n return;\n }\n\n const retainedEntries = store\n .getAllMetadata()\n .filter(({ key }) => !excludedSet.has(key));\n\n const storeBasePath = path.join(this.indexPath, \"vectors\");\n const storeIndexPath = `${storeBasePath}.usearch`;\n const storeMetadataPath = `${storeBasePath}.meta.json`;\n const backupIndexPath = `${storeIndexPath}.bak`;\n const backupMetadataPath = `${storeMetadataPath}.bak`;\n\n let backedUpIndex = false;\n let backedUpMetadata = false;\n let rebuiltCount = 0;\n let skippedCount = 0;\n\n if (existsSync(backupIndexPath)) {\n unlinkSync(backupIndexPath);\n }\n if (existsSync(backupMetadataPath)) {\n unlinkSync(backupMetadataPath);\n }\n\n try {\n if (existsSync(storeIndexPath)) {\n renameSync(storeIndexPath, backupIndexPath);\n backedUpIndex = true;\n }\n if (existsSync(storeMetadataPath)) {\n renameSync(storeMetadataPath, backupMetadataPath);\n backedUpMetadata = true;\n }\n\n store.clear();\n\n for (const { key, metadata } of retainedEntries) {\n const chunk = database.getChunk(key);\n if (!chunk) {\n skippedCount += 1;\n continue;\n }\n\n const embeddingBuffer = database.getEmbedding(chunk.contentHash);\n if (!embeddingBuffer) {\n skippedCount += 1;\n continue;\n }\n\n const vector = bufferToFloat32Array(embeddingBuffer);\n store.add(key, Array.from(vector), metadata);\n rebuiltCount += 1;\n }\n\n store.save();\n\n if (backedUpIndex && existsSync(backupIndexPath)) {\n unlinkSync(backupIndexPath);\n }\n if (backedUpMetadata && existsSync(backupMetadataPath)) {\n unlinkSync(backupMetadataPath);\n }\n\n this.logger.gc(\"info\", \"Rebuilt vector store to avoid native remove\", {\n excludedChunks: excludedSet.size,\n rebuiltChunks: rebuiltCount,\n skippedChunks: skippedCount,\n });\n } catch (error) {\n try {\n store.clear();\n } catch {\n // Ignore best-effort cleanup before restore.\n }\n\n if (existsSync(storeIndexPath)) {\n unlinkSync(storeIndexPath);\n }\n if (existsSync(storeMetadataPath)) {\n unlinkSync(storeMetadataPath);\n }\n\n if (backedUpIndex && existsSync(backupIndexPath)) {\n renameSync(backupIndexPath, storeIndexPath);\n }\n if (backedUpMetadata && existsSync(backupMetadataPath)) {\n renameSync(backupMetadataPath, storeMetadataPath);\n }\n\n if (backedUpIndex || backedUpMetadata) {\n store.load();\n }\n\n throw error;\n }\n }\n\n private getCorruptedIndexWarning(dbPath: string): string {\n if (this.config.scope === \"global\") {\n return `Detected a corrupted shared global SQLite index at ${dbPath}. Automatic repair is disabled for global scope because it may delete other projects' index data. Remove or repair the shared index manually, then rerun index_codebase with force=true.`;\n }\n\n return `Detected a corrupted local SQLite index at ${dbPath} and reset the local index. Run index_codebase to rebuild search data.`;\n }\n\n private async tryResetCorruptedIndex(stage: string, error: unknown): Promise<boolean> {\n if (!isSqliteCorruptionError(error)) {\n return false;\n }\n\n const dbPath = path.join(this.indexPath, \"codebase.db\");\n const warning = this.getCorruptedIndexWarning(dbPath);\n const errorMessage = getErrorMessage(error);\n\n if (this.config.scope === \"global\") {\n this.logger.error(\"Detected corrupted shared global index database\", {\n stage,\n dbPath,\n error: errorMessage,\n });\n throw new Error(`${warning} Original SQLite error: ${errorMessage}`);\n }\n\n this.logger.warn(\"Detected corrupted local index database, resetting local index\", {\n stage,\n dbPath,\n error: errorMessage,\n });\n\n this.store = null;\n this.invertedIndex = null;\n this.database?.close();\n this.database = null;\n this.indexCompatibility = null;\n this.fileHashCache.clear();\n\n const resetPaths = [\n path.join(this.indexPath, \"codebase.db\"),\n path.join(this.indexPath, \"codebase.db-shm\"),\n path.join(this.indexPath, \"codebase.db-wal\"),\n path.join(this.indexPath, \"vectors.usearch\"),\n path.join(this.indexPath, \"inverted-index.json\"),\n path.join(this.indexPath, \"file-hashes.json\"),\n path.join(this.indexPath, \"failed-batches.json\"),\n path.join(this.indexPath, \"indexing.lock\"),\n path.join(this.indexPath, \"vectors\"),\n ];\n\n await Promise.all(resetPaths.map(async (targetPath) => {\n try {\n await fsPromises.rm(targetPath, { recursive: true, force: true });\n } catch {\n // Best-effort cleanup. The follow-up reinitialization will recreate what it needs.\n }\n }));\n\n await fsPromises.mkdir(this.indexPath, { recursive: true });\n return true;\n }\n\n private migrateFromLegacyIndex(): void {\n if (!this.store || !this.database) return;\n\n const allMetadata = this.store.getAllMetadata();\n const chunkIds: string[] = [];\n const chunkDataBatch: ChunkData[] = [];\n\n for (const { key, metadata } of allMetadata) {\n const chunkData: ChunkData = {\n chunkId: key,\n contentHash: metadata.hash,\n filePath: metadata.filePath,\n startLine: metadata.startLine,\n endLine: metadata.endLine,\n nodeType: metadata.chunkType,\n name: metadata.name,\n language: metadata.language,\n };\n chunkDataBatch.push(chunkData);\n chunkIds.push(key);\n }\n\n if (chunkDataBatch.length > 0) {\n this.database.upsertChunksBatch(chunkDataBatch);\n }\n this.database.addChunksToBranchBatch(this.getBranchCatalogKey(), chunkIds);\n }\n\n private loadIndexMetadata(): IndexMetadata | null {\n if (!this.database) return null;\n\n const version = this.database.getMetadata(\"index.version\");\n if (!version) return null;\n\n return {\n indexVersion: version,\n embeddingProvider: this.database.getMetadata(\"index.embeddingProvider\") ?? \"\",\n embeddingModel: this.database.getMetadata(\"index.embeddingModel\") ?? \"\",\n embeddingDimensions: parseInt(this.database.getMetadata(\"index.embeddingDimensions\") ?? \"0\", 10),\n embeddingStrategyVersion: this.loadStoredEmbeddingStrategyVersion() ?? EMBEDDING_STRATEGY_VERSION,\n createdAt: this.database.getMetadata(\"index.createdAt\") ?? \"\",\n updatedAt: this.database.getMetadata(\"index.updatedAt\") ?? \"\",\n };\n }\n\n private saveIndexMetadata(provider: ConfiguredProviderInfo): void {\n if (!this.database) return;\n\n const now = new Date().toISOString();\n const existingCreatedAt = this.database.getMetadata(\"index.createdAt\");\n const completeProjectEmbeddingStrategyReset = !this.hasProjectForceReembedPending();\n\n this.database.setMetadata(\"index.version\", INDEX_METADATA_VERSION);\n this.database.setMetadata(\"index.embeddingProvider\", provider.provider);\n this.database.setMetadata(\"index.embeddingModel\", provider.modelInfo.model);\n this.database.setMetadata(\"index.embeddingDimensions\", provider.modelInfo.dimensions.toString());\n if (this.config.scope === \"global\") {\n if (completeProjectEmbeddingStrategyReset) {\n this.database.setMetadata(this.getProjectEmbeddingStrategyMetadataKey(), EMBEDDING_STRATEGY_VERSION);\n }\n this.database.setMetadata(this.getLegacyMigrationMetadataKey(), \"done\");\n if (completeProjectEmbeddingStrategyReset) {\n this.database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n }\n } else {\n this.database.setMetadata(\"index.embeddingStrategyVersion\", EMBEDDING_STRATEGY_VERSION);\n }\n this.database.setMetadata(\"index.updatedAt\", now);\n\n if (!existingCreatedAt) {\n this.database.setMetadata(\"index.createdAt\", now);\n }\n }\n\n private validateIndexCompatibility(provider: ConfiguredProviderInfo): IndexCompatibility {\n const storedMetadata = this.loadIndexMetadata();\n\n if (!storedMetadata) {\n return { compatible: true };\n }\n\n const currentProvider = provider.provider;\n const currentModel = provider.modelInfo.model;\n const currentDimensions = provider.modelInfo.dimensions;\n\n if (storedMetadata.embeddingDimensions !== currentDimensions) {\n return {\n compatible: false,\n code: IncompatibilityCode.DIMENSION_MISMATCH,\n reason: `Dimension mismatch: index has ${storedMetadata.embeddingDimensions}D vectors (${storedMetadata.embeddingProvider}/${storedMetadata.embeddingModel}), but current provider uses ${currentDimensions}D (${currentProvider}/${currentModel}). Run index_codebase with force=true to rebuild.`,\n storedMetadata,\n };\n }\n\n if (storedMetadata.embeddingModel !== currentModel) {\n return {\n compatible: false,\n code: IncompatibilityCode.MODEL_MISMATCH,\n reason: `Model mismatch: index was built with \"${storedMetadata.embeddingModel}\", but current model is \"${currentModel}\". Embeddings are incompatible. Run index_codebase with force=true to rebuild.`,\n storedMetadata,\n };\n }\n\n if (storedMetadata.embeddingStrategyVersion !== EMBEDDING_STRATEGY_VERSION) {\n return {\n compatible: false,\n code: IncompatibilityCode.EMBEDDING_STRATEGY_MISMATCH,\n reason: `Embedding strategy mismatch: index was built with embedding strategy v${storedMetadata.embeddingStrategyVersion}, but the current code requires v${EMBEDDING_STRATEGY_VERSION}. Run index_codebase with force=true to rebuild cached embeddings.`,\n storedMetadata,\n };\n }\n\n if (storedMetadata.embeddingProvider !== currentProvider) {\n this.logger.warn(\"Provider changed\", {\n storedProvider: storedMetadata.embeddingProvider,\n currentProvider,\n });\n }\n\n return {\n compatible: true,\n storedMetadata,\n };\n }\n\n checkCompatibility(): IndexCompatibility {\n if (!this.indexCompatibility) {\n if (!this.configuredProviderInfo) {\n throw new Error('No embedding provider info, you must initialize the indexer first.');\n }\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo);\n }\n return this.indexCompatibility;\n }\n\n private async ensureInitialized(): Promise<{\n store: VectorStore;\n provider: EmbeddingProviderInterface;\n invertedIndex: InvertedIndex;\n configuredProviderInfo: ConfiguredProviderInfo;\n database: Database;\n }> {\n if (!this.store || !this.provider || !this.invertedIndex || !this.configuredProviderInfo || !this.database) {\n await this.initialize();\n }\n return {\n store: this.store!,\n provider: this.provider!,\n invertedIndex: this.invertedIndex!,\n configuredProviderInfo: this.configuredProviderInfo!,\n database: this.database!,\n };\n }\n\n async estimateCost(): Promise<CostEstimate> {\n const { configuredProviderInfo } = await this.ensureInitialized();\n\n const includePatterns = [...this.config.include, ...this.config.additionalInclude];\n const { files } = await collectFiles(\n this.projectRoot,\n includePatterns,\n this.config.exclude,\n this.config.indexing.maxFileSize,\n this.config.knowledgeBases,\n { maxDepth: this.config.indexing.maxDepth, maxFilesPerDirectory: this.config.indexing.maxFilesPerDirectory }\n );\n\n return createCostEstimate(files, configuredProviderInfo);\n }\n\n async index(onProgress?: ProgressCallback): Promise<IndexStats> {\n const { store, provider, invertedIndex, database, configuredProviderInfo } = await this.ensureInitialized();\n const scopedRoots = this.config.scope === \"global\" ? this.getScopedRoots() : null;\n const branchCatalogKey = this.getBranchCatalogKey();\n const forceScopedReembed = scopedRoots !== null && database.getMetadata(this.getProjectForceReembedMetadataKey()) === \"true\";\n const failedForcedChunkIds = new Set<string>();\n\n if (!this.indexCompatibility?.compatible) {\n throw new Error(\n `${this.indexCompatibility?.reason} ` +\n `Run index_codebase with force=true to rebuild the index.`\n );\n }\n\n this.acquireIndexingLock();\n this.logger.recordIndexingStart();\n this.logger.info(\"Starting indexing\", { projectRoot: this.projectRoot });\n\n const startTime = Date.now();\n const stats: IndexStats = {\n totalFiles: 0,\n totalChunks: 0,\n indexedChunks: 0,\n failedChunks: 0,\n tokensUsed: 0,\n durationMs: 0,\n existingChunks: 0,\n removedChunks: 0,\n skippedFiles: [],\n parseFailures: [],\n };\n const failedBatchesForCurrentRun: FailedBatch[] = [];\n\n onProgress?.({\n phase: \"scanning\",\n filesProcessed: 0,\n totalFiles: 0,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n\n this.loadFileHashCache();\n\n const includePatterns = [...this.config.include, ...this.config.additionalInclude];\n const { files, skipped } = await collectFiles(\n this.projectRoot,\n includePatterns,\n this.config.exclude,\n this.config.indexing.maxFileSize,\n this.config.knowledgeBases,\n { maxDepth: this.config.indexing.maxDepth, maxFilesPerDirectory: this.config.indexing.maxFilesPerDirectory }\n );\n\n stats.totalFiles = files.length;\n stats.skippedFiles = skipped;\n\n this.logger.recordFilesScanned(files.length);\n this.logger.cache(\"debug\", \"Scanning files for changes\", {\n totalFiles: files.length,\n skippedFiles: skipped.length,\n });\n\n const changedFiles: Array<{ path: string; content: string; hash: string }> = [];\n const unchangedFilePaths = new Set<string>();\n const currentFileHashes = new Map<string, string>();\n\n for (const f of files) {\n const currentHash = hashFile(f.path);\n currentFileHashes.set(f.path, currentHash);\n\n if (this.fileHashCache.get(f.path) === currentHash) {\n unchangedFilePaths.add(f.path);\n this.logger.recordCacheHit();\n } else {\n const content = await fsPromises.readFile(f.path, \"utf-8\");\n changedFiles.push({ path: f.path, content, hash: currentHash });\n this.logger.recordCacheMiss();\n }\n }\n\n this.logger.cache(\"info\", \"File hash cache results\", {\n unchanged: unchangedFilePaths.size,\n changed: changedFiles.length,\n });\n\n onProgress?.({\n phase: \"parsing\",\n filesProcessed: 0,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n\n const parseStartTime = performance.now();\n const parsedFiles = parseFiles(changedFiles);\n const parseMs = performance.now() - parseStartTime;\n\n this.logger.recordFilesParsed(parsedFiles.length);\n this.logger.recordParseDuration(parseMs);\n this.logger.debug(\"Parsed changed files\", { parsedCount: parsedFiles.length, parseMs: parseMs.toFixed(2) });\n\n const existingChunks = new Map<string, string>();\n const existingChunksByFile = new Map<string, Set<string>>();\n for (const { key, metadata } of store.getAllMetadata()) {\n if (scopedRoots && !this.isFileInCurrentScope(metadata.filePath, scopedRoots)) {\n continue;\n }\n if (forceScopedReembed && scopedRoots && this.isFileInCurrentScope(metadata.filePath, scopedRoots)) {\n continue;\n }\n existingChunks.set(key, metadata.hash);\n const fileChunks = existingChunksByFile.get(metadata.filePath) || new Set();\n fileChunks.add(key);\n existingChunksByFile.set(metadata.filePath, fileChunks);\n }\n\n const currentChunkIds = new Set<string>();\n const currentFilePaths = new Set<string>();\n const pendingChunks: PendingChunk[] = [];\n\n for (const filePath of unchangedFilePaths) {\n currentFilePaths.add(filePath);\n const fileChunks = existingChunksByFile.get(filePath);\n if (fileChunks) {\n for (const chunkId of fileChunks) {\n currentChunkIds.add(chunkId);\n }\n }\n }\n\n const chunkDataBatch: ChunkData[] = [];\n\n for (const parsed of parsedFiles) {\n currentFilePaths.add(parsed.path);\n\n if (parsed.chunks.length === 0) {\n const relativePath = path.relative(this.projectRoot, parsed.path);\n stats.parseFailures.push(relativePath);\n }\n\n let fileChunkCount = 0;\n let chunksToProcess = parsed.chunks;\n\n if (this.config.indexing.fallbackToTextOnMaxChunks && chunksToProcess.length > this.config.indexing.maxChunksPerFile) {\n const changedFile = changedFiles.find(f => f.path === parsed.path);\n if (changedFile) {\n const textChunks = parseFileAsText(parsed.path, changedFile.content);\n chunksToProcess = textChunks;\n }\n }\n\n for (const chunk of chunksToProcess) {\n if (fileChunkCount >= this.config.indexing.maxChunksPerFile) {\n break;\n }\n\n if (this.config.indexing.semanticOnly && chunk.chunkType === \"other\") {\n continue;\n }\n\n const id = generateChunkId(parsed.path, chunk);\n const contentHash = generateChunkHash(chunk);\n currentChunkIds.add(id);\n\n chunkDataBatch.push({\n chunkId: id,\n contentHash,\n filePath: parsed.path,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n nodeType: chunk.chunkType,\n name: chunk.name,\n language: chunk.language,\n });\n\n if (existingChunks.get(id) === contentHash) {\n fileChunkCount++;\n continue;\n }\n\n const texts = createEmbeddingTexts(chunk, parsed.path, getSafeEmbeddingChunkTokenLimit(configuredProviderInfo)).map((text) => ({\n text,\n tokenCount: estimateTokens(text),\n }));\n const metadata: ChunkMetadata = {\n filePath: parsed.path,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n chunkType: chunk.chunkType,\n name: chunk.name,\n language: chunk.language,\n hash: contentHash,\n };\n\n pendingChunks.push({\n id,\n texts,\n storageText: createPendingChunkStorageText(texts),\n content: chunk.content,\n contentHash,\n metadata,\n });\n fileChunkCount++;\n }\n }\n\n const retryableFailedChunks = this.collectRetryableFailedChunks(\n currentFileHashes,\n unchangedFilePaths,\n getSafeEmbeddingChunkTokenLimit(configuredProviderInfo)\n );\n const retryableFailedAttemptCounts = new Map<string, number>();\n const retryableChunksWithExistingData = new Set<string>();\n if (retryableFailedChunks.length > 0) {\n const pendingChunkIds = new Set(pendingChunks.map((chunk) => chunk.id));\n for (const { chunk, attemptCount } of retryableFailedChunks) {\n retryableFailedAttemptCounts.set(chunk.id, attemptCount);\n if (existingChunks.has(chunk.id)) {\n retryableChunksWithExistingData.add(chunk.id);\n }\n if (!pendingChunkIds.has(chunk.id)) {\n pendingChunks.push(chunk);\n pendingChunkIds.add(chunk.id);\n currentChunkIds.add(chunk.id);\n }\n }\n }\n\n if (chunkDataBatch.length > 0) {\n database.upsertChunksBatch(chunkDataBatch);\n }\n\n const allSymbolIds = new Set<string>();\n const symbolsByFile = new Map<string, SymbolData[]>();\n\n for (let i = 0; i < parsedFiles.length; i++) {\n const parsed = parsedFiles[i];\n const changedFile = changedFiles[i];\n\n database.deleteCallEdgesByFile(parsed.path);\n database.deleteSymbolsByFile(parsed.path);\n\n const fileSymbols: SymbolData[] = [];\n\n for (const chunk of parsed.chunks) {\n if (!chunk.name || !CALL_GRAPH_SYMBOL_CHUNK_TYPES.has(chunk.chunkType)) continue;\n\n const symbolId = `sym_${hashContent(parsed.path + \":\" + chunk.name + \":\" + chunk.chunkType + \":\" + chunk.startLine).slice(0, 16)}`;\n const symbol: SymbolData = {\n id: symbolId,\n filePath: parsed.path,\n name: chunk.name,\n kind: chunk.chunkType,\n startLine: chunk.startLine,\n startCol: 0,\n endLine: chunk.endLine,\n endCol: 0,\n language: chunk.language,\n };\n fileSymbols.push(symbol);\n allSymbolIds.add(symbolId);\n }\n\n // For case-insensitive languages (e.g. Apex), the Rust call extractor\n // already lowercases non-constructor / non-import callee names, so we\n // must lowercase the symbol-map keys here too. Otherwise a declaration\n // like `MyMethod` would not match a lowercased call edge target like\n // `mymethod`, leaving same-file calls unresolved (toSymbolId = NULL).\n const fileLanguage = parsed.chunks[0]?.language;\n const isCaseInsensitiveLanguage =\n !!fileLanguage && CASE_INSENSITIVE_LANGUAGES.has(fileLanguage);\n const normalizeSymbolKey = (name: string): string =>\n isCaseInsensitiveLanguage ? name.toLowerCase() : name;\n\n const symbolsByName = new Map<string, SymbolData[]>();\n for (const symbol of fileSymbols) {\n const key = normalizeSymbolKey(symbol.name);\n const existing = symbolsByName.get(key) ?? [];\n existing.push(symbol);\n symbolsByName.set(key, existing);\n }\n\n if (fileSymbols.length > 0) {\n database.upsertSymbolsBatch(fileSymbols);\n symbolsByFile.set(parsed.path, fileSymbols);\n }\n\n if (!fileLanguage || !CALL_GRAPH_LANGUAGES.has(fileLanguage)) continue;\n\n const callSites = extractCalls(changedFile.content, fileLanguage);\n if (callSites.length === 0) continue;\n\n const edges: CallEdgeData[] = [];\n for (const site of callSites) {\n const enclosingSymbol = fileSymbols.find(\n (sym) => site.line >= sym.startLine && site.line <= sym.endLine\n );\n if (!enclosingSymbol) continue;\n\n const edgeId = `edge_${hashContent(enclosingSymbol.id + \":\" + site.calleeName + \":\" + site.line + \":\" + site.column).slice(0, 16)}`;\n edges.push({\n id: edgeId,\n fromSymbolId: enclosingSymbol.id,\n targetName: site.calleeName,\n toSymbolId: undefined,\n callType: site.callType,\n line: site.line,\n col: site.column,\n isResolved: false,\n });\n }\n\n if (edges.length > 0) {\n database.upsertCallEdgesBatch(edges);\n\n // Resolve same-file calls (with the same case-insensitivity rules\n // used to build symbolsByName above).\n for (const edge of edges) {\n const candidates = symbolsByName.get(normalizeSymbolKey(edge.targetName));\n if (candidates && candidates.length === 1) {\n database.resolveCallEdge(edge.id, candidates[0].id);\n }\n }\n }\n }\n\n for (const filePath of unchangedFilePaths) {\n const existingSymbols = database.getSymbolsByFile(filePath);\n for (const sym of existingSymbols) {\n allSymbolIds.add(sym.id);\n }\n }\n\n const removedChunkIds: string[] = [];\n for (const [chunkId] of existingChunks) {\n if (!currentChunkIds.has(chunkId)) {\n removedChunkIds.push(chunkId);\n }\n }\n\n if (removedChunkIds.length > 0) {\n this.rebuildVectorStoreExcludingChunkIds(store, database, removedChunkIds);\n for (const chunkId of removedChunkIds) {\n invertedIndex.removeChunk(chunkId);\n }\n database.deleteChunksByIds(removedChunkIds);\n }\n\n const removedCount = removedChunkIds.length;\n\n stats.totalChunks = pendingChunks.length;\n stats.existingChunks = currentChunkIds.size - pendingChunks.length;\n stats.removedChunks = removedCount;\n\n this.logger.recordChunksProcessed(currentChunkIds.size);\n this.logger.recordChunksRemoved(removedCount);\n this.logger.info(\"Chunk analysis complete\", {\n pending: pendingChunks.length,\n existing: stats.existingChunks,\n removed: removedCount,\n });\n\n if (pendingChunks.length === 0 && removedCount === 0) {\n database.clearBranch(branchCatalogKey);\n database.addChunksToBranchBatch(branchCatalogKey, Array.from(currentChunkIds));\n database.clearBranchSymbols(branchCatalogKey);\n database.addSymbolsToBranchBatch(branchCatalogKey, Array.from(allSymbolIds));\n if (scopedRoots) {\n this.replaceScopedFileHashCache(currentFileHashes, scopedRoots);\n this.clearScopedFailedBatches(scopedRoots);\n } else {\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\n this.saveFailedBatches([]);\n }\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n stats.durationMs = Date.now() - startTime;\n onProgress?.({\n phase: \"complete\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n this.releaseIndexingLock();\n return stats;\n }\n\n if (pendingChunks.length === 0) {\n database.clearBranch(branchCatalogKey);\n database.addChunksToBranchBatch(branchCatalogKey, Array.from(currentChunkIds));\n database.clearBranchSymbols(branchCatalogKey);\n database.addSymbolsToBranchBatch(branchCatalogKey, Array.from(allSymbolIds));\n store.save();\n invertedIndex.save();\n if (scopedRoots) {\n this.replaceScopedFileHashCache(currentFileHashes, scopedRoots);\n this.clearScopedFailedBatches(scopedRoots);\n } else {\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\n this.saveFailedBatches([]);\n }\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n stats.durationMs = Date.now() - startTime;\n onProgress?.({\n phase: \"complete\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n this.releaseIndexingLock();\n return stats;\n }\n\n onProgress?.({\n phase: \"embedding\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: pendingChunks.length,\n });\n\n const allContentHashes = pendingChunks.map((c) => c.contentHash);\n const missingHashes = new Set(database.getMissingEmbeddings(allContentHashes));\n const forcedReembedChunkIds = forceScopedReembed\n ? new Set(pendingChunks.map((chunk) => chunk.id))\n : new Set<string>();\n\n const chunksNeedingEmbedding = pendingChunks.filter((c) => forcedReembedChunkIds.has(c.id) || missingHashes.has(c.contentHash));\n const chunksWithExistingEmbedding = pendingChunks.filter((c) => !forcedReembedChunkIds.has(c.id) && !missingHashes.has(c.contentHash));\n\n this.logger.cache(\"info\", \"Embedding cache lookup\", {\n needsEmbedding: chunksNeedingEmbedding.length,\n fromCache: chunksWithExistingEmbedding.length,\n });\n this.logger.recordChunksFromCache(chunksWithExistingEmbedding.length);\n\n for (const chunk of chunksWithExistingEmbedding) {\n const embeddingBuffer = database.getEmbedding(chunk.contentHash);\n if (embeddingBuffer) {\n const vector = bufferToFloat32Array(embeddingBuffer);\n store.add(chunk.id, Array.from(vector), chunk.metadata);\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n stats.indexedChunks++;\n }\n }\n\n const providerRateLimits = this.getProviderRateLimits(configuredProviderInfo.provider);\n const queue = new PQueue({\n concurrency: providerRateLimits.concurrency,\n interval: providerRateLimits.intervalMs,\n intervalCap: providerRateLimits.concurrency\n });\n const pendingChunksById = new Map(chunksNeedingEmbedding.map((chunk) => [chunk.id, chunk]));\n const embeddingPartsByChunk = new Map<string, Array<{ vector: number[]; tokenCount: number } | undefined>>();\n const completedChunkIds = new Set<string>();\n const failedChunkIds = new Set<string>();\n const requestBatches = createPendingEmbeddingRequestBatches(\n chunksNeedingEmbedding,\n getDynamicBatchOptions(configuredProviderInfo)\n );\n let rateLimitBackoffMs = 0;\n\n for (const requestBatch of requestBatches) {\n queue.add(async () => {\n if (rateLimitBackoffMs > 0) {\n await new Promise(resolve => setTimeout(resolve, rateLimitBackoffMs));\n }\n\n try {\n const result = await pRetry(\n async () => {\n const texts = requestBatch.map((request) => request.text);\n return provider.embedBatch(texts);\n },\n {\n retries: this.config.indexing.retries,\n minTimeout: Math.max(this.config.indexing.retryDelayMs, providerRateLimits.minRetryMs),\n maxTimeout: providerRateLimits.maxRetryMs,\n factor: 2,\n shouldRetry: (error) => !((error as { error?: Error }).error instanceof CustomProviderNonRetryableError),\n onFailedAttempt: (error) => {\n const message = getErrorMessage(error);\n if (isRateLimitError(error)) {\n rateLimitBackoffMs = Math.min(providerRateLimits.maxRetryMs, (rateLimitBackoffMs || providerRateLimits.minRetryMs) * 2);\n this.logger.embedding(\"warn\", `Rate limited, backing off`, {\n attempt: error.attemptNumber,\n retriesLeft: error.retriesLeft,\n backoffMs: rateLimitBackoffMs,\n });\n } else {\n this.logger.embedding(\"error\", `Embedding batch failed`, {\n attempt: error.attemptNumber,\n error: message,\n });\n }\n },\n }\n );\n\n if (rateLimitBackoffMs > 0) {\n rateLimitBackoffMs = Math.max(0, rateLimitBackoffMs - 2000);\n }\n\n const touchedChunkIds = new Set<string>();\n\n requestBatch.forEach((request, idx) => {\n if (failedChunkIds.has(request.chunk.id) || completedChunkIds.has(request.chunk.id)) {\n return;\n }\n\n const vector = result.embeddings[idx];\n if (!vector) {\n throw new Error(`Embedding API returned too few vectors for chunk ${request.chunk.id}`);\n }\n\n const parts = embeddingPartsByChunk.get(request.chunk.id) ?? [];\n parts[request.partIndex] = {\n vector,\n tokenCount: request.tokenCount,\n };\n embeddingPartsByChunk.set(request.chunk.id, parts);\n touchedChunkIds.add(request.chunk.id);\n });\n\n const pooledResults: Array<{ chunk: PendingChunk; vector: number[] }> = [];\n for (const chunkId of touchedChunkIds) {\n if (failedChunkIds.has(chunkId) || completedChunkIds.has(chunkId)) {\n continue;\n }\n\n const chunk = pendingChunksById.get(chunkId);\n if (!chunk) {\n continue;\n }\n\n const parts = embeddingPartsByChunk.get(chunk.id) ?? [];\n if (!hasAllEmbeddingParts(parts, chunk.texts.length)) {\n continue;\n }\n\n const orderedParts = parts as Array<{ vector: number[]; tokenCount: number }>;\n pooledResults.push({\n chunk,\n vector: poolEmbeddingVectors(\n orderedParts.map((part) => part.vector),\n orderedParts.map((part) => part.tokenCount)\n ),\n });\n }\n\n if (pooledResults.length > 0) {\n const items = pooledResults.map(({ chunk, vector }) => ({\n id: chunk.id,\n vector,\n metadata: chunk.metadata,\n }));\n\n store.addBatch(items);\n\n const embeddingBatchItems = pooledResults.map(({ chunk, vector }) => ({\n contentHash: chunk.contentHash,\n embedding: float32ArrayToBuffer(vector),\n chunkText: chunk.storageText,\n model: configuredProviderInfo.modelInfo.model,\n }));\n\n try {\n database.upsertEmbeddingsBatch(embeddingBatchItems);\n } catch (dbError) {\n this.rebuildVectorStoreExcludingChunkIds(\n store,\n database,\n pooledResults.map(({ chunk }) => chunk.id)\n );\n throw dbError;\n }\n\n for (const { chunk } of pooledResults) {\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n completedChunkIds.add(chunk.id);\n embeddingPartsByChunk.delete(chunk.id);\n }\n\n stats.indexedChunks += pooledResults.length;\n this.logger.recordChunksEmbedded(pooledResults.length);\n }\n\n stats.tokensUsed += result.totalTokensUsed;\n\n this.logger.recordEmbeddingApiCall(result.totalTokensUsed);\n this.logger.embedding(\"debug\", `Embedded batch`, {\n batchSize: pooledResults.length,\n requestCount: requestBatch.length,\n tokens: result.totalTokensUsed,\n });\n\n onProgress?.({\n phase: \"embedding\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: stats.indexedChunks,\n totalChunks: pendingChunks.length,\n });\n } catch (error) {\n const failedChunks = getUniquePendingChunksFromRequests(requestBatch)\n .filter((chunk) => !completedChunkIds.has(chunk.id));\n const failureMessage = getErrorMessage(error);\n const failureTimestamp = new Date().toISOString();\n\n for (const chunk of failedChunks) {\n if (!failedChunkIds.has(chunk.id)) {\n failedChunkIds.add(chunk.id);\n stats.failedChunks += 1;\n }\n\n if (forceScopedReembed) {\n failedForcedChunkIds.add(chunk.id);\n }\n\n embeddingPartsByChunk.delete(chunk.id);\n\n const existingFailedBatchIndex = failedBatchesForCurrentRun.findIndex(\n (failedBatch) => failedBatch.chunks[0]?.id === chunk.id\n );\n const existingFailedBatch = existingFailedBatchIndex === -1\n ? undefined\n : failedBatchesForCurrentRun[existingFailedBatchIndex];\n const failedBatch = {\n chunks: [chunk],\n error: failureMessage,\n attemptCount: (existingFailedBatch?.attemptCount ?? retryableFailedAttemptCounts.get(chunk.id) ?? 0) + 1,\n lastAttempt: failureTimestamp,\n } satisfies FailedBatch;\n\n if (existingFailedBatchIndex === -1) {\n failedBatchesForCurrentRun.push(failedBatch);\n } else {\n failedBatchesForCurrentRun[existingFailedBatchIndex] = failedBatch;\n }\n }\n\n this.logger.recordEmbeddingError();\n this.logger.embedding(\"error\", `Failed to embed batch after retries`, {\n batchSize: failedChunks.length,\n requestCount: requestBatch.length,\n error: failureMessage,\n });\n }\n });\n }\n\n await queue.onIdle();\n if (scopedRoots) {\n this.saveScopedFailedBatches(coalesceFailedBatches(failedBatchesForCurrentRun), scopedRoots);\n } else {\n this.saveFailedBatches(coalesceFailedBatches(failedBatchesForCurrentRun));\n }\n\n onProgress?.({\n phase: \"storing\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: stats.indexedChunks,\n totalChunks: pendingChunks.length,\n });\n\n const branchChunkIds = Array.from(currentChunkIds).filter(\n (chunkId) => {\n const isNewlyFailed = failedChunkIds.has(chunkId) && !retryableChunksWithExistingData.has(chunkId);\n const isForcedFailed = forceScopedReembed && failedForcedChunkIds.has(chunkId);\n return !isNewlyFailed && !isForcedFailed;\n }\n );\n database.clearBranch(branchCatalogKey);\n database.addChunksToBranchBatch(branchCatalogKey, branchChunkIds);\n database.clearBranchSymbols(branchCatalogKey);\n database.addSymbolsToBranchBatch(branchCatalogKey, Array.from(allSymbolIds));\n\n store.save();\n invertedIndex.save();\n if (scopedRoots) {\n this.replaceScopedFileHashCache(currentFileHashes, scopedRoots);\n } else {\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\n }\n\n if (this.config.indexing.autoGc && stats.removedChunks > 0) {\n const gcReset = await this.maybeRunOrphanGc();\n if (gcReset) {\n stats.durationMs = Date.now() - startTime;\n stats.warning = gcReset.warning;\n stats.resetCorruptedIndex = true;\n\n this.logger.recordIndexingEnd();\n this.logger.warn(\"Indexing ended after resetting corrupted local index during automatic GC\", {\n files: stats.totalFiles,\n indexed: stats.indexedChunks,\n existing: stats.existingChunks,\n removed: stats.removedChunks,\n failed: stats.failedChunks,\n tokens: stats.tokensUsed,\n durationMs: stats.durationMs,\n });\n\n return stats;\n }\n }\n\n stats.durationMs = Date.now() - startTime;\n\n if (forceScopedReembed && failedForcedChunkIds.size === 0) {\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n }\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n\n this.logger.recordIndexingEnd();\n this.logger.info(\"Indexing complete\", {\n files: stats.totalFiles,\n indexed: stats.indexedChunks,\n existing: stats.existingChunks,\n removed: stats.removedChunks,\n failed: stats.failedChunks,\n tokens: stats.tokensUsed,\n durationMs: stats.durationMs,\n });\n\n if (stats.failedChunks > 0) {\n stats.failedBatchesPath = this.failedBatchesPath;\n }\n\n onProgress?.({\n phase: \"complete\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: stats.indexedChunks,\n totalChunks: pendingChunks.length,\n });\n\n this.releaseIndexingLock();\n return stats;\n }\n\n private async getQueryEmbedding(query: string, provider: EmbeddingProviderInterface): Promise<number[]> {\n const now = Date.now();\n const cached = this.queryEmbeddingCache.get(query);\n\n if (cached && (now - cached.timestamp) < this.queryCacheTtlMs) {\n this.logger.cache(\"debug\", \"Query embedding cache hit (exact)\", { query: query.slice(0, 50) });\n this.logger.recordQueryCacheHit();\n return cached.embedding;\n }\n\n const similarMatch = this.findSimilarCachedQuery(query, now);\n if (similarMatch) {\n this.logger.cache(\"debug\", \"Query embedding cache hit (similar)\", {\n query: query.slice(0, 50),\n similarTo: similarMatch.key.slice(0, 50),\n similarity: similarMatch.similarity.toFixed(3),\n });\n this.logger.recordQueryCacheSimilarHit();\n return similarMatch.embedding;\n }\n\n this.logger.cache(\"debug\", \"Query embedding cache miss\", { query: query.slice(0, 50) });\n this.logger.recordQueryCacheMiss();\n const { embedding, tokensUsed } = await provider.embedQuery(query);\n this.logger.recordEmbeddingApiCall(tokensUsed);\n\n if (this.queryEmbeddingCache.size >= this.maxQueryCacheSize) {\n const oldestKey = this.queryEmbeddingCache.keys().next().value;\n if (oldestKey) {\n this.queryEmbeddingCache.delete(oldestKey);\n }\n }\n\n this.queryEmbeddingCache.set(query, { embedding, timestamp: now });\n return embedding;\n }\n\n private findSimilarCachedQuery(\n query: string,\n now: number\n ): { key: string; embedding: number[]; similarity: number } | null {\n const queryTokens = this.tokenize(query);\n if (queryTokens.size === 0) return null;\n\n let bestMatch: { key: string; embedding: number[]; similarity: number } | null = null;\n\n for (const [cachedQuery, { embedding, timestamp }] of this.queryEmbeddingCache) {\n if ((now - timestamp) >= this.queryCacheTtlMs) continue;\n\n const cachedTokens = this.tokenize(cachedQuery);\n const similarity = this.jaccardSimilarity(queryTokens, cachedTokens);\n\n if (similarity >= this.querySimilarityThreshold) {\n if (!bestMatch || similarity > bestMatch.similarity) {\n bestMatch = { key: cachedQuery, embedding, similarity };\n }\n }\n }\n\n return bestMatch;\n }\n\n private tokenize(text: string): Set<string> {\n return new Set(\n text\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter(t => t.length > 1)\n );\n }\n\n private jaccardSimilarity(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 1;\n if (a.size === 0 || b.size === 0) return 0;\n\n let intersection = 0;\n for (const token of a) {\n if (b.has(token)) intersection++;\n }\n\n const union = a.size + b.size - intersection;\n return intersection / union;\n }\n\n async search(\n query: string,\n limit?: number,\n options?: {\n hybridWeight?: number;\n fileType?: string;\n directory?: string;\n chunkType?: string;\n contextLines?: number;\n filterByBranch?: boolean;\n metadataOnly?: boolean;\n definitionIntent?: boolean;\n }\n ): Promise<SearchResult[]> {\n const { store, provider, database } = await this.ensureInitialized();\n\n const compatibility = this.checkCompatibility();\n if (!compatibility.compatible) {\n throw new Error(\n `${compatibility.reason ?? \"Index is incompatible with current embedding provider.\"} ` +\n `A possible solution is to run index_codebase with force=true to rebuild the index.`\n );\n }\n\n const searchStartTime = performance.now();\n\n if (store.count() === 0) {\n this.logger.search(\"debug\", \"Search on empty index\", { query });\n return [];\n }\n\n const maxResults = limit ?? this.config.search.maxResults;\n const hybridWeight = options?.hybridWeight ?? this.config.search.hybridWeight;\n const fusionStrategy = this.config.search.fusionStrategy;\n const rrfK = this.config.search.rrfK;\n const rerankTopN = this.config.search.rerankTopN;\n const filterByBranch = options?.filterByBranch ?? true;\n const sourceIntent = options?.definitionIntent === true || classifyQueryIntentRaw(query) === \"source\";\n const identifierHints = extractIdentifierHints(query);\n\n this.logger.search(\"debug\", \"Starting search\", {\n query,\n maxResults,\n hybridWeight,\n fusionStrategy,\n rrfK,\n rerankTopN,\n filterByBranch,\n });\n\n const embeddingStartTime = performance.now();\n const embeddingQuery = stripFilePathHint(query);\n const embedding = await this.getQueryEmbedding(embeddingQuery, provider);\n const embeddingMs = performance.now() - embeddingStartTime;\n\n const vectorStartTime = performance.now();\n const semanticResults = store.search(embedding, maxResults * 4);\n const vectorMs = performance.now() - vectorStartTime;\n\n const keywordStartTime = performance.now();\n const keywordResults = await this.keywordSearch(query, maxResults * 4);\n const keywordMs = performance.now() - keywordStartTime;\n\n let branchChunkIds: Set<string> | null = null;\n if (filterByBranch && (this.config.scope === \"global\" || this.currentBranch !== \"default\")) {\n branchChunkIds = new Set(\n this.getBranchCatalogKeys().flatMap((branchKey) => database.getBranchChunkIds(branchKey))\n );\n }\n\n const prefilterStartTime = performance.now();\n const shouldPrefilterByBranch = branchChunkIds !== null && (this.config.scope === \"global\" || branchChunkIds.size > 0);\n const allowBranchPrefilterFallback = this.config.scope !== \"global\";\n const prefilteredSemantic = shouldPrefilterByBranch && branchChunkIds\n ? semanticResults.filter((r) => branchChunkIds.has(r.id))\n : semanticResults;\n const prefilteredKeyword = shouldPrefilterByBranch && branchChunkIds\n ? keywordResults.filter((r) => branchChunkIds.has(r.id))\n : keywordResults;\n\n const semanticCandidates = (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0)\n ? semanticResults\n : prefilteredSemantic;\n const keywordCandidates = (allowBranchPrefilterFallback && shouldPrefilterByBranch && keywordResults.length > 0 && prefilteredKeyword.length === 0)\n ? keywordResults\n : prefilteredKeyword;\n const prefilterMs = performance.now() - prefilterStartTime;\n\n if (this.config.scope !== \"global\" && branchChunkIds && branchChunkIds.size === 0) {\n this.logger.search(\"warn\", \"Branch prefilter skipped because branch catalog is empty\", {\n branch: this.currentBranch,\n });\n }\n\n if (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0) {\n this.logger.search(\"warn\", \"Branch prefilter produced no semantic overlap, using unfiltered semantic candidates\", {\n branch: this.currentBranch,\n });\n }\n\n if (allowBranchPrefilterFallback && shouldPrefilterByBranch && keywordResults.length > 0 && prefilteredKeyword.length === 0) {\n this.logger.search(\"warn\", \"Branch prefilter produced no keyword overlap, using unfiltered keyword candidates\", {\n branch: this.currentBranch,\n });\n }\n\n const fusionStartTime = performance.now();\n const combined = rankHybridResults(query, semanticCandidates, keywordCandidates, {\n fusionStrategy,\n rrfK,\n rerankTopN,\n limit: maxResults,\n hybridWeight,\n prioritizeSourcePaths: sourceIntent,\n });\n const rerankedCombined = await this.rerankCandidatesWithApi(query, combined, {\n definitionIntent: options?.definitionIntent === true,\n hasIdentifierHints: identifierHints.length > 0,\n });\n const fusionMs = performance.now() - fusionStartTime;\n\n const rescued = promoteIdentifierMatches(\n query,\n rerankedCombined,\n semanticCandidates,\n keywordCandidates,\n database,\n branchChunkIds,\n sourceIntent\n );\n\n const union = unionCandidates(semanticCandidates, keywordCandidates);\n\n const deterministicIdentifierLane = buildDeterministicIdentifierPass(\n query,\n union,\n maxResults,\n sourceIntent\n );\n\n const identifierLane = buildIdentifierDefinitionLane(\n query,\n union,\n maxResults,\n sourceIntent\n );\n\n const symbolLane = buildSymbolDefinitionLane(\n query,\n database,\n branchChunkIds,\n maxResults,\n union,\n sourceIntent\n );\n\n const prePrimaryLane = mergeTieredResults(deterministicIdentifierLane, identifierLane, maxResults * 4);\n const primaryLane = mergeTieredResults(prePrimaryLane, symbolLane, maxResults * 4);\n const tiered = mergeTieredResults(primaryLane, rescued, maxResults * 4);\n const hasCodeHints = extractCodeTermHints(query).length > 0 || identifierHints.length > 0;\n\n const baseFiltered = tiered.filter((r) => matchesSearchFilters(r, options, this.config.search.minScore));\n\n const implementationOnly = baseFiltered.filter((r) =>\n isLikelyImplementationPath(r.metadata.filePath) &&\n isImplementationChunkType(r.metadata.chunkType)\n );\n\n const filtered = (sourceIntent && hasCodeHints && implementationOnly.length > 0\n ? implementationOnly\n : baseFiltered\n ).slice(0, maxResults);\n\n const identifierFallback = (!options?.definitionIntent && filtered.length === 0 && identifierHints.length > 0)\n ? buildSymbolDefinitionLane(query, database, branchChunkIds, maxResults, union, true)\n .filter((r) => matchesSearchFilters(r, options, this.config.search.minScore))\n .slice(0, maxResults)\n : [];\n\n const finalResults = filtered.length > 0 ? filtered : identifierFallback;\n\n const totalSearchMs = performance.now() - searchStartTime;\n this.logger.recordSearch(totalSearchMs, {\n embeddingMs,\n vectorMs,\n keywordMs,\n fusionMs,\n });\n this.logger.search(\"info\", \"Search complete\", {\n query,\n results: finalResults.length,\n totalMs: Math.round(totalSearchMs * 100) / 100,\n embeddingMs: Math.round(embeddingMs * 100) / 100,\n vectorMs: Math.round(vectorMs * 100) / 100,\n keywordMs: Math.round(keywordMs * 100) / 100,\n prefilterMs: Math.round(prefilterMs * 100) / 100,\n fusionMs: Math.round(fusionMs * 100) / 100,\n });\n\n const metadataOnly = options?.metadataOnly ?? false;\n\n return Promise.all(\n finalResults.map(async (r) => {\n let content = \"\";\n let contextStartLine = r.metadata.startLine;\n let contextEndLine = r.metadata.endLine;\n\n if (!metadataOnly && this.config.search.includeContext) {\n try {\n const fileContent = await fsPromises.readFile(\n r.metadata.filePath,\n \"utf-8\"\n );\n const lines = fileContent.split(\"\\n\");\n const contextLines = options?.contextLines ?? this.config.search.contextLines;\n\n contextStartLine = Math.max(1, r.metadata.startLine - contextLines);\n contextEndLine = Math.min(lines.length, r.metadata.endLine + contextLines);\n\n content = lines\n .slice(contextStartLine - 1, contextEndLine)\n .join(\"\\n\");\n } catch {\n content = \"[File not accessible]\";\n }\n }\n\n return {\n filePath: r.metadata.filePath,\n startLine: contextStartLine,\n endLine: contextEndLine,\n content,\n score: r.score,\n chunkType: r.metadata.chunkType,\n name: r.metadata.name,\n };\n })\n );\n }\n\n private async keywordSearch(\n query: string,\n limit: number\n ): Promise<Array<{ id: string; score: number; metadata: ChunkMetadata }>> {\n const { store, invertedIndex } = await this.ensureInitialized();\n const scores = invertedIndex.search(query);\n\n if (scores.size === 0) {\n return [];\n }\n\n // Only fetch metadata for chunks returned by BM25 (O(n) where n = result count)\n // instead of getAllMetadata() which fetches ALL chunks in the index\n const chunkIds = Array.from(scores.keys());\n const metadataMap = store.getMetadataBatch(chunkIds);\n\n const results: Array<{ id: string; score: number; metadata: ChunkMetadata }> = [];\n for (const [chunkId, score] of scores) {\n const metadata = metadataMap.get(chunkId);\n if (metadata && score > 0) {\n results.push({ id: chunkId, score, metadata });\n }\n }\n\n results.sort((a, b) => b.score - a.score);\n return results.slice(0, limit);\n }\n\n async getStatus(): Promise<StatusResult> {\n const { store, configuredProviderInfo, database } = await this.ensureInitialized();\n const failedBatchesCount = this.getFailedBatchesCount();\n\n return {\n indexed: store.count() > 0,\n vectorCount: store.count(),\n provider: configuredProviderInfo.provider,\n model: configuredProviderInfo.modelInfo.model,\n indexPath: this.indexPath,\n currentBranch: this.currentBranch,\n baseBranch: this.baseBranch,\n compatibility: this.indexCompatibility,\n failedBatchesCount,\n failedBatchesPath: failedBatchesCount > 0 ? this.failedBatchesPath : undefined,\n warning: database.getMetadata(STARTUP_WARNING_METADATA_KEY) ?? undefined,\n };\n }\n\n async clearIndex(): Promise<void> {\n const { store, invertedIndex, database } = await this.ensureInitialized();\n\n if (this.config.scope === \"global\") {\n store.load();\n invertedIndex.load();\n this.loadFileHashCache();\n const roots = this.getScopedRoots();\n const compatibility = this.checkCompatibility();\n const allMetadata = store.getAllMetadata();\n const hasForeignData =\n allMetadata.some(({ metadata }) => !this.isFileInCurrentScope(metadata.filePath, roots)) ||\n this.hasForeignScopedBranchData() ||\n this.hasForeignScopedFileHashData(roots) ||\n this.hasForeignScopedFailedBatches(roots);\n\n if (!compatibility.compatible && hasForeignData) {\n if (compatibility.code === IncompatibilityCode.EMBEDDING_STRATEGY_MISMATCH) {\n this.clearSharedIndexProjectData(store, invertedIndex, database, roots);\n this.clearScopedFileHashCache(roots);\n this.clearScopedFailedBatches(roots);\n database.setMetadata(this.getProjectForceReembedMetadataKey(), \"true\");\n database.deleteMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n this.indexCompatibility = { compatible: true };\n return;\n }\n\n throw new Error(\n `Global index compatibility reset is unsafe because the shared index contains files from other projects. ` +\n `The current global index cannot be force-rebuilt for ${this.projectRoot} without deleting other repositories' indexed data. ` +\n `Use scope=\"project\" for isolated rebuilds, or manually delete the shared global index if you intend to rebuild all projects.`\n );\n }\n\n if (!hasForeignData) {\n store.clear();\n store.save();\n invertedIndex.clear();\n invertedIndex.save();\n\n this.fileHashCache.clear();\n this.saveFileHashCache();\n\n database.clearAllIndexedData();\n this.saveFailedBatches([]);\n\n database.deleteMetadata(\"index.version\");\n database.deleteMetadata(\"index.embeddingProvider\");\n database.deleteMetadata(\"index.embeddingModel\");\n database.deleteMetadata(\"index.embeddingDimensions\");\n database.deleteMetadata(\"index.embeddingStrategyVersion\");\n database.deleteMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n database.deleteMetadata(this.getLegacyMigrationMetadataKey());\n database.deleteMetadata(\"index.createdAt\");\n database.deleteMetadata(\"index.updatedAt\");\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo!);\n return;\n }\n\n this.clearSharedIndexProjectData(store, invertedIndex, database, roots);\n this.clearScopedFileHashCache(roots);\n this.clearScopedFailedBatches(roots);\n this.indexCompatibility = compatibility;\n return;\n }\n\n const localProjectIndexPath = path.join(this.projectRoot, \".opencode\", \"index\");\n if (path.resolve(this.indexPath) !== path.resolve(localProjectIndexPath)) {\n throw new Error(\n \"Project-scoped force rebuild is unsafe while using an inherited worktree index. \" +\n \"Create a local project config boundary before clearing the index.\"\n );\n }\n\n store.clear();\n store.save();\n invertedIndex.clear();\n invertedIndex.save();\n\n // Clear file hash cache so all files are re-parsed\n this.fileHashCache.clear();\n this.saveFileHashCache();\n\n // cannot reuse stale chunks, symbols, or embeddings from a prior provider.\n database.clearAllIndexedData();\n this.saveFailedBatches([]);\n\n database.deleteMetadata(\"index.version\");\n database.deleteMetadata(\"index.embeddingProvider\");\n database.deleteMetadata(\"index.embeddingModel\");\n database.deleteMetadata(\"index.embeddingDimensions\");\n database.deleteMetadata(\"index.embeddingStrategyVersion\");\n database.deleteMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n database.deleteMetadata(this.getLegacyMigrationMetadataKey());\n database.deleteMetadata(\"index.createdAt\");\n database.deleteMetadata(\"index.updatedAt\");\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo!);\n }\n\n async healthCheck(): Promise<HealthCheckResult> {\n const { store, invertedIndex, database } = await this.ensureInitialized();\n\n this.logger.gc(\"info\", \"Starting health check\");\n\n const allMetadata = store.getAllMetadata();\n const filePathsToChunkKeys = new Map<string, string[]>();\n\n for (const { key, metadata } of allMetadata) {\n const existing = filePathsToChunkKeys.get(metadata.filePath) || [];\n existing.push(key);\n filePathsToChunkKeys.set(metadata.filePath, existing);\n }\n\n const removedFilePaths: string[] = [];\n const removedChunkKeys: string[] = [];\n const chunkKeysByRemovedFile = new Map<string, string[]>();\n\n for (const [filePath, chunkKeys] of filePathsToChunkKeys) {\n if (!existsSync(filePath)) {\n chunkKeysByRemovedFile.set(filePath, chunkKeys);\n for (const key of chunkKeys) {\n removedChunkKeys.push(key);\n }\n removedFilePaths.push(filePath);\n }\n }\n\n if (removedChunkKeys.length > 0) {\n this.rebuildVectorStoreExcludingChunkIds(store, database, removedChunkKeys);\n for (const key of removedChunkKeys) {\n invertedIndex.removeChunk(key);\n }\n }\n\n for (const filePath of removedFilePaths) {\n const fileChunkKeys = chunkKeysByRemovedFile.get(filePath) ?? [];\n if (fileChunkKeys.length > 0) {\n database.deleteChunksByIds(fileChunkKeys);\n }\n database.deleteCallEdgesByFile(filePath);\n database.deleteSymbolsByFile(filePath);\n }\n\n const removedCount = removedChunkKeys.length;\n\n if (removedCount > 0) {\n store.save();\n invertedIndex.save();\n }\n\n let gcOrphanEmbeddings: number;\n let gcOrphanChunks: number;\n let gcOrphanSymbols: number;\n let gcOrphanCallEdges: number;\n\n try {\n gcOrphanEmbeddings = database.gcOrphanEmbeddings();\n gcOrphanChunks = database.gcOrphanChunks();\n gcOrphanSymbols = database.gcOrphanSymbols();\n gcOrphanCallEdges = database.gcOrphanCallEdges();\n } catch (error) {\n if (!(await this.tryResetCorruptedIndex(\"running index health check\", error))) {\n throw error;\n }\n\n await this.ensureInitialized();\n\n return {\n removed: 0,\n filePaths: [],\n gcOrphanEmbeddings: 0,\n gcOrphanChunks: 0,\n gcOrphanSymbols: 0,\n gcOrphanCallEdges: 0,\n resetCorruptedIndex: true,\n warning: this.getCorruptedIndexWarning(path.join(this.indexPath, \"codebase.db\")),\n };\n }\n\n this.logger.recordGc(removedCount, gcOrphanChunks, gcOrphanEmbeddings);\n this.logger.gc(\"info\", \"Health check complete\", {\n removedStale: removedCount,\n orphanEmbeddings: gcOrphanEmbeddings,\n orphanChunks: gcOrphanChunks,\n removedFiles: removedFilePaths.length,\n });\n\n return { removed: removedCount, filePaths: removedFilePaths, gcOrphanEmbeddings, gcOrphanChunks, gcOrphanSymbols, gcOrphanCallEdges };\n }\n\n async retryFailedBatches(): Promise<{ succeeded: number; failed: number; remaining: number }> {\n const { store, provider, invertedIndex, database, configuredProviderInfo } = await this.ensureInitialized();\n const maxChunkTokens = getSafeEmbeddingChunkTokenLimit(configuredProviderInfo);\n const providerRateLimits = this.getProviderRateLimits(configuredProviderInfo.provider);\n\n const roots = this.config.scope === \"global\" ? this.getScopedRoots() : null;\n const { scoped: scopedFailedBatches, retained: retainedFailedBatches } = roots\n ? this.partitionFailedBatches(roots, maxChunkTokens)\n : { scoped: this.loadFailedBatches(maxChunkTokens), retained: [] as FailedBatch[] };\n const failedBatches = scopedFailedBatches;\n if (failedBatches.length === 0) {\n return { succeeded: 0, failed: 0, remaining: 0 };\n }\n\n let succeeded = 0;\n let failed = 0;\n const stillFailing: FailedBatch[] = [];\n\n for (const batch of failedBatches) {\n const batchChunksById = new Map(batch.chunks.map((chunk) => [chunk.id, chunk]));\n const embeddingPartsByChunk = new Map<string, Array<{ vector: number[]; tokenCount: number } | undefined>>();\n const completedChunkIds = new Set<string>();\n const failedChunkIds = new Set<string>();\n const failedChunksForBatch = new Map<string, FailedBatch>();\n const pooledResults: Array<{ chunk: PendingChunk; vector: number[] }> = [];\n try {\n const requestBatches = createPendingEmbeddingRequestBatches(\n batch.chunks,\n getDynamicBatchOptions(configuredProviderInfo)\n );\n\n for (const requestBatch of requestBatches) {\n try {\n const result = await pRetry(\n async () => {\n const texts = requestBatch.map((request) => request.text);\n return provider.embedBatch(texts);\n },\n {\n retries: this.config.indexing.retries,\n minTimeout: Math.max(this.config.indexing.retryDelayMs, providerRateLimits.minRetryMs),\n maxTimeout: providerRateLimits.maxRetryMs,\n factor: 2,\n shouldRetry: (error) => !((error as { error?: Error }).error instanceof CustomProviderNonRetryableError),\n }\n );\n\n const touchedChunkIds = new Set<string>();\n requestBatch.forEach((request, idx) => {\n if (failedChunkIds.has(request.chunk.id) || completedChunkIds.has(request.chunk.id)) {\n return;\n }\n\n const vector = result.embeddings[idx];\n if (!vector) {\n throw new Error(`Embedding API returned too few vectors for chunk ${request.chunk.id}`);\n }\n\n const parts = embeddingPartsByChunk.get(request.chunk.id) ?? [];\n parts[request.partIndex] = {\n vector,\n tokenCount: request.tokenCount,\n };\n embeddingPartsByChunk.set(request.chunk.id, parts);\n touchedChunkIds.add(request.chunk.id);\n });\n\n for (const chunkId of touchedChunkIds) {\n if (failedChunkIds.has(chunkId) || completedChunkIds.has(chunkId)) {\n continue;\n }\n\n const chunk = batchChunksById.get(chunkId);\n if (!chunk) {\n continue;\n }\n\n const parts = embeddingPartsByChunk.get(chunk.id) ?? [];\n if (!hasAllEmbeddingParts(parts, chunk.texts.length)) {\n continue;\n }\n\n const orderedParts = parts as Array<{ vector: number[]; tokenCount: number }>;\n pooledResults.push({\n chunk,\n vector: poolEmbeddingVectors(\n orderedParts.map((part) => part.vector),\n orderedParts.map((part) => part.tokenCount)\n ),\n });\n }\n\n this.logger.recordEmbeddingApiCall(result.totalTokensUsed);\n } catch (error) {\n const failureMessage = String(error);\n const failureTimestamp = new Date().toISOString();\n const failedChunks = getUniquePendingChunksFromRequests(requestBatch)\n .filter((chunk) => !completedChunkIds.has(chunk.id) && !failedChunkIds.has(chunk.id));\n\n for (const chunk of failedChunks) {\n failedChunkIds.add(chunk.id);\n embeddingPartsByChunk.delete(chunk.id);\n failedChunksForBatch.set(chunk.id, {\n chunks: [chunk],\n attemptCount: batch.attemptCount + 1,\n lastAttempt: failureTimestamp,\n error: failureMessage,\n });\n }\n\n failed += failedChunks.length;\n this.logger.recordEmbeddingError();\n }\n }\n\n const successfulResults = pooledResults.filter(({ chunk }) => !failedChunkIds.has(chunk.id));\n\n const items = successfulResults.map(({ chunk, vector }) => ({\n id: chunk.id,\n vector,\n metadata: chunk.metadata,\n }));\n\n if (items.length > 0) {\n store.addBatch(items);\n }\n\n if (successfulResults.length > 0) {\n try {\n database.upsertEmbeddingsBatch(\n successfulResults.map(({ chunk, vector }) => ({\n contentHash: chunk.contentHash,\n embedding: float32ArrayToBuffer(vector),\n chunkText: chunk.storageText,\n model: configuredProviderInfo.modelInfo.model,\n }))\n );\n } catch (dbError) {\n this.rebuildVectorStoreExcludingChunkIds(\n store,\n database,\n successfulResults.map(({ chunk }) => chunk.id)\n );\n throw dbError;\n }\n }\n\n for (const { chunk } of successfulResults) {\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n completedChunkIds.add(chunk.id);\n embeddingPartsByChunk.delete(chunk.id);\n }\n\n database.addChunksToBranchBatch(\n this.getBranchCatalogKey(),\n successfulResults.map(({ chunk }) => chunk.id)\n );\n\n this.logger.recordChunksEmbedded(successfulResults.length);\n\n succeeded += successfulResults.length;\n stillFailing.push(...failedChunksForBatch.values());\n } catch (error) {\n const failureMessage = getErrorMessage(error);\n const failureTimestamp = new Date().toISOString();\n const unaccountedChunks = batch.chunks.filter(\n (chunk) => !failedChunksForBatch.has(chunk.id) && !completedChunkIds.has(chunk.id)\n );\n\n for (const chunk of unaccountedChunks) {\n failedChunksForBatch.set(chunk.id, {\n chunks: [chunk],\n attemptCount: batch.attemptCount + 1,\n lastAttempt: failureTimestamp,\n error: failureMessage,\n });\n }\n\n failed += unaccountedChunks.length;\n this.logger.recordEmbeddingError();\n stillFailing.push(...coalesceFailedBatches(Array.from(failedChunksForBatch.values())));\n }\n }\n\n const persistedStillFailing = coalesceFailedBatches(stillFailing);\n\n if (roots) {\n this.saveFailedBatches([...retainedFailedBatches, ...persistedStillFailing]);\n } else {\n this.saveFailedBatches(persistedStillFailing);\n }\n\n if (succeeded > 0) {\n store.save();\n invertedIndex.save();\n }\n\n if (roots && succeeded > 0 && persistedStillFailing.length === 0 && this.hasProjectForceReembedPending()) {\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n }\n\n return { succeeded, failed, remaining: persistedStillFailing.length };\n }\n\n getFailedBatchesCount(): number {\n if (this.config.scope === \"global\") {\n return this.partitionFailedBatches(this.getScopedRoots()).scoped.length;\n }\n return this.loadFailedBatches().length;\n }\n\n getCurrentBranch(): string {\n return this.currentBranch;\n }\n\n getBaseBranch(): string {\n return this.baseBranch;\n }\n\n refreshBranchInfo(): void {\n if (isGitRepo(this.projectRoot)) {\n this.currentBranch = getBranchOrDefault(this.projectRoot);\n this.baseBranch = getBaseBranch(this.projectRoot);\n }\n }\n\n async getDatabaseStats(): Promise<{ embeddingCount: number; chunkCount: number; branchChunkCount: number; branchCount: number } | null> {\n const { database } = await this.ensureInitialized();\n return database.getStats();\n }\n\n getLogger(): Logger {\n return this.logger;\n }\n\n async findSimilar(\n code: string,\n limit: number = this.config.search.maxResults,\n options?: {\n fileType?: string;\n directory?: string;\n chunkType?: string;\n excludeFile?: string;\n filterByBranch?: boolean;\n }\n ): Promise<SearchResult[]> {\n const { store, provider, database } = await this.ensureInitialized();\n\n const compatibility = this.checkCompatibility();\n if (!compatibility.compatible) {\n throw new Error(\n `${compatibility.reason ?? \"Index is incompatible with current embedding provider.\"} ` +\n `Run index_codebase with force=true to rebuild the index.`\n );\n }\n\n const searchStartTime = performance.now();\n\n if (store.count() === 0) {\n this.logger.search(\"debug\", \"Find similar on empty index\");\n return [];\n }\n\n const filterByBranch = options?.filterByBranch ?? true;\n\n this.logger.search(\"debug\", \"Starting find similar\", {\n codeLength: code.length,\n limit,\n filterByBranch,\n });\n\n const embeddingStartTime = performance.now();\n const { embedding, tokensUsed } = await provider.embedDocument(code);\n const embeddingMs = performance.now() - embeddingStartTime;\n this.logger.recordEmbeddingApiCall(tokensUsed);\n\n const vectorStartTime = performance.now();\n const semanticResults = store.search(embedding, limit * 2);\n const vectorMs = performance.now() - vectorStartTime;\n\n let branchChunkIds: Set<string> | null = null;\n if (filterByBranch && (this.config.scope === \"global\" || this.currentBranch !== \"default\")) {\n branchChunkIds = new Set(\n this.getBranchCatalogKeys().flatMap((branchKey) => database.getBranchChunkIds(branchKey))\n );\n }\n\n const prefilterStartTime = performance.now();\n const shouldPrefilterByBranch = branchChunkIds !== null && (this.config.scope === \"global\" || branchChunkIds.size > 0);\n const allowBranchPrefilterFallback = this.config.scope !== \"global\";\n const prefilteredSemantic = shouldPrefilterByBranch && branchChunkIds\n ? semanticResults.filter((r) => branchChunkIds.has(r.id))\n : semanticResults;\n const semanticCandidates = (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0)\n ? semanticResults\n : prefilteredSemantic;\n const prefilterMs = performance.now() - prefilterStartTime;\n\n if (this.config.scope !== \"global\" && branchChunkIds && branchChunkIds.size === 0) {\n this.logger.search(\"warn\", \"Branch prefilter skipped because branch catalog is empty\", {\n branch: this.currentBranch,\n });\n }\n\n if (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0) {\n this.logger.search(\"warn\", \"Branch prefilter produced no semantic overlap, using unfiltered semantic candidates\", {\n branch: this.currentBranch,\n });\n }\n\n const rerankTopN = this.config.search.rerankTopN;\n\n const ranked = rankSemanticOnlyResults(code, semanticCandidates, {\n rerankTopN,\n limit,\n prioritizeSourcePaths: false,\n });\n\n const filtered = ranked.filter((r) => {\n if (r.score < this.config.search.minScore) return false;\n\n if (options?.excludeFile) {\n if (r.metadata.filePath === options.excludeFile) return false;\n }\n\n if (options?.fileType) {\n const ext = r.metadata.filePath.split(\".\").pop()?.toLowerCase();\n if (ext !== options.fileType.toLowerCase().replace(/^\\./, \"\")) return false;\n }\n\n if (options?.directory) {\n const normalizedDir = options.directory.replace(/^\\/|\\/$/g, \"\");\n if (!r.metadata.filePath.includes(`/${normalizedDir}/`) &&\n !r.metadata.filePath.includes(`${normalizedDir}/`)) return false;\n }\n\n if (options?.chunkType) {\n if (r.metadata.chunkType !== options.chunkType) return false;\n }\n\n return true;\n }).slice(0, limit);\n\n const totalSearchMs = performance.now() - searchStartTime;\n this.logger.recordSearch(totalSearchMs, {\n embeddingMs,\n vectorMs,\n keywordMs: 0,\n fusionMs: 0,\n });\n this.logger.search(\"info\", \"Find similar complete\", {\n codeLength: code.length,\n results: filtered.length,\n totalMs: Math.round(totalSearchMs * 100) / 100,\n embeddingMs: Math.round(embeddingMs * 100) / 100,\n vectorMs: Math.round(vectorMs * 100) / 100,\n prefilterMs: Math.round(prefilterMs * 100) / 100,\n });\n\n return Promise.all(\n filtered.map(async (r) => {\n let content = \"\";\n\n if (this.config.search.includeContext) {\n try {\n const fileContent = await fsPromises.readFile(\n r.metadata.filePath,\n \"utf-8\"\n );\n const lines = fileContent.split(\"\\n\");\n content = lines\n .slice(r.metadata.startLine - 1, r.metadata.endLine)\n .join(\"\\n\");\n } catch {\n content = \"[File not accessible]\";\n }\n }\n\n return {\n filePath: r.metadata.filePath,\n startLine: r.metadata.startLine,\n endLine: r.metadata.endLine,\n content,\n score: r.score,\n chunkType: r.metadata.chunkType,\n name: r.metadata.name,\n };\n })\n );\n }\n\n async getCallers(targetName: string): Promise<CallEdgeData[]> {\n const { database } = await this.ensureInitialized();\n const seen = new Set<string>();\n const results: CallEdgeData[] = [];\n\n for (const branchKey of this.getBranchCatalogKeys()) {\n for (const edge of database.getCallersWithContext(targetName, branchKey)) {\n if (!seen.has(edge.id)) {\n seen.add(edge.id);\n results.push(edge);\n }\n }\n }\n\n return results;\n }\n\n async getCallees(symbolId: string): Promise<CallEdgeData[]> {\n const { database } = await this.ensureInitialized();\n const seen = new Set<string>();\n const results: CallEdgeData[] = [];\n\n for (const branchKey of this.getBranchCatalogKeys()) {\n for (const edge of database.getCallees(symbolId, branchKey)) {\n if (!seen.has(edge.id)) {\n seen.add(edge.id);\n results.push(edge);\n }\n }\n }\n\n return results;\n }\n\n async close(): Promise<void> {\n await this.database?.close();\n this.database = null;\n this.store = null;\n this.invertedIndex = null;\n this.provider = null;\n this.reranker = null;\n }\n}\n","import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n","export class TimeoutError extends Error {\n\tname = 'TimeoutError';\n\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tError.captureStackTrace?.(this, TimeoutError);\n\t}\n}\n\nconst getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t\tsignal,\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (signal?.aborted) {\n\t\t\treject(getAbortedReason(signal));\n\t\t\treturn;\n\t\t}\n\n\t\tif (signal) {\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\t// Use .then() instead of async IIFE to preserve stack traces\n\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\tpromise.then(resolve, reject);\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\t});\n\n\t// eslint-disable-next-line promise/prefer-await-to-then\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && signal) {\n\t\t\tsignal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n const { priority = 0, id, } = options ?? {};\n const element = {\n priority,\n id,\n run,\n };\n if (this.size === 0 || this.#queue[this.size - 1].priority >= priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n setPriority(id, priority) {\n const index = this.#queue.findIndex((element) => element.id === id);\n if (index === -1) {\n throw new ReferenceError(`No promise function with the id \"${id}\" exists in the queue.`);\n }\n const [item] = this.#queue.splice(index, 1);\n this.enqueue(item.run, { priority, id });\n }\n remove(idOrRun) {\n const index = this.#queue.findIndex((element) => {\n if (typeof idOrRun === 'string') {\n return element.id === idOrRun;\n }\n return element.run === idOrRun;\n });\n if (index !== -1) {\n this.#queue.splice(index, 1);\n }\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n","import { EventEmitter } from 'eventemitter3';\nimport pTimeout from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverIntervalCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #rateLimitedInInterval = false;\n #rateLimitFlushScheduled = false;\n #interval;\n #intervalEnd = 0;\n #lastExecutionTime = 0;\n #intervalId;\n #timeoutId;\n #strict;\n // Circular buffer implementation for better performance\n #strictTicks = [];\n #strictTicksStartIndex = 0;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n // Track currently running tasks for debugging\n #runningTasks = new Map();\n #queueAbortListenerCleanupFunctions = new Set();\n /**\n Get or set the default timeout for all tasks. Can be changed at runtime.\n\n Operations will throw a `TimeoutError` if they don't complete within the specified time.\n\n The timeout begins when the operation is dequeued and starts execution, not while it's waiting in the queue.\n\n @example\n ```\n const queue = new PQueue({timeout: 5000});\n\n // Change timeout for all future tasks\n queue.timeout = 10000;\n ```\n */\n timeout;\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverIntervalCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n strict: false,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n if (options.strict && options.interval === 0) {\n throw new TypeError('The `strict` option requires a non-zero `interval`');\n }\n if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) {\n throw new TypeError('The `strict` option requires a finite `intervalCap`');\n }\n // TODO: Remove this fallback in the next major version\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n this.#carryoverIntervalCount = options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#strict = options.strict;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) {\n throw new TypeError(`Expected \\`timeout\\` to be a positive finite number, got \\`${options.timeout}\\` (${typeof options.timeout})`);\n }\n this.timeout = options.timeout;\n this.#isPaused = options.autoStart === false;\n this.#setupRateLimitTracking();\n }\n #cleanupStrictTicks(now) {\n // Remove ticks outside the current interval window using circular buffer approach\n while (this.#strictTicksStartIndex < this.#strictTicks.length) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n if (oldestTick !== undefined && now - oldestTick >= this.#interval) {\n this.#strictTicksStartIndex++;\n }\n else {\n break;\n }\n }\n // Compact the array when it becomes inefficient or fully consumed\n // Compact when: (start index is large AND more than half wasted) OR all ticks expired\n const shouldCompact = (this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2)\n || this.#strictTicksStartIndex === this.#strictTicks.length;\n if (shouldCompact) {\n this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex);\n this.#strictTicksStartIndex = 0;\n }\n }\n // Helper methods for interval consumption\n #consumeIntervalSlot(now) {\n if (this.#strict) {\n this.#strictTicks.push(now);\n }\n else {\n this.#intervalCount++;\n }\n }\n #rollbackIntervalSlot() {\n if (this.#strict) {\n // Pop from the end of the actual data (not from start index)\n if (this.#strictTicks.length > this.#strictTicksStartIndex) {\n this.#strictTicks.pop();\n }\n }\n else if (this.#intervalCount > 0) {\n this.#intervalCount--;\n }\n }\n #getActiveTicksCount() {\n return this.#strictTicks.length - this.#strictTicksStartIndex;\n }\n get #doesIntervalAllowAnother() {\n if (this.#isIntervalIgnored) {\n return true;\n }\n if (this.#strict) {\n // Cleanup already done by #isIntervalPausedAt before this is called\n return this.#getActiveTicksCount() < this.#intervalCap;\n }\n return this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n if (this.#pending === 0) {\n this.emit('pendingZero');\n }\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n // Clear timeout ID before processing to prevent race condition\n // Must clear before #onInterval to allow new timeouts to be scheduled\n this.#timeoutId = undefined;\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n }\n #isIntervalPausedAt(now) {\n // Strict mode: check if we need to wait for oldest tick to age out\n if (this.#strict) {\n this.#cleanupStrictTicks(now);\n // If at capacity, need to wait for oldest tick to age out\n const activeTicksCount = this.#getActiveTicksCount();\n if (activeTicksCount >= this.#intervalCap) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n // After cleanup, remaining ticks are within interval, so delay is always > 0\n const delay = this.#interval - (now - oldestTick);\n this.#createIntervalTimeout(delay);\n return true;\n }\n return false;\n }\n // Fixed window mode (original logic)\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // If the interval has expired while idle, check if we should enforce the interval\n // from the last task execution. This ensures proper spacing between tasks even\n // when the queue becomes empty and then new tasks are added.\n if (this.#lastExecutionTime > 0) {\n const timeSinceLastExecution = now - this.#lastExecutionTime;\n if (timeSinceLastExecution < this.#interval) {\n // Not enough time has passed since the last task execution\n this.#createIntervalTimeout(this.#interval - timeSinceLastExecution);\n return true;\n }\n }\n // Enough time has passed or no previous execution, allow execution\n this.#intervalCount = (this.#carryoverIntervalCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n this.#createIntervalTimeout(delay);\n return true;\n }\n }\n return false;\n }\n #createIntervalTimeout(delay) {\n if (this.#timeoutId !== undefined) {\n return;\n }\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n #clearIntervalTimer() {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n }\n #clearTimeoutTimer() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = undefined;\n }\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n this.#clearIntervalTimer();\n this.emit('empty');\n if (this.#pending === 0) {\n // Clear timeout as well when completely idle\n this.#clearTimeoutTimer();\n // Compact strict ticks when idle to free memory\n if (this.#strict && this.#strictTicksStartIndex > 0) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n }\n this.emit('idle');\n }\n return false;\n }\n let taskStarted = false;\n if (!this.#isPaused) {\n const now = Date.now();\n const canInitializeInterval = !this.#isIntervalPausedAt(now);\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!this.#isIntervalIgnored) {\n this.#consumeIntervalSlot(now);\n this.#scheduleRateLimitUpdate();\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n taskStarted = true;\n }\n }\n return taskStarted;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n // Strict mode uses timeouts instead of interval timers\n if (this.#strict) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n // Non-strict mode uses interval timers and intervalCount\n if (!this.#strict) {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n this.#clearIntervalTimer();\n }\n this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0;\n }\n this.#processQueue();\n this.#scheduleRateLimitUpdate();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n /**\n Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.\n\n For example, this can be used to prioritize a promise function to run earlier.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦀', {priority: 0, id: '🦀'});\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦄', {priority: 1});\n\n queue.setPriority('🦀', 2);\n ```\n\n In this case, the promise function with `id: '🦀'` runs second.\n\n You can also deprioritize a promise function to delay its execution:\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦀', {priority: 1, id: '🦀'});\n queue.add(async () => '🦄');\n queue.add(async () => '🦄', {priority: 0});\n\n queue.setPriority('🦀', -1);\n ```\n Here, the promise function with `id: '🦀'` executes last.\n */\n setPriority(id, priority) {\n if (typeof priority !== 'number' || !Number.isFinite(priority)) {\n throw new TypeError(`Expected \\`priority\\` to be a finite number, got \\`${priority}\\` (${typeof priority})`);\n }\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // Create a copy to avoid mutating the original options object\n options = {\n timeout: this.timeout,\n ...options,\n // Assign unique ID if not provided\n id: options.id ?? (this.#idAssigner++).toString(),\n };\n return new Promise((resolve, reject) => {\n // Create a unique symbol for tracking this task\n const taskSymbol = Symbol(`task-${options.id}`);\n let cleanupQueueAbortHandler = () => undefined;\n const run = async () => {\n // Task is now running — remove the queued-state abort listener\n cleanupQueueAbortHandler();\n this.#pending++;\n // Track this running task\n this.#runningTasks.set(taskSymbol, {\n id: options.id,\n priority: options.priority ?? 0, // Match priority-queue default\n startTime: Date.now(),\n timeout: options.timeout,\n });\n let eventListener;\n try {\n // Check abort signal - if aborted, need to decrement the counter\n // that was incremented in tryToStartAnother\n try {\n options.signal?.throwIfAborted();\n }\n catch (error) {\n this.#rollbackIntervalConsumption();\n // Clean up tracking before throwing\n this.#runningTasks.delete(taskSymbol);\n throw error;\n }\n this.#lastExecutionTime = Date.now();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), {\n milliseconds: options.timeout,\n message: `Task timed out after ${options.timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)`,\n });\n }\n if (options.signal) {\n const { signal } = options;\n operation = Promise.race([operation, new Promise((_resolve, reject) => {\n eventListener = () => {\n reject(signal.reason);\n };\n signal.addEventListener('abort', eventListener, { once: true });\n })]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n reject(error);\n this.emit('error', error);\n }\n finally {\n // Clean up abort event listener\n if (eventListener) {\n options.signal?.removeEventListener('abort', eventListener);\n }\n // Remove from running tasks\n this.#runningTasks.delete(taskSymbol);\n // Use queueMicrotask to prevent deep recursion while maintaining timing\n queueMicrotask(() => {\n this.#next();\n });\n }\n };\n this.#queue.enqueue(run, options);\n const removeQueuedTask = () => {\n if (this.#queue instanceof PriorityQueue) {\n this.#queue.remove(run);\n return;\n }\n this.#queue.remove?.(options.id); // Intentionally best-effort: queued abort removal is only supported for queue classes that implement `.remove()`.\n };\n // Handle abort while task is waiting in the queue\n if (options.signal) {\n const { signal } = options;\n const queueAbortHandler = () => {\n cleanupQueueAbortHandler();\n removeQueuedTask();\n reject(signal.reason);\n this.#tryToStartAnother();\n this.emit('next');\n };\n cleanupQueueAbortHandler = () => {\n signal.removeEventListener('abort', queueAbortHandler);\n this.#queueAbortListenerCleanupFunctions.delete(cleanupQueueAbortHandler);\n };\n if (signal.aborted) {\n queueAbortHandler();\n return;\n }\n signal.addEventListener('abort', queueAbortHandler, { once: true });\n this.#queueAbortListenerCleanupFunctions.add(cleanupQueueAbortHandler);\n }\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n for (const cleanupQueueAbortHandler of this.#queueAbortListenerCleanupFunctions) {\n cleanupQueueAbortHandler();\n }\n this.#queue = new this.#queueClass();\n // Clear interval timer since queue is now empty (consistent with #tryToStartAnother)\n this.#clearIntervalTimer();\n // Note: We preserve strict mode rate-limiting state (ticks and timeout)\n // because clear() only clears queued tasks, not rate limit history.\n // This ensures that rate limits are still enforced after clearing the queue.\n // Note: We don't clear #runningTasks as those tasks are still running\n // They will be removed when they complete in the finally block\n // Force synchronous update since clear() should have immediate effect\n this.#updateRateLimitState();\n // Emit events so waiters (onEmpty, onIdle, onSizeLessThan) can resolve\n this.emit('empty');\n if (this.#pending === 0) {\n this.#clearTimeoutTimer();\n this.emit('idle');\n }\n this.emit('next');\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n /**\n The difference with `.onIdle` is that `.onPendingZero` only waits for currently running tasks to finish, ignoring queued tasks.\n\n @returns A promise that settles when all currently running tasks have completed; `queue.pending === 0`.\n */\n async onPendingZero() {\n if (this.#pending === 0) {\n return;\n }\n await this.#onEvent('pendingZero');\n }\n /**\n @returns A promise that settles when the queue becomes rate-limited due to intervalCap.\n */\n async onRateLimit() {\n if (this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimit');\n }\n /**\n @returns A promise that settles when the queue is no longer rate-limited.\n */\n async onRateLimitCleared() {\n if (!this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimitCleared');\n }\n /**\n @returns A promise that rejects when any task in the queue errors.\n\n Use with `Promise.race([queue.onError(), queue.onIdle()])` to fail fast on the first error while still resolving normally when the queue goes idle.\n\n Important: The promise returned by `add()` still rejects. You must handle each `add()` promise (for example, `.catch(() => {})`) to avoid unhandled rejections.\n\n @example\n ```\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n queue.add(() => fetchData(1)).catch(() => {});\n queue.add(() => fetchData(2)).catch(() => {});\n queue.add(() => fetchData(3)).catch(() => {});\n\n // Stop processing on first error\n try {\n await Promise.race([\n queue.onError(),\n queue.onIdle()\n ]);\n } catch (error) {\n queue.pause(); // Stop processing remaining tasks\n console.error('Queue failed:', error);\n }\n ```\n */\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n onError() {\n return new Promise((_resolve, reject) => {\n const handleError = (error) => {\n this.off('error', handleError);\n reject(error);\n };\n this.on('error', handleError);\n });\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n #setupRateLimitTracking() {\n // Only schedule updates when rate limiting is enabled\n if (this.#isIntervalIgnored) {\n return;\n }\n // Wire up to lifecycle events that affect rate limit state\n // Only 'add' and 'next' can actually change rate limit state\n this.on('add', () => {\n if (this.#queue.size > 0) {\n this.#scheduleRateLimitUpdate();\n }\n });\n this.on('next', () => {\n this.#scheduleRateLimitUpdate();\n });\n }\n #scheduleRateLimitUpdate() {\n // Skip if rate limiting is not enabled or already scheduled\n if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) {\n return;\n }\n this.#rateLimitFlushScheduled = true;\n queueMicrotask(() => {\n this.#rateLimitFlushScheduled = false;\n this.#updateRateLimitState();\n });\n }\n #rollbackIntervalConsumption() {\n if (this.#isIntervalIgnored) {\n return;\n }\n this.#rollbackIntervalSlot();\n this.#scheduleRateLimitUpdate();\n }\n #updateRateLimitState() {\n const previous = this.#rateLimitedInInterval;\n // Early exit if rate limiting is disabled or queue is empty\n if (this.#isIntervalIgnored || this.#queue.size === 0) {\n if (previous) {\n this.#rateLimitedInInterval = false;\n this.emit('rateLimitCleared');\n }\n return;\n }\n // Get the current count based on mode\n let count;\n if (this.#strict) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n count = this.#getActiveTicksCount();\n }\n else {\n count = this.#intervalCount;\n }\n const shouldBeRateLimited = count >= this.#intervalCap;\n if (shouldBeRateLimited !== previous) {\n this.#rateLimitedInInterval = shouldBeRateLimited;\n this.emit(shouldBeRateLimited ? 'rateLimit' : 'rateLimitCleared');\n }\n }\n /**\n Whether the queue is currently rate-limited due to intervalCap.\n */\n get isRateLimited() {\n return this.#rateLimitedInInterval;\n }\n /**\n Whether the queue is saturated. Returns `true` when:\n - All concurrency slots are occupied and tasks are waiting, OR\n - The queue is rate-limited and tasks are waiting\n\n Useful for detecting backpressure and potential hanging tasks.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n // Backpressure handling\n if (queue.isSaturated) {\n console.log('Queue is saturated, waiting for capacity...');\n await queue.onSizeLessThan(queue.concurrency);\n }\n\n // Monitoring for stuck tasks\n setInterval(() => {\n if (queue.isSaturated) {\n console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);\n }\n }, 60000);\n ```\n */\n get isSaturated() {\n return (this.#pending === this.#concurrency && this.#queue.size > 0)\n || (this.isRateLimited && this.#queue.size > 0);\n }\n /**\n The tasks currently being executed. Each task includes its `id`, `priority`, `startTime`, and `timeout` (if set).\n\n Returns an array of task info objects.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n // Add tasks with IDs for better debugging\n queue.add(() => fetchUser(123), {id: 'user-123'});\n queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});\n\n // Check what's running\n console.log(queue.runningTasks);\n // => [{\n // id: 'user-123',\n // priority: 0,\n // startTime: 1759253001716,\n // timeout: undefined\n // }, {\n // id: 'posts-456',\n // priority: 1,\n // startTime: 1759253001916,\n // timeout: undefined\n // }]\n ```\n */\n get runningTasks() {\n // Return fresh array with fresh objects to prevent mutations\n return [...this.#runningTasks.values()].map(task => ({ ...task }));\n }\n}\n/**\nError thrown when a task times out.\n\n@example\n```\nimport PQueue, {TimeoutError} from 'p-queue';\n\nconst queue = new PQueue({timeout: 1000});\n\ntry {\n await queue.add(() => someTask());\n} catch (error) {\n if (error instanceof TimeoutError) {\n console.log('Task timed out');\n }\n}\n```\n*/\nexport { TimeoutError } from 'p-timeout';\n","const objectToString = Object.prototype.toString;\n\nconst isError = value => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n\t' A network error occurred.', // Bun (WebKit)\n\t'Network connection lost', // Cloudflare Workers (fetch)\n]);\n\nexport default function isNetworkError(error) {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\tconst {message, stack} = error;\n\n\t// Safari 17+ has generic message but no stack for network errors\n\tif (message === 'Load failed') {\n\t\treturn stack === undefined\n\t\t\t// Sentry adds its own stack trace to the fetch error, so also check for that\n\t\t\t|| '__sentry_captured__' in error;\n\t}\n\n\t// Deno network errors start with specific text\n\tif (message.startsWith('error sending request for url')) {\n\t\treturn true;\n\t}\n\n\t// Chrome: exact \"Failed to fetch\" or with hostname: \"Failed to fetch (example.com)\"\n\tif (message === 'Failed to fetch' || (message.startsWith('Failed to fetch (') && message.endsWith(')'))) {\n\t\treturn true;\n\t}\n\n\t// Standard network error messages\n\treturn errorMessages.has(message);\n}\n","import isNetworkError from 'is-network-error';\n\nfunction validateRetries(retries) {\n\tif (typeof retries === 'number') {\n\t\tif (retries < 0) {\n\t\t\tthrow new TypeError('Expected `retries` to be a non-negative number.');\n\t\t}\n\n\t\tif (Number.isNaN(retries)) {\n\t\t\tthrow new TypeError('Expected `retries` to be a valid number or Infinity, got NaN.');\n\t\t}\n\t} else if (retries !== undefined) {\n\t\tthrow new TypeError('Expected `retries` to be a number or Infinity.');\n\t}\n}\n\nfunction validateNumberOption(name, value, {min = 0, allowInfinity = false} = {}) {\n\tif (value === undefined) {\n\t\treturn;\n\t}\n\n\tif (typeof value !== 'number' || Number.isNaN(value)) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be a number${allowInfinity ? ' or Infinity' : ''}.`);\n\t}\n\n\tif (!allowInfinity && !Number.isFinite(value)) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be a finite number.`);\n\t}\n\n\tif (value < min) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be \\u2265 ${min}.`);\n\t}\n}\n\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nfunction calculateDelay(retriesConsumed, options) {\n\tconst attempt = Math.max(1, retriesConsumed + 1);\n\tconst random = options.randomize ? (Math.random() + 1) : 1;\n\n\tlet timeout = Math.round(random * options.minTimeout * (options.factor ** (attempt - 1)));\n\ttimeout = Math.min(timeout, options.maxTimeout);\n\n\treturn timeout;\n}\n\nfunction calculateRemainingTime(start, max) {\n\tif (!Number.isFinite(max)) {\n\t\treturn max;\n\t}\n\n\treturn max - (performance.now() - start);\n}\n\nasync function onAttemptFailure({error, attemptNumber, retriesConsumed, startTime, options}) {\n\tconst normalizedError = error instanceof Error\n\t\t? error\n\t\t: new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`);\n\n\tif (normalizedError instanceof AbortError) {\n\t\tthrow normalizedError.originalError;\n\t}\n\n\tconst retriesLeft = Number.isFinite(options.retries)\n\t\t? Math.max(0, options.retries - retriesConsumed)\n\t\t: options.retries;\n\n\tconst maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;\n\n\tconst context = Object.freeze({\n\t\terror: normalizedError,\n\t\tattemptNumber,\n\t\tretriesLeft,\n\t\tretriesConsumed,\n\t});\n\n\tawait options.onFailedAttempt(context);\n\n\tif (calculateRemainingTime(startTime, maxRetryTime) <= 0) {\n\t\tthrow normalizedError;\n\t}\n\n\tconst consumeRetry = await options.shouldConsumeRetry(context);\n\n\tconst remainingTime = calculateRemainingTime(startTime, maxRetryTime);\n\n\tif (remainingTime <= 0 || retriesLeft <= 0) {\n\t\tthrow normalizedError;\n\t}\n\n\tif (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {\n\t\tif (consumeRetry) {\n\t\t\tthrow normalizedError;\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\t\treturn false;\n\t}\n\n\tif (!await options.shouldRetry(context)) {\n\t\tthrow normalizedError;\n\t}\n\n\tif (!consumeRetry) {\n\t\toptions.signal?.throwIfAborted();\n\t\treturn false;\n\t}\n\n\tconst delayTime = calculateDelay(retriesConsumed, options);\n\tconst finalDelay = Math.min(delayTime, remainingTime);\n\n\toptions.signal?.throwIfAborted();\n\n\tif (finalDelay > 0) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tclearTimeout(timeoutToken);\n\t\t\t\toptions.signal?.removeEventListener('abort', onAbort);\n\t\t\t\treject(options.signal.reason);\n\t\t\t};\n\n\t\t\tconst timeoutToken = setTimeout(() => {\n\t\t\t\toptions.signal?.removeEventListener('abort', onAbort);\n\t\t\t\tresolve();\n\t\t\t}, finalDelay);\n\n\t\t\tif (options.unref) {\n\t\t\t\ttimeoutToken.unref?.();\n\t\t\t}\n\n\t\t\toptions.signal?.addEventListener('abort', onAbort, {once: true});\n\t\t});\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\treturn true;\n}\n\nexport default async function pRetry(input, options = {}) {\n\toptions = {...options};\n\n\tvalidateRetries(options.retries);\n\n\tif (Object.hasOwn(options, 'forever')) {\n\t\tthrow new Error('The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.');\n\t}\n\n\toptions.retries ??= 10;\n\toptions.factor ??= 2;\n\toptions.minTimeout ??= 1000;\n\toptions.maxTimeout ??= Number.POSITIVE_INFINITY;\n\toptions.maxRetryTime ??= Number.POSITIVE_INFINITY;\n\toptions.randomize ??= false;\n\toptions.onFailedAttempt ??= () => {};\n\toptions.shouldRetry ??= () => true;\n\toptions.shouldConsumeRetry ??= () => true;\n\n\t// Validate numeric options and normalize edge cases\n\tvalidateNumberOption('factor', options.factor, {min: 0, allowInfinity: false});\n\tvalidateNumberOption('minTimeout', options.minTimeout, {min: 0, allowInfinity: false});\n\tvalidateNumberOption('maxTimeout', options.maxTimeout, {min: 0, allowInfinity: true});\n\tvalidateNumberOption('maxRetryTime', options.maxRetryTime, {min: 0, allowInfinity: true});\n\n\t// Treat non-positive factor as 1 to avoid zero backoff or negative behavior\n\tif (!(options.factor > 0)) {\n\t\toptions.factor = 1;\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tlet attemptNumber = 0;\n\tlet retriesConsumed = 0;\n\tconst startTime = performance.now();\n\n\twhile (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {\n\t\tattemptNumber++;\n\n\t\ttry {\n\t\t\toptions.signal?.throwIfAborted();\n\n\t\t\tconst result = await input(attemptNumber);\n\n\t\t\toptions.signal?.throwIfAborted();\n\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tif (await onAttemptFailure({\n\t\t\t\terror,\n\t\t\t\tattemptNumber,\n\t\t\t\tretriesConsumed,\n\t\t\t\tstartTime,\n\t\t\t\toptions,\n\t\t\t})) {\n\t\t\t\tretriesConsumed++;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Should not reach here, but in case it does, throw an error\n\tthrow new Error('Retry attempts exhausted without throwing an error.');\n}\n\nexport function makeRetriable(function_, options) {\n\treturn function (...arguments_) {\n\t\treturn pRetry(() => function_.apply(this, arguments_), options);\n\t};\n}\n","import { type EmbeddingProvider, type CustomProviderConfig, type BaseModelInfo, getDefaultModelForProvider, isValidModel, autoDetectProviders, EmbeddingModelName, EMBEDDING_MODELS } from \"../config\";\nimport { existsSync, readFileSync } from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\n\nexport interface ProviderCredentials {\n provider: EmbeddingProvider | 'custom';\n apiKey?: string;\n baseUrl?: string;\n refreshToken?: string;\n accessToken?: string;\n tokenExpires?: number;\n}\n\nexport interface CustomModelInfo extends BaseModelInfo {\n provider: 'custom';\n timeoutMs: number;\n maxBatchSize?: number;\n}\n\nexport type ConfiguredProviderInfo = {\n [P in EmbeddingProvider]: {\n provider: P;\n credentials: ProviderCredentials;\n modelInfo: (typeof EMBEDDING_MODELS)[P][keyof (typeof EMBEDDING_MODELS)[P]];\n }\n}[EmbeddingProvider] | {\n provider: 'custom';\n credentials: ProviderCredentials;\n modelInfo: CustomModelInfo;\n}\n\ninterface OpenCodeAuthOAuth {\n type: \"oauth\";\n refresh: string;\n access: string;\n expires: number;\n enterpriseUrl?: string;\n}\n\ninterface OpenCodeAuthAPI {\n type: \"api\";\n key: string;\n}\n\ntype OpenCodeAuth = OpenCodeAuthOAuth | OpenCodeAuthAPI;\n\nfunction getOpenCodeAuthPath(): string {\n return path.join(os.homedir(), \".local\", \"share\", \"opencode\", \"auth.json\");\n}\n\nfunction loadOpenCodeAuth(): Record<string, OpenCodeAuth> {\n const authPath = getOpenCodeAuthPath();\n try {\n if (existsSync(authPath)) {\n return JSON.parse(readFileSync(authPath, \"utf-8\"));\n }\n } catch {\n // Ignore auth file read errors\n }\n return {};\n}\n\nexport async function detectEmbeddingProvider<P extends EmbeddingProvider>(\n preferredProvider: P, model?: EmbeddingModelName\n): Promise<ConfiguredProviderInfo> {\n const credentials = await getProviderCredentials(preferredProvider);\n if (credentials) {\n if (!model) {\n return {\n provider: preferredProvider,\n credentials,\n modelInfo: getDefaultModelForProvider(preferredProvider),\n } as ConfiguredProviderInfo;\n }\n if (!isValidModel(model, preferredProvider)) {\n throw new Error(\n `Model '${model}' is not supported by provider '${preferredProvider}'`\n );\n }\n const providerModels = EMBEDDING_MODELS[preferredProvider];\n return {\n provider: preferredProvider,\n credentials,\n modelInfo: providerModels[model],\n } as ConfiguredProviderInfo;\n }\n throw new Error(\n `Preferred provider '${preferredProvider}' is not configured or authenticated`\n );\n}\n\nexport async function tryDetectProvider(): Promise<ConfiguredProviderInfo> {\n for (const provider of autoDetectProviders) {\n const credentials = await getProviderCredentials(provider);\n if (credentials) {\n return {\n provider,\n credentials,\n modelInfo: getDefaultModelForProvider(provider),\n } as ConfiguredProviderInfo;\n }\n }\n\n throw new Error(\n `No embedding-capable provider found. Please authenticate with OpenCode using one of: ${autoDetectProviders.join(\", \")}.`\n );\n}\n\nasync function getProviderCredentials(\n provider: EmbeddingProvider\n): Promise<ProviderCredentials | null> {\n switch (provider) {\n case \"github-copilot\":\n return getGitHubCopilotCredentials();\n case \"openai\":\n return getOpenAICredentials();\n case \"google\":\n return getGoogleCredentials();\n case \"ollama\":\n return getOllamaCredentials();\n default:\n return null;\n }\n}\n\nfunction getGitHubCopilotCredentials(): ProviderCredentials | null {\n const authData = loadOpenCodeAuth();\n const copilotAuth = authData[\"github-copilot\"] || authData[\"github-copilot-enterprise\"];\n\n if (!copilotAuth || copilotAuth.type !== \"oauth\") {\n return null;\n }\n\n // Use GitHub Models API for embeddings (models.github.ai)\n // Enterprise uses different URL pattern\n const auth = copilotAuth as OpenCodeAuthOAuth;\n const baseUrl = auth.enterpriseUrl\n ? `https://copilot-api.${auth.enterpriseUrl.replace(/^https?:\\/\\//, \"\").replace(/\\/$/, \"\")}`\n : \"https://models.github.ai\";\n\n return {\n provider: \"github-copilot\",\n baseUrl,\n refreshToken: copilotAuth.refresh,\n accessToken: copilotAuth.access,\n tokenExpires: copilotAuth.expires,\n };\n}\n\nfunction getOpenAICredentials(): ProviderCredentials | null {\n const authData = loadOpenCodeAuth();\n const openaiAuth = authData[\"openai\"];\n\n if (openaiAuth?.type === \"api\") {\n return {\n provider: \"openai\",\n apiKey: openaiAuth.key,\n baseUrl: \"https://api.openai.com/v1\",\n };\n }\n\n return null;\n}\n\nfunction getGoogleCredentials(): ProviderCredentials | null {\n const authData = loadOpenCodeAuth();\n const googleAuth = authData[\"google\"] || authData[\"google-generative-ai\"];\n\n if (googleAuth?.type === \"api\") {\n return {\n provider: \"google\",\n apiKey: googleAuth.key,\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta\",\n };\n }\n\n return null;\n}\n\nasync function getOllamaCredentials(): Promise<ProviderCredentials | null> {\n const baseUrl = process.env.OLLAMA_HOST || \"http://localhost:11434\";\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 2000);\n\n const response = await fetch(`${baseUrl}/api/tags`, {\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n const data = await response.json() as { models?: Array<{ name: string }> };\n const hasEmbeddingModel = data.models?.some(\n (m: { name: string }) =>\n m.name.includes(\"nomic-embed\") ||\n m.name.includes(\"mxbai-embed\") ||\n m.name.includes(\"all-minilm\")\n );\n\n if (hasEmbeddingModel) {\n return {\n provider: \"ollama\",\n baseUrl,\n };\n }\n }\n } catch {\n return null;\n }\n\n return null;\n}\n\nexport function getProviderDisplayName(provider: EmbeddingProvider | 'custom'): string {\n switch (provider) {\n case \"github-copilot\":\n return \"GitHub Copilot\";\n case \"openai\":\n return \"OpenAI\";\n case \"google\":\n return \"Google (Gemini)\";\n case \"ollama\":\n return \"Ollama (Local)\";\n case \"custom\":\n return \"Custom (OpenAI-compatible)\";\n default:\n return provider;\n }\n}\n\nexport function createCustomProviderInfo(config: CustomProviderConfig): ConfiguredProviderInfo {\n // Normalize baseUrl defensively — parseConfig() already strips trailing slashes,\n // but direct callers (e.g. tests) may pass unnormalized URLs.\n const baseUrl = config.baseUrl.replace(/\\/+$/, '');\n return {\n provider: 'custom',\n credentials: {\n provider: 'custom',\n baseUrl,\n apiKey: config.apiKey,\n },\n modelInfo: {\n provider: 'custom',\n model: config.model,\n dimensions: config.dimensions,\n maxTokens: config.maxTokens ?? 8192,\n costPer1MTokens: 0,\n timeoutMs: config.timeoutMs ?? 30_000,\n maxBatchSize: config.maxBatchSize,\n },\n };\n}\n","import { type BaseModelInfo } from \"../config/schema.js\";\n\nimport { type ProviderCredentials } from \"./detector.js\";\n\nexport interface EmbeddingResult {\n embedding: number[];\n tokensUsed: number;\n}\n\nexport interface EmbeddingBatchResult {\n embeddings: number[][];\n totalTokensUsed: number;\n}\n\nexport interface EmbeddingProviderInterface {\n embedQuery(query: string): Promise<EmbeddingResult>;\n embedDocument(document: string): Promise<EmbeddingResult>;\n embedBatch(texts: string[]): Promise<EmbeddingBatchResult>;\n getModelInfo(): BaseModelInfo;\n}\n\nexport abstract class BaseEmbeddingProvider<TModelInfo extends BaseModelInfo>\n implements EmbeddingProviderInterface {\n public constructor(\n protected readonly credentials: ProviderCredentials,\n protected readonly modelInfo: TModelInfo\n ) { }\n\n public async embedQuery(query: string): Promise<EmbeddingResult> {\n const result = await this.embedBatch([query]);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public async embedDocument(document: string): Promise<EmbeddingResult> {\n const result = await this.embedBatch([document]);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public getModelInfo(): TModelInfo {\n return this.modelInfo;\n }\n\n public abstract embedBatch(texts: string[]): Promise<EmbeddingBatchResult>;\n}\n\n/**\n * Thrown by CustomEmbeddingProvider for HTTP 4xx errors (except 429 rate limit).\n * The Indexer's pRetry config uses instanceof to bail immediately on these errors\n * instead of retrying — preventing long retry loops on bad API keys or invalid models.\n */\nexport class CustomProviderNonRetryableError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"CustomProviderNonRetryableError\";\n }\n}\n","/**\n * URL validation utilities to prevent SSRF attacks against cloud metadata services.\n *\n * IMPORTANT: This intentionally allows localhost and private IPs because the custom\n * embedding provider is commonly used with local servers (Ollama, llama.cpp, vLLM,\n * text-embeddings-inference). The threat model is a malicious committed config file\n * targeting cloud metadata endpoints, not blocking legitimate local usage.\n *\n * KNOWN LIMITATION: This validates the hostname string only, not the resolved IP.\n * A DNS rebinding attack (hostname that resolves to 169.254.169.254) bypasses this\n * check. Full mitigation would require DNS resolution pinning (resolve → check IP →\n * connect), which needs a custom HTTP agent. Acceptable for now given the local-only\n * threat model and the low likelihood of DNS rebinding in committed config files.\n */\n\n/** Cloud metadata service IPs and hostnames that should never be contacted. */\nconst BLOCKED_METADATA_IPS = [\n /^169\\.254\\.169\\.254$/, // AWS/Azure/GCP metadata\n /^169\\.254\\.170\\.2$/, // AWS ECS task metadata\n /^fd00:ec2::254$/, // AWS IMDSv2 IPv6\n];\n\nconst BLOCKED_HOSTNAMES = new Set([\n \"metadata.google.internal\",\n \"metadata.google\",\n \"metadata.goog\",\n \"kubernetes.default.svc\",\n]);\n\nexport interface UrlValidationResult {\n valid: boolean;\n reason?: string;\n}\n\n/**\n * Validates that a URL does not point to cloud metadata services or use dangerous protocols.\n * Allows localhost and private IPs for local embedding servers.\n * Returns { valid: true } if the URL is safe, or { valid: false, reason } if blocked.\n */\nexport function validateExternalUrl(urlString: string): UrlValidationResult {\n let parsed: URL;\n try {\n parsed = new URL(urlString);\n } catch {\n return { valid: false, reason: `Invalid URL: ${sanitizeUrlForError(urlString)}` };\n }\n\n // Block non-HTTP protocols (file://, gopher://, ftp://, etc.)\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return { valid: false, reason: `Blocked protocol: ${parsed.protocol}` };\n }\n\n const hostname = parsed.hostname.toLowerCase();\n\n // Block known cloud metadata hostnames\n if (BLOCKED_HOSTNAMES.has(hostname)) {\n return { valid: false, reason: `Blocked: cloud metadata service (${hostname})` };\n }\n\n // Block cloud metadata IPs\n for (const pattern of BLOCKED_METADATA_IPS) {\n if (pattern.test(hostname)) {\n return { valid: false, reason: `Blocked: cloud metadata IP (${hostname})` };\n }\n }\n\n // Block link-local range (169.254.x.x) — used exclusively for metadata/APIPA, not user servers\n if (/^169\\.254\\./.test(hostname)) {\n return { valid: false, reason: `Blocked: link-local address (${hostname})` };\n }\n\n return { valid: true };\n}\n\n/**\n * Strips credentials and sensitive parts from a URL for safe inclusion in error messages.\n */\nexport function sanitizeUrlForError(url: string): string {\n try {\n const parsed = new URL(url);\n // Remove username:password from URL\n parsed.username = \"\";\n parsed.password = \"\";\n return parsed.toString();\n } catch {\n // If URL can't be parsed, truncate and mask\n const maxLen = 80;\n if (url.length > maxLen) {\n return url.slice(0, maxLen) + \"...\";\n }\n return url;\n }\n}\n","import { type CustomModelInfo, type ProviderCredentials } from \"../detector.js\";\nimport {\n BaseEmbeddingProvider,\n CustomProviderNonRetryableError,\n type EmbeddingBatchResult,\n} from \"../provider-types.js\";\nimport { sanitizeUrlForError, validateExternalUrl } from \"../../utils/url-validation.js\";\n\nexport class CustomEmbeddingProvider extends BaseEmbeddingProvider<CustomModelInfo> {\n public constructor(credentials: ProviderCredentials, modelInfo: CustomModelInfo) {\n super(credentials, modelInfo);\n }\n\n private splitIntoRequestBatches(texts: string[]): string[][] {\n const maxBatchSize = this.modelInfo.maxBatchSize;\n\n if (!maxBatchSize || texts.length <= maxBatchSize) {\n return [texts];\n }\n\n const batches: string[][] = [];\n for (let i = 0; i < texts.length; i += maxBatchSize) {\n batches.push(texts.slice(i, i + maxBatchSize));\n }\n return batches;\n }\n\n private async embedRequest(texts: string[]): Promise<EmbeddingBatchResult> {\n if (texts.length === 0) {\n return {\n embeddings: [],\n totalTokensUsed: 0,\n };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (this.credentials.apiKey) {\n headers.Authorization = `Bearer ${this.credentials.apiKey}`;\n }\n\n const baseUrl = this.credentials.baseUrl ?? \"\";\n const fullUrl = `${baseUrl}/embeddings`;\n\n const urlCheck = validateExternalUrl(fullUrl);\n if (!urlCheck.valid) {\n throw new CustomProviderNonRetryableError(\n `Custom embedding provider URL blocked (SSRF protection): ${urlCheck.reason}`\n );\n }\n\n const timeoutMs = this.modelInfo.timeoutMs;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n let response: Response;\n try {\n response = await fetch(fullUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model: this.modelInfo.model,\n input: texts,\n }),\n signal: controller.signal,\n });\n } catch (error: unknown) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Custom embedding API request timed out after ${timeoutMs}ms for ${sanitizeUrlForError(fullUrl)}`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n\n if (!response.ok) {\n const errorText = (await response.text()).slice(0, 500);\n if (response.status >= 400 && response.status < 500 && response.status !== 429) {\n throw new CustomProviderNonRetryableError(`Custom embedding API error (non-retryable): ${response.status} - ${errorText}`);\n }\n throw new Error(`Custom embedding API error: ${response.status} - ${errorText}`);\n }\n\n const data = await response.json() as {\n data?: Array<{ embedding: number[] }>;\n usage?: { total_tokens: number };\n };\n\n if (data.data && Array.isArray(data.data)) {\n if (data.data.length > 0) {\n const actualDims = data.data[0].embedding.length;\n if (actualDims !== this.modelInfo.dimensions) {\n throw new Error(\n `Dimension mismatch: customProvider.dimensions is ${this.modelInfo.dimensions}, ` +\n `but the API returned vectors with ${actualDims} dimensions. ` +\n `Update your config to match the model's actual output dimensions.`\n );\n }\n }\n\n if (data.data.length !== texts.length) {\n throw new Error(\n `Embedding count mismatch: sent ${texts.length} texts but received ${data.data.length} embeddings. ` +\n `The custom embedding server may not support batch input.`\n );\n }\n\n return {\n embeddings: data.data.map((d) => d.embedding),\n totalTokensUsed: data.usage?.total_tokens ?? texts.reduce((sum, t) => sum + Math.ceil(t.length / 4), 0),\n };\n }\n\n throw new Error(\"Custom embedding API returned unexpected response format. Expected OpenAI-compatible format with data[].embedding.\");\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const requestBatches = this.splitIntoRequestBatches(texts);\n const embeddings: number[][] = [];\n let totalTokensUsed = 0;\n\n for (const batch of requestBatches) {\n const result = await this.embedRequest(batch);\n embeddings.push(...result.embeddings);\n totalTokensUsed += result.totalTokensUsed;\n }\n\n return {\n embeddings,\n totalTokensUsed,\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport { BaseEmbeddingProvider, type EmbeddingBatchResult } from \"../provider-types.js\";\n\nexport class GitHubCopilotEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"github-copilot\"]> {\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"github-copilot\"]\n ) {\n super(credentials, modelInfo);\n }\n\n private getToken(): string {\n if (!this.credentials.refreshToken) {\n throw new Error(\"No OAuth token available for GitHub\");\n }\n return this.credentials.refreshToken;\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const token = this.getToken();\n\n const response = await fetch(`${this.credentials.baseUrl}/inference/embeddings`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n body: JSON.stringify({\n model: `openai/${this.modelInfo.model}`,\n input: texts,\n }),\n });\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`GitHub Copilot embedding API error: ${response.status} - ${error}`);\n }\n\n const data = await response.json() as {\n data: Array<{ embedding: number[] }>;\n usage: { total_tokens: number };\n };\n\n return {\n embeddings: data.data.map((d) => d.embedding),\n totalTokensUsed: data.usage.total_tokens,\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport {\n BaseEmbeddingProvider,\n type EmbeddingBatchResult,\n type EmbeddingResult,\n} from \"../provider-types.js\";\n\nexport class GoogleEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"google\"]> {\n private static readonly BATCH_SIZE = 20;\n\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"google\"]\n ) {\n super(credentials, modelInfo);\n }\n\n public async embedQuery(query: string): Promise<EmbeddingResult> {\n const taskType = this.modelInfo.taskAble ? \"CODE_RETRIEVAL_QUERY\" : undefined;\n const result = await this.embedWithTaskType([query], taskType);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public async embedDocument(document: string): Promise<EmbeddingResult> {\n const taskType = this.modelInfo.taskAble ? \"RETRIEVAL_DOCUMENT\" : undefined;\n const result = await this.embedWithTaskType([document], taskType);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const taskType = this.modelInfo.taskAble ? \"RETRIEVAL_DOCUMENT\" : undefined;\n return this.embedWithTaskType(texts, taskType);\n }\n\n private async embedWithTaskType(\n texts: string[],\n taskType?: string\n ): Promise<EmbeddingBatchResult> {\n const batches: string[][] = [];\n for (let i = 0; i < texts.length; i += GoogleEmbeddingProvider.BATCH_SIZE) {\n batches.push(texts.slice(i, i + GoogleEmbeddingProvider.BATCH_SIZE));\n }\n\n const batchResults = await Promise.all(\n batches.map(async (batch) => {\n const requests = batch.map((text) => ({\n model: `models/${this.modelInfo.model}`,\n content: {\n parts: [{ text }],\n },\n taskType,\n outputDimensionality: this.modelInfo.dimensions,\n }));\n\n const response = await fetch(\n `${this.credentials.baseUrl}/models/${this.modelInfo.model}:batchEmbedContents`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(this.credentials.apiKey && { \"x-goog-api-key\": this.credentials.apiKey }),\n },\n body: JSON.stringify({ requests }),\n }\n );\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`Google embedding API error: ${response.status} - ${error}`);\n }\n\n const data = (await response.json()) as {\n embeddings: Array<{ values: number[] }>;\n };\n\n return {\n embeddings: data.embeddings.map((e) => e.values),\n tokensUsed: batch.reduce((sum, text) => sum + Math.ceil(text.length / 4), 0),\n };\n })\n );\n\n return {\n embeddings: batchResults.flatMap((r) => r.embeddings),\n totalTokensUsed: batchResults.reduce((sum, r) => sum + r.tokensUsed, 0),\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport { BaseEmbeddingProvider, type EmbeddingBatchResult } from \"../provider-types.js\";\n\nexport class OllamaEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"ollama\"]> {\n private static readonly MIN_TRUNCATION_CHARS = 512;\n\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"ollama\"]\n ) {\n super(credentials, modelInfo);\n }\n\n private estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n }\n\n private truncateToCharLimit(text: string, maxChars: number): string {\n if (text.length <= maxChars) {\n return text;\n }\n\n return `${text.slice(0, Math.max(0, maxChars - 17))}\\n... [truncated]`;\n }\n\n private isContextLengthError(error: unknown): boolean {\n const message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n return (message.includes(\"context length\") && (message.includes(\"exceed\") || message.includes(\"exceeded\") || message.includes(\"too long\")))\n || message.includes(\"input length exceeds the context length\")\n || message.includes(\"context length exceeded\");\n }\n\n private buildTruncationCandidates(text: string): string[] {\n const baseMaxChars = Math.max(1, this.modelInfo.maxTokens * 4);\n const candidateLimits = new Set<number>();\n const baselineLimit = text.length > baseMaxChars\n ? baseMaxChars\n : Math.max(\n OllamaEmbeddingProvider.MIN_TRUNCATION_CHARS,\n Math.floor(text.length * 0.9)\n );\n\n if (baselineLimit < text.length) {\n candidateLimits.add(baselineLimit);\n }\n\n for (const factor of [0.75, 0.6, 0.45, 0.35, 0.25]) {\n const scaledLimit = Math.max(\n OllamaEmbeddingProvider.MIN_TRUNCATION_CHARS,\n Math.floor(baselineLimit * factor)\n );\n if (scaledLimit < text.length) {\n candidateLimits.add(scaledLimit);\n }\n }\n\n candidateLimits.add(Math.min(text.length - 1, OllamaEmbeddingProvider.MIN_TRUNCATION_CHARS));\n\n const candidates: string[] = [];\n const seen = new Set<string>();\n for (const limit of [...candidateLimits].sort((a, b) => b - a)) {\n if (limit <= 0 || limit >= text.length) {\n continue;\n }\n\n const truncated = this.truncateToCharLimit(text, limit);\n if (truncated === text || seen.has(truncated)) {\n continue;\n }\n\n seen.add(truncated);\n candidates.push(truncated);\n }\n\n return candidates;\n }\n\n private async embedSingleWithFallback(text: string): Promise<{ embedding: number[]; tokensUsed: number }> {\n try {\n return await this.embedSingle(text);\n } catch (error) {\n if (!this.isContextLengthError(error)) {\n throw error;\n }\n\n let lastError: unknown = error;\n for (const truncated of this.buildTruncationCandidates(text)) {\n try {\n return await this.embedSingle(truncated);\n } catch (retryError) {\n if (!this.isContextLengthError(retryError)) {\n throw retryError;\n }\n lastError = retryError;\n }\n }\n\n throw lastError;\n }\n }\n\n private async embedSingle(text: string): Promise<{ embedding: number[]; tokensUsed: number }> {\n const response = await fetch(`${this.credentials.baseUrl}/api/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: this.modelInfo.model,\n prompt: text,\n truncate: false,\n }),\n });\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`Ollama embedding API error: ${response.status} - ${error}`);\n }\n\n const data = (await response.json()) as {\n embedding: number[];\n };\n\n return {\n embedding: data.embedding,\n tokensUsed: this.estimateTokens(text),\n };\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const results: Array<{ embedding: number[]; tokensUsed: number }> = [];\n\n for (const text of texts) {\n results.push(await this.embedSingleWithFallback(text));\n }\n\n return {\n embeddings: results.map((r) => r.embedding),\n totalTokensUsed: results.reduce((sum, r) => sum + r.tokensUsed, 0),\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport { BaseEmbeddingProvider, type EmbeddingBatchResult } from \"../provider-types.js\";\n\nexport class OpenAIEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"openai\"]> {\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"openai\"]\n ) {\n super(credentials, modelInfo);\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const response = await fetch(`${this.credentials.baseUrl}/embeddings`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.credentials.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: this.modelInfo.model,\n input: texts,\n }),\n });\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`OpenAI embedding API error: ${response.status} - ${error}`);\n }\n\n const data = await response.json() as {\n data: Array<{ embedding: number[] }>;\n usage: { total_tokens: number };\n };\n\n return {\n embeddings: data.data.map((d) => d.embedding),\n totalTokensUsed: data.usage.total_tokens,\n };\n }\n}\n","import { type ConfiguredProviderInfo } from \"./detector.js\";\nimport { CustomEmbeddingProvider } from \"./providers/custom.js\";\nimport { GitHubCopilotEmbeddingProvider } from \"./providers/github-copilot.js\";\nimport { GoogleEmbeddingProvider } from \"./providers/google.js\";\nimport { OllamaEmbeddingProvider } from \"./providers/ollama.js\";\nimport { OpenAIEmbeddingProvider } from \"./providers/openai.js\";\n\nexport {\n BaseEmbeddingProvider,\n CustomProviderNonRetryableError,\n type EmbeddingBatchResult,\n type EmbeddingProviderInterface,\n type EmbeddingResult,\n} from \"./provider-types.js\";\n\nexport function createEmbeddingProvider(\n configuredProviderInfo: ConfiguredProviderInfo,\n): import(\"./provider-types.js\").EmbeddingProviderInterface {\n switch (configuredProviderInfo.provider) {\n case \"github-copilot\":\n return new GitHubCopilotEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"openai\":\n return new OpenAIEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"google\":\n return new GoogleEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"ollama\":\n return new OllamaEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"custom\":\n return new CustomEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n default: {\n const _exhaustive: never = configuredProviderInfo;\n throw new Error(`Unsupported embedding provider: ${(_exhaustive as ConfiguredProviderInfo).provider}`);\n }\n }\n}\n","import { RerankerConfig } from \"../config/schema.js\";\n\nexport interface RerankResult {\n index: number;\n relevanceScore: number;\n document?: string;\n}\n\nexport interface RerankResponse {\n results: RerankResult[];\n tokensUsed?: number;\n}\n\nexport interface RerankerInterface {\n isAvailable(): boolean;\n rerank(query: string, documents: string[], topN?: number): Promise<RerankResponse>;\n}\n\nexport function createReranker(config: RerankerConfig): RerankerInterface {\n if (!config.enabled) {\n return new NoOpReranker();\n }\n return new SiliconFlowReranker(config);\n}\n\nclass NoOpReranker implements RerankerInterface {\n isAvailable(): boolean {\n return false;\n }\n\n async rerank(_query: string, documents: string[], _topN?: number): Promise<RerankResponse> {\n return {\n results: documents.map((_, index) => ({ index, relevanceScore: 0 })),\n };\n }\n}\n\nclass SiliconFlowReranker implements RerankerInterface {\n private config: RerankerConfig;\n\n constructor(config: RerankerConfig) {\n this.config = config;\n }\n\n isAvailable(): boolean {\n return this.config.enabled && !!this.config.baseUrl && !!this.config.model;\n }\n\n async rerank(query: string, documents: string[], topN?: number): Promise<RerankResponse> {\n if (documents.length === 0) {\n return { results: [] };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (this.config.apiKey) {\n headers[\"Authorization\"] = `Bearer ${this.config.apiKey}`;\n }\n\n const baseUrl = this.config.baseUrl;\n if (!baseUrl) {\n throw new Error(\"Reranker baseUrl is required. Configure reranker.baseUrl in your codebase-index.json.\");\n }\n const timeoutMs = this.config.timeoutMs ?? 30000;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(`${baseUrl}/rerank`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model: this.config.model,\n query,\n documents,\n top_n: topN ?? this.config.topN ?? 20,\n return_documents: false,\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Rerank API error: ${response.status} - ${errorText}`);\n }\n\n const data = await response.json() as {\n results: Array<{\n index: number;\n relevance_score: number;\n document?: { text: string };\n }>;\n meta?: {\n tokens?: {\n input_tokens: number;\n output_tokens: number;\n };\n };\n };\n\n return {\n results: data.results.map((r) => ({\n index: r.index,\n relevanceScore: r.relevance_score,\n document: r.document?.text,\n })),\n tokensUsed: data.meta?.tokens?.input_tokens,\n };\n } catch (error: unknown) {\n clearTimeout(timeout);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`Rerank API request timed out after ${timeoutMs}ms`);\n }\n throw error;\n }\n }\n}\n","import { BaseModelInfo } from \"../config/schema.js\";\nimport { getProviderDisplayName, ConfiguredProviderInfo } from \"../embeddings/detector.js\";\n\nexport interface CostEstimate {\n filesCount: number;\n totalSizeBytes: number;\n estimatedChunks: number;\n estimatedTokens: number;\n estimatedCost: number;\n provider: string;\n model: string;\n isFree: boolean;\n}\n\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nexport function estimateChunksFromFiles(\n files: Array<{ path: string; size: number }>\n): number {\n let totalChunks = 0;\n\n for (const file of files) {\n const avgChunkSize = 400;\n const chunksPerFile = Math.max(1, Math.ceil(file.size / avgChunkSize));\n totalChunks += chunksPerFile;\n }\n\n return totalChunks;\n}\n\nexport function estimateCost(\n estimatedTokens: number,\n modelInfo: BaseModelInfo\n): number {\n return (estimatedTokens / 1_000_000) * modelInfo.costPer1MTokens;\n}\n\nexport function createCostEstimate(\n files: Array<{ path: string; size: number }>,\n provider: ConfiguredProviderInfo\n): CostEstimate {\n const filesCount = files.length;\n const totalSizeBytes = files.reduce((sum, f) => sum + f.size, 0);\n const estimatedChunks = estimateChunksFromFiles(files);\n const avgTokensPerChunk = 150;\n const estimatedTokens = estimatedChunks * avgTokensPerChunk;\n const estimatedCost = estimateCost(estimatedTokens, provider.modelInfo);\n\n return {\n filesCount,\n totalSizeBytes,\n estimatedChunks,\n estimatedTokens,\n estimatedCost,\n provider: getProviderDisplayName(provider.provider),\n model: provider.modelInfo.model,\n isFree: provider.modelInfo.costPer1MTokens === 0,\n };\n}\n\nexport function formatCostEstimate(estimate: CostEstimate): string {\n const sizeFormatted = formatBytes(estimate.totalSizeBytes);\n const filesFormatted = `${estimate.filesCount.toLocaleString()} files`;\n const costFormatted = estimate.isFree\n ? \"Free\"\n : `~$${estimate.estimatedCost.toFixed(4)}`;\n\n return `\n┌─────────────────────────────────────────────────────────────────┐\n│ 📊 Indexing Estimate │\n├─────────────────────────────────────────────────────────────────┤\n│ │\n│ Files to index: ${filesFormatted.padEnd(40)}│\n│ Total size: ${sizeFormatted.padEnd(40)}│\n│ Estimated chunks: ${(\"~\" + estimate.estimatedChunks.toLocaleString() + \" chunks\").padEnd(40)}│\n│ Estimated tokens: ${(\"~\" + estimate.estimatedTokens.toLocaleString() + \" tokens\").padEnd(40)}│\n│ │\n│ Provider: ${estimate.provider.padEnd(52)}│\n│ Model: ${estimate.model.padEnd(52)}│\n│ Cost: ${costFormatted.padEnd(52)}│\n│ │\n└─────────────────────────────────────────────────────────────────┘\n`;\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return \"0 B\";\n const k = 1024;\n const sizes = [\"B\", \"KB\", \"MB\", \"GB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + \" \" + sizes[i];\n}\n\n\nexport interface ConfirmationResult {\n confirmed: boolean;\n rememberChoice: boolean;\n}\n\nexport function formatConfirmationPrompt(): string {\n return `\nProceed with indexing? [Y/n/always]\n\n Y - Index now\n n - Cancel\n always - Index now and don't ask again for this project\n`;\n}\n\nexport function parseConfirmationResponse(response: string): ConfirmationResult {\n const normalized = response.toLowerCase().trim();\n\n if (normalized === \"\" || normalized === \"y\" || normalized === \"yes\") {\n return { confirmed: true, rememberChoice: false };\n }\n\n if (normalized === \"always\" || normalized === \"a\") {\n return { confirmed: true, rememberChoice: true };\n }\n\n return { confirmed: false, rememberChoice: false };\n}\n","import type { DebugConfig, LogLevel } from \"../config/schema.js\";\n\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nexport interface Metrics {\n indexingStartTime?: number;\n indexingEndTime?: number;\n filesScanned: number;\n filesParsed: number;\n parseMs: number;\n chunksProcessed: number;\n chunksEmbedded: number;\n chunksFromCache: number;\n chunksRemoved: number;\n embeddingApiCalls: number;\n embeddingTokensUsed: number;\n embeddingErrors: number;\n \n searchCount: number;\n searchTotalMs: number;\n searchAvgMs: number;\n searchLastMs: number;\n embeddingCallMs: number;\n vectorSearchMs: number;\n keywordSearchMs: number;\n fusionMs: number;\n \n cacheHits: number;\n cacheMisses: number;\n \n queryCacheHits: number;\n queryCacheSimilarHits: number;\n queryCacheMisses: number;\n \n gcRuns: number;\n gcOrphansRemoved: number;\n gcChunksRemoved: number;\n gcEmbeddingsRemoved: number;\n}\n\nexport interface LogEntry {\n timestamp: string;\n level: LogLevel;\n category: string;\n message: string;\n data?: Record<string, unknown>;\n}\n\nfunction createEmptyMetrics(): Metrics {\n return {\n filesScanned: 0,\n filesParsed: 0,\n parseMs: 0,\n chunksProcessed: 0,\n chunksEmbedded: 0,\n chunksFromCache: 0,\n chunksRemoved: 0,\n embeddingApiCalls: 0,\n embeddingTokensUsed: 0,\n embeddingErrors: 0,\n searchCount: 0,\n searchTotalMs: 0,\n searchAvgMs: 0,\n searchLastMs: 0,\n embeddingCallMs: 0,\n vectorSearchMs: 0,\n keywordSearchMs: 0,\n fusionMs: 0,\n cacheHits: 0,\n cacheMisses: 0,\n queryCacheHits: 0,\n queryCacheSimilarHits: 0,\n queryCacheMisses: 0,\n gcRuns: 0,\n gcOrphansRemoved: 0,\n gcChunksRemoved: 0,\n gcEmbeddingsRemoved: 0,\n };\n}\n\nexport class Logger {\n private config: DebugConfig;\n private metrics: Metrics;\n private logs: LogEntry[] = [];\n private maxLogs = 1000;\n\n constructor(config: DebugConfig) {\n this.config = config;\n this.metrics = createEmptyMetrics();\n }\n\n private shouldLog(level: LogLevel): boolean {\n if (!this.config.enabled) return false;\n return LOG_LEVEL_PRIORITY[level] <= LOG_LEVEL_PRIORITY[this.config.logLevel];\n }\n\n private log(level: LogLevel, category: string, message: string, data?: Record<string, unknown>): void {\n if (!this.shouldLog(level)) return;\n\n const entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n category,\n message,\n data,\n };\n\n this.logs.push(entry);\n if (this.logs.length > this.maxLogs) {\n this.logs.shift();\n }\n }\n\n private withMetrics(fn: () => void): void {\n if (!this.config.metrics) return;\n fn();\n }\n\n search(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logSearch) {\n this.log(level, \"search\", message, data);\n }\n }\n\n embedding(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logEmbedding) {\n this.log(level, \"embedding\", message, data);\n }\n }\n\n cache(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logCache) {\n this.log(level, \"cache\", message, data);\n }\n }\n\n gc(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logGc) {\n this.log(level, \"gc\", message, data);\n }\n }\n\n branch(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logBranch) {\n this.log(level, \"branch\", message, data);\n }\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.log(\"info\", \"general\", message, data);\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.log(\"warn\", \"general\", message, data);\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.log(\"error\", \"general\", message, data);\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.log(\"debug\", \"general\", message, data);\n }\n\n recordIndexingStart(): void {\n this.withMetrics(() => {\n this.metrics.indexingStartTime = Date.now();\n });\n }\n\n recordIndexingEnd(): void {\n this.withMetrics(() => {\n this.metrics.indexingEndTime = Date.now();\n });\n }\n\n recordFilesScanned(count: number): void {\n this.withMetrics(() => {\n this.metrics.filesScanned = count;\n });\n }\n\n recordFilesParsed(count: number): void {\n this.withMetrics(() => {\n this.metrics.filesParsed = count;\n });\n }\n\n recordParseDuration(durationMs: number): void {\n this.withMetrics(() => {\n this.metrics.parseMs = durationMs;\n });\n }\n\n recordChunksProcessed(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksProcessed += count;\n });\n }\n\n recordChunksEmbedded(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksEmbedded += count;\n });\n }\n\n recordChunksFromCache(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksFromCache += count;\n });\n }\n\n recordChunksRemoved(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksRemoved += count;\n });\n }\n\n recordEmbeddingApiCall(tokens: number): void {\n this.withMetrics(() => {\n this.metrics.embeddingApiCalls++;\n this.metrics.embeddingTokensUsed += tokens;\n });\n }\n\n recordEmbeddingError(): void {\n this.withMetrics(() => {\n this.metrics.embeddingErrors++;\n });\n }\n\n recordSearch(durationMs: number, breakdown?: { embeddingMs: number; vectorMs: number; keywordMs: number; fusionMs: number }): void {\n this.withMetrics(() => {\n this.metrics.searchCount++;\n this.metrics.searchTotalMs += durationMs;\n this.metrics.searchLastMs = durationMs;\n this.metrics.searchAvgMs = this.metrics.searchTotalMs / this.metrics.searchCount;\n\n if (breakdown) {\n this.metrics.embeddingCallMs = breakdown.embeddingMs;\n this.metrics.vectorSearchMs = breakdown.vectorMs;\n this.metrics.keywordSearchMs = breakdown.keywordMs;\n this.metrics.fusionMs = breakdown.fusionMs;\n }\n });\n }\n\n recordCacheHit(): void {\n this.withMetrics(() => {\n this.metrics.cacheHits++;\n });\n }\n\n recordCacheMiss(): void {\n this.withMetrics(() => {\n this.metrics.cacheMisses++;\n });\n }\n\n recordQueryCacheHit(): void {\n this.withMetrics(() => {\n this.metrics.queryCacheHits++;\n });\n }\n\n recordQueryCacheSimilarHit(): void {\n this.withMetrics(() => {\n this.metrics.queryCacheSimilarHits++;\n });\n }\n\n recordQueryCacheMiss(): void {\n this.withMetrics(() => {\n this.metrics.queryCacheMisses++;\n });\n }\n\n recordGc(orphans: number, chunks: number, embeddings: number): void {\n this.withMetrics(() => {\n this.metrics.gcRuns++;\n this.metrics.gcOrphansRemoved += orphans;\n this.metrics.gcChunksRemoved += chunks;\n this.metrics.gcEmbeddingsRemoved += embeddings;\n });\n }\n\n getMetrics(): Metrics {\n return { ...this.metrics };\n }\n\n getLogs(limit?: number): LogEntry[] {\n const logs = [...this.logs];\n if (limit) {\n return logs.slice(-limit);\n }\n return logs;\n }\n\n getLogsByCategory(category: string, limit?: number): LogEntry[] {\n const filtered = this.logs.filter(l => l.category === category);\n if (limit) {\n return filtered.slice(-limit);\n }\n return filtered;\n }\n\n getLogsByLevel(level: LogLevel, limit?: number): LogEntry[] {\n const filtered = this.logs.filter(l => l.level === level);\n if (limit) {\n return filtered.slice(-limit);\n }\n return filtered;\n }\n\n resetMetrics(): void {\n this.metrics = createEmptyMetrics();\n }\n\n clearLogs(): void {\n this.logs = [];\n }\n\n formatMetrics(): string {\n const m = this.metrics;\n const lines: string[] = [];\n \n if (m.indexingStartTime && m.indexingEndTime) {\n const duration = m.indexingEndTime - m.indexingStartTime;\n lines.push(`Indexing duration: ${(duration / 1000).toFixed(2)}s`);\n }\n \n lines.push(\"\");\n lines.push(\"Indexing:\");\n lines.push(` Files scanned: ${m.filesScanned}`);\n lines.push(` Files parsed: ${m.filesParsed}`);\n lines.push(` Chunks processed: ${m.chunksProcessed}`);\n lines.push(` Chunks embedded: ${m.chunksEmbedded}`);\n lines.push(` Chunks from cache: ${m.chunksFromCache}`);\n lines.push(` Chunks removed: ${m.chunksRemoved}`);\n \n lines.push(\"\");\n lines.push(\"Embedding API:\");\n lines.push(` API calls: ${m.embeddingApiCalls}`);\n lines.push(` Tokens used: ${m.embeddingTokensUsed.toLocaleString()}`);\n lines.push(` Errors: ${m.embeddingErrors}`);\n \n if (m.searchCount > 0) {\n lines.push(\"\");\n lines.push(\"Search:\");\n lines.push(` Total searches: ${m.searchCount}`);\n lines.push(` Average time: ${m.searchAvgMs.toFixed(2)}ms`);\n lines.push(` Last search: ${m.searchLastMs.toFixed(2)}ms`);\n if (m.embeddingCallMs > 0) {\n lines.push(` - Embedding: ${m.embeddingCallMs.toFixed(2)}ms`);\n lines.push(` - Vector search: ${m.vectorSearchMs.toFixed(2)}ms`);\n lines.push(` - Keyword search: ${m.keywordSearchMs.toFixed(2)}ms`);\n lines.push(` - Fusion: ${m.fusionMs.toFixed(2)}ms`);\n }\n }\n \n const totalCacheOps = m.cacheHits + m.cacheMisses;\n if (totalCacheOps > 0) {\n lines.push(\"\");\n lines.push(\"Cache:\");\n lines.push(` Hits: ${m.cacheHits}`);\n lines.push(` Misses: ${m.cacheMisses}`);\n lines.push(` Hit rate: ${((m.cacheHits / totalCacheOps) * 100).toFixed(1)}%`);\n }\n \n if (m.gcRuns > 0) {\n lines.push(\"\");\n lines.push(\"Garbage Collection:\");\n lines.push(` GC runs: ${m.gcRuns}`);\n lines.push(` Orphans removed: ${m.gcOrphansRemoved}`);\n lines.push(` Chunks removed: ${m.gcChunksRemoved}`);\n lines.push(` Embeddings removed: ${m.gcEmbeddingsRemoved}`);\n }\n \n return lines.join(\"\\n\");\n }\n\n formatRecentLogs(limit = 20): string {\n const logs = this.getLogs(limit);\n if (logs.length === 0) {\n return \"No logs recorded.\";\n }\n \n return logs.map(l => {\n const dataStr = l.data ? ` ${JSON.stringify(l.data)}` : \"\";\n return `[${l.timestamp}] [${l.level.toUpperCase()}] [${l.category}] ${l.message}${dataStr}`;\n }).join(\"\\n\");\n }\n\n isEnabled(): boolean {\n return this.config.enabled;\n }\n\n isMetricsEnabled(): boolean {\n return this.config.enabled && this.config.metrics;\n }\n}\n\nlet globalLogger: Logger | null = null;\n\nexport function initializeLogger(config: DebugConfig): Logger {\n globalLogger = new Logger(config);\n return globalLogger;\n}\n\nexport function getLogger(): Logger | null {\n return globalLogger;\n}\n","import * as path from \"path\";\nimport * as os from \"os\";\nimport * as module from \"module\";\nimport { fileURLToPath } from \"url\";\n\nfunction getNativeBinding() {\n const platform = os.platform();\n const arch = os.arch();\n\n let bindingName: string;\n \n if (platform === \"darwin\" && arch === \"arm64\") {\n bindingName = \"codebase-index-native.darwin-arm64.node\";\n } else if (platform === \"darwin\" && arch === \"x64\") {\n bindingName = \"codebase-index-native.darwin-x64.node\";\n } else if (platform === \"linux\" && arch === \"x64\") {\n bindingName = \"codebase-index-native.linux-x64-gnu.node\";\n } else if (platform === \"linux\" && arch === \"arm64\") {\n bindingName = \"codebase-index-native.linux-arm64-gnu.node\";\n } else if (platform === \"win32\" && arch === \"x64\") {\n bindingName = \"codebase-index-native.win32-x64-msvc.node\";\n } else {\n throw new Error(`Unsupported platform: ${platform}-${arch}`);\n }\n\n // Determine the current directory - handle ESM, CJS, and bundled contexts\n let currentDir: string;\n let requireTarget: string;\n \n // Check for ESM context with valid import.meta.url\n if (typeof import.meta !== 'undefined' && import.meta.url) {\n currentDir = path.dirname(fileURLToPath(import.meta.url));\n requireTarget = import.meta.url;\n } \n // Fallback to __dirname for CJS/bundled contexts\n else if (typeof __dirname !== 'undefined') {\n currentDir = __dirname;\n requireTarget = __filename;\n }\n // Last resort: use process.cwd() - shouldn't normally hit this\n else {\n currentDir = process.cwd();\n requireTarget = path.join(currentDir, \"index.js\");\n }\n \n // The native module is in the 'native' folder at package root\n // From dist/index.js, we go up one level to package root, then into native/\n // From src/native/index.ts (dev/test), we go up two levels to package root\n const normalizedDir = currentDir.replace(/\\\\/g, '/');\n const isDevMode = normalizedDir.includes('/src/native') || currentDir.includes(path.join('src', 'native'));\n const packageRoot = isDevMode\n ? path.resolve(currentDir, '../..')\n : path.resolve(currentDir, '..');\n const nativePath = path.join(packageRoot, 'native', bindingName);\n \n // Load the native module - use standard require for .node files\n const require = module.createRequire(requireTarget);\n return require(nativePath);\n}\n\nfunction createMockNativeBinding() {\n const error = new Error(\"Native module not available. Please rebuild with 'npm run build:native'.\");\n \n return {\n parseFile: () => { throw error; },\n parseFiles: () => { throw error; },\n hashContent: () => { throw error; },\n hashFile: () => { throw error; },\n extractCalls: () => { throw error; },\n VectorStore: class {\n constructor() { throw error; }\n },\n InvertedIndex: class {\n constructor() { throw error; }\n serialize() { throw error; }\n deserialize() { throw error; }\n },\n Database: class {\n constructor() { throw error; }\n close() { throw error; }\n },\n };\n}\n\nlet native: any;\ntry {\n native = getNativeBinding();\n} catch (e) {\n console.error(\"[codebase-index] Failed to load native module:\", e);\n native = createMockNativeBinding();\n}\n\nexport interface FileInput {\n path: string;\n content: string;\n}\n\nexport interface CodeChunk {\n content: string;\n startLine: number;\n endLine: number;\n chunkType: ChunkType;\n name?: string;\n language: string;\n}\n\nexport type ChunkType =\n | \"function\"\n | \"class\"\n | \"method\"\n | \"interface\"\n | \"type\"\n | \"enum\"\n | \"struct\"\n | \"impl\"\n | \"trait\"\n | \"module\"\n | \"import\"\n | \"export\"\n | \"comment\"\n | \"other\";\n\nexport interface ParsedFile {\n path: string;\n chunks: CodeChunk[];\n hash: string;\n}\n\n\nexport type CallType = \"Call\" | \"MethodCall\" | \"Constructor\" | \"Import\";\n\nexport interface CallSiteData {\n calleeName: string;\n line: number;\n column: number;\n callType: CallType;\n}\n\nexport interface SymbolData {\n id: string;\n filePath: string;\n name: string;\n kind: string;\n startLine: number;\n startCol: number;\n endLine: number;\n endCol: number;\n language: string;\n}\n\nexport interface CallEdgeData {\n id: string;\n fromSymbolId: string;\n fromSymbolName?: string;\n fromSymbolFilePath?: string;\n targetName: string;\n toSymbolId?: string;\n callType: string;\n line: number;\n col: number;\n isResolved: boolean;\n}\n\nexport interface SearchResult {\n id: string;\n score: number;\n metadata: ChunkMetadata;\n}\n\nexport interface ChunkMetadata {\n filePath: string;\n startLine: number;\n endLine: number;\n chunkType: ChunkType;\n name?: string;\n language: string;\n hash: string;\n}\n\nexport function parseFile(filePath: string, content: string): CodeChunk[] {\n const result = native.parseFile(filePath, content);\n return result.map(mapChunk);\n}\n\nexport function parseFileAsText(filePath: string, content: string): CodeChunk[] {\n const result = native.parseFileAsText(filePath, content);\n return result.map(mapChunk);\n}\n\nexport function parseFiles(files: FileInput[]): ParsedFile[] {\n const result = native.parseFiles(files);\n return result.map((f: any) => ({\n path: f.path,\n chunks: f.chunks.map(mapChunk),\n hash: f.hash,\n }));\n}\n\nfunction mapChunk(c: any): CodeChunk {\n return {\n content: c.content,\n startLine: c.startLine ?? c.start_line,\n endLine: c.endLine ?? c.end_line,\n chunkType: (c.chunkType ?? c.chunk_type) as ChunkType,\n name: c.name ?? undefined,\n language: c.language,\n };\n}\n\nexport function hashContent(content: string): string {\n return native.hashContent(content);\n}\n\nexport function hashFile(filePath: string): string {\n return native.hashFile(filePath);\n}\n\n\nexport function extractCalls(content: string, language: string): CallSiteData[] {\n return native.extractCalls(content, language);\n}\n\nexport class VectorStore {\n private inner: any;\n private dimensions: number;\n\n constructor(indexPath: string, dimensions: number) {\n this.inner = new native.VectorStore(indexPath, dimensions);\n this.dimensions = dimensions;\n }\n\n add(id: string, vector: number[], metadata: ChunkMetadata): void {\n if (vector.length !== this.dimensions) {\n throw new Error(\n `Vector dimension mismatch: expected ${this.dimensions}, got ${vector.length}`\n );\n }\n this.inner.add(id, vector, JSON.stringify(metadata));\n }\n\n addBatch(\n items: Array<{ id: string; vector: number[]; metadata: ChunkMetadata }>\n ): void {\n const ids = items.map((i) => i.id);\n const vectors = items.map((i) => {\n if (i.vector.length !== this.dimensions) {\n throw new Error(\n `Vector dimension mismatch for ${i.id}: expected ${this.dimensions}, got ${i.vector.length}`\n );\n }\n return i.vector;\n });\n const metadata = items.map((i) => JSON.stringify(i.metadata));\n this.inner.addBatch(ids, vectors, metadata);\n }\n\n search(queryVector: number[], limit: number = 10): SearchResult[] {\n if (queryVector.length !== this.dimensions) {\n throw new Error(\n `Query vector dimension mismatch: expected ${this.dimensions}, got ${queryVector.length}`\n );\n }\n const results = this.inner.search(queryVector, limit);\n return results.map((r: any) => ({\n id: r.id,\n score: r.score,\n metadata: JSON.parse(r.metadata) as ChunkMetadata,\n }));\n }\n\n remove(id: string): boolean {\n return this.inner.remove(id);\n }\n\n save(): void {\n this.inner.save();\n }\n\n load(): void {\n this.inner.load();\n }\n\n count(): number {\n return this.inner.count();\n }\n\n clear(): void {\n this.inner.clear();\n }\n\n getDimensions(): number {\n return this.dimensions;\n }\n\n getAllKeys(): string[] {\n return this.inner.getAllKeys();\n }\n\n getAllMetadata(): Array<{ key: string; metadata: ChunkMetadata }> {\n const results = this.inner.getAllMetadata();\n return results.map((r: { key: string; metadata: string }) => ({\n key: r.key,\n metadata: JSON.parse(r.metadata) as ChunkMetadata,\n }));\n }\n\n getMetadata(id: string): ChunkMetadata | undefined {\n const result = this.inner.getMetadata(id);\n if (result === null || result === undefined) {\n return undefined;\n }\n return JSON.parse(result) as ChunkMetadata;\n }\n\n getMetadataBatch(ids: string[]): Map<string, ChunkMetadata> {\n const results = this.inner.getMetadataBatch(ids);\n const map = new Map<string, ChunkMetadata>();\n for (const { key, metadata } of results) {\n map.set(key, JSON.parse(metadata) as ChunkMetadata);\n }\n return map;\n }\n}\n\n// Token estimation: ~4 chars per token for code (conservative)\nconst CHARS_PER_TOKEN = 4;\nconst MAX_BATCH_TOKENS = 7500; // Leave buffer under 8192 API limit\nconst MAX_SINGLE_CHUNK_TOKENS = 2000; // Default truncation cap for individual chunks\n\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nfunction getEmbeddingHeaderParts(chunk: CodeChunk, filePath: string): string[] {\n const parts: string[] = [];\n\n const fileName = filePath.split(\"/\").pop() || filePath;\n const dirPath = filePath.split(\"/\").slice(-3, -1).join(\"/\");\n\n const langDescriptors: Record<string, string> = {\n typescript: \"TypeScript\",\n javascript: \"JavaScript\",\n python: \"Python\",\n rust: \"Rust\",\n go: \"Go\",\n java: \"Java\",\n };\n\n const typeDescriptors: Record<string, string> = {\n function_declaration: \"function\",\n function: \"function\",\n arrow_function: \"arrow function\",\n method_definition: \"method\",\n class_declaration: \"class\",\n interface_declaration: \"interface\",\n type_alias_declaration: \"type alias\",\n enum_declaration: \"enum\",\n export_statement: \"export\",\n lexical_declaration: \"variable declaration\",\n function_definition: \"function\",\n class_definition: \"class\",\n function_item: \"function\",\n impl_item: \"implementation\",\n struct_item: \"struct\",\n enum_item: \"enum\",\n trait_item: \"trait\",\n };\n\n const lang = langDescriptors[chunk.language] || chunk.language;\n const typeDesc = typeDescriptors[chunk.chunkType] || chunk.chunkType;\n\n if (chunk.name) {\n parts.push(`${lang} ${typeDesc} \"${chunk.name}\"`);\n } else {\n parts.push(`${lang} ${typeDesc}`);\n }\n\n if (dirPath) {\n parts.push(`in ${dirPath}/${fileName}`);\n } else {\n parts.push(`in ${fileName}`);\n }\n\n const semanticHints = extractSemanticHints(chunk.name || \"\", chunk.content);\n if (semanticHints.length > 0) {\n parts.push(`Purpose: ${semanticHints.join(\", \")}`);\n }\n\n return parts;\n}\n\nfunction buildEmbeddingText(headerParts: string[], content: string, partIndex?: number, partCount?: number): string {\n const parts = [...headerParts];\n if (partCount && partCount > 1 && partIndex) {\n parts.push(`Part ${partIndex}/${partCount}`);\n }\n parts.push(\"\");\n parts.push(content);\n return parts.join(\"\\n\");\n}\n\nfunction splitOversizedContent(content: string, maxContentChars: number): string[] {\n if (content.length <= maxContentChars) {\n return [content];\n }\n\n const overlapChars = Math.max(CHARS_PER_TOKEN * 32, Math.min(Math.floor(maxContentChars * 0.15), CHARS_PER_TOKEN * 128));\n const stepChars = Math.max(1, maxContentChars - overlapChars);\n const segments: string[] = [];\n\n for (let start = 0; start < content.length; start += stepChars) {\n const end = Math.min(content.length, start + maxContentChars);\n segments.push(content.slice(start, end));\n if (end >= content.length) {\n break;\n }\n }\n\n return segments;\n}\n\nexport function createEmbeddingTexts(chunk: CodeChunk, filePath: string, maxChunkTokens = MAX_SINGLE_CHUNK_TOKENS): string[] {\n const headerParts = getEmbeddingHeaderParts(chunk, filePath);\n const headerLength = buildEmbeddingText(headerParts, \"\", 1, 9).length;\n const maxContentChars = Math.max(1, (maxChunkTokens * CHARS_PER_TOKEN) - headerLength);\n const segments = splitOversizedContent(chunk.content, maxContentChars);\n\n if (segments.length === 1) {\n return [buildEmbeddingText(headerParts, segments[0])];\n }\n\n return segments.map((segment, index) => buildEmbeddingText(headerParts, segment, index + 1, segments.length));\n}\n\nexport function createEmbeddingText(chunk: CodeChunk, filePath: string, maxChunkTokens = MAX_SINGLE_CHUNK_TOKENS): string {\n const text = createEmbeddingTexts(chunk, filePath, maxChunkTokens)[0];\n if (!text) {\n return \"\";\n }\n\n const maxChars = maxChunkTokens * CHARS_PER_TOKEN;\n if (text.length <= maxChars) {\n return text;\n }\n\n return text.slice(0, Math.max(0, maxChars - 17)) + \"\\n... [truncated]\";\n}\n\nexport interface DynamicBatchOptions {\n maxBatchTokens?: number;\n maxBatchItems?: number;\n}\n\nexport function createDynamicBatches<T extends { text: string; tokenCount?: number }>(chunks: T[], options: DynamicBatchOptions = {}): T[][] {\n const batches: T[][] = [];\n let currentBatch: T[] = [];\n let currentTokens = 0;\n const maxBatchTokens = Math.max(1, options.maxBatchTokens ?? MAX_BATCH_TOKENS);\n const maxBatchItems = Math.max(1, options.maxBatchItems ?? Number.MAX_SAFE_INTEGER);\n \n for (const chunk of chunks) {\n const chunkTokens = chunk.tokenCount ?? estimateTokens(chunk.text);\n\n if (\n currentBatch.length > 0\n && (currentTokens + chunkTokens > maxBatchTokens || currentBatch.length >= maxBatchItems)\n ) {\n batches.push(currentBatch);\n currentBatch = [];\n currentTokens = 0;\n }\n \n currentBatch.push(chunk);\n currentTokens += chunkTokens;\n }\n \n if (currentBatch.length > 0) {\n batches.push(currentBatch);\n }\n \n return batches;\n}\n\nfunction extractSemanticHints(name: string, content: string): string[] {\n const hints: string[] = [];\n const combined = `${name} ${content}`.toLowerCase();\n \n const signature = extractFunctionSignature(content);\n if (signature) {\n hints.push(signature);\n }\n \n const patterns: Array<[RegExp, string]> = [\n [/auth|login|logout|signin|signout|credential/i, \"authentication\"],\n [/password|hash|bcrypt|argon/i, \"password handling\"],\n [/token|jwt|bearer|oauth/i, \"token management\"],\n [/user|account|profile|member/i, \"user management\"],\n [/permission|role|access|authorize/i, \"authorization\"],\n [/validate|verify|check|assert/i, \"validation\"],\n [/error|exception|throw|catch/i, \"error handling\"],\n [/log|debug|trace|info|warn/i, \"logging\"],\n [/cache|memoize|store/i, \"caching\"],\n [/fetch|request|response|api|http/i, \"HTTP/API\"],\n [/database|db|query|sql|mongo/i, \"database\"],\n [/file|read|write|stream|path/i, \"file operations\"],\n [/parse|serialize|json|xml/i, \"data parsing\"],\n [/encrypt|decrypt|crypto|secret|cipher|cryptographic/i, \"encryption/cryptography\"],\n [/test|spec|mock|stub|expect/i, \"testing\"],\n [/config|setting|option|env/i, \"configuration\"],\n [/route|endpoint|handler|controller|middleware/i, \"routing/middleware\"],\n [/render|component|view|template/i, \"UI rendering\"],\n [/state|redux|store|dispatch/i, \"state management\"],\n [/hook|effect|memo|callback/i, \"React hooks\"],\n ];\n \n for (const [pattern, hint] of patterns) {\n if (pattern.test(combined) && !hints.includes(hint)) {\n hints.push(hint);\n }\n }\n \n return hints.slice(0, 6);\n}\n\nfunction extractFunctionSignature(content: string): string | null {\n const tsJsPatterns = [\n /(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*(?:<[^>]+>)?\\s*\\(([^)]*)\\)\\s*(?::\\s*([^{]+))?/,\n /(?:export\\s+)?const\\s+(\\w+)\\s*(?::\\s*[^=]+)?\\s*=\\s*(?:async\\s+)?\\(([^)]*)\\)\\s*(?::\\s*([^=>{]+))?\\s*=>/,\n /(?:export\\s+)?const\\s+(\\w+)\\s*(?::\\s*[^=]+)?\\s*=\\s*(?:async\\s+)?function\\s*\\(([^)]*)\\)/,\n ];\n \n const pyPatterns = [\n /def\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*(?:->\\s*([^:]+))?:/,\n /async\\s+def\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*(?:->\\s*([^:]+))?:/,\n ];\n \n const goPatterns = [\n /func\\s+(?:\\([^)]+\\)\\s+)?(\\w+)\\s*\\(([^)]*)\\)\\s*(?:\\(([^)]+)\\)|([^{\\n]+))?/,\n ];\n \n const rustPatterns = [\n /(?:pub\\s+)?(?:async\\s+)?fn\\s+(\\w+)\\s*(?:<[^>]+>)?\\s*\\(([^)]*)\\)\\s*(?:->\\s*([^{]+))?/,\n ];\n \n for (const pattern of [...tsJsPatterns, ...pyPatterns, ...goPatterns, ...rustPatterns]) {\n const match = content.match(pattern);\n if (match) {\n const funcName = match[1];\n const params = match[2]?.trim() || \"\";\n const returnType = (match[3] || match[4])?.trim();\n \n const paramNames = extractParamNames(params);\n \n let sig = `${funcName}(${paramNames.join(\", \")})`;\n if (returnType && returnType.length < 50) {\n sig += ` -> ${returnType.replace(/\\s+/g, \" \").trim()}`;\n }\n \n if (sig.length < 100) {\n return sig;\n }\n }\n }\n \n return null;\n}\n\nfunction extractParamNames(params: string): string[] {\n if (!params.trim()) return [];\n \n const names: string[] = [];\n const parts = params.split(\",\");\n \n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed) continue;\n \n const tsMatch = trimmed.match(/^(\\w+)\\s*[?:]?/);\n const pyMatch = trimmed.match(/^(\\w+)\\s*(?::|=)/);\n const goMatch = trimmed.match(/^(\\w+)\\s+\\w/);\n const rustMatch = trimmed.match(/^(\\w+)\\s*:/);\n \n const match = tsMatch || pyMatch || goMatch || rustMatch;\n if (match && match[1] !== \"self\" && match[1] !== \"this\") {\n names.push(match[1]);\n }\n }\n \n return names.slice(0, 5);\n}\n\nexport function generateChunkId(filePath: string, chunk: CodeChunk): string {\n const hash = hashContent(`${filePath}:${chunk.startLine}:${chunk.endLine}:${chunk.content}`);\n return `chunk_${hash.slice(0, 16)}`;\n}\n\nexport function generateChunkHash(chunk: CodeChunk): string {\n return hashContent(chunk.content);\n}\n\nexport interface KeywordSearchResult {\n chunkId: string;\n score: number;\n}\n\nexport class InvertedIndex {\n private inner: any;\n\n constructor(indexPath: string) {\n this.inner = new native.InvertedIndex(indexPath);\n }\n\n load(): void {\n this.inner.load();\n }\n\n save(): void {\n this.inner.save();\n }\n\n serialize(): string {\n return this.inner.serialize();\n }\n\n deserialize(json: string): void {\n this.inner.deserialize(json);\n }\n\n addChunk(chunkId: string, content: string): void {\n this.inner.addChunk(chunkId, content);\n }\n\n removeChunk(chunkId: string): boolean {\n return this.inner.removeChunk(chunkId);\n }\n\n search(query: string, limit?: number): Map<string, number> {\n const results = this.inner.search(query, limit ?? 100);\n const map = new Map<string, number>();\n for (const r of results) {\n map.set(r.chunkId, r.score);\n }\n return map;\n }\n\n hasChunk(chunkId: string): boolean {\n return this.inner.hasChunk(chunkId);\n }\n\n clear(): void {\n this.inner.clear();\n }\n\n getDocumentCount(): number {\n return this.inner.documentCount();\n }\n}\n\nexport interface ChunkData {\n chunkId: string;\n contentHash: string;\n filePath: string;\n startLine: number;\n endLine: number;\n nodeType?: string;\n name?: string;\n language: string;\n}\n\nexport interface BranchDelta {\n added: string[];\n removed: string[];\n}\n\nexport interface DatabaseStats {\n embeddingCount: number;\n chunkCount: number;\n branchChunkCount: number;\n branchCount: number;\n symbolCount: number;\n callEdgeCount: number;\n}\n\nexport class Database {\n private inner: any;\n private closed = false;\n\n constructor(dbPath: string) {\n this.inner = new native.Database(dbPath);\n }\n\n private throwIfClosed(): void {\n if (this.closed) {\n throw new Error(\"Database is closed\");\n }\n }\n\n close(): void {\n if (this.closed) {\n return;\n }\n\n if (typeof this.inner.close === \"function\") {\n this.inner.close();\n }\n\n this.closed = true;\n }\n\n embeddingExists(contentHash: string): boolean {\n this.throwIfClosed();\n return this.inner.embeddingExists(contentHash);\n }\n\n getEmbedding(contentHash: string): Buffer | null {\n this.throwIfClosed();\n return this.inner.getEmbedding(contentHash) ?? null;\n }\n\n upsertEmbedding(\n contentHash: string,\n embedding: Buffer,\n chunkText: string,\n model: string\n ): void {\n this.throwIfClosed();\n this.inner.upsertEmbedding(contentHash, embedding, chunkText, model);\n }\n\n upsertEmbeddingsBatch(\n items: Array<{\n contentHash: string;\n embedding: Buffer;\n chunkText: string;\n model: string;\n }>\n ): void {\n this.throwIfClosed();\n if (items.length === 0) return;\n this.inner.upsertEmbeddingsBatch(items);\n }\n\n getMissingEmbeddings(contentHashes: string[]): string[] {\n this.throwIfClosed();\n return this.inner.getMissingEmbeddings(contentHashes);\n }\n\n upsertChunk(chunk: ChunkData): void {\n this.throwIfClosed();\n this.inner.upsertChunk(chunk);\n }\n\n upsertChunksBatch(chunks: ChunkData[]): void {\n this.throwIfClosed();\n if (chunks.length === 0) return;\n this.inner.upsertChunksBatch(chunks);\n }\n\n getChunk(chunkId: string): ChunkData | null {\n this.throwIfClosed();\n return this.inner.getChunk(chunkId) ?? null;\n }\n\n getChunksByFile(filePath: string): ChunkData[] {\n this.throwIfClosed();\n return this.inner.getChunksByFile(filePath);\n }\n\n getChunksByName(name: string): ChunkData[] {\n this.throwIfClosed();\n return this.inner.getChunksByName(name);\n }\n\n getChunksByNameCi(name: string): ChunkData[] {\n this.throwIfClosed();\n return this.inner.getChunksByNameCi(name);\n }\n\n deleteChunksByFile(filePath: string): number {\n this.throwIfClosed();\n return this.inner.deleteChunksByFile(filePath);\n }\n\n deleteChunksByIds(chunkIds: string[]): number {\n this.throwIfClosed();\n if (chunkIds.length === 0) return 0;\n return this.inner.deleteChunksByIds(chunkIds);\n }\n\n addChunksToBranch(branch: string, chunkIds: string[]): void {\n this.throwIfClosed();\n this.inner.addChunksToBranch(branch, chunkIds);\n }\n\n addChunksToBranchBatch(branch: string, chunkIds: string[]): void {\n this.throwIfClosed();\n if (chunkIds.length === 0) return;\n this.inner.addChunksToBranchBatch(branch, chunkIds);\n }\n\n clearBranch(branch: string): number {\n this.throwIfClosed();\n return this.inner.clearBranch(branch);\n }\n\n deleteBranchChunksByChunkIds(chunkIds: string[]): number {\n this.throwIfClosed();\n if (chunkIds.length === 0) return 0;\n return this.inner.deleteBranchChunksByChunkIds(chunkIds);\n }\n\n deleteBranchChunksForBranch(branch: string, chunkIds: string[]): number {\n this.throwIfClosed();\n if (chunkIds.length === 0) return 0;\n return this.inner.deleteBranchChunksForBranch(branch, chunkIds);\n }\n\n getBranchChunkIds(branch: string): string[] {\n this.throwIfClosed();\n return this.inner.getBranchChunkIds(branch);\n }\n\n getBranchDelta(branch: string, baseBranch: string): BranchDelta {\n this.throwIfClosed();\n return this.inner.getBranchDelta(branch, baseBranch);\n }\n\n getReferencedChunkIds(chunkIds: string[]): string[] {\n this.throwIfClosed();\n if (chunkIds.length === 0) return [];\n return this.inner.getReferencedChunkIds(chunkIds);\n }\n\n chunkExistsOnBranch(branch: string, chunkId: string): boolean {\n this.throwIfClosed();\n return this.inner.chunkExistsOnBranch(branch, chunkId);\n }\n\n getAllBranches(): string[] {\n this.throwIfClosed();\n return this.inner.getAllBranches();\n }\n\n getMetadata(key: string): string | null {\n this.throwIfClosed();\n return this.inner.getMetadata(key) ?? null;\n }\n\n setMetadata(key: string, value: string): void {\n this.throwIfClosed();\n this.inner.setMetadata(key, value);\n }\n\n deleteMetadata(key: string): boolean {\n this.throwIfClosed();\n return this.inner.deleteMetadata(key);\n }\n\n clearAllIndexedData(): void {\n this.throwIfClosed();\n this.inner.clearAllIndexedData();\n }\n\n clearCallEdgeTargetsForSymbols(symbolIds: string[]): number {\n this.throwIfClosed();\n if (symbolIds.length === 0) return 0;\n return this.inner.clearCallEdgeTargetsForSymbols(symbolIds);\n }\n\n gcOrphanEmbeddings(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanEmbeddings();\n }\n\n gcOrphanChunks(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanChunks();\n }\n\n getStats(): DatabaseStats {\n this.throwIfClosed();\n return this.inner.getStats();\n }\n\n\n\n upsertSymbol(symbol: SymbolData): void {\n this.throwIfClosed();\n this.inner.upsertSymbol(symbol);\n }\n\n upsertSymbolsBatch(symbols: SymbolData[]): void {\n this.throwIfClosed();\n if (symbols.length === 0) return;\n this.inner.upsertSymbolsBatch(symbols);\n }\n\n getSymbolsByFile(filePath: string): SymbolData[] {\n this.throwIfClosed();\n return this.inner.getSymbolsByFile(filePath);\n }\n\n getSymbolByName(name: string, filePath: string): SymbolData | null {\n this.throwIfClosed();\n return this.inner.getSymbolByName(name, filePath) ?? null;\n }\n\n getSymbolsByName(name: string): SymbolData[] {\n this.throwIfClosed();\n return this.inner.getSymbolsByName(name);\n }\n\n getSymbolsByNameCi(name: string): SymbolData[] {\n this.throwIfClosed();\n return this.inner.getSymbolsByNameCi(name);\n }\n\n deleteSymbolsByFile(filePath: string): number {\n this.throwIfClosed();\n return this.inner.deleteSymbolsByFile(filePath);\n }\n\n\n\n upsertCallEdge(edge: CallEdgeData): void {\n this.throwIfClosed();\n this.inner.upsertCallEdge(edge);\n }\n\n upsertCallEdgesBatch(edges: CallEdgeData[]): void {\n this.throwIfClosed();\n if (edges.length === 0) return;\n this.inner.upsertCallEdgesBatch(edges);\n }\n\n getCallers(targetName: string, branch: string): CallEdgeData[] {\n this.throwIfClosed();\n return this.inner.getCallers(targetName, branch);\n }\n\n getCallersWithContext(targetName: string, branch: string): CallEdgeData[] {\n this.throwIfClosed();\n return this.inner.getCallersWithContext(targetName, branch);\n }\n\n getCallees(symbolId: string, branch: string): CallEdgeData[] {\n this.throwIfClosed();\n return this.inner.getCallees(symbolId, branch);\n }\n\n deleteCallEdgesByFile(filePath: string): number {\n this.throwIfClosed();\n return this.inner.deleteCallEdgesByFile(filePath);\n }\n\n resolveCallEdge(edgeId: string, toSymbolId: string): void {\n this.throwIfClosed();\n this.inner.resolveCallEdge(edgeId, toSymbolId);\n }\n\n\n\n addSymbolsToBranch(branch: string, symbolIds: string[]): void {\n this.throwIfClosed();\n this.inner.addSymbolsToBranch(branch, symbolIds);\n }\n\n addSymbolsToBranchBatch(branch: string, symbolIds: string[]): void {\n this.throwIfClosed();\n if (symbolIds.length === 0) return;\n this.inner.addSymbolsToBranchBatch(branch, symbolIds);\n }\n\n getBranchSymbolIds(branch: string): string[] {\n this.throwIfClosed();\n return this.inner.getBranchSymbolIds(branch);\n }\n\n clearBranchSymbols(branch: string): number {\n this.throwIfClosed();\n return this.inner.clearBranchSymbols(branch);\n }\n\n getReferencedSymbolIds(symbolIds: string[]): string[] {\n this.throwIfClosed();\n if (symbolIds.length === 0) return [];\n return this.inner.getReferencedSymbolIds(symbolIds);\n }\n\n deleteBranchSymbolsBySymbolIds(symbolIds: string[]): number {\n this.throwIfClosed();\n if (symbolIds.length === 0) return 0;\n return this.inner.deleteBranchSymbolsBySymbolIds(symbolIds);\n }\n\n deleteBranchSymbolsForBranch(branch: string, symbolIds: string[]): number {\n this.throwIfClosed();\n if (symbolIds.length === 0) return 0;\n return this.inner.deleteBranchSymbolsForBranch(branch, symbolIds);\n }\n\n\n\n gcOrphanSymbols(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanSymbols();\n }\n\n gcOrphanCallEdges(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanCallEdges();\n }\n}\n","import { IndexStats, IndexProgress, SearchResult, HealthCheckResult, StatusResult } from \"../indexer/index.js\";\nimport type { LogEntry } from \"../utils/logger.js\";\n\nconst MAX_CONTENT_LINES = 30;\n\nfunction truncateContent(content: string): string {\n const lines = content.split(\"\\n\");\n if (lines.length <= MAX_CONTENT_LINES) return content;\n return (\n lines.slice(0, MAX_CONTENT_LINES).join(\"\\n\") +\n `\\n// ... (${lines.length - MAX_CONTENT_LINES} more lines)`\n );\n}\n\nexport function formatIndexStats(stats: IndexStats, verbose: boolean = false): string {\n if (stats.resetCorruptedIndex) {\n return stats.warning ?? \"Detected a corrupted local index and reset it during indexing. Run index_codebase again to rebuild search data.\";\n }\n\n const lines: string[] = [];\n\n if (stats.failedChunks > 0) {\n lines.push(`INDEXING WARNING: ${stats.failedChunks} chunks failed to embed.`);\n if (stats.failedBatchesPath) {\n lines.push(`Inspect failed batches at: ${stats.failedBatchesPath}`);\n }\n lines.push(\"\");\n }\n \n if (stats.indexedChunks === 0 && stats.removedChunks === 0) {\n lines.push(`${stats.totalFiles} files processed, ${stats.existingChunks} code chunks already up to date.`);\n } else if (stats.indexedChunks === 0) {\n lines.push(`${stats.totalFiles} files, removed ${stats.removedChunks} stale chunks, ${stats.existingChunks} chunks remain.`);\n } else {\n let main = `${stats.totalFiles} files processed, ${stats.indexedChunks} new chunks embedded.`;\n if (stats.existingChunks > 0) {\n main += ` ${stats.existingChunks} unchanged chunks skipped.`;\n }\n lines.push(main);\n\n if (stats.removedChunks > 0) {\n lines.push(`Removed ${stats.removedChunks} stale chunks.`);\n }\n\n if (stats.failedChunks > 0) {\n lines.push(`Failed: ${stats.failedChunks} chunks.`);\n }\n\n lines.push(`Tokens: ${stats.tokensUsed.toLocaleString()}, Duration: ${(stats.durationMs / 1000).toFixed(1)}s`);\n }\n\n if (verbose) {\n if (stats.skippedFiles.length > 0) {\n const tooLarge = stats.skippedFiles.filter(f => f.reason === \"too_large\");\n const excluded = stats.skippedFiles.filter(f => f.reason === \"excluded\");\n const gitignored = stats.skippedFiles.filter(f => f.reason === \"gitignore\");\n \n lines.push(\"\");\n lines.push(`Skipped files: ${stats.skippedFiles.length}`);\n if (tooLarge.length > 0) {\n lines.push(` Too large (${tooLarge.length}): ${tooLarge.slice(0, 5).map(f => f.path).join(\", \")}${tooLarge.length > 5 ? \"...\" : \"\"}`);\n }\n if (excluded.length > 0) {\n lines.push(` Excluded (${excluded.length}): ${excluded.slice(0, 5).map(f => f.path).join(\", \")}${excluded.length > 5 ? \"...\" : \"\"}`);\n }\n if (gitignored.length > 0) {\n lines.push(` Gitignored (${gitignored.length}): ${gitignored.slice(0, 5).map(f => f.path).join(\", \")}${gitignored.length > 5 ? \"...\" : \"\"}`);\n }\n }\n\n if (stats.parseFailures.length > 0) {\n lines.push(\"\");\n lines.push(`Files with no extractable chunks (${stats.parseFailures.length}): ${stats.parseFailures.slice(0, 10).join(\", \")}${stats.parseFailures.length > 10 ? \"...\" : \"\"}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatStatus(status: StatusResult): string {\n if (!status.indexed) {\n if (status.warning) {\n return status.warning;\n }\n\n if (status.failedBatchesCount > 0) {\n const lines = [\n \"Codebase is not indexed. The last indexing run left failed embedding batches.\",\n \"Fix the provider/model configuration, then rerun index_codebase normally to retry the saved failed batches. Use force=true only for a full rebuild or compatibility reset.\",\n ];\n\n if (status.failedBatchesPath) {\n lines.push(`Failed batches: ${status.failedBatchesPath}`);\n }\n\n return lines.join(\"\\n\");\n }\n\n return \"Codebase is not indexed. Run index_codebase to create an index.\";\n }\n\n const lines = [\n `Indexed chunks: ${status.vectorCount.toLocaleString()}`,\n `Provider: ${status.provider}`,\n `Model: ${status.model}`,\n `Location: ${status.indexPath}`,\n ];\n\n if (status.currentBranch !== \"default\") {\n lines.push(`Current branch: ${status.currentBranch}`);\n lines.push(`Base branch: ${status.baseBranch}`);\n }\n\n if (status.failedBatchesCount > 0) {\n lines.push(\"\");\n lines.push(`INDEXING WARNING: ${status.failedBatchesCount} failed embedding batch${status.failedBatchesCount === 1 ? \" remains\" : \"es remain\"}.`);\n if (status.failedBatchesPath) {\n lines.push(`Failed batches: ${status.failedBatchesPath}`);\n }\n }\n\n if (status.compatibility && !status.compatibility.compatible) {\n lines.push(\"\");\n lines.push(`COMPATIBILITY WARNING: ${status.compatibility.reason}`);\n if (status.compatibility.storedMetadata) {\n const stored = status.compatibility.storedMetadata;\n lines.push(`Index was built with: ${stored.embeddingProvider}/${stored.embeddingModel} (${stored.embeddingDimensions}D)`);\n lines.push(`Current config: ${status.provider}/${status.model}`);\n }\n } else if (!status.compatibility) {\n lines.push(`Compatibility: No compatibility information found. Maybe the index is not initialized yet, try running index_codebase.`);\n } else {\n lines.push(`Compatibility: Index is compatible with the current provider and model.`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatProgressTitle(progress: IndexProgress): string {\n switch (progress.phase) {\n case \"scanning\":\n return \"Scanning files...\";\n case \"parsing\":\n return `Parsing: ${progress.filesProcessed}/${progress.totalFiles} files`;\n case \"embedding\":\n return `Embedding: ${progress.chunksProcessed}/${progress.totalChunks} chunks`;\n case \"storing\":\n return \"Storing index...\";\n case \"complete\":\n return \"Indexing complete\";\n default:\n return \"Indexing...\";\n }\n}\n\nexport function calculatePercentage(progress: IndexProgress): number {\n if (progress.phase === \"scanning\") return 0;\n if (progress.phase === \"complete\") return 100;\n \n if (progress.phase === \"parsing\") {\n if (progress.totalFiles === 0) return 5;\n return Math.round(5 + (progress.filesProcessed / progress.totalFiles) * 15);\n }\n \n if (progress.phase === \"embedding\") {\n if (progress.totalChunks === 0) return 20;\n return Math.round(20 + (progress.chunksProcessed / progress.totalChunks) * 70);\n }\n \n if (progress.phase === \"storing\") return 95;\n \n return 0;\n}\n\nexport function formatCodebasePeek(results: SearchResult[]): string {\n if (results.length === 0) {\n return \"No matching code found. Try a different query or run index_codebase first.\";\n }\n\n const formatted = results.map((r, idx) => {\n const location = `${r.filePath}:${r.startLine}-${r.endLine}`;\n const name = r.name ? `\"${r.name}\"` : \"(anonymous)\";\n return `[${idx + 1}] ${r.chunkType} ${name} at ${location} (score: ${r.score.toFixed(2)})`;\n });\n\n return formatted.join(\"\\n\");\n}\n\nexport function formatHealthCheck(result: HealthCheckResult): string {\n if (result.resetCorruptedIndex) {\n return result.warning ?? \"Detected a corrupted local index and reset it. Run index_codebase to rebuild search data.\";\n }\n\n if (result.removed === 0 && result.gcOrphanEmbeddings === 0 && result.gcOrphanChunks === 0 && result.gcOrphanSymbols === 0 && result.gcOrphanCallEdges === 0) {\n return \"Index is healthy. No stale entries found.\";\n }\n\n const lines: string[] = [];\n \n if (result.removed > 0) {\n lines.push(`Removed stale entries: ${result.removed}`);\n }\n \n if (result.gcOrphanEmbeddings > 0) {\n lines.push(`Garbage collected orphan embeddings: ${result.gcOrphanEmbeddings}`);\n }\n \n if (result.gcOrphanChunks > 0) {\n lines.push(`Garbage collected orphan chunks: ${result.gcOrphanChunks}`);\n }\n\n if (result.gcOrphanSymbols > 0) {\n lines.push(`Garbage collected orphan symbols: ${result.gcOrphanSymbols}`);\n }\n\n if (result.gcOrphanCallEdges > 0) {\n lines.push(`Garbage collected orphan call edges: ${result.gcOrphanCallEdges}`);\n }\n\n if (result.filePaths.length > 0) {\n lines.push(`Cleaned paths: ${result.filePaths.join(\", \")}`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatLogs(logs: LogEntry[]): string {\n if (logs.length === 0) {\n return \"No logs recorded yet. Logs are captured during indexing and search operations.\";\n }\n\n return logs.map(l => {\n const dataStr = l.data ? ` ${JSON.stringify(l.data)}` : \"\";\n return `[${l.timestamp}] [${l.level.toUpperCase()}] [${l.category}] ${l.message}${dataStr}`;\n }).join(\"\\n\");\n}\n\nfunction formatResultHeader(result: SearchResult, index: number): string {\n return result.name\n ? `[${index + 1}] ${result.chunkType} \"${result.name}\" in ${result.filePath}:${result.startLine}-${result.endLine}`\n : `[${index + 1}] ${result.chunkType} in ${result.filePath}:${result.startLine}-${result.endLine}`;\n}\n\nexport function formatDefinitionLookup(results: SearchResult[], query: string): string {\n if (results.length === 0) {\n return `No definition found for \"${query}\". Try codebase_search for broader discovery, or verify the symbol name.`;\n }\n\n const formatted = results.map((r, idx) => {\n const header = formatResultHeader(r, idx);\n return `${header} (score: ${r.score.toFixed(2)})\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return formatted.join(\"\\n\\n\");\n}\n\nexport type ScoreFormat = \"score\" | \"similarity\";\n\nexport function formatSearchResults(results: SearchResult[], scoreFormat: ScoreFormat = \"similarity\"): string {\n const formatted = results.map((r, idx) => {\n const header = formatResultHeader(r, idx);\n\n const scoreLabel = scoreFormat === \"similarity\"\n ? `(similarity: ${(r.score * 100).toFixed(1)}%)`\n : `(score: ${r.score.toFixed(2)})`;\n\n return `${header} ${scoreLabel}\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return formatted.join(\"\\n\\n\");\n}\n","import * as path from \"path\";\n\nimport { normalizePathSeparators } from \"../utils/paths.js\";\n\nexport function resolveConfigPathValue(value: string, baseDir: string): string {\n const trimmed = value.trim();\n if (!trimmed) {\n return trimmed;\n }\n\n const absolutePath = path.isAbsolute(trimmed) ? trimmed : path.resolve(baseDir, trimmed);\n return path.normalize(absolutePath);\n}\n\nexport function serializeConfigPathValue(value: string, baseDir: string): string {\n const trimmed = value.trim();\n if (!trimmed) {\n return trimmed;\n }\n\n if (!path.isAbsolute(trimmed)) {\n return normalizePathSeparators(path.normalize(trimmed));\n }\n\n const relativePath = path.relative(baseDir, trimmed);\n if (!relativePath || (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath))) {\n return normalizePathSeparators(path.normalize(relativePath || \".\"));\n }\n\n return path.normalize(trimmed);\n}\n\nexport function resolveKnowledgeBasePath(value: string, projectRoot: string): string {\n return path.isAbsolute(value) ? value : path.resolve(projectRoot, value);\n}\n\nexport function normalizeKnowledgeBasePath(value: string, projectRoot: string): string {\n return path.normalize(resolveKnowledgeBasePath(value, projectRoot));\n}\n\nexport function hasMatchingKnowledgeBasePath(\n knowledgeBases: string[],\n inputPath: string,\n projectRoot: string,\n): boolean {\n const normalizedInput = path.normalize(inputPath);\n return knowledgeBases.some((kb) => normalizeKnowledgeBasePath(kb, projectRoot) === normalizedInput);\n}\n\nexport function findKnowledgeBasePathIndex(\n knowledgeBases: string[],\n inputPath: string,\n projectRoot: string,\n): number {\n const normalizedInput = path.normalize(inputPath);\n return knowledgeBases.findIndex(\n (kb) => path.normalize(kb) === normalizedInput || normalizeKnowledgeBasePath(kb, projectRoot) === normalizedInput\n );\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"fs\";\nimport * as path from \"path\";\n\nimport { loadMergedConfig, loadProjectConfigLayer } from \"../config/merger.js\";\nimport { resolveWritableProjectConfigPath } from \"../config/paths.js\";\nimport { resolveConfigPathValue, serializeConfigPathValue } from \"./knowledge-base-paths.js\";\n\nfunction normalizeKnowledgeBasePaths(\n config: Record<string, unknown>,\n projectRoot: string,\n): Record<string, unknown> {\n const normalized = { ...config };\n\n if (Array.isArray(normalized.knowledgeBases)) {\n normalized.knowledgeBases = (normalized.knowledgeBases as string[]).map((kb) =>\n resolveConfigPathValue(kb, projectRoot)\n );\n }\n\n return normalized;\n}\n\nfunction toConfigRecord(rawConfig: unknown): Record<string, unknown> {\n if (!rawConfig || typeof rawConfig !== \"object\") {\n return {};\n }\n\n return { ...(rawConfig as Record<string, unknown>) };\n}\n\nexport function getConfigPath(projectRoot: string): string {\n return resolveWritableProjectConfigPath(projectRoot);\n}\n\nexport function loadRuntimeConfig(projectRoot: string): Record<string, unknown> {\n return normalizeKnowledgeBasePaths(toConfigRecord(loadMergedConfig(projectRoot)), projectRoot);\n}\n\nexport function loadEditableConfig(projectRoot: string): Record<string, unknown> {\n return normalizeKnowledgeBasePaths(toConfigRecord(loadProjectConfigLayer(projectRoot)), projectRoot);\n}\n\nexport function saveConfig(projectRoot: string, config: Record<string, unknown>): void {\n const configPath = getConfigPath(projectRoot);\n const configDir = path.dirname(configPath);\n const configBaseDir = path.dirname(configDir);\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true });\n }\n\n const serializableConfig: Record<string, unknown> = { ...config };\n\n if (Array.isArray(serializableConfig.knowledgeBases)) {\n serializableConfig.knowledgeBases = (serializableConfig.knowledgeBases as string[]).map((kb) =>\n serializeConfigPathValue(kb, configBaseDir)\n );\n }\n\n writeFileSync(configPath, JSON.stringify(serializableConfig, null, 2) + \"\\n\", \"utf-8\");\n}\n","import { existsSync, readdirSync, readFileSync } from \"fs\";\nimport * as path from \"path\";\n\nexport interface CommandDefinition {\n description: string;\n template: string;\n}\n\nfunction parseFrontmatter(content: string): { frontmatter: Record<string, string>; body: string } {\n const frontmatterRegex = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n const match = content.match(frontmatterRegex);\n \n if (!match) {\n return { frontmatter: {}, body: content.trim() };\n }\n\n const frontmatterLines = match[1].split(\"\\n\");\n const frontmatter: Record<string, string> = {};\n \n for (const line of frontmatterLines) {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const value = line.slice(colonIndex + 1).trim();\n frontmatter[key] = value;\n }\n }\n\n return { frontmatter, body: match[2].trim() };\n}\n\nexport function loadCommandsFromDirectory(commandsDir: string): Map<string, CommandDefinition> {\n const commands = new Map<string, CommandDefinition>();\n\n if (!existsSync(commandsDir)) {\n return commands;\n }\n\n const files = readdirSync(commandsDir).filter((f) => f.endsWith(\".md\"));\n\n for (const file of files) {\n const filePath = path.join(commandsDir, file);\n let content: string;\n\n try {\n content = readFileSync(filePath, \"utf-8\");\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load command file ${filePath}: ${message}`);\n }\n\n const { frontmatter, body } = parseFrontmatter(content);\n \n const name = path.basename(file, \".md\");\n const description = frontmatter.description || `Run the ${name} command`;\n\n commands.set(name, {\n description,\n template: body,\n });\n }\n\n return commands;\n}\n","const EXTERNAL_HINTS = [\n \"docs\",\n \"documentation\",\n \"official docs\",\n \"github example\",\n \"github examples\",\n \"github repo\",\n \"github repository\",\n \"web search\",\n \"website\",\n \"url\",\n \"npm\",\n \"pypi\",\n \"crate\",\n \"library\",\n \"package\",\n \"framework\",\n \"context7\",\n \"stackoverflow\",\n];\n\nconst NON_DISCOVERY_HINTS = [\n \"commit\",\n \"rebase\",\n \"push\",\n \"pull request\",\n \"pr\",\n \"lint\",\n \"typecheck\",\n \"build\",\n \"test\",\n \"release\",\n \"deploy\",\n \"screenshot\",\n \"browser\",\n \"open the website\",\n];\n\nconst CONCEPTUAL_DISCOVERY_HINTS = [\n \"where is\",\n \"where are\",\n \"which file\",\n \"what file\",\n \"how does\",\n \"how do we\",\n \"how is\",\n \"find the code\",\n \"find code\",\n \"find where\",\n \"find logic\",\n \"implementation\",\n \"implements\",\n \"handler\",\n \"flow\",\n \"logic\",\n \"middleware\",\n \"parser\",\n \"validation\",\n \"rate limiting\",\n \"error handling\",\n \"auth flow\",\n \"responsible for\",\n \"similar code\",\n \"pattern\",\n \"code that\",\n];\n\nconst DEFINITION_HINTS = [\n \"defined\",\n \"definition\",\n \"jump to\",\n \"definition site\",\n \"authoritative definition\",\n];\n\nconst EXACT_MATCH_HINTS = [\n \"exact\",\n \"all references\",\n \"all occurrences\",\n \"literal\",\n \"regex\",\n \"grep\",\n \"identifier\",\n \"symbol\",\n \"named\",\n \"definition of\",\n];\n\nconst FILE_PATH_PATTERN = /(?:^|\\s)(?:\\.?\\.?\\/)?[\\w.-]+(?:\\/[\\w.-]+)+/;\nconst URL_PATTERN = /https?:\\/\\//;\nconst CAMEL_OR_PASCAL_PATTERN = /\\b[A-Za-z_$][A-Za-z0-9_$]*\\b/g;\nconst SNAKE_PATTERN = /\\b[a-z0-9]+_[a-z0-9_]+\\b/g;\nconst KEBAB_PATTERN = /\\b[a-z0-9]+-[a-z0-9-]+\\b/g;\nconst BACKTICK_IDENTIFIER_PATTERN = /`([^`]+)`/g;\nconst BACKTICK_IDENTIFIER_PRESENCE_PATTERN = /`([^`]+)`/;\nconst DOUBLE_QUOTED_PATTERN = /\"[^\"]+\"/;\nconst SINGLE_QUOTED_PATTERN = /'[^']+'/;\n\nexport function normalizeText(text: string): string {\n return text.trim().replace(/\\s+/g, \" \");\n}\n\nfunction includesHint(text: string, hints: string[]): boolean {\n return hints.some((hint) => text.includes(hint));\n}\n\nexport function countWords(text: string): number {\n if (!text) {\n return 0;\n }\n\n return text.split(/\\s+/).filter(Boolean).length;\n}\n\nexport function isExternalLookup(text: string): boolean {\n return URL_PATTERN.test(text) || includesHint(text, EXTERNAL_HINTS);\n}\n\nexport function hasConceptualDiscoveryHint(text: string): boolean {\n return includesHint(text, CONCEPTUAL_DISCOVERY_HINTS);\n}\n\nexport function hasDefinitionHint(text: string): boolean {\n return includesHint(text, DEFINITION_HINTS);\n}\n\nexport function hasExactMatchHint(text: string): boolean {\n return includesHint(text, EXACT_MATCH_HINTS);\n}\n\nexport function hasNonDiscoveryHint(text: string): boolean {\n return includesHint(text, NON_DISCOVERY_HINTS);\n}\n\nexport function hasIdentifierShape(text: string): boolean {\n const matches = [\n ...(text.match(CAMEL_OR_PASCAL_PATTERN) ?? []),\n ...(text.match(SNAKE_PATTERN) ?? []),\n ...(text.match(KEBAB_PATTERN) ?? []),\n ...Array.from(text.matchAll(BACKTICK_IDENTIFIER_PATTERN), (match) => match[1]),\n ];\n\n return matches.some((match) => {\n if (match.length < 3) {\n return false;\n }\n\n return /[A-Z]/.test(match) || match.includes(\"_\") || match.includes(\"-\") || /`/.test(match);\n });\n}\n\nexport function containsQuotedIdentifier(text: string): boolean {\n return BACKTICK_IDENTIFIER_PRESENCE_PATTERN.test(text) || DOUBLE_QUOTED_PATTERN.test(text) || SINGLE_QUOTED_PATTERN.test(text);\n}\n\nexport function looksLikeDirectPath(text: string): boolean {\n return FILE_PATH_PATTERN.test(text) || /\\b[a-z0-9_-]+\\.(ts|tsx|js|jsx|rs|py|go|java|json|md|yaml|yml)\\b/i.test(text);\n}\n","import type { StatusResult } from \"./indexer/index.js\";\nimport {\n containsQuotedIdentifier,\n countWords,\n hasConceptualDiscoveryHint,\n hasDefinitionHint,\n hasExactMatchHint,\n hasIdentifierShape,\n hasNonDiscoveryHint,\n isExternalLookup,\n looksLikeDirectPath,\n normalizeText,\n} from \"./routing-hints-patterns.js\";\n\nexport type RoutingIntent =\n | \"local_conceptual\"\n | \"definition_lookup\"\n | \"exact_identifier\"\n | \"external\"\n | \"direct_path\"\n | \"other\";\n\nexport interface RoutingAssessment {\n intent: RoutingIntent;\n text: string;\n reason: string;\n}\n\nexport interface RoutingSessionState {\n assessment: RoutingAssessment;\n pendingHint: boolean;\n updatedAt: number;\n}\n\ninterface TextPartLike {\n type?: string;\n text?: string;\n}\n\nexport function extractUserText(parts: TextPartLike[]): string {\n return normalizeText(\n parts\n .filter((part) => part.type === \"text\" && typeof part.text === \"string\")\n .map((part) => part.text ?? \"\")\n .join(\" \"),\n );\n}\n\nexport function assessRoutingIntent(text: string): RoutingAssessment {\n const normalizedText = normalizeText(text);\n const lowered = normalizedText.toLowerCase();\n\n if (!lowered) {\n return {\n intent: \"other\",\n text: normalizedText,\n reason: \"empty_text\",\n };\n }\n\n if (isExternalLookup(lowered)) {\n return {\n intent: \"external\",\n text: normalizedText,\n reason: \"external_lookup\",\n };\n }\n\n const matchedConceptualHint = hasConceptualDiscoveryHint(lowered);\n const matchedDefinitionHint = hasDefinitionHint(lowered);\n const matchedExactMatchHint = hasExactMatchHint(lowered);\n const matchedNonDiscoveryHint = hasNonDiscoveryHint(lowered);\n const hasIdentifier = hasIdentifierShape(normalizedText);\n const hasQuotedIdentifier = containsQuotedIdentifier(normalizedText);\n const shortQuery = countWords(lowered) <= 10;\n\n if (matchedNonDiscoveryHint && !matchedConceptualHint) {\n return {\n intent: \"other\",\n text: normalizedText,\n reason: \"non_discovery_task\",\n };\n }\n\n if (looksLikeDirectPath(normalizedText)) {\n return {\n intent: \"direct_path\",\n text: normalizedText,\n reason: \"direct_path_reference\",\n };\n }\n\n if ((matchedDefinitionHint || lowered.includes(\"where is\") || lowered.includes(\"where are\")) && (lowered.includes(\"defined\") || lowered.includes(\"definition\"))) {\n return {\n intent: \"definition_lookup\",\n text: normalizedText,\n reason: \"definition_lookup_request\",\n };\n }\n\n if ((matchedExactMatchHint || hasQuotedIdentifier || hasIdentifier) && !matchedConceptualHint && shortQuery) {\n return {\n intent: \"exact_identifier\",\n text: normalizedText,\n reason: matchedExactMatchHint || hasQuotedIdentifier ? \"exact_match_request\" : \"identifier_shaped_query\",\n };\n }\n\n if (matchedConceptualHint) {\n return {\n intent: \"local_conceptual\",\n text: normalizedText,\n reason: \"conceptual_local_discovery\",\n };\n }\n\n return {\n intent: \"other\",\n text: normalizedText,\n reason: \"no_local_discovery_signal\",\n };\n}\n\nexport function buildRoutingHint(\n assessment: RoutingAssessment,\n status: Pick<StatusResult, \"indexed\" | \"compatibility\"> | null,\n): string | null {\n if (assessment.intent === \"definition_lookup\") {\n if (!status || !status.indexed || status.compatibility?.compatible === false) {\n return \"For this turn, if you need a symbol definition, check `index_status` first and run `index_codebase` if the index is missing or incompatible. Then use `implementation_lookup` for the definition site. Use `grep` for exhaustive literal matches.\";\n }\n\n return \"For this turn, prefer `implementation_lookup` to find the authoritative definition site. Use `codebase_search` only if no definition is found, and use `grep` for exhaustive literal matches.\";\n }\n\n if (assessment.intent !== \"local_conceptual\") {\n return null;\n }\n\n if (!status || !status.indexed || status.compatibility?.compatible === false) {\n return \"For this turn, if local code discovery by behavior is needed, check `index_status` first and run `index_codebase` if the index is missing or incompatible. Use `grep` for exact identifiers or exhaustive matches.\";\n }\n\n return \"For this turn, prefer `codebase_peek` for local code discovery by behavior or likely location, then use `codebase_search` when you need implementation content. Use `grep` for exact identifiers or exhaustive matches.\";\n}\n\nexport class RoutingHintController {\n private readonly sessionState = new Map<string, RoutingSessionState>();\n\n constructor(\n private readonly getStatus: () => Promise<Pick<StatusResult, \"indexed\" | \"compatibility\">>,\n private readonly maxSessions: number = 200,\n ) {}\n\n observeUserMessage(sessionID: string, parts: TextPartLike[]): RoutingAssessment {\n const assessment = assessRoutingIntent(extractUserText(parts));\n\n this.compactSessions();\n this.sessionState.set(sessionID, {\n assessment,\n pendingHint: assessment.intent === \"local_conceptual\" || assessment.intent === \"definition_lookup\",\n updatedAt: Date.now(),\n });\n\n return assessment;\n }\n\n async getSystemHints(sessionID?: string): Promise<string[]> {\n if (!sessionID) {\n return [];\n }\n\n const state = this.sessionState.get(sessionID);\n if (!state || !state.pendingHint) {\n return [];\n }\n\n const status = await this.safeGetStatus();\n const hint = buildRoutingHint(state.assessment, status);\n\n return hint ? [hint] : [];\n }\n\n markToolUsed(sessionID: string, toolName: string): void {\n const state = this.sessionState.get(sessionID);\n if (!state || !state.pendingHint) {\n return;\n }\n\n if (\n toolName === \"codebase_peek\"\n || toolName === \"codebase_search\"\n || toolName === \"implementation_lookup\"\n || toolName === \"index_status\"\n || toolName === \"index_codebase\"\n ) {\n state.pendingHint = false;\n state.updatedAt = Date.now();\n this.sessionState.set(sessionID, state);\n }\n }\n\n getSessionState(sessionID: string): RoutingSessionState | undefined {\n return this.sessionState.get(sessionID);\n }\n\n private async safeGetStatus(): Promise<Pick<StatusResult, \"indexed\" | \"compatibility\"> | null> {\n try {\n return await this.getStatus();\n } catch {\n return null;\n }\n }\n\n private compactSessions(): void {\n if (this.sessionState.size < this.maxSessions) {\n return;\n }\n\n const oldestSession = [...this.sessionState.entries()]\n .sort((left, right) => left[1].updatedAt - right[1].updatedAt)\n .at(0);\n\n if (oldestSession) {\n this.sessionState.delete(oldestSession[0]);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0CAAAA,SAAA;AAAA;AACA,aAAS,UAAW,SAAS;AAC3B,aAAO,MAAM,QAAQ,OAAO,IACxB,UACA,CAAC,OAAO;AAAA,IACd;AAEA,QAAM,YAAY;AAClB,QAAM,QAAQ;AACd,QAAM,QAAQ;AACd,QAAM,SAAS;AACf,QAAM,wBAAwB;AAC9B,QAAM,mCAAmC;AACzC,QAAM,4CAA4C;AAClD,QAAM,qCAAqC;AAC3C,QAAM,sBAAsB;AAU5B,QAAM,0BAA0B;AAEhC,QAAM,4BAA4B;AAElC,QAAMC,SAAQ;AAGd,QAAI,iBAAiB;AAErB,QAAI,OAAO,WAAW,aAAa;AACjC,uBAAiB,uBAAO,IAAI,aAAa;AAAA,IAC3C;AACA,QAAM,aAAa;AAEnB,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AAK,CAAC;AACtE,eAAO,OAAO,KAAK,GAAG,KAAK;AAAA,MAC7B;AAAA,MAEA,MAAM,qBAAqB,OAAO;AAChC,sBAAc,aAAa,MAAM,WAAW,MAAM,IAAI;AAAA,MACxD;AAAA,MAEA,MAAM,OAAO,KAAK;AAChB,YAAI,UAAU,IAAI,WAAW,CAAC;AAE9B,cAAM,cAAc,eAAe;AACnC,cAAM,WAAW,0BAA0B,WAAW;AAEtD,mBAAW,CAAC,MAAM,UAAU,KAAK,UAAU;AACzC,cAAI,QAAQ,IAAI,IAAI;AAAA,QACtB;AAAA,MACF;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,MAAM,iDAAiD,KAAK;AAEpE,WAAO;AAAA,MACL,MAAM;AAAA,MACN,MAAM,SAAS;AAAA,MAAC;AAAA,IAClB;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;","names":["module","SLASH","path","Ignore","module","EventEmitter","path","fileURLToPath","existsSync","readFileSync","os","path","existsSync","path","existsSync","readFileSync","statSync","path","existsSync","stat","statSync","readFileSync","existsSync","existsSync","path","path","isStringArray","existsSync","readFileSync","readdir","stat","sp","path","basename","lstat","stat","lstat","stat","path","rawEmitter","listener","basename","dirname","newStats","closer","resolve","realpath","stats","relative","path","testString","readdir","stats","stat","now","path","existsSync","readFileSync","path","existsSync","ignore","readFileSync","stat","path","path","getIndexer","existsSync","readFileSync","writeFileSync","mkdirSync","fsPromises","path","performance","resolve","EventEmitter","resolve","reject","resolve","existsSync","readFileSync","path","os","path","os","platform","arch","require","existsSync","readFileSync","mkdirSync","writeFileSync","fsPromises","performance","resolve","failedBatch","lines","path","normalizeKnowledgeBasePath","existsSync","statSync","path","existsSync","mkdirSync","writeFileSync","path","existsSync","mkdirSync","writeFileSync","os","existsSync","formatted","stat","statSync","result","existsSync","readdirSync","readFileSync","path","fileURLToPath"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/ignore/index.js","../node_modules/eventemitter3/index.js","../src/index.ts","../src/config/constants.ts","../src/config/defaults.ts","../src/config/env-substitution.ts","../src/config/validators.ts","../src/config/schema.ts","../src/config/merger.ts","../src/config/paths.ts","../src/git/index.ts","../src/git/refs.ts","../src/config/rebase.ts","../src/utils/paths.ts","../node_modules/chokidar/index.js","../node_modules/readdirp/index.js","../node_modules/chokidar/handler.js","../src/watcher/file-watcher.ts","../src/utils/files.ts","../src/watcher/git-head-watcher.ts","../src/watcher/index.ts","../src/tools/index.ts","../src/indexer/index.ts","../node_modules/eventemitter3/index.mjs","../node_modules/p-timeout/index.js","../node_modules/p-queue/dist/lower-bound.js","../node_modules/p-queue/dist/priority-queue.js","../node_modules/p-queue/dist/index.js","../node_modules/is-network-error/index.js","../node_modules/p-retry/index.js","../src/embeddings/detector.ts","../src/embeddings/provider-types.ts","../src/utils/url-validation.ts","../src/embeddings/providers/custom.ts","../src/embeddings/providers/github-copilot.ts","../src/embeddings/providers/google.ts","../src/embeddings/providers/ollama.ts","../src/embeddings/providers/openai.ts","../src/embeddings/provider.ts","../src/rerank/index.ts","../src/utils/cost.ts","../src/utils/logger.ts","../src/native/index.ts","../src/tools/utils.ts","../src/tools/knowledge-base-paths.ts","../src/tools/config-state.ts","../src/commands/loader.ts","../src/routing-hints-patterns.ts","../src/routing-hints.ts"],"sourcesContent":["// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\nconst REGEX_TEST_BLANK_LINE = /^\\s+$/\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst REGEX_TEST_INVALID_PATH = /^\\.{0,2}\\/|^\\.{1,2}$/\n\nconst REGEX_TEST_TRAILING_SLASH = /\\/$/\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g\n\nconst RETURN_FALSE = () => false\n\n// Sanitize the range of a regular expression\n// The cases are complicated, see test cases for details\nconst sanitizeRange = range => range.replace(\n REGEX_REGEXP_RANGE,\n (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)\n ? match\n // Invalid range (out of order) which is ok for gitignore rules but\n // fatal for JavaScript regular expression, so eliminate it.\n : EMPTY\n)\n\n// See fixtures #59\nconst cleanRangeBackSlash = slashes => {\n const {length} = slashes\n return slashes.slice(0, length - length % 2)\n}\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\nconst REPLACERS = [\n\n [\n // Remove BOM\n // TODO:\n // Other similar zero-width characters?\n /^\\uFEFF/,\n () => EMPTY\n ],\n\n // > Trailing spaces are ignored unless they are quoted with backslash (\"\\\")\n [\n // (a\\ ) -> (a )\n // (a ) -> (a)\n // (a ) -> (a)\n // (a \\ ) -> (a )\n /((?:\\\\\\\\)*?)(\\\\?\\s+)$/,\n (_, m1, m2) => m1 + (\n m2.indexOf('\\\\') === 0\n ? SPACE\n : EMPTY\n )\n ],\n\n // Replace (\\ ) with ' '\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n /(\\\\+?)\\s/g,\n (_, m1) => {\n const {length} = m1\n return m1.slice(0, length - length % 2) + SPACE\n }\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^'\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/'\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*\\\\\\*\\\\\\*\\\\\\//,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n /^(?=[^^])/,\n function startingReplacer () {\n // If has a slash `/` at the beginning or middle\n return !/\\/(?!$)/.test(this)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n ? '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder\n : '\\\\/.+'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n }\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE\n ],\n\n [\n // > The range notation, e.g. [a-zA-Z],\n // > can be used to match one of the characters in a range.\n\n // `\\` is escaped by step 3\n /(\\\\)?\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE\n // '\\\\[bar]' -> '\\\\\\\\[bar\\\\]'\n ? `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}`\n : close === ']'\n ? endEscape.length % 2 === 0\n // A normal case, and it is a range notation\n // '[bar]'\n // '[bar\\\\\\\\]'\n ? `[${sanitizeRange(range)}${endEscape}]`\n // Invalid range notaton\n // '[bar\\\\]' -> '[bar\\\\\\\\]'\n : '[]'\n : '[]'\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n /(?:[^*])$/,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n match => /\\/$/.test(match)\n // foo/ will not match 'foo'\n ? `${match}$`\n // foo matches 'foo' and 'foo/'\n : `${match}(?=$|\\\\/$)`\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\\\\\*$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst TRAILING_WILD_CARD_REPLACERS = {\n [MODE_IGNORE] (_, p1) {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n },\n\n [MODE_CHECK_IGNORE] (_, p1) {\n // When doing `git check-ignore`\n const prefix = p1\n // '\\\\\\/':\n // 'abc/*' DOES match 'abc/' !\n ? `${p1}[^/]*`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n }\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => REPLACERS.reduce(\n (prev, [matcher, replacer]) =>\n prev.replace(matcher, replacer.bind(pattern)),\n pattern\n)\n\nconst isString = subject => typeof subject === 'string'\n\n// > A blank line matches no files, so it can serve as a separator for readability.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_TEST_BLANK_LINE.test(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\n // > A line starting with # serves as a comment.\n && pattern.indexOf('#') !== 0\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = this.regexPrefix.replace(\n REGEX_REPLACE_TRAILING_WILDCARD,\n\n // It does not need to bind pattern\n TRAILING_WILD_CARD_REPLACERS[mode]\n )\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n let negative = false\n let body = pattern\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body.indexOf('!') === 0) {\n negative = true\n body = body.substr(1)\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n if (checkPattern(pattern.pattern)) {\n const rule = createRule(pattern, this._ignoreCase)\n this._added = true\n this._rules.push(rule)\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n return this._added\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - checkUnignored `boolean` whether should check if the path is unignored,\n // setting `checkUnignored` to `false` could reduce additional\n // path matching.\n // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult} true if a file is ignored\n test (path, checkUnignored, mode) {\n let ignored = false\n let unignored = false\n let matchedRule\n\n this._rules.forEach(rule => {\n const {negative} = rule\n\n // | ignored : unignored\n // -------- | ---------------------------------------\n // negative | 0:0 | 0:1 | 1:0 | 1:1\n // -------- | ------- | ------- | ------- | --------\n // 0 | TEST | TEST | SKIP | X\n // 1 | TESTIF | SKIP | TEST | X\n\n // - SKIP: always skip\n // - TEST: always test\n // - TESTIF: only test if checkUnignored\n // - X: that never happen\n if (\n unignored === negative && ignored !== unignored\n || negative && !ignored && !unignored && !checkUnignored\n ) {\n return\n }\n\n const matched = rule[mode].test(path)\n\n if (!matched) {\n return\n }\n\n ignored = !negative\n unignored = negative\n\n matchedRule = negative\n ? UNDEFINED\n : rule\n })\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\nconst isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path)\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache, checkUnignored, slices) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache, checkUnignored, slices)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (!REGEX_TEST_TRAILING_SLASH.test(path)) {\n return this.test(path)\n }\n\n const slices = path.split(SLASH).filter(Boolean)\n slices.pop()\n\n if (slices.length) {\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n this._testCache,\n true,\n slices\n )\n\n if (parent.ignored) {\n return parent\n }\n }\n\n return this._rules.test(path, false, MODE_CHECK_IGNORE)\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache,\n\n // Whether should check if the path is unignored\n checkUnignored,\n\n // The path slices\n slices\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n if (!slices) {\n // path/to/a.js\n // ['path', 'to', 'a.js']\n slices = path.split(SLASH).filter(Boolean)\n }\n\n slices.pop()\n\n // If the path has no parent directory, just test it\n if (!slices.length) {\n return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n cache,\n checkUnignored,\n slices\n )\n\n // If the path contains a parent directory, check the parent first\n return cache[path] = parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache, false).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache, true)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import type { Plugin } from \"@opencode-ai/plugin\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport { parseConfig } from \"./config/schema.js\";\nimport { loadMergedConfig } from \"./config/merger.js\";\nimport { createWatcherWithIndexer } from \"./watcher/index.js\";\nimport {\n codebase_search,\n codebase_peek,\n index_codebase,\n index_status,\n index_health_check,\n index_metrics,\n index_logs,\n find_similar,\n call_graph,\n call_graph_path,\n implementation_lookup,\n add_knowledge_base,\n list_knowledge_bases,\n remove_knowledge_base,\n getIndexerForProject,\n initializeTools,\n} from \"./tools/index.js\";\nimport { loadCommandsFromDirectory } from \"./commands/loader.js\";\nimport { RoutingHintController } from \"./routing-hints.js\";\nimport { hasProjectMarker } from \"./utils/files.js\";\nimport type { CombinedWatcher } from \"./watcher/index.js\";\n\nconst activeWatchers = new Map<string, CombinedWatcher>();\n\nfunction replaceActiveWatcher(projectRoot: string, nextWatcher: CombinedWatcher | null): void {\n const existing = activeWatchers.get(projectRoot);\n if (existing) {\n existing.stop();\n activeWatchers.delete(projectRoot);\n }\n if (nextWatcher) {\n activeWatchers.set(projectRoot, nextWatcher);\n }\n}\n\nfunction getCommandsDir(): string {\n let currentDir = process.cwd();\n \n if (typeof import.meta !== \"undefined\" && import.meta.url) {\n currentDir = path.dirname(fileURLToPath(import.meta.url));\n }\n \n return path.join(currentDir, \"..\", \"commands\");\n}\n\nfunction appendRoutingHints(\n output: { system?: string[]; developer?: string[] },\n hints: string[],\n preferredRole: \"system\" | \"developer\",\n): void {\n const preferredBucket = preferredRole === \"developer\" ? output.developer : output.system;\n if (Array.isArray(preferredBucket)) {\n preferredBucket.push(...hints);\n return;\n }\n\n // Compatibility fallback for runtimes that do not expose a developer channel yet.\n if (Array.isArray(output.system)) {\n output.system.push(...hints);\n }\n}\n\ninterface ChatTransformInput {\n sessionID?: string;\n}\n\ninterface ChatTransformOutput {\n system?: string[];\n developer?: string[];\n}\n\nconst plugin: Plugin = async ({ directory, worktree }) => {\n try {\n const projectRoot = worktree || directory;\n const rawConfig = loadMergedConfig(projectRoot);\n const config = parseConfig(rawConfig);\n\n initializeTools(projectRoot, config);\n\n const getProjectIndexer = () => getIndexerForProject(projectRoot);\n const routingHints = config.search.routingHints\n ? new RoutingHintController(() => getProjectIndexer().getStatus())\n : null;\n\n const isHomeDir = path.resolve(projectRoot) === path.resolve(os.homedir());\n const isValidProject = !isHomeDir && (!config.indexing.requireProjectMarker || hasProjectMarker(projectRoot));\n\n if (isHomeDir) {\n console.warn(\n `[codebase-index] Refusing to watch or index home directory \"${projectRoot}\". ` +\n `Open a specific project directory instead.`\n );\n } else if (!isValidProject) {\n console.warn(\n `[codebase-index] Skipping file watching and auto-indexing: no project marker found in \"${projectRoot}\". ` +\n `Set \"indexing.requireProjectMarker\": false in config to override.`\n );\n }\n\n if (config.indexing.autoIndex && isValidProject) {\n const indexer = getProjectIndexer();\n indexer.initialize().then(() => {\n indexer.index().catch(() => {});\n }).catch(() => {});\n }\n\n if (config.indexing.watchFiles && isValidProject) {\n replaceActiveWatcher(projectRoot, createWatcherWithIndexer(getProjectIndexer, projectRoot, config));\n } else {\n replaceActiveWatcher(projectRoot, null);\n }\n\n return {\n tool: {\n codebase_search,\n codebase_peek,\n index_codebase,\n index_status,\n index_health_check,\n index_metrics,\n index_logs,\n find_similar,\n call_graph,\n call_graph_path,\n implementation_lookup,\n add_knowledge_base,\n list_knowledge_bases,\n remove_knowledge_base,\n },\n\n async \"chat.message\"(input, output) {\n routingHints?.observeUserMessage(input.sessionID, output.parts);\n },\n\n async \"experimental.chat.system.transform\"(input: ChatTransformInput, output: ChatTransformOutput) {\n if (config.search.routingHintRole !== \"system\") {\n return;\n }\n\n const hints = await routingHints?.getSystemHints(input.sessionID) ?? [];\n appendRoutingHints(output, hints, \"system\");\n },\n\n async \"experimental.chat.developer.transform\"(input: ChatTransformInput, output: ChatTransformOutput) {\n if (config.search.routingHintRole !== \"developer\") {\n return;\n }\n\n const hints = await routingHints?.getSystemHints(input.sessionID) ?? [];\n appendRoutingHints(output, hints, \"developer\");\n },\n\n async \"tool.execute.after\"(input) {\n routingHints?.markToolUsed(input.sessionID, input.tool);\n },\n\n async config(cfg) {\n cfg.command = cfg.command ?? {};\n\n const commandsDir = getCommandsDir();\n const commands = loadCommandsFromDirectory(commandsDir);\n\n for (const [name, definition] of commands) {\n cfg.command[name] = definition;\n }\n },\n };\n } catch {\n console.error(\"[codebase-index] Failed to initialize plugin (check config and network)\");\n // Return a plugin with no tools to prevent opencode from crashing\n return {\n tool: undefined,\n async config() {},\n };\n }\n};\n\nexport default plugin;\n","export const DEFAULT_INCLUDE = [\n \"**/*.{ts,tsx,js,jsx,mjs,cjs}\",\n \"**/*.{py,pyi}\",\n \"**/*.{go,rs,java,kt,scala}\",\n \"**/*.{c,cpp,cc,h,hpp}\",\n \"**/*.{rb,php,inc,swift}\",\n \"**/*.{cls,trigger}\",\n \"**/*.{vue,svelte,astro}\",\n \"**/*.{sql,graphql,proto}\",\n \"**/*.{yaml,yml,toml}\",\n \"**/*.{md,mdx}\",\n \"**/*.{sh,bash,zsh}\",\n \"**/*.{txt,html,htm}\",\n \"**/*.zig\",\n \"**/*.gd\",\n];\n\nexport const DEFAULT_EXCLUDE = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/*build*/**\",\n \"**/*.min.js\",\n \"**/*.bundle.js\",\n \"**/vendor/**\",\n \"**/__pycache__/**\",\n \"**/target/**\",\n \"**/coverage/**\",\n \"**/.next/**\",\n \"**/.nuxt/**\",\n \"**/.opencode/**\",\n \"**/.*\",\n \"**/.*/**\",\n];\n\nexport const EMBEDDING_MODELS = {\n \"google\": {\n // `text-embedding-004` is DEPRECATED - https://ai.google.dev/gemini-api/docs/deprecations\n \"text-embedding-005\": {\n provider: \"google\",\n model: \"text-embedding-005\",\n dimensions: 768,\n maxTokens: 2048,\n costPer1MTokens: 0.025,\n taskAble: false,\n // Note: on reality, this model allows for task-specific embeddings. See: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/embeddings/task-types\n },\n \"gemini-embedding-001\": {\n provider: \"google\",\n model: \"gemini-embedding-001\",\n // Native output is 3072D, but we use Matryoshka truncation via outputDimensionality\n // to reduce to 1536D for better storage/search efficiency with minimal quality loss.\n // Google recommends 768, 1536, or 3072. See: https://ai.google.dev/gemini-api/docs/embeddings\n dimensions: 1536,\n maxTokens: 2048,\n costPer1MTokens: 0.15,\n taskAble: true,\n },\n },\n \"openai\": {\n \"text-embedding-3-small\": {\n provider: \"openai\",\n model: \"text-embedding-3-small\",\n dimensions: 1536,\n maxTokens: 8191,\n costPer1MTokens: 0.02,\n },\n \"text-embedding-3-large\": {\n provider: \"openai\",\n model: \"text-embedding-3-large\",\n dimensions: 3072,\n maxTokens: 8191,\n costPer1MTokens: 0.13,\n },\n },\n \"ollama\": {\n \"nomic-embed-text\": {\n provider: \"ollama\",\n model: \"nomic-embed-text\",\n dimensions: 768,\n maxTokens: 2048,\n costPer1MTokens: 0.00,\n },\n \"mxbai-embed-large\": {\n provider: \"ollama\",\n model: \"mxbai-embed-large\",\n dimensions: 1024,\n maxTokens: 512,\n costPer1MTokens: 0.00,\n },\n },\n \"github-copilot\": {\n \"text-embedding-3-small\": {\n provider: \"github-copilot\",\n model: \"text-embedding-3-small\",\n dimensions: 1536,\n maxTokens: 8191,\n costPer1MTokens: 0.00,\n },\n },\n} as const;\n\nexport const DEFAULT_PROVIDER_MODELS = {\n \"github-copilot\": \"text-embedding-3-small\",\n \"openai\": \"text-embedding-3-small\",\n \"google\": \"gemini-embedding-001\",\n \"ollama\": \"nomic-embed-text\",\n} as const;\n\nexport const AUTO_DETECT_PROVIDER_ORDER = [\n \"ollama\",\n \"github-copilot\",\n \"openai\",\n \"google\",\n] as const;\n","import type {\n DebugConfig,\n IndexingConfig,\n RerankerProvider,\n SearchConfig,\n} from \"./schema.js\";\n\nexport function getDefaultIndexingConfig(): IndexingConfig {\n return {\n autoIndex: false,\n watchFiles: true,\n maxFileSize: 1048576,\n maxChunksPerFile: 100,\n semanticOnly: false,\n retries: 3,\n retryDelayMs: 1000,\n autoGc: true,\n gcIntervalDays: 7,\n gcOrphanThreshold: 100,\n requireProjectMarker: true,\n maxDepth: 5,\n maxFilesPerDirectory: 100,\n fallbackToTextOnMaxChunks: true,\n };\n}\n\nexport function getDefaultSearchConfig(): SearchConfig {\n return {\n maxResults: 20,\n minScore: 0.1,\n includeContext: true,\n hybridWeight: 0.5,\n fusionStrategy: \"rrf\",\n rrfK: 60,\n rerankTopN: 20,\n contextLines: 0,\n routingHints: true,\n routingHintRole: \"system\",\n };\n}\n\nexport function getDefaultRerankerBaseUrl(provider: RerankerProvider): string {\n switch (provider) {\n case \"cohere\":\n return \"https://api.cohere.ai/v1\";\n case \"jina\":\n return \"https://api.jina.ai/v1\";\n case \"custom\":\n return \"\";\n }\n}\n\nexport function getDefaultDebugConfig(): DebugConfig {\n return {\n enabled: false,\n logLevel: \"info\",\n logSearch: true,\n logEmbedding: true,\n logCache: true,\n logGc: true,\n logBranch: true,\n metrics: true,\n };\n}\n","const ENV_REFERENCE_PATTERN = /^\\{env:([A-Z_][A-Z0-9_]*)\\}$/;\nconst ENV_REFERENCE_LIKE_PATTERN = /\\{env:[^}]+\\}/;\n\nexport function substituteEnvString(value: string, keyPath: string): string {\n const match = value.match(ENV_REFERENCE_PATTERN);\n\n if (!match) {\n if (ENV_REFERENCE_LIKE_PATTERN.test(value)) {\n throw new Error(\n `Invalid environment variable reference at '${keyPath}'. ` +\n \"Expected the entire string to match '{env:VAR_NAME}' with VAR_NAME matching [A-Z_][A-Z0-9_]*.\"\n );\n }\n\n return value;\n }\n\n const variableName = match[1];\n const envValue = process.env[variableName];\n\n if (envValue === undefined) {\n throw new Error(`Missing environment variable '${variableName}' referenced by config at '${keyPath}'.`);\n }\n\n return envValue;\n}\n\nexport function substituteEnvReferences(raw: unknown, keyPath = \"$root\"): unknown {\n if (typeof raw === \"string\") {\n return substituteEnvString(raw, keyPath);\n }\n\n if (Array.isArray(raw)) {\n return raw.map((item, index) => substituteEnvReferences(item, `${keyPath}[${index}]`));\n }\n\n if (raw && typeof raw === \"object\") {\n return Object.fromEntries(\n Object.entries(raw).map(([key, value]) => [key, substituteEnvReferences(value, `${keyPath}.${key}`)])\n );\n }\n\n return raw;\n}\n","import type {\n EmbeddingProvider,\n IndexScope,\n LogLevel,\n ProviderModels,\n RerankerProvider,\n SearchConfig,\n} from \"./schema.js\";\n\nimport { EMBEDDING_MODELS } from \"./constants.js\";\nimport { substituteEnvString } from \"./env-substitution.js\";\n\nconst VALID_SCOPES: IndexScope[] = [\"project\", \"global\"];\nconst VALID_LOG_LEVELS: LogLevel[] = [\"error\", \"warn\", \"info\", \"debug\"];\n\nexport function isValidFusionStrategy(value: unknown): value is SearchConfig[\"fusionStrategy\"] {\n return value === \"weighted\" || value === \"rrf\";\n}\n\nexport function isValidRerankerProvider(value: unknown): value is RerankerProvider {\n return value === \"cohere\" || value === \"jina\" || value === \"custom\";\n}\n\nexport function isValidProvider(value: unknown): value is EmbeddingProvider {\n return typeof value === \"string\" && Object.keys(EMBEDDING_MODELS).includes(value);\n}\n\nexport function isValidModel<P extends EmbeddingProvider>(\n value: unknown,\n provider: P\n): value is ProviderModels[P] {\n return typeof value === \"string\" && Object.keys(EMBEDDING_MODELS[provider]).includes(value);\n}\n\nexport function isValidScope(value: unknown): value is IndexScope {\n return typeof value === \"string\" && VALID_SCOPES.includes(value as IndexScope);\n}\n\nexport function isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every(item => typeof item === \"string\");\n}\n\nexport function getResolvedString(value: unknown, keyPath: string): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n return substituteEnvString(value, keyPath);\n}\n\nexport function getResolvedStringArray(value: unknown, keyPath: string): string[] | undefined {\n if (!isStringArray(value)) {\n return undefined;\n }\n\n return value.map((item, index) => substituteEnvString(item, `${keyPath}[${index}]`));\n}\n\nexport function isValidLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && VALID_LOG_LEVELS.includes(value as LogLevel);\n}\n","// Config schema without zod dependency to avoid version conflicts with OpenCode SDK\n\nimport { AUTO_DETECT_PROVIDER_ORDER, DEFAULT_INCLUDE, DEFAULT_EXCLUDE, EMBEDDING_MODELS, DEFAULT_PROVIDER_MODELS } from \"./constants.js\";\nimport {\n getDefaultDebugConfig,\n getDefaultIndexingConfig,\n getDefaultRerankerBaseUrl,\n getDefaultSearchConfig,\n} from \"./defaults.js\";\nimport {\n getResolvedString,\n getResolvedStringArray,\n isStringArray,\n isValidFusionStrategy,\n isValidLogLevel,\n isValidModel,\n isValidProvider,\n isValidRerankerProvider,\n isValidScope,\n} from \"./validators.js\";\n\nexport { isValidModel } from \"./validators.js\";\n\nexport type IndexScope = \"project\" | \"global\";\n\nexport interface IndexingConfig {\n autoIndex: boolean;\n watchFiles: boolean;\n maxFileSize: number;\n maxChunksPerFile: number;\n semanticOnly: boolean;\n retries: number;\n retryDelayMs: number;\n autoGc: boolean;\n gcIntervalDays: number;\n gcOrphanThreshold: number;\n /**\n * When true (default), requires a project marker (.git, package.json, Cargo.toml, etc.)\n * to be present before enabling file watching and auto-indexing.\n */\n requireProjectMarker: boolean;\n /**\n * Max directory traversal depth. -1 = unlimited, 0 = only files in the root dir,\n * 1 = one level of subdirectories, etc. Default: 5\n */\n maxDepth: number;\n /**\n * Max number of files to index per directory. Always picks the smallest files first.\n * Default: 100\n */\n maxFilesPerDirectory: number;\n /**\n * When a file hits maxChunksPerFile, fallback to text-based (chunk_by_lines) parsing\n * instead of skipping the rest of the file. Default: true\n */\n fallbackToTextOnMaxChunks: boolean;\n}\n\nexport interface SearchConfig {\n maxResults: number;\n minScore: number;\n includeContext: boolean;\n hybridWeight: number;\n fusionStrategy: \"weighted\" | \"rrf\";\n rrfK: number;\n rerankTopN: number;\n contextLines: number;\n routingHints: boolean;\n routingHintRole: \"system\" | \"developer\";\n}\n\nexport type RerankerProvider = \"cohere\" | \"jina\" | \"custom\";\n\nexport interface RerankerConfig {\n /** Whether to enable reranking. Default: false */\n enabled: boolean;\n /** Provider shortcut for hosted rerank APIs. Use 'custom' to provide only baseUrl. */\n provider: RerankerProvider;\n /** Model name for reranking */\n model: string;\n /** Base URL of the rerank API endpoint */\n baseUrl: string;\n /** API key for the rerank service */\n apiKey?: string;\n /** Number of top documents to rerank */\n topN: number;\n /** Request timeout in milliseconds */\n timeoutMs: number;\n}\n\nexport type LogLevel = \"error\" | \"warn\" | \"info\" | \"debug\";\n\nexport interface DebugConfig {\n enabled: boolean;\n logLevel: LogLevel;\n logSearch: boolean;\n logEmbedding: boolean;\n logCache: boolean;\n logGc: boolean;\n logBranch: boolean;\n metrics: boolean;\n}\n\nexport interface CustomProviderConfig {\n /** Base URL of the OpenAI-compatible embeddings API. The path /embeddings is appended automatically (e.g. \"http://localhost:11434/v1\", \"https://api.example.com/v1\") */\n baseUrl: string;\n /** Model name to send in the API request (e.g. \"nomic-embed-text\") */\n model: string;\n /** Vector dimensions the model produces (e.g. 768 for nomic-embed-text) */\n dimensions: number;\n /** Optional API key for authenticated endpoints */\n apiKey?: string;\n /** Max tokens per input text (default: 8192) */\n maxTokens?: number;\n /** Request timeout in milliseconds (default: 30000) */\n timeoutMs?: number;\n /** Max concurrent embedding requests (default: 3). Increase for local servers like llama.cpp or vLLM. */\n concurrency?: number;\n /** Minimum delay between requests in milliseconds (default: 1000). Set to 0 for local servers. */\n requestIntervalMs?: number;\n maxBatchSize?: number;\n max_batch_size?: number;\n}\n\nexport interface CodebaseIndexConfig {\n embeddingProvider: EmbeddingProvider | 'custom' | 'auto';\n embeddingModel?: EmbeddingModelName;\n /** Configuration for custom OpenAI-compatible embedding providers (required when embeddingProvider is 'custom') */\n customProvider?: CustomProviderConfig;\n scope: IndexScope;\n indexing?: Partial<IndexingConfig>;\n search?: Partial<SearchConfig>;\n debug?: Partial<DebugConfig>;\n /** Reranking configuration for improving search result quality */\n reranker?: Partial<RerankerConfig>;\n /** External directories to index as knowledge bases (absolute or relative paths) */\n knowledgeBases?: string[];\n /** Override the default include patterns (replaces defaults) */\n include: string[];\n /** Override the default exclude patterns (replaces defaults) */\n exclude: string[];\n /** Additional file patterns to include (extends defaults) */\n additionalInclude?: string[];\n}\n\nexport type ParsedCodebaseIndexConfig = CodebaseIndexConfig & {\n indexing: IndexingConfig;\n search: SearchConfig;\n debug: DebugConfig;\n reranker?: RerankerConfig;\n knowledgeBases: string[];\n additionalInclude: string[];\n};\n\nexport function parseConfig(raw: unknown): ParsedCodebaseIndexConfig {\n const input = (raw && typeof raw === \"object\" ? raw : {}) as Record<string, unknown>;\n const embeddingProviderValue = getResolvedString(input.embeddingProvider, \"$root.embeddingProvider\");\n const scopeValue = getResolvedString(input.scope, \"$root.scope\");\n const includeValue = getResolvedStringArray(input.include, \"$root.include\");\n const excludeValue = getResolvedStringArray(input.exclude, \"$root.exclude\");\n\n const defaultIndexing = getDefaultIndexingConfig();\n const defaultSearch = getDefaultSearchConfig();\n const defaultDebug = getDefaultDebugConfig();\n\n const rawIndexing = (input.indexing && typeof input.indexing === \"object\" ? input.indexing : {}) as Record<string, unknown>;\n const indexing: IndexingConfig = {\n autoIndex: typeof rawIndexing.autoIndex === \"boolean\" ? rawIndexing.autoIndex : defaultIndexing.autoIndex,\n watchFiles: typeof rawIndexing.watchFiles === \"boolean\" ? rawIndexing.watchFiles : defaultIndexing.watchFiles,\n maxFileSize: typeof rawIndexing.maxFileSize === \"number\" ? rawIndexing.maxFileSize : defaultIndexing.maxFileSize,\n maxChunksPerFile: typeof rawIndexing.maxChunksPerFile === \"number\" ? Math.max(1, rawIndexing.maxChunksPerFile) : defaultIndexing.maxChunksPerFile,\n semanticOnly: typeof rawIndexing.semanticOnly === \"boolean\" ? rawIndexing.semanticOnly : defaultIndexing.semanticOnly,\n retries: typeof rawIndexing.retries === \"number\" ? rawIndexing.retries : defaultIndexing.retries,\n retryDelayMs: typeof rawIndexing.retryDelayMs === \"number\" ? rawIndexing.retryDelayMs : defaultIndexing.retryDelayMs,\n autoGc: typeof rawIndexing.autoGc === \"boolean\" ? rawIndexing.autoGc : defaultIndexing.autoGc,\n gcIntervalDays: typeof rawIndexing.gcIntervalDays === \"number\" ? Math.max(1, rawIndexing.gcIntervalDays) : defaultIndexing.gcIntervalDays,\n gcOrphanThreshold: typeof rawIndexing.gcOrphanThreshold === \"number\" ? Math.max(0, rawIndexing.gcOrphanThreshold) : defaultIndexing.gcOrphanThreshold,\n requireProjectMarker: typeof rawIndexing.requireProjectMarker === \"boolean\" ? rawIndexing.requireProjectMarker : defaultIndexing.requireProjectMarker,\n maxDepth: typeof rawIndexing.maxDepth === \"number\" ? (rawIndexing.maxDepth < -1 ? -1 : rawIndexing.maxDepth) : defaultIndexing.maxDepth,\n maxFilesPerDirectory: typeof rawIndexing.maxFilesPerDirectory === \"number\" ? Math.max(1, rawIndexing.maxFilesPerDirectory) : defaultIndexing.maxFilesPerDirectory,\n fallbackToTextOnMaxChunks: typeof rawIndexing.fallbackToTextOnMaxChunks === \"boolean\" ? rawIndexing.fallbackToTextOnMaxChunks : defaultIndexing.fallbackToTextOnMaxChunks,\n };\n\n const rawSearch = (input.search && typeof input.search === \"object\" ? input.search : {}) as Record<string, unknown>;\n const search: SearchConfig = {\n maxResults: typeof rawSearch.maxResults === \"number\" ? rawSearch.maxResults : defaultSearch.maxResults,\n minScore: typeof rawSearch.minScore === \"number\" ? rawSearch.minScore : defaultSearch.minScore,\n includeContext: typeof rawSearch.includeContext === \"boolean\" ? rawSearch.includeContext : defaultSearch.includeContext,\n hybridWeight: typeof rawSearch.hybridWeight === \"number\" ? Math.min(1, Math.max(0, rawSearch.hybridWeight)) : defaultSearch.hybridWeight,\n fusionStrategy: isValidFusionStrategy(rawSearch.fusionStrategy) ? rawSearch.fusionStrategy : defaultSearch.fusionStrategy,\n rrfK: typeof rawSearch.rrfK === \"number\" ? Math.max(1, Math.floor(rawSearch.rrfK)) : defaultSearch.rrfK,\n rerankTopN: typeof rawSearch.rerankTopN === \"number\" ? Math.min(200, Math.max(0, Math.floor(rawSearch.rerankTopN))) : defaultSearch.rerankTopN,\n contextLines: typeof rawSearch.contextLines === \"number\" ? Math.min(50, Math.max(0, rawSearch.contextLines)) : defaultSearch.contextLines,\n routingHints: typeof rawSearch.routingHints === \"boolean\" ? rawSearch.routingHints : defaultSearch.routingHints,\n routingHintRole: rawSearch.routingHintRole === \"developer\" || rawSearch.routingHintRole === \"system\"\n ? rawSearch.routingHintRole\n : defaultSearch.routingHintRole,\n };\n\n const rawDebug = (input.debug && typeof input.debug === \"object\" ? input.debug : {}) as Record<string, unknown>;\n const debug: DebugConfig = {\n enabled: typeof rawDebug.enabled === \"boolean\" ? rawDebug.enabled : defaultDebug.enabled,\n logLevel: isValidLogLevel(rawDebug.logLevel) ? rawDebug.logLevel : defaultDebug.logLevel,\n logSearch: typeof rawDebug.logSearch === \"boolean\" ? rawDebug.logSearch : defaultDebug.logSearch,\n logEmbedding: typeof rawDebug.logEmbedding === \"boolean\" ? rawDebug.logEmbedding : defaultDebug.logEmbedding,\n logCache: typeof rawDebug.logCache === \"boolean\" ? rawDebug.logCache : defaultDebug.logCache,\n logGc: typeof rawDebug.logGc === \"boolean\" ? rawDebug.logGc : defaultDebug.logGc,\n logBranch: typeof rawDebug.logBranch === \"boolean\" ? rawDebug.logBranch : defaultDebug.logBranch,\n metrics: typeof rawDebug.metrics === \"boolean\" ? rawDebug.metrics : defaultDebug.metrics,\n };\n\n const rawKnowledgeBases = input.knowledgeBases;\n const knowledgeBases: string[] = isStringArray(rawKnowledgeBases)\n ? rawKnowledgeBases.filter(p => typeof p === \"string\" && p.trim().length > 0).map(p => p.trim())\n : [];\n\n const rawAdditionalInclude = input.additionalInclude;\n const additionalInclude: string[] = isStringArray(rawAdditionalInclude)\n ? rawAdditionalInclude\n .filter(p => typeof p === \"string\" && p.trim().length > 0)\n .map(p => p.trim())\n : [];\n\n let embeddingProvider: EmbeddingProvider | 'custom' | 'auto';\n let embeddingModel: EmbeddingModelName | undefined;\n let customProvider: CustomProviderConfig | undefined;\n let reranker: RerankerConfig | undefined;\n if (embeddingProviderValue === 'custom') {\n embeddingProvider = 'custom';\n const rawCustom = (input.customProvider && typeof input.customProvider === 'object' ? input.customProvider : null) as Record<string, unknown> | null;\n const baseUrlValue = getResolvedString(rawCustom?.baseUrl, \"$root.customProvider.baseUrl\");\n const modelValue = getResolvedString(rawCustom?.model, \"$root.customProvider.model\");\n const apiKeyValue = getResolvedString(rawCustom?.apiKey, \"$root.customProvider.apiKey\");\n if (rawCustom && typeof baseUrlValue === 'string' && baseUrlValue.trim().length > 0 && typeof modelValue === 'string' && modelValue.trim().length > 0 && typeof rawCustom.dimensions === 'number' && Number.isInteger(rawCustom.dimensions) && rawCustom.dimensions > 0) {\n customProvider = {\n baseUrl: baseUrlValue.trim().replace(/\\/+$/, ''),\n model: modelValue,\n dimensions: rawCustom.dimensions,\n apiKey: apiKeyValue,\n maxTokens: typeof rawCustom.maxTokens === 'number' ? rawCustom.maxTokens : undefined,\n timeoutMs: typeof rawCustom.timeoutMs === 'number' ? Math.max(1000, rawCustom.timeoutMs) : undefined,\n concurrency: typeof rawCustom.concurrency === 'number' ? Math.max(1, Math.floor(rawCustom.concurrency)) : undefined,\n requestIntervalMs: typeof rawCustom.requestIntervalMs === 'number' ? Math.max(0, Math.floor(rawCustom.requestIntervalMs)) : undefined,\n maxBatchSize: typeof rawCustom.maxBatchSize === 'number'\n ? Math.max(1, Math.floor(rawCustom.maxBatchSize))\n : typeof rawCustom.max_batch_size === 'number'\n ? Math.max(1, Math.floor(rawCustom.max_batch_size))\n : undefined,\n };\n // Warn if baseUrl doesn't end with an API version path like /v1.\n // Note: using console.warn here because Logger isn't initialized yet at config parse time.\n if (!/\\/v\\d+\\/?$/.test(customProvider.baseUrl)) {\n console.warn(\n `[codebase-index] Warning: customProvider.baseUrl (\"${customProvider.baseUrl}\") does not end with an API version path like /v1. ` +\n `The plugin appends /embeddings automatically, so the full URL will be \"${customProvider.baseUrl}/embeddings\". ` +\n `If your provider expects /v1/embeddings, set baseUrl to \"${customProvider.baseUrl}/v1\".`\n );\n }\n } else {\n throw new Error(\n \"embeddingProvider is 'custom' but customProvider config is missing or invalid. \" +\n \"Required fields: baseUrl (string), model (string), dimensions (positive integer).\"\n );\n }\n } else if (isValidProvider(embeddingProviderValue)) {\n embeddingProvider = embeddingProviderValue;\n const rawEmbeddingModel = input.embeddingModel;\n if (typeof rawEmbeddingModel === \"string\") {\n const embeddingModelValue = getResolvedString(rawEmbeddingModel, \"$root.embeddingModel\");\n if (embeddingModelValue) {\n embeddingModel = isValidModel(embeddingModelValue, embeddingProvider) ? embeddingModelValue : DEFAULT_PROVIDER_MODELS[embeddingProvider];\n }\n } else if (rawEmbeddingModel) {\n embeddingModel = DEFAULT_PROVIDER_MODELS[embeddingProvider];\n }\n } else {\n embeddingProvider = 'auto';\n }\n\n const rawReranker = (input.reranker && typeof input.reranker === \"object\"\n ? input.reranker\n : {}) as Record<string, unknown>;\n const rerankerEnabled = typeof rawReranker.enabled === \"boolean\" ? rawReranker.enabled : false;\n if (rerankerEnabled) {\n const provider = isValidRerankerProvider(rawReranker.provider) ? rawReranker.provider : \"custom\";\n const model = getResolvedString(rawReranker.model, \"$root.reranker.model\");\n if (!model || model.trim().length === 0) {\n throw new Error(\"reranker is enabled but reranker.model is missing or invalid.\");\n }\n\n const configuredBaseUrl = getResolvedString(rawReranker.baseUrl, \"$root.reranker.baseUrl\");\n const baseUrl = configuredBaseUrl?.trim() || getDefaultRerankerBaseUrl(provider);\n if (baseUrl.length === 0) {\n throw new Error(\"reranker is enabled but reranker.baseUrl is missing or invalid for provider 'custom'.\");\n }\n\n const apiKey = getResolvedString(rawReranker.apiKey, \"$root.reranker.apiKey\");\n if ((provider === \"cohere\" || provider === \"jina\") && (!apiKey || apiKey.trim().length === 0)) {\n throw new Error(`reranker provider '${provider}' requires reranker.apiKey when enabled.`);\n }\n\n reranker = {\n enabled: true,\n provider,\n model: model.trim(),\n baseUrl: baseUrl.replace(/\\/+$/, \"\"),\n apiKey: apiKey?.trim() || undefined,\n topN: typeof rawReranker.topN === \"number\" ? Math.min(50, Math.max(1, Math.floor(rawReranker.topN))) : 15,\n timeoutMs: typeof rawReranker.timeoutMs === \"number\" ? Math.max(1000, Math.floor(rawReranker.timeoutMs)) : 10000,\n };\n }\n\n return {\n embeddingProvider,\n embeddingModel,\n customProvider,\n scope: isValidScope(scopeValue) ? scopeValue : \"project\",\n include: includeValue ?? DEFAULT_INCLUDE,\n exclude: excludeValue ?? DEFAULT_EXCLUDE,\n additionalInclude,\n indexing,\n search,\n debug,\n reranker,\n knowledgeBases,\n };\n}\n\nexport function getDefaultModelForProvider(provider: EmbeddingProvider): EmbeddingModelInfo {\n const models = EMBEDDING_MODELS[provider];\n const providerDefault = DEFAULT_PROVIDER_MODELS[provider];\n return models[providerDefault as keyof typeof models];\n}\n\n/**\n * Built-in embedding providers derived from the static EMBEDDING_MODELS catalog.\n * 'custom' is intentionally excluded from this union because it has no static model\n * catalog — its model/dimensions/config are entirely user-defined at runtime via\n * CustomProviderConfig. Code that handles all providers uses `EmbeddingProvider | 'custom'`.\n */\nexport type EmbeddingProvider = keyof typeof EMBEDDING_MODELS;\n\nexport const availableProviders: EmbeddingProvider[] = Object.keys(EMBEDDING_MODELS) as EmbeddingProvider[];\n\nexport const autoDetectProviders: EmbeddingProvider[] = AUTO_DETECT_PROVIDER_ORDER.filter(\n (provider): provider is EmbeddingProvider => provider in EMBEDDING_MODELS,\n);\n\nexport type ProviderModels = {\n [P in keyof typeof EMBEDDING_MODELS]: keyof (typeof EMBEDDING_MODELS)[P]\n}\n\nexport type EmbeddingModelName = ProviderModels[keyof ProviderModels];\n\nexport type EmbeddingProviderModelInfo = {\n [P in EmbeddingProvider]: (typeof EMBEDDING_MODELS)[P][keyof (typeof EMBEDDING_MODELS)[P]]\n}\n\n\n/** Shared fields across all embedding model types (built-in and custom) */\nexport interface BaseModelInfo {\n model: string;\n dimensions: number;\n maxTokens: number;\n costPer1MTokens: number;\n}\n\nexport type EmbeddingModelInfo = EmbeddingProviderModelInfo[EmbeddingProvider];\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { resolveProjectConfigPath } from \"./paths.js\";\nimport { resolveInheritedKnowledgeBaseEntries } from \"./rebase.js\";\n\nconst PROJECT_OVERRIDE_KEYS = [\n \"embeddingProvider\",\n \"customProvider\",\n \"embeddingModel\",\n \"reranker\",\n \"include\",\n \"exclude\",\n \"indexing\",\n \"search\",\n \"debug\",\n \"scope\",\n] as const;\n\nconst MERGE_ARRAY_KEYS = [\"knowledgeBases\", \"additionalInclude\"] as const;\n\ntype ProjectOverrideKey = (typeof PROJECT_OVERRIDE_KEYS)[number];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\nfunction applyProjectOverride(\n merged: Record<string, unknown>,\n normalizedProjectConfig: Record<string, unknown>,\n globalConfig: Record<string, unknown>,\n key: ProjectOverrideKey,\n): void {\n if (key in normalizedProjectConfig) {\n merged[key] = normalizedProjectConfig[key];\n return;\n }\n\n if (key in globalConfig) {\n merged[key] = globalConfig[key];\n }\n}\n\nfunction mergeUniqueStringArray(values: unknown[]): string[] {\n return [...new Set(values.map((value) => String(value).trim()))];\n}\n\nfunction normalizeKnowledgeBasePath(value: unknown): string {\n let normalized = path.normalize(String(value).trim());\n const root = path.parse(normalized).root;\n\n while (normalized.length > root.length && /[\\\\/]$/.test(normalized)) {\n normalized = normalized.slice(0, -1);\n }\n\n return normalized;\n}\n\nfunction mergeKnowledgeBasePaths(values: unknown[]): string[] {\n return [...new Set(values.map((value) => normalizeKnowledgeBasePath(value)).filter((value) => value.length > 0))];\n}\n\nfunction validateConfigLayerShape(rawConfig: unknown, filePath: string): Record<string, unknown> {\n if (!isRecord(rawConfig)) {\n throw new Error(`Config file ${filePath} must contain a JSON object at the root.`);\n }\n\n if (rawConfig.knowledgeBases !== undefined && !isStringArray(rawConfig.knowledgeBases)) {\n throw new Error(`Config file ${filePath} field 'knowledgeBases' must be an array of strings.`);\n }\n if (rawConfig.additionalInclude !== undefined && !isStringArray(rawConfig.additionalInclude)) {\n throw new Error(`Config file ${filePath} field 'additionalInclude' must be an array of strings.`);\n }\n if (rawConfig.include !== undefined && !isStringArray(rawConfig.include)) {\n throw new Error(`Config file ${filePath} field 'include' must be an array of strings.`);\n }\n if (rawConfig.exclude !== undefined && !isStringArray(rawConfig.exclude)) {\n throw new Error(`Config file ${filePath} field 'exclude' must be an array of strings.`);\n }\n\n for (const section of [\"customProvider\", \"indexing\", \"search\", \"debug\", \"reranker\"] as const) {\n const value = rawConfig[section];\n if (value !== undefined && !isRecord(value)) {\n throw new Error(`Config file ${filePath} field '${section}' must be an object.`);\n }\n }\n\n return rawConfig;\n}\n\nfunction loadJsonFile(filePath: string): unknown {\n if (!existsSync(filePath)) {\n return null;\n }\n\n try {\n const content = readFileSync(filePath, \"utf-8\");\n return validateConfigLayerShape(JSON.parse(content), filePath);\n } catch (error: unknown) {\n if (error instanceof Error && error.message.startsWith(\"Config file \")) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load config file ${filePath}: ${message}`);\n }\n\n return null;\n}\n\nexport function materializeLocalProjectConfig(projectRoot: string, config: unknown): string {\n const localConfigPath = path.join(projectRoot, \".opencode\", \"codebase-index.json\");\n mkdirSync(path.dirname(localConfigPath), { recursive: true });\n writeFileSync(localConfigPath, JSON.stringify(config, null, 2), \"utf-8\");\n return localConfigPath;\n}\n\nexport function loadProjectConfigLayer(projectRoot: string): Record<string, unknown> {\n const projectConfigPath = resolveProjectConfigPath(projectRoot);\n const projectConfig = loadJsonFile(projectConfigPath) as Record<string, unknown> | null;\n\n if (!projectConfig) {\n return {};\n }\n\n const normalizedConfig: Record<string, unknown> = { ...projectConfig };\n const projectConfigBaseDir = path.dirname(path.dirname(projectConfigPath));\n\n if (Array.isArray(normalizedConfig.knowledgeBases)) {\n normalizedConfig.knowledgeBases = resolveInheritedKnowledgeBaseEntries(\n normalizedConfig.knowledgeBases,\n projectConfigBaseDir,\n projectRoot,\n );\n }\n\n return normalizedConfig;\n}\n\n/**\n * Loads and merges global and project configs.\n * \n * Merge rules:\n * - Global config is the base\n * - For most fields: project overrides global if set, otherwise load global (fallback)\n * - For knowledgeBases: merge arrays (union, deduplicated)\n * - For additionalInclude: merge arrays (union, deduplicated)\n * - For include/exclude: project overrides global if set, otherwise load global\n */\nexport function loadMergedConfig(projectRoot: string): unknown {\n const globalConfigPath = os.homedir() + \"/.config/opencode/codebase-index.json\";\n const projectConfigPath = resolveProjectConfigPath(projectRoot);\n let globalConfig: Record<string, unknown> | null = null;\n let globalConfigError: Error | null = null;\n\n try {\n globalConfig = loadJsonFile(globalConfigPath) as Record<string, unknown> | null;\n } catch (error: unknown) {\n globalConfigError = error instanceof Error ? error : new Error(String(error));\n }\n\n const projectConfig = loadJsonFile(projectConfigPath) as Record<string, unknown> | null;\n const normalizedProjectConfig = loadProjectConfigLayer(projectRoot);\n\n if (globalConfigError) {\n if (!projectConfig) {\n throw globalConfigError;\n }\n globalConfig = null;\n }\n\n if (!globalConfig && !projectConfig) {\n return {};\n }\n\n if (!projectConfig && globalConfig) {\n return globalConfig;\n }\n\n if (!globalConfig && projectConfig) {\n return normalizedProjectConfig;\n }\n\n if (!globalConfig || !projectConfig) {\n return globalConfig ?? normalizedProjectConfig;\n }\n\n\n const merged: Record<string, unknown> = { ...globalConfig };\n\n for (const key of PROJECT_OVERRIDE_KEYS) {\n applyProjectOverride(merged, normalizedProjectConfig, globalConfig, key);\n }\n\n // For other config sections: project overrides if set, otherwise use global\n if (projectConfig) {\n for (const key of Object.keys(projectConfig)) {\n if (\n PROJECT_OVERRIDE_KEYS.includes(key as ProjectOverrideKey) ||\n MERGE_ARRAY_KEYS.includes(key as (typeof MERGE_ARRAY_KEYS)[number])\n ) {\n continue; // Already handled above\n }\n merged[key] = normalizedProjectConfig[key];\n }\n }\n\n // For knowledgeBases: merge arrays (union, deduplicated)\n const globalKbs = globalConfig && Array.isArray(globalConfig.knowledgeBases) ? globalConfig.knowledgeBases : [];\n const projectKbs = projectConfig\n ? (Array.isArray(normalizedProjectConfig.knowledgeBases) ? normalizedProjectConfig.knowledgeBases as string[] : [])\n : [];\n const allKbs = [...globalKbs, ...projectKbs];\n merged.knowledgeBases = mergeKnowledgeBasePaths(allKbs);\n\n // For additionalInclude: merge arrays (union, deduplicated)\n const globalAdditional = globalConfig && Array.isArray(globalConfig.additionalInclude) ? globalConfig.additionalInclude : [];\n const projectAdditional = projectConfig && Array.isArray(projectConfig.additionalInclude) ? projectConfig.additionalInclude : [];\n const allAdditional = [...globalAdditional, ...projectAdditional];\n merged.additionalInclude = mergeUniqueStringArray(allAdditional);\n\n return merged;\n}\n","import { existsSync } from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { resolveWorktreeMainRepoRoot } from \"../git/index.js\";\n\nconst PROJECT_CONFIG_RELATIVE_PATH = path.join(\".opencode\", \"codebase-index.json\");\nconst PROJECT_INDEX_RELATIVE_PATH = path.join(\".opencode\", \"index\");\n\nfunction resolveWorktreeFallbackPath(projectRoot: string, relativePath: string): string | null {\n const mainRepoRoot = resolveWorktreeMainRepoRoot(projectRoot);\n if (!mainRepoRoot) {\n return null;\n }\n\n const fallbackPath = path.join(mainRepoRoot, relativePath);\n return existsSync(fallbackPath) ? fallbackPath : null;\n}\n\nfunction hasProjectConfig(projectRoot: string): boolean {\n return existsSync(path.join(projectRoot, PROJECT_CONFIG_RELATIVE_PATH));\n}\n\nexport function getGlobalIndexPath(): string {\n return path.join(os.homedir(), \".opencode\", \"global-index\");\n}\n\nexport function resolveProjectConfigPath(projectRoot: string): string {\n const localConfigPath = path.join(projectRoot, PROJECT_CONFIG_RELATIVE_PATH);\n if (existsSync(localConfigPath)) {\n return localConfigPath;\n }\n\n return resolveWorktreeFallbackPath(projectRoot, PROJECT_CONFIG_RELATIVE_PATH) ?? localConfigPath;\n}\n\nexport function resolveWritableProjectConfigPath(projectRoot: string): string {\n return path.join(projectRoot, PROJECT_CONFIG_RELATIVE_PATH);\n}\n\nexport function resolveProjectIndexPath(projectRoot: string, scope: \"project\" | \"global\"): string {\n if (scope === \"global\") {\n return getGlobalIndexPath();\n }\n\n const localIndexPath = path.join(projectRoot, PROJECT_INDEX_RELATIVE_PATH);\n if (existsSync(localIndexPath)) {\n return localIndexPath;\n }\n\n if (hasProjectConfig(projectRoot)) {\n return localIndexPath;\n }\n\n return resolveWorktreeFallbackPath(projectRoot, PROJECT_INDEX_RELATIVE_PATH) ?? localIndexPath;\n}\n","import { existsSync, readFileSync, statSync } from \"fs\";\nimport * as path from \"path\";\nimport { collectBranchRefs, readPackedRefs, resolveCommonGitDir, tryResolveRefCommit } from \"./refs.js\";\n\nexport function resolveWorktreeMainRepoRoot(repoRoot: string): string | null {\n const gitDir = resolveGitDir(repoRoot);\n if (!gitDir) {\n return null;\n }\n\n const commonGitDir = resolveCommonGitDir(gitDir);\n if (commonGitDir === gitDir || path.basename(commonGitDir) !== \".git\") {\n return null;\n }\n\n const mainRepoRoot = path.dirname(commonGitDir);\n if (!existsSync(mainRepoRoot)) {\n return null;\n }\n\n return path.resolve(mainRepoRoot) === path.resolve(repoRoot) ? null : mainRepoRoot;\n}\n\n/**\n * Resolves the actual git directory path.\n * \n * In a normal repo, `.git` is a directory containing HEAD, refs, etc.\n * In a worktree, `.git` is a file containing `gitdir: /path/to/actual/git/dir`.\n * \n * @returns The resolved git directory path, or null if not a git repo\n */\nexport function resolveGitDir(repoRoot: string): string | null {\n const gitPath = path.join(repoRoot, \".git\");\n \n if (!existsSync(gitPath)) {\n return null;\n }\n \n try {\n const stat = statSync(gitPath);\n \n if (stat.isDirectory()) {\n return gitPath;\n }\n \n if (stat.isFile()) {\n const content = readFileSync(gitPath, \"utf-8\").trim();\n const match = content.match(/^gitdir:\\s*(.+)$/);\n if (match) {\n const gitdir = match[1];\n // Handle relative paths\n const resolvedPath = path.isAbsolute(gitdir)\n ? gitdir\n : path.resolve(repoRoot, gitdir);\n \n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n }\n }\n } catch {\n // Ignore errors (permission issues, etc.)\n }\n \n return null;\n}\n\nexport function isGitRepo(dir: string): boolean {\n return resolveGitDir(dir) !== null;\n}\n\nexport function getCurrentBranch(repoRoot: string): string | null {\n const gitDir = resolveGitDir(repoRoot);\n if (!gitDir) {\n return null;\n }\n \n const headPath = path.join(gitDir, \"HEAD\");\n \n if (!existsSync(headPath)) {\n return null;\n }\n\n try {\n const headContent = readFileSync(headPath, \"utf-8\").trim();\n \n const match = headContent.match(/^ref: refs\\/heads\\/(.+)$/);\n if (match) {\n return match[1];\n }\n\n if (/^[0-9a-f]{40}$/i.test(headContent)) {\n return headContent.slice(0, 7);\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport function getCurrentCommit(repoRoot: string): string | null {\n const gitDir = resolveGitDir(repoRoot);\n if (!gitDir) {\n return null;\n }\n const refStoreDir = resolveCommonGitDir(gitDir);\n\n const headPath = path.join(gitDir, \"HEAD\");\n if (!existsSync(headPath)) {\n return null;\n }\n\n try {\n const headContent = readFileSync(headPath, \"utf-8\").trim();\n\n if (/^[0-9a-f]{40}$/i.test(headContent)) {\n return headContent;\n }\n\n const refMatch = headContent.match(/^ref:\\s*(.+)$/);\n if (!refMatch) {\n return null;\n }\n\n return tryResolveRefCommit(refStoreDir, refMatch[1]);\n } catch {\n return null;\n }\n}\n\nexport function getBaseBranch(repoRoot: string): string {\n const gitDir = resolveGitDir(repoRoot);\n const refStoreDir = gitDir ? resolveCommonGitDir(gitDir) : null;\n const candidates = [\"main\", \"master\", \"develop\", \"trunk\"];\n \n if (refStoreDir) {\n for (const candidate of candidates) {\n const refPath = path.join(refStoreDir, \"refs\", \"heads\", candidate);\n if (existsSync(refPath)) {\n return candidate;\n }\n\n const packedRefs = readPackedRefs(refStoreDir);\n if (packedRefs.some((line) => line.endsWith(` refs/heads/${candidate}`))) {\n return candidate;\n }\n }\n }\n\n return getCurrentBranch(repoRoot) ?? \"main\";\n}\n\nexport function getAllBranches(repoRoot: string): string[] {\n const branchSet = new Set<string>();\n const gitDir = resolveGitDir(repoRoot);\n const refStoreDir = gitDir ? resolveCommonGitDir(gitDir) : null;\n \n if (!refStoreDir) {\n return [];\n }\n \n const refsPath = path.join(refStoreDir, \"refs\", \"heads\");\n \n if (!existsSync(refsPath)) {\n return [];\n }\n\n const looseBranches: string[] = [];\n collectBranchRefs(looseBranches, refsPath);\n for (const branch of looseBranches) {\n branchSet.add(branch);\n }\n\n const packedRefs = readPackedRefs(refStoreDir);\n for (const line of packedRefs) {\n const splitIndex = line.indexOf(\" \");\n if (splitIndex <= 0) {\n continue;\n }\n\n const ref = line.slice(splitIndex + 1).trim();\n const prefix = \"refs/heads/\";\n if (ref.startsWith(prefix)) {\n branchSet.add(ref.slice(prefix.length));\n }\n }\n\n return Array.from(branchSet).sort();\n}\n\nexport function getBranchOrDefault(repoRoot: string): string {\n if (!isGitRepo(repoRoot)) {\n return \"default\";\n }\n \n return getCurrentBranch(repoRoot) ?? \"default\";\n}\n\nexport function getHeadPath(repoRoot: string): string {\n const gitDir = resolveGitDir(repoRoot);\n if (gitDir) {\n return path.join(gitDir, \"HEAD\");\n }\n return path.join(repoRoot, \".git\", \"HEAD\");\n}\n","import { existsSync, readFileSync, readdirSync, statSync } from \"fs\";\nimport * as path from \"path\";\n\nexport function readPackedRefs(gitDir: string): string[] {\n const packedRefsPath = path.join(gitDir, \"packed-refs\");\n if (!existsSync(packedRefsPath)) {\n return [];\n }\n\n try {\n return readFileSync(packedRefsPath, \"utf-8\")\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\") && !line.startsWith(\"^\"));\n } catch {\n return [];\n }\n}\n\nexport function resolveCommonGitDir(gitDir: string): string {\n const commonDirPath = path.join(gitDir, \"commondir\");\n if (!existsSync(commonDirPath)) {\n return gitDir;\n }\n\n try {\n const raw = readFileSync(commonDirPath, \"utf-8\").trim();\n if (!raw) {\n return gitDir;\n }\n\n const resolved = path.isAbsolute(raw) ? raw : path.resolve(gitDir, raw);\n if (existsSync(resolved)) {\n return resolved;\n }\n } catch {\n return gitDir;\n }\n\n return gitDir;\n}\n\nexport function tryResolveRefCommit(gitDir: string, refPath: string): string | null {\n const looseRefPath = path.join(gitDir, refPath);\n if (existsSync(looseRefPath)) {\n try {\n const value = readFileSync(looseRefPath, \"utf-8\").trim();\n if (/^[0-9a-f]{40}$/i.test(value)) {\n return value;\n }\n } catch {\n return null;\n }\n }\n\n const packedRefs = readPackedRefs(gitDir);\n for (const line of packedRefs) {\n const splitIndex = line.indexOf(\" \");\n if (splitIndex <= 0) {\n continue;\n }\n\n const commit = line.slice(0, splitIndex).trim();\n const packedRef = line.slice(splitIndex + 1).trim();\n if (packedRef === refPath && /^[0-9a-f]{40}$/i.test(commit)) {\n return commit;\n }\n }\n\n return null;\n}\n\nexport function collectBranchRefs(branches: string[], baseDir: string, prefix = \"\"): void {\n if (!existsSync(baseDir)) {\n return;\n }\n\n try {\n const entries = readdirSync(baseDir);\n for (const entry of entries) {\n const nextPath = path.join(baseDir, entry);\n const nextPrefix = prefix ? `${prefix}/${entry}` : entry;\n const stat = statSync(nextPath);\n if (stat.isDirectory()) {\n collectBranchRefs(branches, nextPath, nextPrefix);\n } else if (stat.isFile()) {\n branches.push(nextPrefix);\n }\n }\n } catch {\n return;\n }\n}\n","import * as path from \"path\";\n\nimport { normalizePathSeparators } from \"../utils/paths.js\";\n\n\nfunction isWithinRoot(rootDir: string, targetPath: string): boolean {\n const relativePath = path.relative(rootDir, targetPath);\n return relativePath === \"\" || (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath));\n}\n\nexport function rebasePathEntries(\n values: unknown,\n fromDir: string,\n toDir: string,\n): string[] {\n if (!Array.isArray(values)) {\n return [];\n }\n\n return values\n .filter((value): value is string => typeof value === \"string\")\n .map((value) => {\n const trimmed = value.trim();\n if (!trimmed || path.isAbsolute(trimmed)) {\n return trimmed;\n }\n\n return normalizePathSeparators(path.normalize(path.relative(toDir, path.resolve(fromDir, trimmed))));\n })\n .filter(Boolean);\n}\n\nexport function resolveInheritedKnowledgeBaseEntries(\n values: unknown,\n sourceRoot: string,\n targetRoot: string,\n): string[] {\n if (!Array.isArray(values)) {\n return [];\n }\n\n return values\n .filter((value): value is string => typeof value === \"string\")\n .map((value) => {\n const trimmed = value.trim();\n if (!trimmed) {\n return trimmed;\n }\n\n if (path.isAbsolute(trimmed)) {\n if (isWithinRoot(sourceRoot, trimmed)) {\n return normalizePathSeparators(path.normalize(path.relative(sourceRoot, trimmed) || \".\"));\n }\n\n return path.normalize(trimmed);\n }\n\n const resolvedFromSource = path.resolve(sourceRoot, trimmed);\n if (isWithinRoot(sourceRoot, resolvedFromSource)) {\n return normalizePathSeparators(path.normalize(trimmed));\n }\n\n return normalizePathSeparators(path.normalize(path.relative(targetRoot, resolvedFromSource)));\n })\n .filter(Boolean);\n}\n","import * as path from \"path\";\n\nexport function normalizePathSeparators(value: string): string {\n return value.replace(/\\\\/g, \"/\");\n}\n\nexport function isHiddenPathSegment(part: string): boolean {\n return part.startsWith(\".\") && part !== \".\" && part !== \"..\";\n}\n\nexport function isBuildPathSegment(part: string): boolean {\n return part.toLowerCase().includes(\"build\");\n}\n\nexport function hasFilteredPathSegment(relativePath: string, separator: string = path.sep): boolean {\n return relativePath.split(separator).some(\n (part) => isHiddenPathSegment(part) || isBuildPathSegment(part)\n );\n}\n\n/**\n * Directories that should never be watched when they appear as a top-level\n * segment of a relative path. These are OS-level directories that are either\n * permission-restricted or irrelevant to source code projects.\n *\n * macOS: Library, Applications, System, Volumes, private, cores\n * Linux: proc, sys, dev, run, snap\n * Windows: Windows, ProgramData, Program Files, $Recycle.Bin\n */\nconst RESTRICTED_DIRECTORIES = new Set([\n // macOS\n \"library\",\n \"applications\",\n \"system\",\n \"volumes\",\n \"private\",\n \"cores\",\n // Linux\n \"proc\",\n \"sys\",\n \"dev\",\n \"run\",\n \"snap\",\n // Windows\n \"windows\",\n \"programdata\",\n \"program files\",\n \"program files (x86)\",\n \"$recycle.bin\",\n]);\n\n/**\n * Returns true if the first path segment is a known OS-restricted directory.\n * This prevents the watcher from descending into paths like ~/Library/ on macOS.\n */\nexport function isRestrictedDirectory(relativePath: string, separator: string = path.sep): boolean {\n const firstSegment = relativePath.split(separator)[0];\n if (!firstSegment) return false;\n return RESTRICTED_DIRECTORIES.has(firstSegment.toLowerCase());\n}\n","/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */\nimport { EventEmitter } from 'node:events';\nimport { stat as statcb, Stats } from 'node:fs';\nimport { readdir, stat } from 'node:fs/promises';\nimport * as sp from 'node:path';\nimport { readdirp, ReaddirpStream } from 'readdirp';\nimport { EMPTY_FN, EVENTS as EV, isIBMi, isWindows, NodeFsHandler, STR_CLOSE, STR_END, } from './handler.js';\nconst SLASH = '/';\nconst SLASH_SLASH = '//';\nconst ONE_DOT = '.';\nconst TWO_DOTS = '..';\nconst STRING_TYPE = 'string';\nconst BACK_SLASH_RE = /\\\\/g;\nconst DOUBLE_SLASH_RE = /\\/\\//g;\nconst DOT_RE = /\\..*\\.(sw[px])$|~$|\\.subl.*\\.tmp/;\nconst REPLACER_RE = /^\\.[/\\\\]/;\nfunction arrify(item) {\n return Array.isArray(item) ? item : [item];\n}\nconst isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);\nfunction createPattern(matcher) {\n if (typeof matcher === 'function')\n return matcher;\n if (typeof matcher === 'string')\n return (string) => matcher === string;\n if (matcher instanceof RegExp)\n return (string) => matcher.test(string);\n if (typeof matcher === 'object' && matcher !== null) {\n return (string) => {\n if (matcher.path === string)\n return true;\n if (matcher.recursive) {\n const relative = sp.relative(matcher.path, string);\n if (!relative) {\n return false;\n }\n return !relative.startsWith('..') && !sp.isAbsolute(relative);\n }\n return false;\n };\n }\n return () => false;\n}\nfunction normalizePath(path) {\n if (typeof path !== 'string')\n throw new Error('string expected');\n path = sp.normalize(path);\n path = path.replace(/\\\\/g, '/');\n let prepend = false;\n if (path.startsWith('//'))\n prepend = true;\n path = path.replace(DOUBLE_SLASH_RE, '/');\n if (prepend)\n path = '/' + path;\n return path;\n}\nfunction matchPatterns(patterns, testString, stats) {\n const path = normalizePath(testString);\n for (let index = 0; index < patterns.length; index++) {\n const pattern = patterns[index];\n if (pattern(path, stats)) {\n return true;\n }\n }\n return false;\n}\nfunction anymatch(matchers, testString) {\n if (matchers == null) {\n throw new TypeError('anymatch: specify first argument');\n }\n // Early cache for matchers.\n const matchersArray = arrify(matchers);\n const patterns = matchersArray.map((matcher) => createPattern(matcher));\n if (testString == null) {\n return (testString, stats) => {\n return matchPatterns(patterns, testString, stats);\n };\n }\n return matchPatterns(patterns, testString);\n}\nconst unifyPaths = (paths_) => {\n const paths = arrify(paths_).flat();\n if (!paths.every((p) => typeof p === STRING_TYPE)) {\n throw new TypeError(`Non-string provided as watch path: ${paths}`);\n }\n return paths.map(normalizePathToUnix);\n};\n// If SLASH_SLASH occurs at the beginning of path, it is not replaced\n// because \"//StoragePC/DrivePool/Movies\" is a valid network path\nconst toUnix = (string) => {\n let str = string.replace(BACK_SLASH_RE, SLASH);\n let prepend = false;\n if (str.startsWith(SLASH_SLASH)) {\n prepend = true;\n }\n str = str.replace(DOUBLE_SLASH_RE, SLASH);\n if (prepend) {\n str = SLASH + str;\n }\n return str;\n};\n// Our version of upath.normalize\n// TODO: this is not equal to path-normalize module - investigate why\nconst normalizePathToUnix = (path) => toUnix(sp.normalize(toUnix(path)));\n// TODO: refactor\nconst normalizeIgnored = (cwd = '') => (path) => {\n if (typeof path === 'string') {\n return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));\n }\n else {\n return path;\n }\n};\nconst getAbsolutePath = (path, cwd) => {\n if (sp.isAbsolute(path)) {\n return path;\n }\n return sp.join(cwd, path);\n};\nconst EMPTY_SET = Object.freeze(new Set());\n/**\n * Directory entry.\n */\nclass DirEntry {\n path;\n _removeWatcher;\n items;\n constructor(dir, removeWatcher) {\n this.path = dir;\n this._removeWatcher = removeWatcher;\n this.items = new Set();\n }\n add(item) {\n const { items } = this;\n if (!items)\n return;\n if (item !== ONE_DOT && item !== TWO_DOTS)\n items.add(item);\n }\n async remove(item) {\n const { items } = this;\n if (!items)\n return;\n items.delete(item);\n if (items.size > 0)\n return;\n const dir = this.path;\n try {\n await readdir(dir);\n }\n catch (err) {\n if (this._removeWatcher) {\n this._removeWatcher(sp.dirname(dir), sp.basename(dir));\n }\n }\n }\n has(item) {\n const { items } = this;\n if (!items)\n return;\n return items.has(item);\n }\n getChildren() {\n const { items } = this;\n if (!items)\n return [];\n return [...items.values()];\n }\n dispose() {\n this.items.clear();\n this.path = '';\n this._removeWatcher = EMPTY_FN;\n this.items = EMPTY_SET;\n Object.freeze(this);\n }\n}\nconst STAT_METHOD_F = 'stat';\nconst STAT_METHOD_L = 'lstat';\nexport class WatchHelper {\n fsw;\n path;\n watchPath;\n fullWatchPath;\n dirParts;\n followSymlinks;\n statMethod;\n constructor(path, follow, fsw) {\n this.fsw = fsw;\n const watchPath = path;\n this.path = path = path.replace(REPLACER_RE, '');\n this.watchPath = watchPath;\n this.fullWatchPath = sp.resolve(watchPath);\n this.dirParts = [];\n this.dirParts.forEach((parts) => {\n if (parts.length > 1)\n parts.pop();\n });\n this.followSymlinks = follow;\n this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;\n }\n entryPath(entry) {\n return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));\n }\n filterPath(entry) {\n const { stats } = entry;\n if (stats && stats.isSymbolicLink())\n return this.filterDir(entry);\n const resolvedPath = this.entryPath(entry);\n // TODO: what if stats is undefined? remove !\n return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);\n }\n filterDir(entry) {\n return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);\n }\n}\n/**\n * Watches files & directories for changes. Emitted events:\n * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`\n *\n * new FSWatcher()\n * .add(directories)\n * .on('add', path => log('File', path, 'was added'))\n */\nexport class FSWatcher extends EventEmitter {\n closed;\n options;\n _closers;\n _ignoredPaths;\n _throttled;\n _streams;\n _symlinkPaths;\n _watched;\n _pendingWrites;\n _pendingUnlinks;\n _readyCount;\n _emitReady;\n _closePromise;\n _userIgnored;\n _readyEmitted;\n _emitRaw;\n _boundRemove;\n _nodeFsHandler;\n // Not indenting methods for history sake; for now.\n constructor(_opts = {}) {\n super();\n this.closed = false;\n this._closers = new Map();\n this._ignoredPaths = new Set();\n this._throttled = new Map();\n this._streams = new Set();\n this._symlinkPaths = new Map();\n this._watched = new Map();\n this._pendingWrites = new Map();\n this._pendingUnlinks = new Map();\n this._readyCount = 0;\n this._readyEmitted = false;\n const awf = _opts.awaitWriteFinish;\n const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };\n const opts = {\n // Defaults\n persistent: true,\n ignoreInitial: false,\n ignorePermissionErrors: false,\n interval: 100,\n binaryInterval: 300,\n followSymlinks: true,\n usePolling: false,\n // useAsync: false,\n atomic: true, // NOTE: overwritten later (depends on usePolling)\n ..._opts,\n // Change format\n ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),\n awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,\n };\n // Always default to polling on IBM i because fs.watch() is not available on IBM i.\n if (isIBMi)\n opts.usePolling = true;\n // Editor atomic write normalization enabled by default with fs.watch\n if (opts.atomic === undefined)\n opts.atomic = !opts.usePolling;\n // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;\n // Global override. Useful for developers, who need to force polling for all\n // instances of chokidar, regardless of usage / dependency depth\n const envPoll = process.env.CHOKIDAR_USEPOLLING;\n if (envPoll !== undefined) {\n const envLower = envPoll.toLowerCase();\n if (envLower === 'false' || envLower === '0')\n opts.usePolling = false;\n else if (envLower === 'true' || envLower === '1')\n opts.usePolling = true;\n else\n opts.usePolling = !!envLower;\n }\n const envInterval = process.env.CHOKIDAR_INTERVAL;\n if (envInterval)\n opts.interval = Number.parseInt(envInterval, 10);\n // This is done to emit ready only once, but each 'add' will increase that?\n let readyCalls = 0;\n this._emitReady = () => {\n readyCalls++;\n if (readyCalls >= this._readyCount) {\n this._emitReady = EMPTY_FN;\n this._readyEmitted = true;\n // use process.nextTick to allow time for listener to be bound\n process.nextTick(() => this.emit(EV.READY));\n }\n };\n this._emitRaw = (...args) => this.emit(EV.RAW, ...args);\n this._boundRemove = this._remove.bind(this);\n this.options = opts;\n this._nodeFsHandler = new NodeFsHandler(this);\n // You’re frozen when your heart’s not open.\n Object.freeze(opts);\n }\n _addIgnoredPath(matcher) {\n if (isMatcherObject(matcher)) {\n // return early if we already have a deeply equal matcher object\n for (const ignored of this._ignoredPaths) {\n if (isMatcherObject(ignored) &&\n ignored.path === matcher.path &&\n ignored.recursive === matcher.recursive) {\n return;\n }\n }\n }\n this._ignoredPaths.add(matcher);\n }\n _removeIgnoredPath(matcher) {\n this._ignoredPaths.delete(matcher);\n // now find any matcher objects with the matcher as path\n if (typeof matcher === 'string') {\n for (const ignored of this._ignoredPaths) {\n // TODO (43081j): make this more efficient.\n // probably just make a `this._ignoredDirectories` or some\n // such thing.\n if (isMatcherObject(ignored) && ignored.path === matcher) {\n this._ignoredPaths.delete(ignored);\n }\n }\n }\n }\n // Public methods\n /**\n * Adds paths to be watched on an existing FSWatcher instance.\n * @param paths_ file or file list. Other arguments are unused\n */\n add(paths_, _origAdd, _internal) {\n const { cwd } = this.options;\n this.closed = false;\n this._closePromise = undefined;\n let paths = unifyPaths(paths_);\n if (cwd) {\n paths = paths.map((path) => {\n const absPath = getAbsolutePath(path, cwd);\n // Check `path` instead of `absPath` because the cwd portion can't be a glob\n return absPath;\n });\n }\n paths.forEach((path) => {\n this._removeIgnoredPath(path);\n });\n this._userIgnored = undefined;\n if (!this._readyCount)\n this._readyCount = 0;\n this._readyCount += paths.length;\n Promise.all(paths.map(async (path) => {\n const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);\n if (res)\n this._emitReady();\n return res;\n })).then((results) => {\n if (this.closed)\n return;\n results.forEach((item) => {\n if (item)\n this.add(sp.dirname(item), sp.basename(_origAdd || item));\n });\n });\n return this;\n }\n /**\n * Close watchers or start ignoring events from specified paths.\n */\n unwatch(paths_) {\n if (this.closed)\n return this;\n const paths = unifyPaths(paths_);\n const { cwd } = this.options;\n paths.forEach((path) => {\n // convert to absolute path unless relative path already matches\n if (!sp.isAbsolute(path) && !this._closers.has(path)) {\n if (cwd)\n path = sp.join(cwd, path);\n path = sp.resolve(path);\n }\n this._closePath(path);\n this._addIgnoredPath(path);\n if (this._watched.has(path)) {\n this._addIgnoredPath({\n path,\n recursive: true,\n });\n }\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = undefined;\n });\n return this;\n }\n /**\n * Close watchers and remove all listeners from watched paths.\n */\n close() {\n if (this._closePromise) {\n return this._closePromise;\n }\n this.closed = true;\n // Memory management.\n this.removeAllListeners();\n const closers = [];\n this._closers.forEach((closerList) => closerList.forEach((closer) => {\n const promise = closer();\n if (promise instanceof Promise)\n closers.push(promise);\n }));\n this._streams.forEach((stream) => stream.destroy());\n this._userIgnored = undefined;\n this._readyCount = 0;\n this._readyEmitted = false;\n this._watched.forEach((dirent) => dirent.dispose());\n this._closers.clear();\n this._watched.clear();\n this._streams.clear();\n this._symlinkPaths.clear();\n this._throttled.clear();\n this._closePromise = closers.length\n ? Promise.all(closers).then(() => undefined)\n : Promise.resolve();\n return this._closePromise;\n }\n /**\n * Expose list of watched paths\n * @returns for chaining\n */\n getWatched() {\n const watchList = {};\n this._watched.forEach((entry, dir) => {\n const key = this.options.cwd ? sp.relative(this.options.cwd, dir) : dir;\n const index = key || ONE_DOT;\n watchList[index] = entry.getChildren().sort();\n });\n return watchList;\n }\n emitWithAll(event, args) {\n this.emit(event, ...args);\n if (event !== EV.ERROR)\n this.emit(EV.ALL, event, ...args);\n }\n // Common helpers\n // --------------\n /**\n * Normalize and emit events.\n * Calling _emit DOES NOT MEAN emit() would be called!\n * @param event Type of event\n * @param path File or directory path\n * @param stats arguments to be passed with event\n * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n async _emit(event, path, stats) {\n if (this.closed)\n return;\n const opts = this.options;\n if (isWindows)\n path = sp.normalize(path);\n if (opts.cwd)\n path = sp.relative(opts.cwd, path);\n const args = [path];\n if (stats != null)\n args.push(stats);\n const awf = opts.awaitWriteFinish;\n let pw;\n if (awf && (pw = this._pendingWrites.get(path))) {\n pw.lastChange = new Date();\n return this;\n }\n if (opts.atomic) {\n if (event === EV.UNLINK) {\n this._pendingUnlinks.set(path, [event, ...args]);\n setTimeout(() => {\n this._pendingUnlinks.forEach((entry, path) => {\n this.emit(...entry);\n this.emit(EV.ALL, ...entry);\n this._pendingUnlinks.delete(path);\n });\n }, typeof opts.atomic === 'number' ? opts.atomic : 100);\n return this;\n }\n if (event === EV.ADD && this._pendingUnlinks.has(path)) {\n event = EV.CHANGE;\n this._pendingUnlinks.delete(path);\n }\n }\n if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) {\n const awfEmit = (err, stats) => {\n if (err) {\n event = EV.ERROR;\n args[0] = err;\n this.emitWithAll(event, args);\n }\n else if (stats) {\n // if stats doesn't exist the file must have been deleted\n if (args.length > 1) {\n args[1] = stats;\n }\n else {\n args.push(stats);\n }\n this.emitWithAll(event, args);\n }\n };\n this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);\n return this;\n }\n if (event === EV.CHANGE) {\n const isThrottled = !this._throttle(EV.CHANGE, path, 50);\n if (isThrottled)\n return this;\n }\n if (opts.alwaysStat &&\n stats === undefined &&\n (event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)) {\n const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;\n let stats;\n try {\n stats = await stat(fullPath);\n }\n catch (err) {\n // do nothing\n }\n // Suppress event when fs_stat fails, to avoid sending undefined 'stat'\n if (!stats || this.closed)\n return;\n args.push(stats);\n }\n this.emitWithAll(event, args);\n return this;\n }\n /**\n * Common handler for errors\n * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n _handleError(error) {\n const code = error && error.code;\n if (error &&\n code !== 'ENOENT' &&\n code !== 'ENOTDIR' &&\n (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {\n this.emit(EV.ERROR, error);\n }\n return error || this.closed;\n }\n /**\n * Helper utility for throttling\n * @param actionType type being throttled\n * @param path being acted upon\n * @param timeout duration of time to suppress duplicate actions\n * @returns tracking object or false if action should be suppressed\n */\n _throttle(actionType, path, timeout) {\n if (!this._throttled.has(actionType)) {\n this._throttled.set(actionType, new Map());\n }\n const action = this._throttled.get(actionType);\n if (!action)\n throw new Error('invalid throttle');\n const actionPath = action.get(path);\n if (actionPath) {\n actionPath.count++;\n return false;\n }\n // eslint-disable-next-line prefer-const\n let timeoutObject;\n const clear = () => {\n const item = action.get(path);\n const count = item ? item.count : 0;\n action.delete(path);\n clearTimeout(timeoutObject);\n if (item)\n clearTimeout(item.timeoutObject);\n return count;\n };\n timeoutObject = setTimeout(clear, timeout);\n const thr = { timeoutObject, clear, count: 0 };\n action.set(path, thr);\n return thr;\n }\n _incrReadyCount() {\n return this._readyCount++;\n }\n /**\n * Awaits write operation to finish.\n * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.\n * @param path being acted upon\n * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished\n * @param event\n * @param awfEmit Callback to be called when ready for event to be emitted.\n */\n _awaitWriteFinish(path, threshold, event, awfEmit) {\n const awf = this.options.awaitWriteFinish;\n if (typeof awf !== 'object')\n return;\n const pollInterval = awf.pollInterval;\n let timeoutHandler;\n let fullPath = path;\n if (this.options.cwd && !sp.isAbsolute(path)) {\n fullPath = sp.join(this.options.cwd, path);\n }\n const now = new Date();\n const writes = this._pendingWrites;\n function awaitWriteFinishFn(prevStat) {\n statcb(fullPath, (err, curStat) => {\n if (err || !writes.has(path)) {\n if (err && err.code !== 'ENOENT')\n awfEmit(err);\n return;\n }\n const now = Number(new Date());\n if (prevStat && curStat.size !== prevStat.size) {\n writes.get(path).lastChange = now;\n }\n const pw = writes.get(path);\n const df = now - pw.lastChange;\n if (df >= threshold) {\n writes.delete(path);\n awfEmit(undefined, curStat);\n }\n else {\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);\n }\n });\n }\n if (!writes.has(path)) {\n writes.set(path, {\n lastChange: now,\n cancelWait: () => {\n writes.delete(path);\n clearTimeout(timeoutHandler);\n return event;\n },\n });\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);\n }\n }\n /**\n * Determines whether user has asked to ignore this path.\n */\n _isIgnored(path, stats) {\n if (this.options.atomic && DOT_RE.test(path))\n return true;\n if (!this._userIgnored) {\n const { cwd } = this.options;\n const ign = this.options.ignored;\n const ignored = (ign || []).map(normalizeIgnored(cwd));\n const ignoredPaths = [...this._ignoredPaths];\n const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];\n this._userIgnored = anymatch(list, undefined);\n }\n return this._userIgnored(path, stats);\n }\n _isntIgnored(path, stat) {\n return !this._isIgnored(path, stat);\n }\n /**\n * Provides a set of common helpers and properties relating to symlink handling.\n * @param path file or directory pattern being watched\n */\n _getWatchHelpers(path) {\n return new WatchHelper(path, this.options.followSymlinks, this);\n }\n // Directory helpers\n // -----------------\n /**\n * Provides directory tracking objects\n * @param directory path of the directory\n */\n _getWatchedDir(directory) {\n const dir = sp.resolve(directory);\n if (!this._watched.has(dir))\n this._watched.set(dir, new DirEntry(dir, this._boundRemove));\n return this._watched.get(dir);\n }\n // File helpers\n // ------------\n /**\n * Check for read permissions: https://stackoverflow.com/a/11781404/1358405\n */\n _hasReadPermissions(stats) {\n if (this.options.ignorePermissionErrors)\n return true;\n return Boolean(Number(stats.mode) & 0o400);\n }\n /**\n * Handles emitting unlink events for\n * files and directories, and via recursion, for\n * files and directories within directories that are unlinked\n * @param directory within which the following item is located\n * @param item base path of item/directory\n */\n _remove(directory, item, isDirectory) {\n // if what is being deleted is a directory, get that directory's paths\n // for recursive deleting and cleaning of watched object\n // if it is not a directory, nestedDirectoryChildren will be empty array\n const path = sp.join(directory, item);\n const fullPath = sp.resolve(path);\n isDirectory =\n isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);\n // prevent duplicate handling in case of arriving here nearly simultaneously\n // via multiple paths (such as _handleFile and _handleDir)\n if (!this._throttle('remove', path, 100))\n return;\n // if the only watched file is removed, watch for its return\n if (!isDirectory && this._watched.size === 1) {\n this.add(directory, item, true);\n }\n // This will create a new entry in the watched object in either case\n // so we got to do the directory check beforehand\n const wp = this._getWatchedDir(path);\n const nestedDirectoryChildren = wp.getChildren();\n // Recursively remove children directories / files.\n nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));\n // Check if item was on the watched list and remove it\n const parent = this._getWatchedDir(directory);\n const wasTracked = parent.has(item);\n parent.remove(item);\n // Fixes issue #1042 -> Relative paths were detected and added as symlinks\n // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),\n // but never removed from the map in case the path was deleted.\n // This leads to an incorrect state if the path was recreated:\n // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553\n if (this._symlinkPaths.has(fullPath)) {\n this._symlinkPaths.delete(fullPath);\n }\n // If we wait for this file to be fully written, cancel the wait.\n let relPath = path;\n if (this.options.cwd)\n relPath = sp.relative(this.options.cwd, path);\n if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {\n const event = this._pendingWrites.get(relPath).cancelWait();\n if (event === EV.ADD)\n return;\n }\n // The Entry will either be a directory that just got removed\n // or a bogus entry to a file, in either case we have to remove it\n this._watched.delete(path);\n this._watched.delete(fullPath);\n const eventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK;\n if (wasTracked && !this._isIgnored(path))\n this._emit(eventName, path);\n // Avoid conflicts if we later create another file with the same name\n this._closePath(path);\n }\n /**\n * Closes all watchers for a path\n */\n _closePath(path) {\n this._closeFile(path);\n const dir = sp.dirname(path);\n this._getWatchedDir(dir).remove(sp.basename(path));\n }\n /**\n * Closes only file-specific watchers\n */\n _closeFile(path) {\n const closers = this._closers.get(path);\n if (!closers)\n return;\n closers.forEach((closer) => closer());\n this._closers.delete(path);\n }\n _addPathCloser(path, closer) {\n if (!closer)\n return;\n let list = this._closers.get(path);\n if (!list) {\n list = [];\n this._closers.set(path, list);\n }\n list.push(closer);\n }\n _readdirp(root, opts) {\n if (this.closed)\n return;\n const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };\n let stream = readdirp(root, options);\n this._streams.add(stream);\n stream.once(STR_CLOSE, () => {\n stream = undefined;\n });\n stream.once(STR_END, () => {\n if (stream) {\n this._streams.delete(stream);\n stream = undefined;\n }\n });\n return stream;\n }\n}\n/**\n * Instantiates watcher with paths to be tracked.\n * @param paths file / directory paths\n * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others\n * @returns an instance of FSWatcher for chaining.\n * @example\n * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });\n * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })\n */\nexport function watch(paths, options = {}) {\n const watcher = new FSWatcher(options);\n watcher.add(paths);\n return watcher;\n}\nexport default { watch: watch, FSWatcher: FSWatcher };\n","import { lstat, readdir, realpath, stat } from 'node:fs/promises';\nimport { join as pjoin, relative as prelative, resolve as presolve, sep as psep } from 'node:path';\nimport { Readable } from 'node:stream';\nexport const EntryTypes = {\n FILE_TYPE: 'files',\n DIR_TYPE: 'directories',\n FILE_DIR_TYPE: 'files_directories',\n EVERYTHING_TYPE: 'all',\n};\nconst defaultOptions = {\n root: '.',\n fileFilter: (_entryInfo) => true,\n directoryFilter: (_entryInfo) => true,\n type: EntryTypes.FILE_TYPE,\n lstat: false,\n depth: 2147483648,\n alwaysStat: false,\n highWaterMark: 4096,\n};\nObject.freeze(defaultOptions);\nconst RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';\nconst NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);\nconst ALL_TYPES = [\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n];\nconst DIR_TYPES = new Set([\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n]);\nconst FILE_TYPES = new Set([\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n]);\nconst isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);\nconst wantBigintFsStats = process.platform === 'win32';\nconst emptyFn = (_entryInfo) => true;\nconst normalizeFilter = (filter) => {\n if (filter === undefined)\n return emptyFn;\n if (typeof filter === 'function')\n return filter;\n if (typeof filter === 'string') {\n const fl = filter.trim();\n return (entry) => entry.basename === fl;\n }\n if (Array.isArray(filter)) {\n const trItems = filter.map((item) => item.trim());\n return (entry) => trItems.some((f) => entry.basename === f);\n }\n return emptyFn;\n};\n/** Readable readdir stream, emitting new files as they're being listed. */\nexport class ReaddirpStream extends Readable {\n parents;\n reading;\n parent;\n _stat;\n _maxDepth;\n _wantsDir;\n _wantsFile;\n _wantsEverything;\n _root;\n _isDirent;\n _statsProp;\n _rdOptions;\n _fileFilter;\n _directoryFilter;\n constructor(options = {}) {\n super({\n objectMode: true,\n autoDestroy: true,\n highWaterMark: options.highWaterMark,\n });\n const opts = { ...defaultOptions, ...options };\n const { root, type } = opts;\n this._fileFilter = normalizeFilter(opts.fileFilter);\n this._directoryFilter = normalizeFilter(opts.directoryFilter);\n const statMethod = opts.lstat ? lstat : stat;\n // Use bigint stats if it's windows and stat() supports options (node 10+).\n if (wantBigintFsStats) {\n this._stat = (path) => statMethod(path, { bigint: true });\n }\n else {\n this._stat = statMethod;\n }\n this._maxDepth =\n opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;\n this._wantsDir = type ? DIR_TYPES.has(type) : false;\n this._wantsFile = type ? FILE_TYPES.has(type) : false;\n this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;\n this._root = presolve(root);\n this._isDirent = !opts.alwaysStat;\n this._statsProp = this._isDirent ? 'dirent' : 'stats';\n this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };\n // Launch stream with one parent, the root dir.\n this.parents = [this._exploreDir(root, 1)];\n this.reading = false;\n this.parent = undefined;\n }\n async _read(batch) {\n if (this.reading)\n return;\n this.reading = true;\n try {\n while (!this.destroyed && batch > 0) {\n const par = this.parent;\n const fil = par && par.files;\n if (fil && fil.length > 0) {\n const { path, depth } = par;\n const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));\n const awaited = await Promise.all(slice);\n for (const entry of awaited) {\n if (!entry)\n continue;\n if (this.destroyed)\n return;\n const entryType = await this._getEntryType(entry);\n if (entryType === 'directory' && this._directoryFilter(entry)) {\n if (depth <= this._maxDepth) {\n this.parents.push(this._exploreDir(entry.fullPath, depth + 1));\n }\n if (this._wantsDir) {\n this.push(entry);\n batch--;\n }\n }\n else if ((entryType === 'file' || this._includeAsFile(entry)) &&\n this._fileFilter(entry)) {\n if (this._wantsFile) {\n this.push(entry);\n batch--;\n }\n }\n }\n }\n else {\n const parent = this.parents.pop();\n if (!parent) {\n this.push(null);\n break;\n }\n this.parent = await parent;\n if (this.destroyed)\n return;\n }\n }\n }\n catch (error) {\n this.destroy(error);\n }\n finally {\n this.reading = false;\n }\n }\n async _exploreDir(path, depth) {\n let files;\n try {\n files = await readdir(path, this._rdOptions);\n }\n catch (error) {\n this._onError(error);\n }\n return { files, depth, path };\n }\n async _formatEntry(dirent, path) {\n let entry;\n const basename = this._isDirent ? dirent.name : dirent;\n try {\n const fullPath = presolve(pjoin(path, basename));\n entry = { path: prelative(this._root, fullPath), fullPath, basename };\n entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);\n }\n catch (err) {\n this._onError(err);\n return;\n }\n return entry;\n }\n _onError(err) {\n if (isNormalFlowError(err) && !this.destroyed) {\n this.emit('warn', err);\n }\n else {\n this.destroy(err);\n }\n }\n async _getEntryType(entry) {\n // entry may be undefined, because a warning or an error were emitted\n // and the statsProp is undefined\n if (!entry && this._statsProp in entry) {\n return '';\n }\n const stats = entry[this._statsProp];\n if (stats.isFile())\n return 'file';\n if (stats.isDirectory())\n return 'directory';\n if (stats && stats.isSymbolicLink()) {\n const full = entry.fullPath;\n try {\n const entryRealPath = await realpath(full);\n const entryRealPathStats = await lstat(entryRealPath);\n if (entryRealPathStats.isFile()) {\n return 'file';\n }\n if (entryRealPathStats.isDirectory()) {\n const len = entryRealPath.length;\n if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {\n const recursiveError = new Error(`Circular symlink detected: \"${full}\" points to \"${entryRealPath}\"`);\n // @ts-ignore\n recursiveError.code = RECURSIVE_ERROR_CODE;\n return this._onError(recursiveError);\n }\n return 'directory';\n }\n }\n catch (error) {\n this._onError(error);\n return '';\n }\n }\n }\n _includeAsFile(entry) {\n const stats = entry && entry[this._statsProp];\n return stats && this._wantsEverything && !stats.isDirectory();\n }\n}\n/**\n * Streaming version: Reads all files and directories in given root recursively.\n * Consumes ~constant small amount of RAM.\n * @param root Root directory\n * @param options Options to specify root (start directory), filters and recursion depth\n */\nexport function readdirp(root, options = {}) {\n // @ts-ignore\n let type = options.entryType || options.type;\n if (type === 'both')\n type = EntryTypes.FILE_DIR_TYPE; // backwards-compatibility\n if (type)\n options.type = type;\n if (!root) {\n throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');\n }\n else if (typeof root !== 'string') {\n throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');\n }\n else if (type && !ALL_TYPES.includes(type)) {\n throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);\n }\n options.root = root;\n return new ReaddirpStream(options);\n}\n/**\n * Promise version: Reads all files and directories in given root recursively.\n * Compared to streaming version, will consume a lot of RAM e.g. when 1 million files are listed.\n * @returns array of paths and their entry infos\n */\nexport function readdirpPromise(root, options = {}) {\n return new Promise((resolve, reject) => {\n const files = [];\n readdirp(root, options)\n .on('data', (entry) => files.push(entry))\n .on('end', () => resolve(files))\n .on('error', (error) => reject(error));\n });\n}\nexport default readdirp;\n","import { watch as fs_watch, unwatchFile, watchFile } from 'node:fs';\nimport { realpath as fsrealpath, lstat, open, stat } from 'node:fs/promises';\nimport { type as osType } from 'node:os';\nimport * as sp from 'node:path';\nexport const STR_DATA = 'data';\nexport const STR_END = 'end';\nexport const STR_CLOSE = 'close';\nexport const EMPTY_FN = () => { };\nexport const IDENTITY_FN = (val) => val;\nconst pl = process.platform;\nexport const isWindows = pl === 'win32';\nexport const isMacos = pl === 'darwin';\nexport const isLinux = pl === 'linux';\nexport const isFreeBSD = pl === 'freebsd';\nexport const isIBMi = osType() === 'OS400';\nexport const EVENTS = {\n ALL: 'all',\n READY: 'ready',\n ADD: 'add',\n CHANGE: 'change',\n ADD_DIR: 'addDir',\n UNLINK: 'unlink',\n UNLINK_DIR: 'unlinkDir',\n RAW: 'raw',\n ERROR: 'error',\n};\nconst EV = EVENTS;\nconst THROTTLE_MODE_WATCH = 'watch';\nconst statMethods = { lstat, stat };\nconst KEY_LISTENERS = 'listeners';\nconst KEY_ERR = 'errHandlers';\nconst KEY_RAW = 'rawEmitters';\nconst HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];\n// prettier-ignore\nconst binaryExtensions = new Set([\n '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',\n 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',\n 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',\n 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',\n 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',\n 'dtshd', 'dvb', 'dwg', 'dxf',\n 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',\n 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',\n 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',\n 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',\n 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',\n 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',\n 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',\n 'mobi', 'mov', 'movie', 'mp3',\n 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',\n 'nef', 'npx', 'numbers', 'nupkg',\n 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',\n 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',\n 'potx', 'ppa', 'ppam',\n 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',\n 'qt',\n 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',\n 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',\n 'stl', 'suo', 'sub', 'swf',\n 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',\n 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',\n 'viv', 'vob',\n 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',\n 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',\n 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',\n 'xmind', 'xpi', 'xpm', 'xwd', 'xz',\n 'z', 'zip', 'zipx',\n]);\nconst isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());\n// TODO: emit errors properly. Example: EMFILE on Macos.\nconst foreach = (val, fn) => {\n if (val instanceof Set) {\n val.forEach(fn);\n }\n else {\n fn(val);\n }\n};\nconst addAndConvert = (main, prop, item) => {\n let container = main[prop];\n if (!(container instanceof Set)) {\n main[prop] = container = new Set([container]);\n }\n container.add(item);\n};\nconst clearItem = (cont) => (key) => {\n const set = cont[key];\n if (set instanceof Set) {\n set.clear();\n }\n else {\n delete cont[key];\n }\n};\nconst delFromSet = (main, prop, item) => {\n const container = main[prop];\n if (container instanceof Set) {\n container.delete(item);\n }\n else if (container === item) {\n delete main[prop];\n }\n};\nconst isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);\nconst FsWatchInstances = new Map();\n/**\n * Instantiates the fs_watch interface\n * @param path to be watched\n * @param options to be passed to fs_watch\n * @param listener main event handler\n * @param errHandler emits info about errors\n * @param emitRaw emits raw event data\n * @returns {NativeFsWatcher}\n */\nfunction createFsWatchInstance(path, options, listener, errHandler, emitRaw) {\n const handleEvent = (rawEvent, evPath) => {\n listener(path);\n emitRaw(rawEvent, evPath, { watchedPath: path });\n // emit based on events occurring for files from a directory's watcher in\n // case the file's watcher misses it (and rely on throttling to de-dupe)\n if (evPath && path !== evPath) {\n fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));\n }\n };\n try {\n return fs_watch(path, {\n persistent: options.persistent,\n }, handleEvent);\n }\n catch (error) {\n errHandler(error);\n return undefined;\n }\n}\n/**\n * Helper for passing fs_watch event data to a collection of listeners\n * @param fullPath absolute path bound to fs_watch instance\n */\nconst fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {\n const cont = FsWatchInstances.get(fullPath);\n if (!cont)\n return;\n foreach(cont[listenerType], (listener) => {\n listener(val1, val2, val3);\n });\n};\n/**\n * Instantiates the fs_watch interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path\n * @param fullPath absolute path\n * @param options to be passed to fs_watch\n * @param handlers container for event listener functions\n */\nconst setFsWatchListener = (path, fullPath, options, handlers) => {\n const { listener, errHandler, rawEmitter } = handlers;\n let cont = FsWatchInstances.get(fullPath);\n let watcher;\n if (!options.persistent) {\n watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);\n if (!watcher)\n return;\n return watcher.close.bind(watcher);\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_ERR, errHandler);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here\n fsWatchBroadcast.bind(null, fullPath, KEY_RAW));\n if (!watcher)\n return;\n watcher.on(EV.ERROR, async (error) => {\n const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);\n if (cont)\n cont.watcherUnusable = true; // documented since Node 10.4.1\n // Workaround for https://github.com/joyent/node/issues/4337\n if (isWindows && error.code === 'EPERM') {\n try {\n const fd = await open(path, 'r');\n await fd.close();\n broadcastErr(error);\n }\n catch (err) {\n // do nothing\n }\n }\n else {\n broadcastErr(error);\n }\n });\n cont = {\n listeners: listener,\n errHandlers: errHandler,\n rawEmitters: rawEmitter,\n watcher,\n };\n FsWatchInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // removes this instance's listeners and closes the underlying fs_watch\n // instance if there are no more listeners left\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_ERR, errHandler);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n // Check to protect against issue gh-730.\n // if (cont.watcherUnusable) {\n cont.watcher.close();\n // }\n FsWatchInstances.delete(fullPath);\n HANDLER_KEYS.forEach(clearItem(cont));\n // @ts-ignore\n cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n// fs_watchFile helpers\n// object to hold per-process fs_watchFile instances\n// (may be shared across chokidar FSWatcher instances)\nconst FsWatchFileInstances = new Map();\n/**\n * Instantiates the fs_watchFile interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path to be watched\n * @param fullPath absolute path\n * @param options options to be passed to fs_watchFile\n * @param handlers container for event listener functions\n * @returns closer\n */\nconst setFsWatchFileListener = (path, fullPath, options, handlers) => {\n const { listener, rawEmitter } = handlers;\n let cont = FsWatchFileInstances.get(fullPath);\n // let listeners = new Set();\n // let rawEmitters = new Set();\n const copts = cont && cont.options;\n if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {\n // \"Upgrade\" the watcher to persistence or a quicker interval.\n // This creates some unlikely edge case issues if the user mixes\n // settings in a very weird way, but solving for those cases\n // doesn't seem worthwhile for the added complexity.\n // listeners = cont.listeners;\n // rawEmitters = cont.rawEmitters;\n unwatchFile(fullPath);\n cont = undefined;\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n // TODO\n // listeners.add(listener);\n // rawEmitters.add(rawEmitter);\n cont = {\n listeners: listener,\n rawEmitters: rawEmitter,\n options,\n watcher: watchFile(fullPath, options, (curr, prev) => {\n foreach(cont.rawEmitters, (rawEmitter) => {\n rawEmitter(EV.CHANGE, fullPath, { curr, prev });\n });\n const currmtime = curr.mtimeMs;\n if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {\n foreach(cont.listeners, (listener) => listener(path, curr));\n }\n }),\n };\n FsWatchFileInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // Removes this instance's listeners and closes the underlying fs_watchFile\n // instance if there are no more listeners left.\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n FsWatchFileInstances.delete(fullPath);\n unwatchFile(fullPath);\n cont.options = cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n/**\n * @mixin\n */\nexport class NodeFsHandler {\n fsw;\n _boundHandleError;\n constructor(fsW) {\n this.fsw = fsW;\n this._boundHandleError = (error) => fsW._handleError(error);\n }\n /**\n * Watch file for changes with fs_watchFile or fs_watch.\n * @param path to file or dir\n * @param listener on fs change\n * @returns closer for the watcher instance\n */\n _watchWithNodeFs(path, listener) {\n const opts = this.fsw.options;\n const directory = sp.dirname(path);\n const basename = sp.basename(path);\n const parent = this.fsw._getWatchedDir(directory);\n parent.add(basename);\n const absolutePath = sp.resolve(path);\n const options = {\n persistent: opts.persistent,\n };\n if (!listener)\n listener = EMPTY_FN;\n let closer;\n if (opts.usePolling) {\n const enableBin = opts.interval !== opts.binaryInterval;\n options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;\n closer = setFsWatchFileListener(path, absolutePath, options, {\n listener,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n else {\n closer = setFsWatchListener(path, absolutePath, options, {\n listener,\n errHandler: this._boundHandleError,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n return closer;\n }\n /**\n * Watch a file and emit add event if warranted.\n * @returns closer for the watcher instance\n */\n _handleFile(file, stats, initialAdd) {\n if (this.fsw.closed) {\n return;\n }\n const dirname = sp.dirname(file);\n const basename = sp.basename(file);\n const parent = this.fsw._getWatchedDir(dirname);\n // stats is always present\n let prevStats = stats;\n // if the file is already being watched, do nothing\n if (parent.has(basename))\n return;\n const listener = async (path, newStats) => {\n if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))\n return;\n if (!newStats || newStats.mtimeMs === 0) {\n try {\n const newStats = await stat(file);\n if (this.fsw.closed)\n return;\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {\n this.fsw._closeFile(path);\n prevStats = newStats;\n const closer = this._watchWithNodeFs(file, listener);\n if (closer)\n this.fsw._addPathCloser(path, closer);\n }\n else {\n prevStats = newStats;\n }\n }\n catch (error) {\n // Fix issues where mtime is null but file is still present\n this.fsw._remove(dirname, basename);\n }\n // add is about to be emitted if file not already tracked in parent\n }\n else if (parent.has(basename)) {\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n prevStats = newStats;\n }\n };\n // kick off the watcher\n const closer = this._watchWithNodeFs(file, listener);\n // emit an add event if we're supposed to\n if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {\n if (!this.fsw._throttle(EV.ADD, file, 0))\n return;\n this.fsw._emit(EV.ADD, file, stats);\n }\n return closer;\n }\n /**\n * Handle symlinks encountered while reading a dir.\n * @param entry returned by readdirp\n * @param directory path of dir being read\n * @param path of this item\n * @param item basename of this item\n * @returns true if no more processing is needed for this entry.\n */\n async _handleSymlink(entry, directory, path, item) {\n if (this.fsw.closed) {\n return;\n }\n const full = entry.fullPath;\n const dir = this.fsw._getWatchedDir(directory);\n if (!this.fsw.options.followSymlinks) {\n // watch symlink directly (don't follow) and detect changes\n this.fsw._incrReadyCount();\n let linkPath;\n try {\n linkPath = await fsrealpath(path);\n }\n catch (e) {\n this.fsw._emitReady();\n return true;\n }\n if (this.fsw.closed)\n return;\n if (dir.has(item)) {\n if (this.fsw._symlinkPaths.get(full) !== linkPath) {\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.CHANGE, path, entry.stats);\n }\n }\n else {\n dir.add(item);\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.ADD, path, entry.stats);\n }\n this.fsw._emitReady();\n return true;\n }\n // don't follow the same symlink more than once\n if (this.fsw._symlinkPaths.has(full)) {\n return true;\n }\n this.fsw._symlinkPaths.set(full, true);\n }\n _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {\n // Normalize the directory name on Windows\n directory = sp.join(directory, '');\n const throttleKey = target ? `${directory}:${target}` : directory;\n throttler = this.fsw._throttle('readdir', throttleKey, 1000);\n if (!throttler)\n return;\n const previous = this.fsw._getWatchedDir(wh.path);\n const current = new Set();\n let stream = this.fsw._readdirp(directory, {\n fileFilter: (entry) => wh.filterPath(entry),\n directoryFilter: (entry) => wh.filterDir(entry),\n });\n if (!stream)\n return;\n stream\n .on(STR_DATA, async (entry) => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const item = entry.path;\n let path = sp.join(directory, item);\n current.add(item);\n if (entry.stats.isSymbolicLink() &&\n (await this._handleSymlink(entry, directory, path, item))) {\n return;\n }\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n // Files that present in current directory snapshot\n // but absent in previous are added to watch list and\n // emit `add` event.\n if (item === target || (!target && !previous.has(item))) {\n this.fsw._incrReadyCount();\n // ensure relativeness of path is preserved in case of watcher reuse\n path = sp.join(dir, sp.relative(dir, path));\n this._addToNodeFs(path, initialAdd, wh, depth + 1);\n }\n })\n .on(EV.ERROR, this._boundHandleError);\n return new Promise((resolve, reject) => {\n if (!stream)\n return reject();\n stream.once(STR_END, () => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const wasThrottled = throttler ? throttler.clear() : false;\n resolve(undefined);\n // Files that absent in current directory snapshot\n // but present in previous emit `remove` event\n // and are removed from @watched[directory].\n previous\n .getChildren()\n .filter((item) => {\n return item !== directory && !current.has(item);\n })\n .forEach((item) => {\n this.fsw._remove(directory, item);\n });\n stream = undefined;\n // one more time for any missed in case changes came in extremely quickly\n if (wasThrottled)\n this._handleRead(directory, false, wh, target, dir, depth, throttler);\n });\n });\n }\n /**\n * Read directory to add / remove files from `@watched` list and re-read it on change.\n * @param dir fs path\n * @param stats\n * @param initialAdd\n * @param depth relative to user-supplied path\n * @param target child path targeted for watch\n * @param wh Common watch helpers for this path\n * @param realpath\n * @returns closer for the watcher instance.\n */\n async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {\n const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));\n const tracked = parentDir.has(sp.basename(dir));\n if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {\n this.fsw._emit(EV.ADD_DIR, dir, stats);\n }\n // ensure dir is tracked (harmless if redundant)\n parentDir.add(sp.basename(dir));\n this.fsw._getWatchedDir(dir);\n let throttler;\n let closer;\n const oDepth = this.fsw.options.depth;\n if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {\n if (!target) {\n await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);\n if (this.fsw.closed)\n return;\n }\n closer = this._watchWithNodeFs(dir, (dirPath, stats) => {\n // if current directory is removed, do nothing\n if (stats && stats.mtimeMs === 0)\n return;\n this._handleRead(dirPath, false, wh, target, dir, depth, throttler);\n });\n }\n return closer;\n }\n /**\n * Handle added file, directory, or glob pattern.\n * Delegates call to _handleFile / _handleDir after checks.\n * @param path to file or ir\n * @param initialAdd was the file added at watch instantiation?\n * @param priorWh depth relative to user-supplied path\n * @param depth Child path actually targeted for watch\n * @param target Child path actually targeted for watch\n */\n async _addToNodeFs(path, initialAdd, priorWh, depth, target) {\n const ready = this.fsw._emitReady;\n if (this.fsw._isIgnored(path) || this.fsw.closed) {\n ready();\n return false;\n }\n const wh = this.fsw._getWatchHelpers(path);\n if (priorWh) {\n wh.filterPath = (entry) => priorWh.filterPath(entry);\n wh.filterDir = (entry) => priorWh.filterDir(entry);\n }\n // evaluate what is at the path we're being asked to watch\n try {\n const stats = await statMethods[wh.statMethod](wh.watchPath);\n if (this.fsw.closed)\n return;\n if (this.fsw._isIgnored(wh.watchPath, stats)) {\n ready();\n return false;\n }\n const follow = this.fsw.options.followSymlinks;\n let closer;\n if (stats.isDirectory()) {\n const absPath = sp.resolve(path);\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (absPath !== targetPath && targetPath !== undefined) {\n this.fsw._symlinkPaths.set(absPath, targetPath);\n }\n }\n else if (stats.isSymbolicLink()) {\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n const parent = sp.dirname(wh.watchPath);\n this.fsw._getWatchedDir(parent).add(wh.watchPath);\n this.fsw._emit(EV.ADD, wh.watchPath, stats);\n closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (targetPath !== undefined) {\n this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);\n }\n }\n else {\n closer = this._handleFile(wh.watchPath, stats, initialAdd);\n }\n ready();\n if (closer)\n this.fsw._addPathCloser(path, closer);\n return false;\n }\n catch (error) {\n if (this.fsw._handleError(error)) {\n ready();\n return path;\n }\n }\n }\n}\n","import chokidar, { FSWatcher } from \"chokidar\";\nimport * as path from \"path\";\n\nimport type { CodebaseIndexConfig } from \"../config/schema.js\";\nimport { createIgnoreFilter, shouldIncludeFile } from \"../utils/files.js\";\nimport { hasFilteredPathSegment, isRestrictedDirectory } from \"../utils/paths.js\";\n\nexport type FileChangeType = \"add\" | \"change\" | \"unlink\";\n\nexport interface FileChange {\n type: FileChangeType;\n path: string;\n}\n\nexport type ChangeHandler = (changes: FileChange[]) => Promise<void>;\n\nexport class FileWatcher {\n private watcher: FSWatcher | null = null;\n private projectRoot: string;\n private config: CodebaseIndexConfig;\n private pendingChanges: Map<string, FileChangeType> = new Map();\n private debounceTimer: NodeJS.Timeout | null = null;\n private debounceMs = 1000;\n private onChanges: ChangeHandler | null = null;\n\n constructor(projectRoot: string, config: CodebaseIndexConfig) {\n this.projectRoot = projectRoot;\n this.config = config;\n }\n\n start(handler: ChangeHandler): void {\n if (this.watcher) {\n return;\n }\n\n this.onChanges = handler;\n const ignoreFilter = createIgnoreFilter(this.projectRoot);\n\n this.watcher = chokidar.watch(this.projectRoot, {\n ignored: (filePath: string) => {\n const relativePath = path.relative(this.projectRoot, filePath);\n if (!relativePath) return false;\n\n if (hasFilteredPathSegment(relativePath, path.sep)) {\n return true;\n }\n\n if (isRestrictedDirectory(relativePath, path.sep)) {\n return true;\n }\n\n if (ignoreFilter.ignores(relativePath)) {\n return true;\n }\n\n return false;\n },\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 300,\n pollInterval: 100,\n },\n });\n\n this.watcher.on(\"error\", (error: unknown) => {\n const err = error instanceof Error ? (error as NodeJS.ErrnoException) : null;\n if (err?.code === \"EPERM\" || err?.code === \"EACCES\") {\n // Silently ignore permission errors — common on macOS restricted paths\n return;\n }\n console.error(\"[codebase-index] Watcher error:\", err?.message ?? error);\n });\n\n this.watcher.on(\"add\", (filePath) => this.handleChange(\"add\", filePath));\n this.watcher.on(\"change\", (filePath) => this.handleChange(\"change\", filePath));\n this.watcher.on(\"unlink\", (filePath) => this.handleChange(\"unlink\", filePath));\n }\n\n private handleChange(type: FileChangeType, filePath: string): void {\n const includePatterns = [...this.config.include, ...(this.config.additionalInclude ?? [])];\n if (\n !shouldIncludeFile(\n filePath,\n this.projectRoot,\n includePatterns,\n this.config.exclude,\n createIgnoreFilter(this.projectRoot)\n )\n ) {\n return;\n }\n\n this.pendingChanges.set(filePath, type);\n this.scheduleFlush();\n }\n\n private scheduleFlush(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n }\n\n this.debounceTimer = setTimeout(() => {\n this.flush();\n }, this.debounceMs);\n }\n\n private async flush(): Promise<void> {\n if (this.pendingChanges.size === 0 || !this.onChanges) {\n return;\n }\n\n const changes: FileChange[] = Array.from(this.pendingChanges.entries()).map(\n ([path, type]) => ({ path, type })\n );\n\n this.pendingChanges.clear();\n\n try {\n await this.onChanges(changes);\n } catch (error) {\n console.error(\"Error handling file changes:\", error);\n }\n }\n\n stop(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n\n if (this.watcher) {\n this.watcher.close();\n this.watcher = null;\n }\n\n this.pendingChanges.clear();\n this.onChanges = null;\n }\n\n isRunning(): boolean {\n return this.watcher !== null;\n }\n}\n","import ignore, { Ignore } from \"ignore\";\nimport { existsSync, readFileSync, promises as fsPromises } from \"fs\";\nimport * as path from \"path\";\n\nimport { hasFilteredPathSegment, isBuildPathSegment, isHiddenPathSegment } from \"./paths.js\";\n\nconst PROJECT_MARKERS = [\n \".git\",\n \"package.json\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"setup.py\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n \"pom.xml\",\n \"build.gradle\",\n \"CMakeLists.txt\",\n \"Makefile\",\n \".opencode\",\n];\n\nexport function hasProjectMarker(projectRoot: string): boolean {\n for (const marker of PROJECT_MARKERS) {\n if (existsSync(path.join(projectRoot, marker))) {\n return true;\n }\n }\n return false;\n}\n\nexport interface SkippedFile {\n path: string;\n reason: \"too_large\" | \"excluded\" | \"gitignore\" | \"no_match\";\n}\n\nexport interface CollectFilesResult {\n files: Array<{ path: string; size: number }>;\n skipped: SkippedFile[];\n}\n\nexport function createIgnoreFilter(projectRoot: string): Ignore {\n const ig = ignore();\n\n const defaultIgnores = [\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \".nuxt\",\n \"coverage\",\n \"__pycache__\",\n \"target\",\n \"vendor\",\n \".opencode\",\n \".*\",\n \"**/.*\",\n \"**/.*/**\",\n \"**/*build*/**\",\n ];\n\n ig.add(defaultIgnores);\n\n const gitignorePath = path.join(projectRoot, \".gitignore\");\n if (existsSync(gitignorePath)) {\n const gitignoreContent = readFileSync(gitignorePath, \"utf-8\");\n ig.add(gitignoreContent);\n }\n\n return ig;\n}\n\nexport function shouldIncludeFile(\n filePath: string,\n projectRoot: string,\n includePatterns: string[],\n excludePatterns: string[],\n ignoreFilter: Ignore\n): boolean {\n const relativePath = path.relative(projectRoot, filePath);\n\n if (hasFilteredPathSegment(relativePath, path.sep)) {\n return false;\n }\n\n if (ignoreFilter.ignores(relativePath)) {\n return false;\n }\n\n for (const pattern of excludePatterns) {\n if (matchGlob(relativePath, pattern)) {\n return false;\n }\n }\n\n for (const pattern of includePatterns) {\n if (matchGlob(relativePath, pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction matchGlob(filePath: string, pattern: string): boolean {\n if (pattern.startsWith(\"**/\")) {\n const withoutPrefix = pattern.slice(3);\n if (withoutPrefix && matchGlob(filePath, withoutPrefix)) {\n return true;\n }\n }\n\n const escapedPattern = pattern.replace(/[.+^$()|[\\]\\\\]/g, \"\\\\$&\");\n\n let regexPattern = escapedPattern\n .replace(/\\*\\*/g, \"<<<DOUBLESTAR>>>\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/<<<DOUBLESTAR>>>/g, \".*\")\n .replace(/\\?/g, \".\")\n .replace(/\\{([^}]+)\\}/g, (_, p1) => `(${p1.split(\",\").join(\"|\")})`);\n\n // **/*.js → matches both root \"file.js\" and nested \"dir/file.js\"\n if (regexPattern.startsWith(\".*/\")) {\n regexPattern = `(.*\\\\/)?${regexPattern.slice(3)}`;\n }\n\n const regex = new RegExp(`^${regexPattern}$`);\n return regex.test(filePath);\n}\n\nexport interface WalkOptions {\n maxDepth: number;\n maxFilesPerDirectory: number;\n}\n\nexport async function* walkDirectory(\n dir: string,\n projectRoot: string,\n includePatterns: string[],\n excludePatterns: string[],\n ignoreFilter: Ignore,\n maxFileSize: number,\n skipped: SkippedFile[],\n options: WalkOptions,\n currentDepth: number = 0\n): AsyncGenerator<{ path: string; size: number }> {\n const entries = await fsPromises.readdir(dir, { withFileTypes: true });\n\n const filesInDir: Array<{ path: string; size: number }> = [];\n const subdirs: Array<{ fullPath: string; relativePath: string }> = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = path.relative(projectRoot, fullPath);\n\n if (isHiddenPathSegment(entry.name)) {\n if (entry.isDirectory()) {\n skipped.push({ path: relativePath, reason: \"excluded\" });\n }\n continue;\n }\n\n if (entry.isDirectory() && isBuildPathSegment(entry.name)) {\n skipped.push({ path: relativePath, reason: \"excluded\" });\n continue;\n }\n\n if (ignoreFilter.ignores(relativePath)) {\n if (entry.isFile()) {\n skipped.push({ path: relativePath, reason: \"gitignore\" });\n }\n continue;\n }\n\n if (entry.isDirectory()) {\n subdirs.push({ fullPath, relativePath });\n } else if (entry.isFile()) {\n const stat = await fsPromises.stat(fullPath);\n\n if (stat.size > maxFileSize) {\n skipped.push({ path: relativePath, reason: \"too_large\" });\n continue;\n }\n\n for (const pattern of excludePatterns) {\n if (matchGlob(relativePath, pattern)) {\n skipped.push({ path: relativePath, reason: \"excluded\" });\n continue;\n }\n }\n\n let matched = false;\n for (const pattern of includePatterns) {\n if (matchGlob(relativePath, pattern)) {\n matched = true;\n break;\n }\n }\n\n if (matched) {\n filesInDir.push({ path: fullPath, size: stat.size });\n }\n }\n }\n\n filesInDir.sort((a, b) => a.size - b.size);\n const limitedFiles = filesInDir.slice(0, options.maxFilesPerDirectory);\n for (const f of limitedFiles) {\n yield f;\n }\n for (let i = options.maxFilesPerDirectory; i < filesInDir.length; i++) {\n skipped.push({ path: path.relative(projectRoot, filesInDir[i].path), reason: \"excluded\" });\n }\n\n const canRecurse = options.maxDepth === -1 || currentDepth < options.maxDepth;\n if (canRecurse) {\n for (const sub of subdirs) {\n yield* walkDirectory(\n sub.fullPath,\n projectRoot,\n includePatterns,\n excludePatterns,\n ignoreFilter,\n maxFileSize,\n skipped,\n options,\n currentDepth + 1\n );\n }\n }\n}\n\nexport async function collectFiles(\n projectRoot: string,\n includePatterns: string[],\n excludePatterns: string[],\n maxFileSize: number,\n additionalRoots?: string[],\n walkOptions?: WalkOptions\n): Promise<CollectFilesResult> {\n const opts: WalkOptions = walkOptions ?? { maxDepth: 5, maxFilesPerDirectory: 100 };\n const ignoreFilter = createIgnoreFilter(projectRoot);\n const files: Array<{ path: string; size: number }> = [];\n const skipped: SkippedFile[] = [];\n\n for await (const file of walkDirectory(\n projectRoot,\n projectRoot,\n includePatterns,\n excludePatterns,\n ignoreFilter,\n maxFileSize,\n skipped,\n opts,\n 0\n )) {\n files.push(file);\n }\n\n if (additionalRoots && additionalRoots.length > 0) {\n const normalizedRoots = new Set<string>();\n for (const kbRoot of additionalRoots) {\n const resolved = path.normalize(\n path.isAbsolute(kbRoot) ? kbRoot : path.resolve(projectRoot, kbRoot)\n );\n normalizedRoots.add(resolved);\n }\n\n for (const resolvedKbRoot of normalizedRoots) {\n try {\n const stat = await fsPromises.stat(resolvedKbRoot);\n if (!stat.isDirectory()) {\n skipped.push({ path: resolvedKbRoot, reason: \"excluded\" });\n continue;\n }\n const kbIgnoreFilter = createIgnoreFilter(resolvedKbRoot);\n for await (const file of walkDirectory(\n resolvedKbRoot,\n resolvedKbRoot,\n includePatterns,\n excludePatterns,\n kbIgnoreFilter,\n maxFileSize,\n skipped,\n opts,\n 0\n )) {\n files.push(file);\n }\n } catch {\n skipped.push({ path: resolvedKbRoot, reason: \"excluded\" });\n }\n }\n }\n\n return { files, skipped };\n}\n","import chokidar, { FSWatcher } from \"chokidar\";\nimport * as path from \"path\";\n\nimport { getCurrentBranch, getHeadPath, isGitRepo } from \"../git/index.js\";\n\nexport type BranchChangeHandler = (oldBranch: string | null, newBranch: string) => Promise<void>;\n\n/**\n * Watches .git/HEAD for branch changes.\n * When HEAD changes (branch switch, checkout), triggers callback with old and new branch.\n */\nexport class GitHeadWatcher {\n private watcher: FSWatcher | null = null;\n private projectRoot: string;\n private currentBranch: string | null = null;\n private onBranchChange: BranchChangeHandler | null = null;\n private debounceTimer: NodeJS.Timeout | null = null;\n private debounceMs = 100; // Short debounce for git operations\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n start(handler: BranchChangeHandler): void {\n if (this.watcher) {\n return;\n }\n\n if (!isGitRepo(this.projectRoot)) {\n return; // Not a git repo, nothing to watch\n }\n\n this.onBranchChange = handler;\n this.currentBranch = getCurrentBranch(this.projectRoot);\n\n const headPath = getHeadPath(this.projectRoot);\n\n // Also watch refs/heads for when branches are updated\n const refsPath = path.join(this.projectRoot, \".git\", \"refs\", \"heads\");\n\n this.watcher = chokidar.watch([headPath, refsPath], {\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 50,\n pollInterval: 10,\n },\n });\n\n this.watcher.on(\"change\", () => this.handleHeadChange());\n this.watcher.on(\"add\", () => this.handleHeadChange());\n }\n\n private handleHeadChange(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n }\n\n this.debounceTimer = setTimeout(() => {\n this.checkBranchChange();\n }, this.debounceMs);\n }\n\n private async checkBranchChange(): Promise<void> {\n const newBranch = getCurrentBranch(this.projectRoot);\n\n if (newBranch && newBranch !== this.currentBranch && this.onBranchChange) {\n const oldBranch = this.currentBranch;\n this.currentBranch = newBranch;\n\n try {\n await this.onBranchChange(oldBranch, newBranch);\n } catch (error) {\n console.error(\"Error handling branch change:\", error);\n }\n } else if (newBranch) {\n this.currentBranch = newBranch;\n }\n }\n\n getCurrentBranch(): string | null {\n return this.currentBranch;\n }\n\n stop(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n\n if (this.watcher) {\n this.watcher.close();\n this.watcher = null;\n }\n\n this.onBranchChange = null;\n }\n\n isRunning(): boolean {\n return this.watcher !== null;\n }\n}\n","import type { CodebaseIndexConfig } from \"../config/schema.js\";\nimport type { Indexer } from \"../indexer/index.js\";\nimport { isGitRepo } from \"../git/index.js\";\nimport { FileWatcher } from \"./file-watcher.js\";\nimport { GitHeadWatcher } from \"./git-head-watcher.js\";\n\nexport { FileWatcher } from \"./file-watcher.js\";\nexport type { ChangeHandler, FileChange, FileChangeType } from \"./file-watcher.js\";\nexport { GitHeadWatcher } from \"./git-head-watcher.js\";\nexport type { BranchChangeHandler } from \"./git-head-watcher.js\";\n\nexport interface CombinedWatcher {\n fileWatcher: FileWatcher;\n gitWatcher: GitHeadWatcher | null;\n stop(): void;\n}\n\nexport function createWatcherWithIndexer(\n getIndexer: () => Indexer,\n projectRoot: string,\n config: CodebaseIndexConfig\n): CombinedWatcher {\n const fileWatcher = new FileWatcher(projectRoot, config);\n\n fileWatcher.start(async (changes) => {\n const hasAddOrChange = changes.some(\n (c) => c.type === \"add\" || c.type === \"change\"\n );\n const hasDelete = changes.some((c) => c.type === \"unlink\");\n\n if (hasAddOrChange || hasDelete) {\n await getIndexer().index();\n }\n });\n\n let gitWatcher: GitHeadWatcher | null = null;\n \n if (isGitRepo(projectRoot)) {\n gitWatcher = new GitHeadWatcher(projectRoot);\n gitWatcher.start(async (oldBranch, newBranch) => {\n console.log(`Branch changed: ${oldBranch ?? \"(none)\"} -> ${newBranch}`);\n await getIndexer().index();\n });\n }\n\n return {\n fileWatcher,\n gitWatcher,\n stop() {\n fileWatcher.stop();\n gitWatcher?.stop();\n },\n };\n}\n","import { tool, type ToolDefinition } from \"@opencode-ai/plugin\";\n\nimport { parseConfig, type ParsedCodebaseIndexConfig } from \"../config/schema.js\";\nimport { Indexer } from \"../indexer/index.js\";\nimport { formatCostEstimate } from \"../utils/cost.js\";\nimport type { LogLevel } from \"../config/schema.js\";\nimport type { LogEntry } from \"../utils/logger.js\";\nimport {\n formatProgressTitle,\n formatIndexStats,\n formatStatus,\n calculatePercentage,\n formatCodebasePeek,\n formatDefinitionLookup,\n formatHealthCheck,\n formatLogs,\n formatSearchResults,\n} from \"./utils.js\";\nimport {\n findKnowledgeBasePathIndex,\n hasMatchingKnowledgeBasePath,\n resolveKnowledgeBasePath,\n} from \"./knowledge-base-paths.js\";\nimport { existsSync, realpathSync, statSync } from \"fs\";\nimport * as path from \"path\";\nimport { loadProjectConfigLayer, materializeLocalProjectConfig } from \"../config/merger.js\";\nimport { resolveWorktreeMainRepoRoot } from \"../git/index.js\";\nimport { getConfigPath, loadEditableConfig, loadRuntimeConfig, saveConfig } from \"./config-state.js\";\nimport * as os from \"os\";\n\nfunction ensureStringArray(value: unknown): string[] {\n return Array.isArray(value) ? (value as string[]) : [];\n}\n\nconst z = tool.schema;\n\nconst indexerMap = new Map<string, Indexer>();\nlet defaultProjectRoot: string = \"\";\n\nexport function initializeTools(projectRoot: string, config: ParsedCodebaseIndexConfig): void {\n defaultProjectRoot = projectRoot;\n const indexer = new Indexer(projectRoot, config);\n indexerMap.set(projectRoot, indexer);\n}\n\nexport function getSharedIndexer(): Indexer {\n return getIndexerForProject(defaultProjectRoot);\n}\n\nfunction refreshIndexerForDirectory(projectRoot: string): void {\n if (!projectRoot) {\n throw new Error(\"Codebase index tools not initialized. Plugin may not be loaded correctly.\");\n }\n const indexer = new Indexer(projectRoot, parseConfig(loadRuntimeConfig(projectRoot)));\n indexerMap.set(projectRoot, indexer);\n}\n\nfunction shouldForceLocalizeProjectIndex(projectRoot: string): boolean {\n const currentConfig = parseConfig(loadRuntimeConfig(projectRoot));\n if (currentConfig.scope !== \"project\") {\n return false;\n }\n\n const localIndexPath = path.join(projectRoot, \".opencode\", \"index\");\n const mainRepoRoot = resolveWorktreeMainRepoRoot(projectRoot);\n if (!mainRepoRoot) {\n return false;\n }\n\n const inheritedIndexPath = path.join(mainRepoRoot, \".opencode\", \"index\");\n return !existsSync(localIndexPath) && existsSync(inheritedIndexPath);\n}\n\nexport function getIndexerForProject(directory: string): Indexer {\n const projectRoot = directory || defaultProjectRoot;\n if (!projectRoot) {\n throw new Error(\"Codebase index tools not initialized. Plugin may not be loaded correctly.\");\n }\n\n let indexer = indexerMap.get(projectRoot);\n if (!indexer) {\n const config = parseConfig(loadRuntimeConfig(projectRoot));\n indexer = new Indexer(projectRoot, config);\n indexerMap.set(projectRoot, indexer);\n }\n return indexer;\n}\n\nexport const codebase_peek: ToolDefinition = tool({\n description:\n \"Quick lookup of code locations by meaning. Returns only metadata (file, line, name, type) WITHOUT code content. Use this first to find WHERE code is, then use Read tool to examine specific files. Saves tokens by not returning full code blocks. Best for: discovery, navigation, finding multiple related locations.\",\n args: {\n query: z.string().describe(\"Natural language description of what code you're looking for.\"),\n limit: z.number().optional().default(10).describe(\"Maximum number of results to return\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py', 'rs')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils', 'lib')\"),\n chunkType: z.enum([\"function\", \"class\", \"method\", \"interface\", \"type\", \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\"]).optional().describe(\"Filter by code chunk type\"),\n },\n async execute(args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const results = await indexer.search(args.query, args.limit ?? 10, {\n fileType: args.fileType,\n directory: args.directory,\n chunkType: args.chunkType,\n metadataOnly: true,\n });\n\n return formatCodebasePeek(results);\n },\n});\n\nexport const index_codebase: ToolDefinition = tool({\n description:\n \"Index the codebase for semantic search. Creates vector embeddings of code chunks. Incremental - only re-indexes changed files (~50ms when nothing changed). Run before first codebase_search.\",\n args: {\n force: z.boolean().optional().default(false).describe(\"Force reindex even if already indexed\"),\n estimateOnly: z.boolean().optional().default(false).describe(\"Only show cost estimate without indexing\"),\n verbose: z.boolean().optional().default(false).describe(\"Show detailed info about skipped files and parsing failures\"),\n },\n async execute(args, context) {\n const projectRoot = context?.worktree || defaultProjectRoot;\n let indexer = getIndexerForProject(projectRoot);\n\n if (args.estimateOnly) {\n const estimate = await indexer.estimateCost();\n return formatCostEstimate(estimate);\n }\n\n if (args.force) {\n if (shouldForceLocalizeProjectIndex(projectRoot)) {\n materializeLocalProjectConfig(projectRoot, loadProjectConfigLayer(projectRoot));\n refreshIndexerForDirectory(projectRoot);\n indexer = getIndexerForProject(projectRoot);\n }\n await indexer.clearIndex();\n }\n\n const stats = await indexer.index((progress) => {\n context.metadata({\n title: formatProgressTitle(progress),\n metadata: {\n phase: progress.phase,\n filesProcessed: progress.filesProcessed,\n totalFiles: progress.totalFiles,\n chunksProcessed: progress.chunksProcessed,\n totalChunks: progress.totalChunks,\n percentage: calculatePercentage(progress),\n },\n });\n });\n return formatIndexStats(stats, args.verbose ?? false);\n },\n});\n\nexport const index_status: ToolDefinition = tool({\n description:\n \"Check the status of the codebase index. Shows whether the codebase is indexed, how many chunks are stored, and the embedding provider being used.\",\n args: {},\n async execute(_args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const status = await indexer.getStatus();\n return formatStatus(status);\n },\n});\n\nexport const index_health_check: ToolDefinition = tool({\n description:\n \"Check index health and remove stale entries from deleted files. Run this to clean up the index after files have been deleted.\",\n args: {},\n async execute(_args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const result = await indexer.healthCheck();\n\n return formatHealthCheck(result);\n },\n});\n\nexport const index_metrics: ToolDefinition = tool({\n description:\n \"Get metrics and performance statistics for the codebase index. Shows indexing stats, search timings, cache hit rates, and API usage. Requires debug.enabled=true and debug.metrics=true in config.\",\n args: {},\n async execute(_args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const logger = indexer.getLogger();\n\n if (!logger.isEnabled()) {\n return \"Debug mode is disabled. Enable it in your config:\\n\\n```json\\n{\\n \\\"debug\\\": {\\n \\\"enabled\\\": true,\\n \\\"metrics\\\": true\\n }\\n}\\n```\";\n }\n\n if (!logger.isMetricsEnabled()) {\n return \"Metrics collection is disabled. Enable it in your config:\\n\\n```json\\n{\\n \\\"debug\\\": {\\n \\\"enabled\\\": true,\\n \\\"metrics\\\": true\\n }\\n}\\n```\";\n }\n\n return logger.formatMetrics();\n },\n});\n\nexport const index_logs: ToolDefinition = tool({\n description:\n \"Get recent debug logs from the codebase indexer. Shows timestamped log entries with level and category. Requires debug.enabled=true in config.\",\n args: {\n limit: z.number().optional().default(20).describe(\"Maximum number of log entries to return\"),\n category: z.enum([\"search\", \"embedding\", \"cache\", \"gc\", \"branch\", \"general\"]).optional().describe(\"Filter by log category\"),\n level: z.enum([\"error\", \"warn\", \"info\", \"debug\"]).optional().describe(\"Filter by minimum log level\"),\n },\n async execute(args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const logger = indexer.getLogger();\n\n if (!logger.isEnabled()) {\n return \"Debug mode is disabled. Enable it in your config:\\n\\n```json\\n{\\n \\\"debug\\\": {\\n \\\"enabled\\\": true\\n }\\n}\\n```\";\n }\n\n let logs: LogEntry[];\n if (args.category) {\n logs = logger.getLogsByCategory(args.category, args.limit);\n } else if (args.level) {\n logs = logger.getLogsByLevel(args.level as LogLevel, args.limit);\n } else {\n logs = logger.getLogs(args.limit);\n }\n\n return formatLogs(logs);\n },\n});\n\nexport const find_similar: ToolDefinition = tool({\n description:\n \"Find code similar to a given snippet. Use for duplicate detection, pattern discovery, or refactoring prep. Paste code and find semantically similar implementations elsewhere in the codebase.\",\n args: {\n code: z.string().describe(\"The code snippet to find similar code for\"),\n limit: z.number().optional().default(10).describe(\"Maximum number of results to return\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py', 'rs')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils', 'lib')\"),\n chunkType: z.enum([\"function\", \"class\", \"method\", \"interface\", \"type\", \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\"]).optional().describe(\"Filter by code chunk type\"),\n excludeFile: z.string().optional().describe(\"Exclude results from this file path (useful when searching for duplicates of code from a specific file)\"),\n },\n async execute(args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const results = await indexer.findSimilar(args.code, args.limit, {\n fileType: args.fileType,\n directory: args.directory,\n chunkType: args.chunkType,\n excludeFile: args.excludeFile,\n });\n\n if (results.length === 0) {\n return \"No similar code found. Try a different snippet or run index_codebase first.\";\n }\n\n return formatSearchResults(results);\n },\n});\n\nexport const codebase_search: ToolDefinition = tool({\n description:\n \"Search codebase by MEANING, not keywords. Returns full code content. Use when you need to see actual implementation. For just finding WHERE code is (saves ~90% tokens), use codebase_peek instead. For known identifiers like 'validateToken', use grep - it's faster.\",\n args: {\n query: z.string().describe(\"Natural language description of what code you're looking for. Describe behavior, not syntax.\"),\n limit: z.number().optional().default(5).describe(\"Maximum number of results to return\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py', 'rs')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils', 'lib')\"),\n chunkType: z.enum([\"function\", \"class\", \"method\", \"interface\", \"type\", \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\"]).optional().describe(\"Filter by code chunk type\"),\n contextLines: z.number().optional().describe(\"Number of extra lines to include before/after each match (default: 0)\"),\n },\n async execute(args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const results = await indexer.search(args.query, args.limit ?? 5, {\n fileType: args.fileType,\n directory: args.directory,\n chunkType: args.chunkType,\n contextLines: args.contextLines,\n });\n\n if (results.length === 0) {\n return \"No matching code found. Try a different query or run index_codebase first.\";\n }\n\n return formatSearchResults(results, \"score\");\n },\n});\n\nexport const implementation_lookup: ToolDefinition = tool({\n description:\n \"Jump to symbol definition. Find WHERE something is defined. \" +\n \"Returns the authoritative source location(s) for a function, class, method, type, or variable. \" +\n \"Prefers real implementation files over tests, docs, examples, and fixtures. \" +\n \"Use when you need the definition site, not all usages.\",\n args: {\n query: z.string().describe(\"Symbol name or natural language description (e.g., 'validateToken', 'where is the payment handler defined')\"),\n limit: z.number().optional().default(5).describe(\"Maximum number of results\"),\n fileType: z.string().optional().describe(\"Filter by file extension (e.g., 'ts', 'py')\"),\n directory: z.string().optional().describe(\"Filter by directory path (e.g., 'src/utils')\"),\n },\n async execute(args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const results = await indexer.search(args.query, args.limit ?? 5, {\n fileType: args.fileType,\n directory: args.directory,\n definitionIntent: true,\n });\n return formatDefinitionLookup(results, args.query);\n },\n});\n\nexport const call_graph: ToolDefinition = tool({\n description:\n \"Query the call graph to find callers or callees of a function/method. Use to understand code flow and dependencies between functions.\"\n + \" Supports relationship types: Call, MethodCall, Constructor, Import, Inherits, Implements.\",\n args: {\n name: z.string().describe(\"Function or method name to query\"),\n direction: z.enum([\"callers\", \"callees\"]).default(\"callers\").describe(\"Direction: 'callers' finds who calls this function, 'callees' finds what this function calls\"),\n symbolId: z.string().optional().describe(\"Symbol ID (required for 'callees' direction, returned by previous call_graph queries)\"),\n relationshipType: z.enum([\"Call\", \"MethodCall\", \"Constructor\", \"Import\", \"Inherits\", \"Implements\"]).optional().describe(\"Filter by relationship type. Omit to show all.\"),\n },\n async execute(args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n if (args.direction === \"callees\") {\n if (!args.symbolId) {\n return \"Error: 'symbolId' is required when direction is 'callees'. First use direction='callers' to find the symbol ID.\";\n }\n const callees = await indexer.getCallees(args.symbolId, args.relationshipType);\n if (callees.length === 0) {\n return `No callees found for symbol ${args.symbolId}${args.relationshipType ? ` with type ${args.relationshipType}` : \"\"}. The function may not call any other tracked functions.`;\n }\n const formatted = callees.map((e, i) => {\n const conf = e.confidence !== \"Direct\" ? ` [${e.confidence.toLowerCase()}]` : \"\";\n return `[${i + 1}] \\u2192 ${e.targetName} (${e.callType})${conf} at line ${e.line}${e.isResolved ? ` [resolved: ${e.toSymbolId}]` : \" [unresolved]\"}`;\n });\n return formatted.join(\"\\n\");\n }\n const callers = await indexer.getCallers(args.name, args.relationshipType);\n if (callers.length === 0) {\n return `No callers found for \"${args.name}\"${args.relationshipType ? ` with type ${args.relationshipType}` : \"\"}. It may not be called by any tracked function, or the index needs updating.`;\n }\n const formatted = callers.map((e, i) => {\n const conf = e.confidence !== \"Direct\" ? ` [${e.confidence.toLowerCase()}]` : \"\";\n return `[${i + 1}] \\u2190 from ${e.fromSymbolName ?? \"<unknown>\"} in ${e.fromSymbolFilePath ?? \"<unknown file>\"} [${e.fromSymbolId}] (${e.callType})${conf} at line ${e.line}${e.isResolved ? \" [resolved]\" : \" [unresolved]\"}`;\n });\n return formatted.join(\"\\n\");\n },\n});\n\nexport const call_graph_path: ToolDefinition = tool({\n description:\n \"Find the shortest connection path between two symbols in the call graph. Given a source and target function/method name, returns the chain of calls connecting them.\",\n args: {\n from: z.string().describe(\"Source function/method name (starting point)\"),\n to: z.string().describe(\"Target function/method name (destination)\"),\n maxDepth: z.number().optional().default(10).describe(\"Maximum traversal depth (default: 10)\"),\n },\n async execute(args, context) {\n const indexer = getIndexerForProject(context?.worktree);\n const path = await indexer.findCallPath(args.from, args.to, args.maxDepth);\n if (path.length === 0) {\n return `No path found between \"${args.from}\" and \"${args.to}\". They may be in disconnected components, or the call graph index needs updating.`;\n }\n const formatted = path.map((hop, i) => {\n const prefix = i === 0 ? \"[start]\" : `--${hop.callType}-->`;\n const location = hop.filePath ? ` (${hop.filePath}:${hop.line})` : \"\";\n return `${prefix} ${hop.symbolName}${location}`;\n });\n return `Path (${path.length} hops):\\n${formatted.join(\"\\n\")}`;\n },\n});\n\nexport const add_knowledge_base: ToolDefinition = tool({\n description:\n \"Add a folder as a knowledge base to the semantic search index. \" +\n \"The folder will be indexed alongside the main project code. \" +\n \"Supports absolute paths or relative paths (relative to the project root).\",\n args: {\n path: z.string().describe(\"Path to the folder to add as a knowledge base (absolute or relative to project root)\"),\n },\n async execute(args, context) {\n const projectRoot = context?.worktree || defaultProjectRoot;\n const inputPath = args.path.trim();\n\n const normalizedPath = path.resolve(\n path.isAbsolute(inputPath)\n ? inputPath\n : resolveKnowledgeBasePath(inputPath, projectRoot)\n );\n\n if (!existsSync(normalizedPath)) {\n return `Error: Directory does not exist: ${normalizedPath}`;\n }\n\n // Resolve symlinks to get the real path for security checks only\n let realPath: string;\n try {\n realPath = realpathSync(normalizedPath);\n } catch {\n return `Error: Cannot resolve path: ${normalizedPath}`;\n }\n\n // Security: block sensitive system directories (check against real path to prevent symlink bypass)\n const blockedPrefixes = [\n \"/etc\",\n \"/proc\",\n \"/sys\",\n \"/dev\",\n \"/boot\",\n \"/root\",\n \"/var/run\",\n \"/var/log\",\n ];\n const homeDir = os.homedir();\n const sensitiveDotDirs = [\".ssh\", \".gnupg\", \".aws\", \".config/gcloud\", \".docker\", \".kube\"];\n\n for (const prefix of blockedPrefixes) {\n if (realPath === prefix || realPath.startsWith(prefix + \"/\")) {\n return `Error: Adding system directory as knowledge base is not allowed: ${normalizedPath}`;\n }\n }\n\n for (const dotDir of sensitiveDotDirs) {\n const sensitiveDir = path.join(homeDir, dotDir);\n if (realPath === sensitiveDir || realPath.startsWith(sensitiveDir + \"/\")) {\n return `Error: Adding sensitive directory as knowledge base is not allowed: ${normalizedPath}`;\n }\n }\n\n try {\n const stat = statSync(normalizedPath);\n if (!stat.isDirectory()) {\n return `Error: Path is not a directory: ${normalizedPath}`;\n }\n } catch (error) {\n return `Error: Cannot access directory: ${normalizedPath} - ${error instanceof Error ? error.message : String(error)}`;\n }\n\n const config = loadEditableConfig(projectRoot);\n const knowledgeBases: string[] = ensureStringArray(config.knowledgeBases);\n\n const alreadyExists = hasMatchingKnowledgeBasePath(knowledgeBases, normalizedPath, projectRoot);\n\n if (alreadyExists) {\n return `Knowledge base already configured: ${normalizedPath}`;\n }\n\n knowledgeBases.push(normalizedPath);\n config.knowledgeBases = knowledgeBases;\n saveConfig(projectRoot, config);\n refreshIndexerForDirectory(projectRoot);\n\n let result = `${normalizedPath}\\n`;\n result += `Total knowledge bases: ${knowledgeBases.length}\\n`;\n result += `Config saved to: ${getConfigPath(projectRoot)}\\n`;\n result += `\\nRun /index to rebuild the index with the new knowledge base.`;\n\n return result;\n },\n});\n\nexport const list_knowledge_bases: ToolDefinition = tool({\n description:\n \"List all configured knowledge base folders that are indexed alongside the main project.\",\n args: {},\n async execute(_args, context) {\n const projectRoot = context?.worktree || defaultProjectRoot;\n const config = loadRuntimeConfig(projectRoot);\n const knowledgeBases: string[] = ensureStringArray(config.knowledgeBases);\n\n if (knowledgeBases.length === 0) {\n return \"No knowledge bases configured. Use add_knowledge_base to add folders.\";\n }\n\n let result = `Knowledge Bases (${knowledgeBases.length}):\\n\\n`;\n\n for (let i = 0; i < knowledgeBases.length; i++) {\n const kb = knowledgeBases[i];\n const resolvedPath = resolveKnowledgeBasePath(kb, projectRoot);\n const exists = existsSync(resolvedPath);\n\n result += `[${i + 1}] ${kb}\\n`;\n result += ` Resolved: ${resolvedPath}\\n`;\n result += ` Status: ${exists ? \"Exists\" : \"NOT FOUND\"}\\n`;\n if (exists) {\n try {\n const stat = statSync(resolvedPath);\n result += ` Type: ${stat.isDirectory() ? \"Directory\" : \"File\"}\\n`;\n } catch { /* ignore */ }\n }\n result += \"\\n\";\n }\n\n result += `Config file: ${getConfigPath(projectRoot)}`;\n return result;\n },\n});\n\nexport const remove_knowledge_base: ToolDefinition = tool({\n description:\n \"Remove a knowledge base folder from the semantic search index.\",\n args: {\n path: z.string().describe(\"Path of the knowledge base to remove (must match the configured path exactly)\"),\n },\n async execute(args, context) {\n const projectRoot = context?.worktree || defaultProjectRoot;\n const inputPath = args.path.trim();\n\n const config = loadEditableConfig(projectRoot);\n const knowledgeBases: string[] = ensureStringArray(config.knowledgeBases);\n\n if (knowledgeBases.length === 0) {\n return \"No knowledge bases configured.\";\n }\n\n const index = findKnowledgeBasePathIndex(knowledgeBases, inputPath, projectRoot);\n\n if (index === -1) {\n let result = `Knowledge base not found: ${inputPath}\\n\\n`;\n result += `Currently configured:\\n`;\n for (const kb of knowledgeBases) {\n result += ` - ${kb}\\n`;\n }\n return result;\n }\n\n const removed = knowledgeBases.splice(index, 1)[0];\n config.knowledgeBases = knowledgeBases;\n saveConfig(projectRoot, config);\n refreshIndexerForDirectory(projectRoot);\n\n let result = `Removed: ${removed}\\n\\n`;\n result += `Remaining knowledge bases: ${knowledgeBases.length}\\n`;\n result += `Config saved to: ${getConfigPath(projectRoot)}\\n`;\n result += `\\nRun /index to rebuild the index without the removed knowledge base.`;\n\n return result;\n },\n});\n","import { existsSync, readFileSync, writeFileSync, renameSync, unlinkSync, mkdirSync, promises as fsPromises } from \"fs\";\nimport * as path from \"path\";\nimport { performance } from \"perf_hooks\";\nimport PQueue from \"p-queue\";\nimport pRetry from \"p-retry\";\n\nimport { ParsedCodebaseIndexConfig, type RerankerConfig } from \"../config/schema.js\";\nimport { detectEmbeddingProvider, ConfiguredProviderInfo, tryDetectProvider, createCustomProviderInfo } from \"../embeddings/detector.js\";\nimport {\n createEmbeddingProvider,\n EmbeddingProviderInterface,\n CustomProviderNonRetryableError,\n} from \"../embeddings/provider.js\";\nimport { createReranker, RerankerInterface } from \"../rerank/index.js\";\nimport { collectFiles, SkippedFile } from \"../utils/files.js\";\nimport { createCostEstimate, CostEstimate } from \"../utils/cost.js\";\nimport { Logger, initializeLogger } from \"../utils/logger.js\";\nimport {\n VectorStore,\n InvertedIndex,\n Database,\n parseFiles,\n createEmbeddingTexts,\n generateChunkId,\n generateChunkHash,\n ChunkMetadata,\n ChunkData,\n createDynamicBatches,\n hashFile,\n hashContent,\n extractCalls,\n parseFileAsText,\n estimateTokens,\n} from \"../native/index.js\";\nimport type { SymbolData, CallEdgeData, PathHopData } from \"../native/index.js\";\nimport { getBranchOrDefault, getBaseBranch, isGitRepo } from \"../git/index.js\";\nimport { resolveProjectIndexPath } from \"../config/paths.js\";\n\nexport const CALL_GRAPH_LANGUAGES = new Set([\"typescript\", \"tsx\", \"javascript\", \"jsx\", \"python\", \"go\", \"rust\", \"php\", \"apex\", \"zig\", \"gdscript\", \"matlab\"]);\n// Languages whose identifiers are case-insensitive at the language level.\n// The Rust call_extractor lowercases callee names for these languages (except\n// constructors and imports), so same-file resolution in this file must use\n// the same normalization when looking up symbols by name. Keep this set in\n// sync with the matching branch in native/src/call_extractor.rs.\nexport const CASE_INSENSITIVE_LANGUAGES = new Set([\"apex\"]);\nexport const CALL_GRAPH_SYMBOL_CHUNK_TYPES = new Set([\n \"function_declaration\",\n \"function\",\n \"arrow_function\",\n \"method_definition\",\n \"class_declaration\",\n \"interface_declaration\",\n \"type_alias_declaration\",\n \"enum_declaration\",\n \"function_definition\",\n \"class_definition\",\n \"decorated_definition\",\n \"method_declaration\",\n \"type_declaration\",\n \"type_spec\",\n \"function_item\",\n \"impl_item\",\n \"struct_item\",\n \"enum_item\",\n \"trait_item\",\n \"mod_item\",\n \"trait_declaration\",\n \"trigger_declaration\",\n \"test_declaration\",\n \"struct_declaration\",\n \"union_declaration\",\n // GDScript declarations whose names participate in the call graph.\n // `function_definition` and `class_definition` are already in the set\n // above (shared with Python/C/Bash and Python, respectively).\n \"constructor_definition\",\n \"enum_definition\",\n \"signal_statement\",\n \"const_statement\",\n \"class_name_statement\",\n]);\n\nfunction float32ArrayToBuffer(arr: number[]): Buffer {\n const float32 = new Float32Array(arr);\n return Buffer.from(float32.buffer);\n}\n\nfunction bufferToFloat32Array(buf: Buffer): Float32Array {\n return new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);\n}\n\nfunction getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error && typeof error === \"object\" && \"message\" in error) {\n return String((error as { message: unknown }).message);\n }\n return String(error);\n}\n\nfunction isRateLimitError(error: unknown): boolean {\n const message = getErrorMessage(error);\n return message.includes(\"429\") || message.toLowerCase().includes(\"rate limit\") || message.toLowerCase().includes(\"too many requests\");\n}\n\nfunction getSafeEmbeddingChunkTokenLimit(provider: ConfiguredProviderInfo): number {\n const providerMaxTokens = provider.modelInfo.maxTokens;\n const maxChunkTokens = Math.max(256, Math.floor(providerMaxTokens * 0.75));\n return Math.min(2000, maxChunkTokens);\n}\n\nfunction getDynamicBatchOptions(provider: ConfiguredProviderInfo): { maxBatchTokens?: number; maxBatchItems?: number } {\n if (provider.provider === \"ollama\") {\n return {\n maxBatchTokens: provider.modelInfo.maxTokens,\n maxBatchItems: 1,\n };\n }\n\n return {};\n}\n\nfunction isSqliteCorruptionError(error: unknown): boolean {\n const message = getErrorMessage(error).toLowerCase();\n return message.includes(\"database disk image is malformed\")\n || message.includes(\"file is not a database\")\n || message.includes(\"database schema is corrupt\")\n || message.includes(\"sqlite_corrupt\");\n}\n\nexport interface IndexStats {\n totalFiles: number;\n totalChunks: number;\n indexedChunks: number;\n failedChunks: number;\n tokensUsed: number;\n durationMs: number;\n existingChunks: number;\n removedChunks: number;\n skippedFiles: SkippedFile[];\n parseFailures: string[];\n failedBatchesPath?: string;\n warning?: string;\n resetCorruptedIndex?: boolean;\n}\n\ninterface CorruptedIndexResetResult {\n warning: string;\n resetCorruptedIndex: true;\n}\n\nexport interface SearchResult {\n filePath: string;\n startLine: number;\n endLine: number;\n content: string;\n score: number;\n chunkType: string;\n name?: string;\n}\n\nexport interface HealthCheckResult {\n removed: number;\n filePaths: string[];\n gcOrphanEmbeddings: number;\n gcOrphanChunks: number;\n gcOrphanSymbols: number;\n gcOrphanCallEdges: number;\n warning?: string;\n resetCorruptedIndex?: boolean;\n}\n\nexport interface StatusResult {\n indexed: boolean;\n vectorCount: number;\n provider: string;\n model: string;\n indexPath: string;\n currentBranch: string;\n baseBranch: string;\n compatibility: IndexCompatibility | null;\n failedBatchesCount: number;\n failedBatchesPath?: string;\n warning?: string;\n}\n\nconst STARTUP_WARNING_METADATA_KEY = \"index.startupWarning\";\n\nexport interface IndexProgress {\n phase: \"scanning\" | \"parsing\" | \"embedding\" | \"storing\" | \"complete\";\n filesProcessed: number;\n totalFiles: number;\n chunksProcessed: number;\n totalChunks: number;\n currentFile?: string;\n}\n\nexport type ProgressCallback = (progress: IndexProgress) => void;\n\ninterface PendingChunk {\n id: string;\n texts: Array<{\n text: string;\n tokenCount: number;\n }>;\n storageText: string;\n content: string;\n contentHash: string;\n metadata: ChunkMetadata;\n}\n\ninterface PendingEmbeddingRequest {\n chunk: PendingChunk;\n partIndex: number;\n text: string;\n tokenCount: number;\n}\n\ninterface FailedBatch {\n chunks: PendingChunk[];\n error: string;\n attemptCount: number;\n lastAttempt: string;\n}\n\ninterface RetryableFailedChunk {\n chunk: PendingChunk;\n attemptCount: number;\n}\n\ninterface SerializedFailedBatch {\n chunks: unknown[];\n error: string;\n attemptCount: number;\n lastAttempt: string;\n}\n\ntype RankedCandidate = { id: string; score: number; metadata: ChunkMetadata };\n\ninterface RerankDocumentPayload {\n id: string;\n text: string;\n}\n\ntype ExternalRerankBand = \"implementation\" | \"documentation\" | \"test\" | \"other\";\n\ninterface HybridRankOptions {\n fusionStrategy: \"weighted\" | \"rrf\";\n rrfK: number;\n rerankTopN: number;\n limit: number;\n hybridWeight: number;\n}\n\ninterface SemanticRankOptions {\n rerankTopN: number;\n limit: number;\n prioritizeSourcePaths?: boolean;\n}\n\ninterface IndexMetadata {\n indexVersion: string;\n embeddingProvider: string;\n embeddingModel: string;\n embeddingDimensions: number;\n embeddingStrategyVersion: string;\n createdAt: string;\n updatedAt: string;\n}\n\nenum IncompatibilityCode {\n DIMENSION_MISMATCH = \"DIMENSION_MISMATCH\",\n MODEL_MISMATCH = \"MODEL_MISMATCH\",\n EMBEDDING_STRATEGY_MISMATCH = \"EMBEDDING_STRATEGY_MISMATCH\",\n}\n\ninterface IndexCompatibility {\n compatible: boolean;\n code?: IncompatibilityCode;\n reason?: string;\n storedMetadata?: IndexMetadata;\n}\n\nconst INDEX_METADATA_VERSION = \"1\";\nconst EMBEDDING_STRATEGY_VERSION = \"2\";\nconst RANKING_TOKEN_CACHE_LIMIT = 4096;\nconst RANK_HYBRID_CACHE_LIMIT = 256;\n\nfunction createPendingChunkStorageText(texts: PendingChunk[\"texts\"]): string {\n const primaryText = texts[0]?.text ?? \"\";\n if (texts.length <= 1) {\n return primaryText;\n }\n\n return `${primaryText}\\n\\n... [split into ${texts.length} parts for embedding]`;\n}\n\nfunction normalizePendingChunk(rawChunk: unknown, maxChunkTokens?: number): PendingChunk | null {\n if (!rawChunk || typeof rawChunk !== \"object\") {\n return null;\n }\n\n const chunk = rawChunk as {\n id?: unknown;\n text?: unknown;\n texts?: Array<{ text?: unknown; tokenCount?: unknown }>;\n storageText?: unknown;\n content?: unknown;\n contentHash?: unknown;\n metadata?: unknown;\n };\n\n if (typeof chunk.id !== \"string\" || typeof chunk.contentHash !== \"string\" || !chunk.metadata || typeof chunk.metadata !== \"object\") {\n return null;\n }\n\n const texts = Array.isArray(chunk.texts)\n ? chunk.texts\n .map((entry) => {\n if (!entry || typeof entry.text !== \"string\") {\n return null;\n }\n\n return {\n text: entry.text,\n tokenCount: typeof entry.tokenCount === \"number\" && Number.isFinite(entry.tokenCount)\n ? entry.tokenCount\n : estimateTokens(entry.text),\n };\n })\n .filter((entry): entry is PendingChunk[\"texts\"][number] => entry !== null)\n : [];\n\n if (texts.length === 0 && typeof chunk.text === \"string\") {\n if (typeof chunk.content === \"string\" && chunk.content.length > 0 && chunk.metadata && typeof chunk.metadata === \"object\") {\n const metadata = chunk.metadata as Partial<ChunkMetadata>;\n const rebuiltChunk = {\n content: chunk.content,\n startLine: typeof metadata.startLine === \"number\" ? metadata.startLine : 1,\n endLine: typeof metadata.endLine === \"number\" ? metadata.endLine : 1,\n chunkType: typeof metadata.chunkType === \"string\" ? metadata.chunkType : \"other\",\n name: typeof metadata.name === \"string\" ? metadata.name : undefined,\n language: typeof metadata.language === \"string\" ? metadata.language : \"text\",\n };\n const filePath = typeof metadata.filePath === \"string\" ? metadata.filePath : \"unknown\";\n texts.push(\n ...createEmbeddingTexts(rebuiltChunk, filePath, maxChunkTokens).map((text) => ({\n text,\n tokenCount: estimateTokens(text),\n }))\n );\n } else {\n texts.push({\n text: chunk.text,\n tokenCount: estimateTokens(chunk.text),\n });\n }\n }\n\n if (texts.length === 0) {\n return null;\n }\n\n return {\n id: chunk.id,\n texts,\n storageText: typeof chunk.storageText === \"string\" ? chunk.storageText : createPendingChunkStorageText(texts),\n content: typeof chunk.content === \"string\" ? chunk.content : \"\",\n contentHash: chunk.contentHash,\n metadata: chunk.metadata as ChunkMetadata,\n };\n}\n\nfunction getPendingChunkFilePath(rawChunk: unknown): string | null {\n if (!rawChunk || typeof rawChunk !== \"object\") {\n return null;\n }\n\n const chunk = rawChunk as { metadata?: unknown };\n if (!chunk.metadata || typeof chunk.metadata !== \"object\") {\n return null;\n }\n\n const metadata = chunk.metadata as { filePath?: unknown };\n return typeof metadata.filePath === \"string\" ? metadata.filePath : null;\n}\n\nfunction normalizeFailedBatch(batch: SerializedFailedBatch, maxChunkTokens?: number): FailedBatch | null {\n const chunks = batch.chunks\n .map((chunk) => normalizePendingChunk(chunk, maxChunkTokens))\n .filter((chunk): chunk is PendingChunk => chunk !== null);\n\n if (chunks.length === 0) {\n return null;\n }\n\n return {\n chunks,\n error: batch.error,\n attemptCount: batch.attemptCount,\n lastAttempt: batch.lastAttempt,\n } satisfies FailedBatch;\n}\n\nfunction createPendingEmbeddingRequests(chunks: PendingChunk[]): PendingEmbeddingRequest[] {\n return chunks.flatMap((chunk) =>\n chunk.texts.map((textPart, partIndex) => ({\n chunk,\n partIndex,\n text: textPart.text,\n tokenCount: textPart.tokenCount,\n }))\n );\n}\n\nfunction createPendingEmbeddingRequestBatches(\n chunks: PendingChunk[],\n options: { maxBatchTokens?: number; maxBatchItems?: number } = {}\n): PendingEmbeddingRequest[][] {\n return createDynamicBatches(createPendingEmbeddingRequests(chunks), options);\n}\n\nfunction getUniquePendingChunksFromRequests(requests: PendingEmbeddingRequest[]): PendingChunk[] {\n const uniqueChunks = new Map<string, PendingChunk>();\n for (const request of requests) {\n uniqueChunks.set(request.chunk.id, request.chunk);\n }\n return Array.from(uniqueChunks.values());\n}\n\nfunction coalesceFailedBatches(batches: FailedBatch[]): FailedBatch[] {\n const grouped = new Map<string, FailedBatch>();\n\n for (const batch of batches) {\n const key = `${batch.attemptCount}:${batch.lastAttempt}:${batch.error}`;\n const existing = grouped.get(key);\n if (!existing) {\n grouped.set(key, {\n ...batch,\n chunks: [...batch.chunks],\n });\n continue;\n }\n\n existing.chunks.push(...batch.chunks);\n }\n\n return Array.from(grouped.values());\n}\n\nfunction poolEmbeddingVectors(vectors: number[][], weights: number[]): number[] {\n const firstVector = vectors[0];\n if (!firstVector) {\n return [];\n }\n\n const pooled = new Array<number>(firstVector.length).fill(0);\n let totalWeight = 0;\n\n for (let index = 0; index < vectors.length; index++) {\n const vector = vectors[index];\n const weight = Math.max(1, weights[index] ?? 1);\n totalWeight += weight;\n\n for (let dimension = 0; dimension < vector.length; dimension++) {\n pooled[dimension] += vector[dimension] * weight;\n }\n }\n\n if (totalWeight === 0) {\n return firstVector;\n }\n\n return pooled.map((value) => value / totalWeight);\n}\n\nfunction hasAllEmbeddingParts(\n parts: Array<{ vector: number[]; tokenCount: number } | undefined>,\n expectedPartCount: number\n): boolean {\n if (parts.length !== expectedPartCount) {\n return false;\n }\n\n for (let index = 0; index < expectedPartCount; index++) {\n if (parts[index] === undefined) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isPathWithinRoot(filePath: string, rootPath: string): boolean {\n const normalizedFilePath = path.resolve(filePath);\n const normalizedRoot = path.resolve(rootPath);\n return normalizedFilePath === normalizedRoot || normalizedFilePath.startsWith(`${normalizedRoot}${path.sep}`);\n}\n\nconst rankingQueryTokenCache = new Map<string, Set<string>>();\nconst rankingNameTokenCache = new Map<string, Set<string>>();\nconst rankingPathTokenCache = new Map<string, Set<string>>();\nconst rankingTextTokenCache = new Map<string, Set<string>>();\nconst rankHybridResultsCache = new WeakMap<RankedCandidate[], WeakMap<RankedCandidate[], Map<string, RankedCandidate[]>>>();\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"for\", \"with\", \"from\", \"that\", \"this\", \"into\", \"using\", \"where\",\n \"what\", \"when\", \"why\", \"how\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\n \"find\", \"show\", \"get\", \"run\", \"use\", \"code\", \"function\", \"implementation\",\n \"retrieve\", \"results\", \"result\", \"search\", \"pipeline\", \"top\", \"in\", \"on\", \"of\",\n \"to\", \"by\", \"as\", \"or\", \"an\", \"a\",\n]);\n\nconst TEST_PATH_SEGMENTS = [\n \"tests/\",\n \"__tests__/\",\n \"/test/\",\n \"fixtures/\",\n \"benchmark\",\n \"README\",\n \"ARCHITECTURE\",\n \"docs/\",\n];\n\nconst IMPLEMENTATION_EXCLUDE_PATH_SEGMENTS = [\n \"tests/\",\n \"__tests__/\",\n \"/test/\",\n \"fixtures/\",\n \"benchmark\",\n \"readme\",\n \"architecture\",\n \"docs/\",\n \"examples/\",\n \"example/\",\n \".github/\",\n \"/scripts/\",\n \"/migrations/\",\n \"/generated/\",\n];\n\nconst SOURCE_INTENT_HINTS = new Set([\n \"implement\",\n \"implementation\",\n \"function\",\n \"method\",\n \"class\",\n \"logic\",\n \"algorithm\",\n \"pipeline\",\n \"indexer\",\n \"where\",\n]);\n\nconst DOC_TEST_INTENT_HINTS = new Set([\n \"test\",\n \"tests\",\n \"fixture\",\n \"fixtures\",\n \"benchmark\",\n \"readme\",\n \"docs\",\n \"documentation\",\n]);\n\nconst DOC_INTENT_HINTS = new Set([\n \"readme\",\n \"docs\",\n \"documentation\",\n \"guide\",\n \"usage\",\n]);\n\nfunction setBoundedCache(\n cache: Map<string, Set<string>>,\n key: string,\n value: Set<string>\n): void {\n if (cache.size >= RANKING_TOKEN_CACHE_LIMIT) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) {\n cache.delete(oldest);\n }\n }\n cache.set(key, value);\n}\n\nfunction tokenizeTextForRanking(text: string): Set<string> {\n if (!text) {\n return new Set<string>();\n }\n\n const lowered = text.toLowerCase();\n const cache = rankingQueryTokenCache.get(lowered) ?? rankingTextTokenCache.get(lowered);\n if (cache) {\n return cache;\n }\n\n const tokens = new Set(\n lowered\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter((token) => token.length > 1 && !STOPWORDS.has(token))\n );\n\n setBoundedCache(rankingQueryTokenCache, lowered, tokens);\n setBoundedCache(rankingTextTokenCache, lowered, tokens);\n return tokens;\n}\n\nfunction splitPathTokens(filePath: string): Set<string> {\n const lowered = filePath.toLowerCase();\n const cache = rankingPathTokenCache.get(lowered);\n if (cache) {\n return cache;\n }\n\n const normalized = lowered\n .replace(/[^a-z0-9/._-]/g, \" \")\n .split(/[/._-]+/)\n .filter((token) => token.length > 1);\n const tokens = new Set(normalized);\n setBoundedCache(rankingPathTokenCache, lowered, tokens);\n return tokens;\n}\n\nfunction splitNameTokens(name: string): Set<string> {\n if (!name) {\n return new Set<string>();\n }\n\n const lowered = name.toLowerCase();\n const cache = rankingNameTokenCache.get(lowered);\n if (cache) {\n return cache;\n }\n\n const tokens = new Set(\n lowered\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter((token) => token.length > 1)\n );\n setBoundedCache(rankingNameTokenCache, lowered, tokens);\n return tokens;\n}\n\nfunction chunkTypeBoost(chunkType: string): number {\n switch (chunkType) {\n case \"function\":\n case \"function_declaration\":\n case \"method\":\n case \"method_definition\":\n case \"class\":\n case \"class_declaration\":\n return 0.2;\n case \"interface\":\n case \"type\":\n case \"enum\":\n case \"struct\":\n case \"impl\":\n case \"trait\":\n case \"module\":\n return 0.1;\n default:\n return 0;\n }\n}\n\nfunction isTestOrDocPath(filePath: string): boolean {\n return TEST_PATH_SEGMENTS.some((segment) => filePath.includes(segment));\n}\n\nfunction isLikelyImplementationPath(filePath: string): boolean {\n const lowered = filePath.toLowerCase();\n if (IMPLEMENTATION_EXCLUDE_PATH_SEGMENTS.some((segment) => lowered.includes(segment))) {\n return false;\n }\n\n const ext = lowered.split(\".\").pop() ?? \"\";\n if ([\"md\", \"mdx\", \"txt\", \"rst\", \"adoc\", \"snap\", \"json\", \"yaml\", \"yml\", \"lock\"].includes(ext)) {\n return false;\n }\n\n return true;\n}\n\nfunction isDocumentationPath(filePath: string): boolean {\n const lowered = filePath.toLowerCase();\n const ext = lowered.split(\".\").pop() ?? \"\";\n return lowered.includes(\"readme\") || [\"md\", \"mdx\", \"rst\", \"adoc\", \"txt\"].includes(ext);\n}\n\nfunction classifyExternalRerankBand(\n candidate: RankedCandidate,\n preferSourcePaths: boolean,\n docIntent: boolean\n): ExternalRerankBand {\n const isDocOrTest = isTestOrDocPath(candidate.metadata.filePath);\n const isDocumentation = isDocumentationPath(candidate.metadata.filePath);\n const isImplementation = isLikelyImplementationPath(candidate.metadata.filePath) &&\n isImplementationChunkType(candidate.metadata.chunkType);\n\n if (preferSourcePaths) {\n if (isImplementation) return \"implementation\";\n if (isDocumentation) return \"documentation\";\n if (isDocOrTest) return \"test\";\n return \"other\";\n }\n\n if (docIntent) {\n if (isDocumentation) return \"documentation\";\n if (isImplementation) return \"implementation\";\n if (isDocOrTest) return \"test\";\n return \"other\";\n }\n\n if (isImplementation) return \"implementation\";\n if (isDocumentation) return \"documentation\";\n if (isDocOrTest) return \"test\";\n return \"other\";\n}\n\nfunction classifyQueryIntent(tokens: string[]): \"source\" | \"doc_test\" | \"neutral\" {\n const sourceIntentHits = tokens.filter((t) => SOURCE_INTENT_HINTS.has(t)).length;\n const docTestIntentHits = tokens.filter((t) => DOC_TEST_INTENT_HINTS.has(t)).length;\n\n if (sourceIntentHits === 0 && docTestIntentHits === 0) {\n return \"neutral\";\n }\n\n if (sourceIntentHits > docTestIntentHits) {\n return \"source\";\n }\n\n if (docTestIntentHits > sourceIntentHits) {\n return \"doc_test\";\n }\n\n return \"neutral\";\n}\n\nfunction classifyQueryIntentRaw(query: string): \"source\" | \"doc_test\" | \"neutral\" {\n const lowerQuery = query.toLowerCase();\n const docTestRawHits = Array.from(DOC_TEST_INTENT_HINTS).filter((hint) =>\n new RegExp(`\\\\b${hint}\\\\b`).test(lowerQuery)\n ).length;\n const sourceRawHits = [\n \"implement\",\n \"implementation\",\n \"implements\",\n \"function\",\n \"method\",\n \"class\",\n \"logic\",\n \"algorithm\",\n \"pipeline\",\n \"indexer\",\n ].filter((hint) => new RegExp(`\\\\b${hint}\\\\b`).test(lowerQuery)).length;\n\n if (docTestRawHits > sourceRawHits) {\n return \"doc_test\";\n }\n\n if (sourceRawHits > docTestRawHits && sourceRawHits > 0) {\n return \"source\";\n }\n\n const hasWhereIsPattern = /\\bwhere\\s+is\\b/.test(lowerQuery);\n const hasIdentifierHints = extractIdentifierHints(query).length > 0;\n if (hasWhereIsPattern && hasIdentifierHints && docTestRawHits === 0) {\n return \"source\";\n }\n\n const queryTokens = Array.from(tokenizeTextForRanking(query));\n return classifyQueryIntent(queryTokens);\n}\n\nfunction classifyDocIntent(tokens: string[]): \"docs\" | \"test\" | \"mixed\" | \"none\" {\n const docHits = tokens.filter((t) => DOC_INTENT_HINTS.has(t)).length;\n const testHits = tokens.filter((t) => [\"test\", \"tests\", \"fixture\", \"fixtures\", \"benchmark\"].includes(t)).length;\n\n if (docHits > 0 && testHits === 0) return \"docs\";\n if (testHits > 0 && docHits === 0) return \"test\";\n if (testHits > 0 || docHits > 0) return \"mixed\";\n return \"none\";\n}\n\nfunction isImplementationChunkType(chunkType: string): boolean {\n return [\n \"export_statement\",\n \"function\",\n \"function_declaration\",\n \"method\",\n \"method_definition\",\n \"class\",\n \"class_declaration\",\n \"interface\",\n \"type\",\n \"enum\",\n \"module\",\n ].includes(chunkType);\n}\n\nfunction extractIdentifierHints(query: string): string[] {\n const identifiers = query.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];\n return identifiers\n .filter((id) => id.length >= 3)\n .filter((id) => {\n const lower = id.toLowerCase();\n if (STOPWORDS.has(lower)) return false;\n return /[A-Z]/.test(id) || id.includes(\"_\") || id.endsWith(\"Results\") || id.endsWith(\"Result\");\n })\n .map((id) => id.toLowerCase());\n}\n\nfunction extractCodeTermHints(query: string): string[] {\n const terms = query.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];\n return terms\n .map((term) => term.toLowerCase())\n .filter((term) => term.length >= 3)\n .filter((term) => !STOPWORDS.has(term));\n}\n\nfunction normalizeIdentifierVariants(identifier: string): string[] {\n const lower = identifier.toLowerCase();\n const compact = lower.replace(/[^a-z0-9]/g, \"\");\n const snake = compact.replace(/([a-z])([A-Z])/g, \"$1_$2\").toLowerCase();\n const kebab = snake.replace(/_/g, \"-\");\n const variants = [lower, compact, snake, kebab].filter((value) => value.length > 0);\n return Array.from(new Set(variants));\n}\n\nfunction scoreIdentifierMatch(name: string | undefined, filePath: string, hints: string[]): number {\n const nameLower = (name ?? \"\").toLowerCase();\n const pathLower = filePath.toLowerCase();\n\n let best = 0;\n for (const hint of hints) {\n const variants = normalizeIdentifierVariants(hint);\n for (const variant of variants) {\n if (nameLower === variant) {\n best = Math.max(best, 1);\n } else if (nameLower.includes(variant)) {\n best = Math.max(best, 0.8);\n } else if (pathLower.includes(variant)) {\n best = Math.max(best, 0.6);\n }\n }\n }\n\n return best;\n}\n\nfunction extractPrimaryIdentifierQueryHint(query: string): string | null {\n const identifiers = extractIdentifierHints(query);\n if (identifiers.length > 0) {\n return identifiers[0] ?? null;\n }\n\n const codeTerms = extractCodeTermHints(query);\n const best = codeTerms.find((term) => term.length >= 6);\n return best ?? null;\n}\n\nconst FILE_PATH_HINT_EXTENSIONS = [\n \"ts\", \"tsx\", \"js\", \"jsx\", \"mjs\", \"cjs\", \"mts\", \"cts\",\n \"py\", \"rs\", \"go\", \"java\", \"kt\", \"kts\", \"swift\", \"rb\", \"php\",\n \"c\", \"h\", \"cc\", \"cpp\", \"cxx\", \"hpp\", \"cs\", \"scala\", \"lua\",\n \"sh\", \"bash\", \"zsh\", \"json\", \"yaml\", \"yml\", \"toml\",\n];\n\nconst FILE_PATH_HINT_SUFFIX_REGEX = new RegExp(\n \"\\\\s+\\\\bin\\\\s+[\\\"'`]?((?:\\\\.\\\\/)?(?:[A-Za-z0-9._-]+\\\\/)+[A-Za-z0-9._-]+\\\\.(?:\" +\n FILE_PATH_HINT_EXTENSIONS.join(\"|\") +\n \"))[\\\"'`]?[\\\\])}>.,;!?]*\\\\s*$\",\n \"i\"\n);\n\nfunction normalizeFilePathForHintMatch(filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\").toLowerCase().replace(/^\\.\\//, \"\");\n}\n\nfunction pathMatchesHint(filePath: string, hint: string): boolean {\n const normalizedPath = normalizeFilePathForHintMatch(filePath);\n const normalizedHint = normalizeFilePathForHintMatch(hint);\n\n return normalizedPath.endsWith(normalizedHint) ||\n normalizedPath.includes(`/${normalizedHint}`) ||\n normalizedPath.includes(normalizedHint);\n}\n\nexport function extractFilePathHint(query: string): string | null {\n const match = query.match(FILE_PATH_HINT_SUFFIX_REGEX);\n const rawPath = match?.[1];\n if (!rawPath) {\n return null;\n }\n\n return rawPath.replace(/^\\.\\//, \"\");\n}\n\nexport function stripFilePathHint(query: string): string {\n const stripped = query.replace(FILE_PATH_HINT_SUFFIX_REGEX, \"\").trim();\n return stripped.length > 0 ? stripped : query;\n}\n\nfunction buildDeterministicIdentifierPass(\n query: string,\n candidates: RankedCandidate[],\n limit: number,\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (!prioritizeSourcePaths) {\n return [];\n }\n\n const primary = extractPrimaryIdentifierQueryHint(query);\n if (!primary) {\n return [];\n }\n const filePathHint = extractFilePathHint(query);\n const primaryVariants = normalizeIdentifierVariants(primary);\n\n const hints = [primary, ...extractIdentifierHints(query), ...extractCodeTermHints(query)]\n .map((value) => value.toLowerCase())\n .filter((value, idx, arr) => value.length >= 3 && arr.indexOf(value) === idx)\n .slice(0, 8);\n\n const deterministic = candidates\n .filter((candidate) =>\n isLikelyImplementationPath(candidate.metadata.filePath) &&\n isImplementationChunkType(candidate.metadata.chunkType)\n )\n .map((candidate) => {\n const nameLower = (candidate.metadata.name ?? \"\").toLowerCase();\n const pathLower = candidate.metadata.filePath.toLowerCase();\n let maxMatch = 0;\n const nameMatchesPrimary = primaryVariants.some((variant) =>\n nameLower === variant || nameLower.replace(/[^a-z0-9]/g, \"\") === variant.replace(/[^a-z0-9]/g, \"\")\n );\n const pathMatchesFileHint = filePathHint ? pathMatchesHint(candidate.metadata.filePath, filePathHint) : false;\n\n for (const hint of hints) {\n const variants = normalizeIdentifierVariants(hint);\n for (const variant of variants) {\n if (nameLower === variant) {\n maxMatch = Math.max(maxMatch, 1);\n } else if (nameLower.includes(variant)) {\n maxMatch = Math.max(maxMatch, 0.85);\n } else if (pathLower.includes(variant)) {\n maxMatch = Math.max(maxMatch, 0.7);\n }\n }\n }\n\n if (pathMatchesFileHint && nameMatchesPrimary) {\n maxMatch = Math.max(maxMatch, 1);\n }\n\n return {\n candidate,\n maxMatch,\n pathMatchesFileHint,\n nameMatchesPrimary,\n };\n })\n .filter((entry) => entry.maxMatch >= 0.7)\n .sort((a, b) => {\n const aAnchored = a.pathMatchesFileHint && a.nameMatchesPrimary ? 1 : 0;\n const bAnchored = b.pathMatchesFileHint && b.nameMatchesPrimary ? 1 : 0;\n if (aAnchored !== bAnchored) return bAnchored - aAnchored;\n if (b.maxMatch !== a.maxMatch) return b.maxMatch - a.maxMatch;\n if (b.candidate.score !== a.candidate.score) return b.candidate.score - a.candidate.score;\n return a.candidate.id.localeCompare(b.candidate.id);\n })\n .slice(0, Math.max(limit * 2, 12));\n\n return deterministic.map((entry) => ({\n id: entry.candidate.id,\n score: entry.pathMatchesFileHint && entry.nameMatchesPrimary\n ? 0.995\n : Math.min(1, 0.9 + entry.maxMatch * 0.09),\n metadata: entry.candidate.metadata,\n }));\n}\n\nexport function fuseResultsWeighted(\n semanticResults: RankedCandidate[],\n keywordResults: RankedCandidate[],\n keywordWeight: number,\n limit: number\n): RankedCandidate[] {\n const semanticWeight = 1 - keywordWeight;\n const fusedScores = new Map<string, { score: number; metadata: ChunkMetadata }>();\n\n for (const r of semanticResults) {\n fusedScores.set(r.id, {\n score: r.score * semanticWeight,\n metadata: r.metadata,\n });\n }\n\n for (const r of keywordResults) {\n const existing = fusedScores.get(r.id);\n if (existing) {\n existing.score += r.score * keywordWeight;\n } else {\n fusedScores.set(r.id, {\n score: r.score * keywordWeight,\n metadata: r.metadata,\n });\n }\n }\n\n const results = Array.from(fusedScores.entries()).map(([id, data]) => ({\n id,\n score: data.score,\n metadata: data.metadata,\n }));\n\n results.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return results.slice(0, limit);\n}\n\nexport function fuseResultsRrf(\n semanticResults: RankedCandidate[],\n keywordResults: RankedCandidate[],\n rrfK: number,\n limit: number\n): RankedCandidate[] {\n const maxPossibleRaw = 2 / (rrfK + 1);\n const rankByIdSemantic = new Map<string, number>();\n const rankByIdKeyword = new Map<string, number>();\n const metadataById = new Map<string, ChunkMetadata>();\n\n semanticResults.forEach((result, index) => {\n rankByIdSemantic.set(result.id, index + 1);\n metadataById.set(result.id, result.metadata);\n });\n\n keywordResults.forEach((result, index) => {\n rankByIdKeyword.set(result.id, index + 1);\n if (!metadataById.has(result.id)) {\n metadataById.set(result.id, result.metadata);\n }\n });\n\n const allIds = new Set<string>([...rankByIdSemantic.keys(), ...rankByIdKeyword.keys()]);\n const fused: RankedCandidate[] = [];\n\n for (const id of allIds) {\n const semanticRank = rankByIdSemantic.get(id);\n const keywordRank = rankByIdKeyword.get(id);\n\n const semanticScore = semanticRank ? 1 / (rrfK + semanticRank) : 0;\n const keywordScore = keywordRank ? 1 / (rrfK + keywordRank) : 0;\n\n const metadata = metadataById.get(id);\n if (!metadata) continue;\n\n fused.push({\n id,\n score: maxPossibleRaw > 0 ? (semanticScore + keywordScore) / maxPossibleRaw : 0,\n metadata,\n });\n }\n\n fused.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return fused.slice(0, limit);\n}\n\nexport function rerankResults(\n query: string,\n candidates: RankedCandidate[],\n rerankTopN: number,\n options?: { prioritizeSourcePaths?: boolean }\n): RankedCandidate[] {\n if (rerankTopN <= 0 || candidates.length <= 1) {\n return candidates;\n }\n\n const topN = Math.min(rerankTopN, candidates.length);\n const queryTokens = tokenizeTextForRanking(query);\n if (queryTokens.size === 0) {\n return candidates;\n }\n\n const queryTokenList = Array.from(queryTokens);\n const docIntent = classifyDocIntent(queryTokenList);\n const preferSourcePaths = options?.prioritizeSourcePaths ?? classifyQueryIntentRaw(query) === \"source\";\n const identifierHints = extractIdentifierHints(query);\n\n const head = candidates.slice(0, topN).map((candidate, idx) => {\n const pathTokens = splitPathTokens(candidate.metadata.filePath);\n const nameTokens = splitNameTokens(candidate.metadata.name ?? \"\");\n const chunkTypeTokens = tokenizeTextForRanking(candidate.metadata.chunkType);\n let exactOrPrefixNameHits = 0;\n let pathOverlap = 0;\n let chunkTypeHits = 0;\n\n for (const token of queryTokenList) {\n if (nameTokens.has(token)) {\n exactOrPrefixNameHits += 1;\n } else {\n for (const nameToken of nameTokens) {\n if (nameToken.startsWith(token) || token.startsWith(nameToken)) {\n exactOrPrefixNameHits += 1;\n break;\n }\n }\n }\n\n if (pathTokens.has(token)) {\n pathOverlap += 1;\n }\n\n if (chunkTypeTokens.has(token)) {\n chunkTypeHits += 1;\n }\n }\n\n const likelyTestOrDoc = isTestOrDocPath(candidate.metadata.filePath);\n const lowerPath = candidate.metadata.filePath.toLowerCase();\n const lowerName = (candidate.metadata.name ?? \"\").toLowerCase();\n const hasIdentifierMatch = identifierHints.some((id) => lowerPath.includes(id) || lowerName.includes(id));\n\n const implementationPathBoost = preferSourcePaths && isLikelyImplementationPath(candidate.metadata.filePath) ? 0.08 : 0;\n const isReadmePath = candidate.metadata.filePath.toLowerCase().includes(\"readme\");\n const testDocPenalty = preferSourcePaths && likelyTestOrDoc ? 0.12 : 0;\n const readmeDocBoost = !preferSourcePaths && isReadmePath ? 0.08 : 0;\n const identifierBoost = hasIdentifierMatch ? 0.12 : 0;\n const tokenCoverage = queryTokenList.length > 0\n ? (exactOrPrefixNameHits + pathOverlap + chunkTypeHits) / queryTokenList.length\n : 0;\n const coverageBoost = Math.min(0.12, tokenCoverage * 0.06);\n\n const deterministicBoost =\n exactOrPrefixNameHits * 0.08 +\n pathOverlap * 0.03 +\n chunkTypeHits * 0.02 +\n coverageBoost +\n identifierBoost +\n implementationPathBoost -\n testDocPenalty +\n readmeDocBoost +\n chunkTypeBoost(candidate.metadata.chunkType);\n\n return {\n candidate,\n boostedScore: candidate.score + deterministicBoost,\n originalIndex: idx,\n hasIdentifierMatch,\n implementationChunk: isImplementationChunkType(candidate.metadata.chunkType),\n isLikelyImplementationPath: isLikelyImplementationPath(candidate.metadata.filePath),\n isTestOrDocPath: likelyTestOrDoc,\n isReadmePath,\n };\n });\n\n head.sort((a, b) => {\n if (b.boostedScore !== a.boostedScore) return b.boostedScore - a.boostedScore;\n if (b.candidate.score !== a.candidate.score) return b.candidate.score - a.candidate.score;\n if (a.originalIndex !== b.originalIndex) return a.originalIndex - b.originalIndex;\n return a.candidate.id.localeCompare(b.candidate.id);\n });\n\n if (preferSourcePaths) {\n head.sort((a, b) => {\n const aId = a.hasIdentifierMatch ? 1 : 0;\n const bId = b.hasIdentifierMatch ? 1 : 0;\n if (aId !== bId) return bId - aId;\n\n const aImpl = a.implementationChunk ? 1 : 0;\n const bImpl = b.implementationChunk ? 1 : 0;\n if (aImpl !== bImpl) return bImpl - aImpl;\n\n const aImplementationPath = a.isLikelyImplementationPath ? 1 : 0;\n const bImplementationPath = b.isLikelyImplementationPath ? 1 : 0;\n if (aImplementationPath !== bImplementationPath) return bImplementationPath - aImplementationPath;\n\n const aTestDoc = a.isTestOrDocPath ? 1 : 0;\n const bTestDoc = b.isTestOrDocPath ? 1 : 0;\n if (aTestDoc !== bTestDoc) return aTestDoc - bTestDoc;\n\n return 0;\n });\n } else if (docIntent === \"docs\") {\n head.sort((a, b) => {\n const aReadme = a.isReadmePath ? 1 : 0;\n const bReadme = b.isReadmePath ? 1 : 0;\n if (aReadme !== bReadme) return bReadme - aReadme;\n return 0;\n });\n }\n\n const shouldDiversify = !(preferSourcePaths && identifierHints.length > 0);\n const diversifiedHead = diversifyEntriesByFileAndSymbol(head, (entry) => entry.candidate, shouldDiversify);\n\n const tail = candidates.slice(topN);\n return [...diversifiedHead.map((entry) => entry.candidate), ...tail];\n}\n\nfunction diversifyEntriesByFileAndSymbol<T>(\n entries: T[],\n getCandidate: (entry: T) => RankedCandidate,\n enabled: boolean\n): T[] {\n if (!enabled || entries.length <= 2) {\n return entries;\n }\n\n const groups = new Map<string, T[]>();\n const groupOrder: string[] = [];\n\n for (const entry of entries) {\n const candidate = getCandidate(entry);\n const filePath = candidate.metadata.filePath;\n if (!groups.has(filePath)) {\n groups.set(filePath, []);\n groupOrder.push(filePath);\n }\n groups.get(filePath)?.push(entry);\n }\n\n const diversifiedGroups = groupOrder.map((filePath) => {\n const group = groups.get(filePath) ?? [];\n return diversifyGroupBySymbol(group, getCandidate);\n });\n\n const result: T[] = [];\n let added = true;\n let round = 0;\n while (added) {\n added = false;\n for (const group of diversifiedGroups) {\n const entry = group[round];\n if (entry !== undefined) {\n result.push(entry);\n added = true;\n }\n }\n round += 1;\n }\n\n return result;\n}\n\nfunction diversifyCandidatesByFile(candidates: RankedCandidate[], enabled: boolean): RankedCandidate[] {\n return diversifyEntriesByFileAndSymbol(candidates, (candidate) => candidate, enabled);\n}\n\nfunction diversifyGroupBySymbol<T>(\n entries: T[],\n getCandidate: (entry: T) => RankedCandidate\n): T[] {\n if (entries.length <= 2) {\n return entries;\n }\n\n const seenKeys = new Set<string>();\n const primary: T[] = [];\n const remainder: T[] = [];\n\n for (const entry of entries) {\n const key = buildDiversityKey(getCandidate(entry).metadata);\n if (!seenKeys.has(key)) {\n seenKeys.add(key);\n primary.push(entry);\n } else {\n remainder.push(entry);\n }\n }\n\n return [...primary, ...remainder];\n}\n\nfunction buildDiversityKey(metadata: ChunkMetadata): string {\n const normalizedPath = metadata.filePath.toLowerCase();\n const normalizedName = (metadata.name ?? \"\").trim().toLowerCase();\n if (normalizedName.length > 0) {\n return `${normalizedPath}#${normalizedName}`;\n }\n return normalizedPath;\n}\n\nexport function rankHybridResults(\n query: string,\n semanticResults: RankedCandidate[],\n keywordResults: RankedCandidate[],\n options: HybridRankOptions & { prioritizeSourcePaths?: boolean }\n): RankedCandidate[] {\n const prioritizeSourcePaths = options.prioritizeSourcePaths ?? classifyQueryIntentRaw(query) === \"source\";\n const cacheKey = `${query}\\u0001${options.fusionStrategy}|${options.rrfK}|${options.hybridWeight}|${options.rerankTopN}|${options.limit}|${prioritizeSourcePaths ? 1 : 0}`;\n\n let byKeyword = rankHybridResultsCache.get(semanticResults);\n if (!byKeyword) {\n byKeyword = new WeakMap<RankedCandidate[], Map<string, RankedCandidate[]>>();\n rankHybridResultsCache.set(semanticResults, byKeyword);\n }\n\n let bucket = byKeyword.get(keywordResults);\n if (!bucket) {\n bucket = new Map<string, RankedCandidate[]>();\n byKeyword.set(keywordResults, bucket);\n } else {\n const cached = bucket.get(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n const overfetchLimit = Math.max(options.limit * 4, options.limit);\n const fused = options.fusionStrategy === \"rrf\"\n ? fuseResultsRrf(semanticResults, keywordResults, options.rrfK, overfetchLimit)\n : fuseResultsWeighted(semanticResults, keywordResults, options.hybridWeight, overfetchLimit);\n\n const rerankPoolLimit = Math.max(overfetchLimit, options.rerankTopN * 3, options.limit * 6);\n const rerankPool = fused.slice(0, rerankPoolLimit);\n const ranked = rerankResults(query, rerankPool, options.rerankTopN, {\n prioritizeSourcePaths,\n });\n\n if (bucket.size >= RANK_HYBRID_CACHE_LIMIT) {\n const oldest = bucket.keys().next().value;\n if (oldest !== undefined) {\n bucket.delete(oldest);\n }\n }\n bucket.set(cacheKey, ranked);\n\n return ranked;\n}\n\nexport function rankSemanticOnlyResults(\n query: string,\n semanticResults: RankedCandidate[],\n options: SemanticRankOptions\n): RankedCandidate[] {\n const overfetchLimit = Math.max(options.limit * 4, options.limit);\n const bounded = semanticResults.slice(0, overfetchLimit);\n return rerankResults(query, bounded, options.rerankTopN, {\n prioritizeSourcePaths: options.prioritizeSourcePaths ?? false,\n });\n}\n\nfunction promoteIdentifierMatches(\n query: string,\n combined: RankedCandidate[],\n semanticCandidates: RankedCandidate[],\n keywordCandidates: RankedCandidate[],\n database?: Database,\n branchChunkIds?: Set<string> | null,\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (combined.length === 0) {\n return combined;\n }\n\n if (!prioritizeSourcePaths) {\n return combined;\n }\n\n const identifierHints = extractIdentifierHints(query);\n if (identifierHints.length === 0) {\n return combined;\n }\n\n const combinedById = new Map(combined.map((candidate) => [candidate.id, candidate]));\n const candidateUnion = new Map<string, RankedCandidate>();\n for (const candidate of semanticCandidates) {\n candidateUnion.set(candidate.id, candidate);\n }\n for (const candidate of keywordCandidates) {\n if (!candidateUnion.has(candidate.id)) {\n candidateUnion.set(candidate.id, candidate);\n }\n }\n\n if (database) {\n for (const identifier of identifierHints) {\n const symbols = database.getSymbolsByName(identifier);\n for (const symbol of symbols) {\n const chunks = database.getChunksByFile(symbol.filePath);\n for (const chunk of chunks) {\n if (branchChunkIds && !branchChunkIds.has(chunk.chunkId)) {\n continue;\n }\n\n const chunkType = ((chunk.nodeType ?? \"other\") as ChunkMetadata[\"chunkType\"]);\n if (!isImplementationChunkType(chunkType)) {\n continue;\n }\n\n if (!isLikelyImplementationPath(chunk.filePath)) {\n continue;\n }\n\n if (chunk.startLine > symbol.startLine || chunk.endLine < symbol.endLine) {\n continue;\n }\n\n const existing = combinedById.get(chunk.chunkId) ?? candidateUnion.get(chunk.chunkId);\n const metadata: ChunkMetadata = existing?.metadata ?? {\n filePath: chunk.filePath,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n chunkType,\n name: chunk.name ?? undefined,\n language: chunk.language,\n hash: chunk.contentHash,\n };\n\n const baselineScore = existing?.score ?? 0.5;\n candidateUnion.set(chunk.chunkId, {\n id: chunk.chunkId,\n score: Math.min(1, baselineScore + 0.5),\n metadata,\n });\n }\n }\n }\n }\n\n const promoted: RankedCandidate[] = [];\n for (const candidate of candidateUnion.values()) {\n const filePathLower = candidate.metadata.filePath.toLowerCase();\n const nameLower = (candidate.metadata.name ?? \"\").toLowerCase();\n const exactIdentifierMatch = identifierHints.some((hint) => nameLower === hint);\n const hasIdentifierMatch = exactIdentifierMatch || identifierHints.some((hint) =>\n nameLower.includes(hint) ||\n filePathLower.includes(hint)\n );\n\n if (!hasIdentifierMatch) {\n continue;\n }\n\n if (!isImplementationChunkType(candidate.metadata.chunkType)) {\n continue;\n }\n\n if (!isLikelyImplementationPath(candidate.metadata.filePath)) {\n continue;\n }\n\n const existing = combinedById.get(candidate.id) ?? candidate;\n const rescueBoost = exactIdentifierMatch ? 0.45 : 0.25;\n const boostedScore = Math.min(1, Math.max(existing.score, candidate.score) + rescueBoost);\n promoted.push({\n id: existing.id,\n score: boostedScore,\n metadata: existing.metadata,\n });\n }\n\n if (promoted.length === 0) {\n return combined;\n }\n\n promoted.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n\n const promotedIds = new Set(promoted.map((candidate) => candidate.id));\n const remainder = combined.filter((candidate) => !promotedIds.has(candidate.id));\n return [...promoted, ...remainder];\n}\n\nfunction buildSymbolDefinitionLane(\n query: string,\n database: Database,\n branchChunkIds: Set<string> | null,\n limit: number,\n fallbackCandidates: RankedCandidate[],\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (!prioritizeSourcePaths) {\n return [];\n }\n\n const identifierHints = extractIdentifierHints(query);\n const codeTermHints = extractCodeTermHints(query);\n if (identifierHints.length === 0 && codeTermHints.length === 0) {\n return [];\n }\n\n const symbolCandidates = new Map<string, RankedCandidate>();\n const filePathHint = extractFilePathHint(query);\n const primaryHint = extractPrimaryIdentifierQueryHint(query);\n\n const upsertChunkCandidate = (\n chunk: ReturnType<Database[\"getChunksByName\"]>[number],\n identifier: string,\n normalizedIdentifier: string,\n baseScore?: number\n ) => {\n if (branchChunkIds && !branchChunkIds.has(chunk.chunkId)) {\n return;\n }\n\n const chunkType = (chunk.nodeType ?? \"other\") as ChunkMetadata[\"chunkType\"];\n if (!isImplementationChunkType(chunkType)) {\n return;\n }\n\n if (!isLikelyImplementationPath(chunk.filePath)) {\n return;\n }\n\n const nameLower = (chunk.name ?? \"\").toLowerCase();\n const exactName =\n nameLower === identifier ||\n nameLower.replace(/_/g, \"\") === normalizedIdentifier;\n const base = baseScore ?? (exactName ? 0.99 : 0.88);\n\n const existing = symbolCandidates.get(chunk.chunkId);\n if (!existing || base > existing.score) {\n symbolCandidates.set(chunk.chunkId, {\n id: chunk.chunkId,\n score: base,\n metadata: {\n filePath: chunk.filePath,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n chunkType,\n name: chunk.name ?? undefined,\n language: chunk.language,\n hash: chunk.contentHash,\n },\n });\n }\n };\n\n const normalizedHints = identifierHints\n .flatMap((hint) => [\n hint,\n hint.replace(/_/g, \"\"),\n hint.replace(/_/g, \"-\")\n ])\n .filter((hint, idx, arr) => hint.length >= 3 && arr.indexOf(hint) === idx)\n .slice(0, 6);\n\n for (const identifier of normalizedHints) {\n const symbols = [\n ...database.getSymbolsByName(identifier),\n ...database.getSymbolsByNameCi(identifier),\n ];\n\n const chunksByName = [\n ...database.getChunksByName(identifier),\n ...database.getChunksByNameCi(identifier),\n ];\n\n const normalizedIdentifier = identifier.replace(/_/g, \"\");\n\n const dedupSymbols = new Map<string, typeof symbols[number]>();\n for (const symbol of symbols) {\n dedupSymbols.set(symbol.id, symbol);\n }\n\n for (const symbol of dedupSymbols.values()) {\n const chunks = database.getChunksByFile(symbol.filePath);\n for (const chunk of chunks) {\n if (chunk.startLine > symbol.startLine || chunk.endLine < symbol.endLine) {\n continue;\n }\n\n upsertChunkCandidate(chunk, identifier, normalizedIdentifier);\n }\n }\n\n const dedupChunksByName = new Map<string, typeof chunksByName[number]>();\n for (const chunk of chunksByName) {\n dedupChunksByName.set(chunk.chunkId, chunk);\n }\n\n for (const chunk of dedupChunksByName.values()) {\n upsertChunkCandidate(chunk, identifier, normalizedIdentifier);\n }\n }\n\n if (filePathHint && primaryHint) {\n const primaryChunks = [\n ...database.getChunksByName(primaryHint),\n ...database.getChunksByNameCi(primaryHint),\n ];\n const dedupPrimaryChunks = new Map<string, typeof primaryChunks[number]>();\n for (const chunk of primaryChunks) {\n dedupPrimaryChunks.set(chunk.chunkId, chunk);\n }\n\n for (const chunk of dedupPrimaryChunks.values()) {\n if (!pathMatchesHint(chunk.filePath, filePathHint)) {\n continue;\n }\n const normalizedPrimary = primaryHint.replace(/_/g, \"\");\n upsertChunkCandidate(chunk, primaryHint, normalizedPrimary, 1.0);\n }\n }\n\n const ranked = Array.from(symbolCandidates.values()).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n if (ranked.length === 0) {\n const implementationFallback = fallbackCandidates.filter((candidate) =>\n isImplementationChunkType(candidate.metadata.chunkType) &&\n isLikelyImplementationPath(candidate.metadata.filePath)\n );\n\n for (const candidate of implementationFallback) {\n const nameLower = (candidate.metadata.name ?? \"\").toLowerCase();\n const pathLower = candidate.metadata.filePath.toLowerCase();\n\n const exactHintMatch = normalizedHints.some((hint) => nameLower === hint || nameLower.replace(/_/g, \"\") === hint.replace(/_/g, \"\"));\n const tokenizedName = tokenizeTextForRanking(nameLower);\n const tokenHits = codeTermHints.filter((term) => tokenizedName.has(term) || pathLower.includes(term)).length;\n\n if (!exactHintMatch && tokenHits === 0) {\n continue;\n }\n\n const laneScore = exactHintMatch\n ? Math.min(1, Math.max(candidate.score, 0.97))\n : Math.min(0.95, Math.max(candidate.score, 0.82 + tokenHits * 0.03));\n symbolCandidates.set(candidate.id, {\n id: candidate.id,\n score: laneScore,\n metadata: candidate.metadata,\n });\n }\n\n if (symbolCandidates.size === 0) {\n const queryTokenSet = tokenizeTextForRanking(query);\n const rankedFallback = implementationFallback\n .map((candidate) => {\n const nameTokens = tokenizeTextForRanking(candidate.metadata.name ?? \"\");\n const pathTokens = splitPathTokens(candidate.metadata.filePath);\n let overlap = 0;\n for (const token of queryTokenSet) {\n if (nameTokens.has(token) || pathTokens.has(token)) {\n overlap += 1;\n }\n }\n const overlapScore = queryTokenSet.size > 0 ? overlap / queryTokenSet.size : 0;\n return {\n candidate,\n overlapScore,\n };\n })\n .filter((entry) => entry.overlapScore > 0)\n .sort((a, b) => b.overlapScore - a.overlapScore || b.candidate.score - a.candidate.score)\n .slice(0, Math.max(limit, 3));\n\n for (const entry of rankedFallback) {\n symbolCandidates.set(entry.candidate.id, {\n id: entry.candidate.id,\n score: Math.min(0.94, Math.max(entry.candidate.score, 0.8 + entry.overlapScore * 0.1)),\n metadata: entry.candidate.metadata,\n });\n }\n }\n }\n\n const withFallback = Array.from(symbolCandidates.values()).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return withFallback.slice(0, Math.max(limit * 2, limit));\n}\n\nfunction buildIdentifierDefinitionLane(\n query: string,\n candidates: RankedCandidate[],\n limit: number,\n prioritizeSourcePaths: boolean = classifyQueryIntentRaw(query) === \"source\"\n): RankedCandidate[] {\n if (!prioritizeSourcePaths) {\n return [];\n }\n\n const primaryHint = extractPrimaryIdentifierQueryHint(query);\n if (!primaryHint) {\n return [];\n }\n\n const hints = [primaryHint, ...extractIdentifierHints(query), ...extractCodeTermHints(query)].slice(0, 8);\n const scored = candidates\n .filter((candidate) =>\n isLikelyImplementationPath(candidate.metadata.filePath) &&\n isImplementationChunkType(candidate.metadata.chunkType)\n )\n .map((candidate) => {\n const matchScore = scoreIdentifierMatch(candidate.metadata.name, candidate.metadata.filePath, hints);\n return {\n candidate,\n matchScore,\n };\n })\n .filter((entry) => entry.matchScore > 0)\n .sort((a, b) => {\n if (b.matchScore !== a.matchScore) return b.matchScore - a.matchScore;\n if (b.candidate.score !== a.candidate.score) return b.candidate.score - a.candidate.score;\n return a.candidate.id.localeCompare(b.candidate.id);\n })\n .slice(0, Math.max(limit * 2, 10));\n\n return scored.map((entry) => ({\n id: entry.candidate.id,\n score: Math.min(1, 0.9 + entry.matchScore * 0.09),\n metadata: entry.candidate.metadata,\n }));\n}\n\nexport function mergeTieredResults(\n symbolLane: RankedCandidate[],\n hybridLane: RankedCandidate[],\n limit: number\n): RankedCandidate[] {\n if (symbolLane.length === 0) {\n return hybridLane.slice(0, limit);\n }\n\n const out: RankedCandidate[] = [];\n const seen = new Set<string>();\n\n for (const candidate of symbolLane) {\n if (seen.has(candidate.id)) continue;\n out.push(candidate);\n seen.add(candidate.id);\n if (out.length >= limit) return out;\n }\n\n for (const candidate of hybridLane) {\n if (seen.has(candidate.id)) continue;\n out.push(candidate);\n seen.add(candidate.id);\n if (out.length >= limit) return out;\n }\n\n return out;\n}\n\nfunction matchesSearchFilters(\n candidate: RankedCandidate,\n options: {\n fileType?: string;\n directory?: string;\n chunkType?: string;\n } | undefined,\n minScore: number\n): boolean {\n if (candidate.score < minScore) return false;\n\n if (options?.fileType) {\n const ext = candidate.metadata.filePath.split(\".\").pop()?.toLowerCase();\n if (ext !== options.fileType.toLowerCase().replace(/^\\./, \"\")) return false;\n }\n\n if (options?.directory) {\n const normalizedDir = options.directory.replace(/^\\/|\\/$/g, \"\");\n if (!candidate.metadata.filePath.includes(`/${normalizedDir}/`) &&\n !candidate.metadata.filePath.includes(`${normalizedDir}/`)) return false;\n }\n\n if (options?.chunkType && candidate.metadata.chunkType !== options.chunkType) {\n return false;\n }\n\n return true;\n}\n\nfunction unionCandidates(\n semanticCandidates: RankedCandidate[],\n keywordCandidates: RankedCandidate[]\n): RankedCandidate[] {\n const byId = new Map<string, RankedCandidate>();\n for (const candidate of semanticCandidates) {\n byId.set(candidate.id, candidate);\n }\n for (const candidate of keywordCandidates) {\n const existing = byId.get(candidate.id);\n if (!existing || candidate.score > existing.score) {\n byId.set(candidate.id, candidate);\n }\n }\n return Array.from(byId.values());\n}\n\nexport class Indexer {\n private config: ParsedCodebaseIndexConfig;\n private projectRoot: string;\n private indexPath: string;\n private store: VectorStore | null = null;\n private invertedIndex: InvertedIndex | null = null;\n private database: Database | null = null;\n private provider: EmbeddingProviderInterface | null = null;\n private configuredProviderInfo: ConfiguredProviderInfo | null = null;\n private reranker: RerankerInterface | null = null;\n private fileHashCache: Map<string, string> = new Map();\n private fileHashCachePath: string = \"\";\n private failedBatchesPath: string = \"\";\n private currentBranch: string = \"default\";\n private baseBranch: string = \"main\";\n private logger: Logger;\n private queryEmbeddingCache: Map<string, { embedding: number[]; timestamp: number }> = new Map();\n private readonly maxQueryCacheSize = 100;\n private readonly queryCacheTtlMs = 5 * 60 * 1000;\n private readonly querySimilarityThreshold = 0.85;\n private indexCompatibility: IndexCompatibility | null = null;\n private indexingLockPath: string = \"\";\n\n constructor(projectRoot: string, config: ParsedCodebaseIndexConfig) {\n this.projectRoot = projectRoot;\n this.config = config;\n this.indexPath = this.getIndexPath();\n this.fileHashCachePath = path.join(this.indexPath, \"file-hashes.json\");\n this.failedBatchesPath = path.join(this.indexPath, \"failed-batches.json\");\n this.indexingLockPath = path.join(this.indexPath, \"indexing.lock\");\n this.logger = initializeLogger(config.debug);\n }\n\n private getIndexPath(): string {\n return resolveProjectIndexPath(this.projectRoot, this.config.scope);\n }\n\n private loadFileHashCache(): void {\n if (!existsSync(this.fileHashCachePath)) {\n return;\n }\n\n try {\n const data = readFileSync(this.fileHashCachePath, \"utf-8\");\n const parsed = JSON.parse(data);\n this.fileHashCache = new Map(Object.entries(parsed));\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.warn(\"Failed to load file hash cache, resetting cache state\", {\n fileHashCachePath: this.fileHashCachePath,\n error: message,\n });\n this.fileHashCache = new Map();\n }\n }\n\n private saveFileHashCache(): void {\n const obj: Record<string, string> = {};\n for (const [k, v] of this.fileHashCache) {\n obj[k] = v;\n }\n this.atomicWriteSync(this.fileHashCachePath, JSON.stringify(obj));\n }\n\n private atomicWriteSync(targetPath: string, data: string): void {\n const tempPath = `${targetPath}.tmp`;\n mkdirSync(path.dirname(targetPath), { recursive: true });\n writeFileSync(tempPath, data);\n renameSync(tempPath, targetPath);\n }\n\n private getScopedRoots(): string[] {\n const roots = new Set<string>([path.resolve(this.projectRoot)]);\n\n for (const kbRoot of this.config.knowledgeBases) {\n roots.add(path.resolve(this.projectRoot, kbRoot));\n }\n\n return Array.from(roots);\n }\n\n private getBranchCatalogKey(): string {\n const branchName = this.currentBranch || \"default\";\n if (this.config.scope !== \"global\") {\n return branchName;\n }\n\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `${projectHash}:${branchName}`;\n }\n\n private getLegacyBranchCatalogKey(): string {\n return this.currentBranch || \"default\";\n }\n\n private getLegacyMigrationMetadataKey(): string {\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `index.globalBranchMigration.${projectHash}`;\n }\n\n private getProjectEmbeddingStrategyMetadataKey(): string {\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `index.embeddingStrategyVersion.${projectHash}`;\n }\n\n private getProjectForceReembedMetadataKey(): string {\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n return `index.forceReembed.${projectHash}`;\n }\n\n private hasProjectForceReembedPending(): boolean {\n return this.config.scope === \"global\" && this.database?.getMetadata(this.getProjectForceReembedMetadataKey()) === \"true\";\n }\n\n private hasScopedIndexedData(): boolean {\n if (!this.store || this.config.scope !== \"global\") {\n return false;\n }\n\n if (this.hasProjectForceReembedPending()) {\n return false;\n }\n\n const roots = this.getScopedRoots();\n\n if (Array.from(this.fileHashCache.keys()).some((filePath) => this.isFileInCurrentScope(filePath, roots))) {\n return true;\n }\n\n if (this.loadSerializedFailedBatches().some((batch) =>\n batch.chunks.some((chunk) => {\n const filePath = getPendingChunkFilePath(chunk);\n return filePath !== null && this.isFileInCurrentScope(filePath, roots);\n })\n )) {\n return true;\n }\n\n if (!this.database) {\n return false;\n }\n\n if (this.getBranchCatalogKeys().some((branchKey) => {\n const branchChunkIds = this.database!.getBranchChunkIds(branchKey);\n if (branchChunkIds.length > 0) {\n return true;\n }\n\n return this.database!.getBranchSymbolIds(branchKey).length > 0;\n })) {\n return true;\n }\n\n const hasAnyBranchRows = this.database.getAllBranches().some((branchKey) => {\n const branchChunkIds = this.database!.getBranchChunkIds(branchKey);\n if (branchChunkIds.length > 0) {\n return true;\n }\n\n return this.database!.getBranchSymbolIds(branchKey).length > 0;\n });\n if (hasAnyBranchRows) {\n return false;\n }\n\n return this.store.getAllMetadata().some(({ metadata }) => this.isFileInCurrentScope(metadata.filePath, roots));\n }\n\n private loadStoredEmbeddingStrategyVersion(): string | null {\n if (!this.database) {\n return null;\n }\n\n if (this.hasProjectForceReembedPending()) {\n return null;\n }\n\n if (this.config.scope !== \"global\") {\n return this.database.getMetadata(\"index.embeddingStrategyVersion\") ?? \"1\";\n }\n\n const projectVersion = this.database.getMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n if (projectVersion) {\n return projectVersion;\n }\n\n const legacySharedVersion = this.database.getMetadata(\"index.embeddingStrategyVersion\");\n if (legacySharedVersion && this.hasScopedIndexedData()) {\n return legacySharedVersion;\n }\n\n return null;\n }\n\n private getBranchCatalogKeys(): string[] {\n const primary = this.getBranchCatalogKey();\n if (this.config.scope !== \"global\") {\n return [primary];\n }\n\n if (this.database?.getMetadata(this.getLegacyMigrationMetadataKey()) === \"done\") {\n return [primary];\n }\n\n const legacy = this.getLegacyBranchCatalogKey();\n return primary === legacy ? [primary] : [primary, legacy];\n }\n\n private getBranchCatalogCleanupKeys(): string[] {\n const primary = this.getBranchCatalogKey();\n if (this.config.scope !== \"global\") {\n return [primary];\n }\n\n const legacy = this.getLegacyBranchCatalogKey();\n return primary === legacy ? [primary] : [primary, legacy];\n }\n\n private getProjectLocalScopedOwnershipIds(roots: string[]): {\n chunkIds: Set<string>;\n symbolIds: Set<string>;\n } {\n const chunkIds = new Set<string>();\n const symbolIds = new Set<string>();\n if (!this.database) {\n return { chunkIds, symbolIds };\n }\n\n const projectRootPath = path.resolve(this.projectRoot);\n const projectLocalFilePaths = new Set<string>([\n ...Array.from(this.fileHashCache.keys()).filter(\n (filePath) => this.isFileInCurrentScope(filePath, roots) && isPathWithinRoot(filePath, projectRootPath)\n ),\n ...(this.store?.getAllMetadata() ?? [])\n .map(({ metadata }) => metadata.filePath)\n .filter(\n (filePath) => this.isFileInCurrentScope(filePath, roots) && isPathWithinRoot(filePath, projectRootPath)\n ),\n ]);\n\n for (const filePath of projectLocalFilePaths) {\n for (const chunk of this.database.getChunksByFile(filePath)) {\n chunkIds.add(chunk.chunkId);\n }\n\n for (const symbol of this.database.getSymbolsByFile(filePath)) {\n symbolIds.add(symbol.id);\n }\n }\n\n return { chunkIds, symbolIds };\n }\n\n private getProjectScopedBranchCatalogCleanupKeys(projectChunkIds: string[], projectSymbolIds: string[]): string[] {\n if (this.config.scope !== \"global\") {\n return this.getBranchCatalogCleanupKeys();\n }\n\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n const keys = new Set<string>();\n const projectChunkIdSet = new Set(projectChunkIds);\n const projectSymbolIdSet = new Set(projectSymbolIds);\n\n for (const branchKey of this.database?.getAllBranches() ?? []) {\n if (branchKey.startsWith(`${projectHash}:`)) {\n keys.add(branchKey);\n continue;\n }\n\n if (branchKey.includes(\":\")) {\n continue;\n }\n\n const referencesProjectChunks = this.database?.getBranchChunkIds(branchKey).some((chunkId) => projectChunkIdSet.has(chunkId)) ?? false;\n const referencesProjectSymbols = this.database?.getBranchSymbolIds(branchKey).some((symbolId) => projectSymbolIdSet.has(symbolId)) ?? false;\n if (referencesProjectChunks || referencesProjectSymbols) {\n keys.add(branchKey);\n }\n }\n\n for (const branchKey of this.getBranchCatalogCleanupKeys()) {\n keys.add(branchKey);\n }\n\n return Array.from(keys);\n }\n\n private isFileInCurrentScope(filePath: string, roots: string[]): boolean {\n return roots.some((root) => isPathWithinRoot(filePath, root));\n }\n\n private clearScopedFileHashCache(roots: string[]): void {\n for (const filePath of Array.from(this.fileHashCache.keys())) {\n if (this.isFileInCurrentScope(filePath, roots)) {\n this.fileHashCache.delete(filePath);\n }\n }\n this.saveFileHashCache();\n }\n\n private replaceScopedFileHashCache(currentFileHashes: Map<string, string>, roots: string[]): void {\n for (const filePath of Array.from(this.fileHashCache.keys())) {\n if (this.isFileInCurrentScope(filePath, roots)) {\n this.fileHashCache.delete(filePath);\n }\n }\n\n for (const [filePath, hash] of currentFileHashes) {\n this.fileHashCache.set(filePath, hash);\n }\n\n this.saveFileHashCache();\n }\n\n private partitionFailedBatches(roots: string[], maxChunkTokens?: number): { scoped: FailedBatch[]; retained: SerializedFailedBatch[] } {\n const scoped: FailedBatch[] = [];\n const retained: SerializedFailedBatch[] = [];\n\n for (const batch of this.loadSerializedFailedBatches()) {\n const scopedChunks = batch.chunks.filter((chunk) => {\n const filePath = getPendingChunkFilePath(chunk);\n return filePath !== null && this.isFileInCurrentScope(filePath, roots);\n });\n const retainedChunks = batch.chunks.filter((chunk) => {\n const filePath = getPendingChunkFilePath(chunk);\n return filePath === null || !this.isFileInCurrentScope(filePath, roots);\n });\n\n if (scopedChunks.length > 0) {\n const normalizedBatch = normalizeFailedBatch({ ...batch, chunks: scopedChunks }, maxChunkTokens);\n if (normalizedBatch) {\n scoped.push(normalizedBatch);\n }\n }\n\n if (retainedChunks.length > 0) {\n retained.push({ ...batch, chunks: retainedChunks });\n }\n }\n\n return { scoped, retained };\n }\n\n private clearScopedFailedBatches(roots: string[]): void {\n const { retained: retainedBatches } = this.partitionFailedBatches(roots);\n this.saveFailedBatches(retainedBatches);\n }\n\n private hasForeignScopedFileHashData(roots: string[]): boolean {\n return Array.from(this.fileHashCache.keys()).some((filePath) => !this.isFileInCurrentScope(filePath, roots));\n }\n\n private hasForeignScopedFailedBatches(roots: string[]): boolean {\n const { retained } = this.partitionFailedBatches(roots);\n return retained.length > 0;\n }\n\n private hasForeignScopedBranchData(): boolean {\n if (!this.database || this.config.scope !== \"global\") {\n return false;\n }\n\n const projectHash = hashContent(path.resolve(this.projectRoot)).slice(0, 16);\n const roots = this.getScopedRoots();\n const { chunkIds: projectLocalChunkIds, symbolIds: projectLocalSymbolIds } = this.getProjectLocalScopedOwnershipIds(roots);\n\n return this.database.getAllBranches().some(\n (branchKey) => {\n const branchChunkIds = this.database!.getBranchChunkIds(branchKey);\n const branchSymbolIds = this.database!.getBranchSymbolIds(branchKey);\n const hasBranchData = branchChunkIds.length > 0 || branchSymbolIds.length > 0;\n if (!hasBranchData) {\n return false;\n }\n\n if (branchKey.startsWith(`${projectHash}:`)) {\n return false;\n }\n\n if (!branchKey.includes(\":\")) {\n const referencesCurrentProjectChunks = branchChunkIds.some((chunkId) => projectLocalChunkIds.has(chunkId));\n const referencesCurrentProjectSymbols = branchSymbolIds.some((symbolId) => projectLocalSymbolIds.has(symbolId));\n return !(referencesCurrentProjectChunks || referencesCurrentProjectSymbols);\n }\n\n return true;\n }\n );\n }\n\n private saveScopedFailedBatches(batches: FailedBatch[], roots: string[]): void {\n const { retained } = this.partitionFailedBatches(roots);\n this.saveFailedBatches([...retained, ...batches]);\n }\n\n private clearSharedIndexProjectData(\n store: VectorStore,\n invertedIndex: InvertedIndex,\n database: Database,\n roots: string[]\n ): { removedChunkIds: string[]; hasForeignData: boolean } {\n const allMetadata = store.getAllMetadata();\n const scopedEntries = allMetadata.filter(({ metadata }) => this.isFileInCurrentScope(metadata.filePath, roots));\n const filePaths = new Set<string>([\n ...Array.from(this.fileHashCache.keys()).filter((filePath) => this.isFileInCurrentScope(filePath, roots)),\n ...scopedEntries.map(({ metadata }) => metadata.filePath),\n ]);\n\n const projectRootPath = path.resolve(this.projectRoot);\n const projectLocalFilePaths = new Set<string>(\n Array.from(filePaths).filter((filePath) => isPathWithinRoot(filePath, projectRootPath))\n );\n\n const removedChunkIds = new Set<string>(scopedEntries.map(({ key }) => key));\n for (const filePath of filePaths) {\n for (const chunk of database.getChunksByFile(filePath)) {\n removedChunkIds.add(chunk.chunkId);\n }\n }\n const removedChunkIdList = Array.from(removedChunkIds);\n\n const projectLocalChunkIds = new Set<string>(\n scopedEntries\n .filter(({ metadata }) => isPathWithinRoot(metadata.filePath, projectRootPath))\n .map(({ key }) => key)\n );\n for (const filePath of projectLocalFilePaths) {\n for (const chunk of database.getChunksByFile(filePath)) {\n projectLocalChunkIds.add(chunk.chunkId);\n }\n }\n\n const symbolIds: string[] = [];\n const projectLocalSymbolIds = new Set<string>();\n for (const filePath of filePaths) {\n for (const symbol of database.getSymbolsByFile(filePath)) {\n symbolIds.push(symbol.id);\n if (projectLocalFilePaths.has(filePath)) {\n projectLocalSymbolIds.add(symbol.id);\n }\n }\n }\n\n for (const branchKey of this.getProjectScopedBranchCatalogCleanupKeys(Array.from(projectLocalChunkIds), Array.from(projectLocalSymbolIds))) {\n database.deleteBranchChunksForBranch(branchKey, removedChunkIdList);\n }\n const sharedChunkIds = new Set(database.getReferencedChunkIds(removedChunkIdList));\n const removableChunkIds = removedChunkIdList.filter((chunkId) => !sharedChunkIds.has(chunkId));\n\n if (removableChunkIds.length > 0) {\n this.rebuildVectorStoreExcludingChunkIds(store, database, removableChunkIds);\n for (const chunkId of removableChunkIds) {\n invertedIndex.removeChunk(chunkId);\n }\n }\n\n for (const branchKey of this.getProjectScopedBranchCatalogCleanupKeys(Array.from(projectLocalChunkIds), Array.from(projectLocalSymbolIds))) {\n database.deleteBranchSymbolsForBranch(branchKey, symbolIds);\n }\n const sharedSymbolIds = new Set(database.getReferencedSymbolIds(symbolIds));\n const removableSymbolIds = symbolIds.filter((symbolId) => !sharedSymbolIds.has(symbolId));\n\n database.clearCallEdgeTargetsForSymbols(removableSymbolIds);\n\n for (const filePath of filePaths) {\n const fileChunkIds = database.getChunksByFile(filePath).map((chunk) => chunk.chunkId);\n const fileSymbols = database.getSymbolsByFile(filePath);\n\n if (fileChunkIds.every((chunkId) => !sharedChunkIds.has(chunkId))) {\n database.deleteChunksByFile(filePath);\n }\n\n if (fileSymbols.every((symbol) => !sharedSymbolIds.has(symbol.id))) {\n database.deleteCallEdgesByFile(filePath);\n database.deleteSymbolsByFile(filePath);\n }\n }\n\n database.gcOrphanCallEdges();\n database.gcOrphanSymbols();\n database.gcOrphanEmbeddings();\n database.gcOrphanChunks();\n\n store.save();\n invertedIndex.save();\n\n return {\n removedChunkIds: removedChunkIdList,\n hasForeignData: allMetadata.some(({ metadata }) => !this.isFileInCurrentScope(metadata.filePath, roots)),\n };\n }\n\n private checkForInterruptedIndexing(): boolean {\n return existsSync(this.indexingLockPath);\n }\n\n private acquireIndexingLock(): void {\n const lockData = {\n startedAt: new Date().toISOString(),\n pid: process.pid,\n };\n writeFileSync(this.indexingLockPath, JSON.stringify(lockData));\n }\n\n private releaseIndexingLock(): void {\n if (existsSync(this.indexingLockPath)) {\n unlinkSync(this.indexingLockPath);\n }\n }\n\n private async recoverFromInterruptedIndexing(): Promise<void> {\n this.logger.warn(\"Detected interrupted indexing session, recovering...\");\n\n if (existsSync(this.fileHashCachePath)) {\n unlinkSync(this.fileHashCachePath);\n }\n\n await this.healthCheck();\n this.releaseIndexingLock();\n\n this.logger.info(\"Recovery complete, next index will re-process all files\");\n }\n\n private loadFailedBatches(maxChunkTokens?: number): FailedBatch[] {\n try {\n return this.loadSerializedFailedBatches()\n .map((batch) => normalizeFailedBatch(batch, maxChunkTokens))\n .filter((batch): batch is FailedBatch => batch !== null);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.warn(\"Failed to load failed batch state, skipping persisted retries\", {\n failedBatchesPath: this.failedBatchesPath,\n error: message,\n });\n return [];\n }\n }\n\n private loadSerializedFailedBatches(): SerializedFailedBatch[] {\n if (!existsSync(this.failedBatchesPath)) {\n return [];\n }\n\n const data = readFileSync(this.failedBatchesPath, \"utf-8\");\n const parsed = JSON.parse(data) as Array<{\n chunks?: unknown[];\n error?: unknown;\n attemptCount?: unknown;\n lastAttempt?: unknown;\n }>;\n\n return parsed\n .map((batch) => {\n const chunks = Array.isArray(batch.chunks) ? batch.chunks : [];\n if (chunks.length === 0) {\n return null;\n }\n\n return {\n chunks,\n error: typeof batch.error === \"string\" ? batch.error : \"Unknown embedding error\",\n attemptCount: typeof batch.attemptCount === \"number\" ? batch.attemptCount : 1,\n lastAttempt: typeof batch.lastAttempt === \"string\" ? batch.lastAttempt : new Date().toISOString(),\n } satisfies SerializedFailedBatch;\n })\n .filter((batch): batch is SerializedFailedBatch => batch !== null);\n }\n\n private saveFailedBatches(batches: SerializedFailedBatch[]): void {\n if (batches.length === 0) {\n if (existsSync(this.failedBatchesPath)) {\n try {\n unlinkSync(this.failedBatchesPath);\n } catch {\n // Ignore cleanup failures; stale diagnostics are best-effort only.\n }\n }\n return;\n }\n writeFileSync(this.failedBatchesPath, JSON.stringify(batches, null, 2));\n }\n\n private collectRetryableFailedChunks(\n currentFileHashes: Map<string, string>,\n unchangedFilePaths: Set<string>,\n maxChunkTokens?: number\n ): RetryableFailedChunk[] {\n const retryableById = new Map<string, RetryableFailedChunk>();\n\n for (const batch of this.loadFailedBatches(maxChunkTokens)) {\n for (const chunk of batch.chunks) {\n const filePath = chunk.metadata.filePath;\n if (!currentFileHashes.has(filePath)) {\n continue;\n }\n if (!unchangedFilePaths.has(filePath)) {\n continue;\n }\n\n const existing = retryableById.get(chunk.id);\n if (!existing || batch.attemptCount > existing.attemptCount) {\n retryableById.set(chunk.id, {\n chunk,\n attemptCount: batch.attemptCount,\n });\n }\n }\n }\n\n return Array.from(retryableById.values());\n }\n\n private getProviderRateLimits(provider: string): {\n concurrency: number;\n intervalMs: number;\n minRetryMs: number;\n maxRetryMs: number;\n } {\n switch (provider) {\n case \"github-copilot\":\n return { concurrency: 1, intervalMs: 4000, minRetryMs: 5000, maxRetryMs: 60000 };\n case \"openai\":\n return { concurrency: 3, intervalMs: 500, minRetryMs: 1000, maxRetryMs: 30000 };\n case \"google\":\n return { concurrency: 5, intervalMs: 200, minRetryMs: 1000, maxRetryMs: 30000 };\n case \"ollama\":\n return { concurrency: 5, intervalMs: 0, minRetryMs: 500, maxRetryMs: 5000 };\n case \"custom\": {\n // Custom providers allow user-configurable concurrency and request interval.\n // Defaults are conservative (3 concurrent, 1s interval) for cloud endpoints;\n // users running local servers should set concurrency higher and intervalMs to 0.\n const customConfig = this.config.customProvider;\n return {\n concurrency: customConfig?.concurrency ?? 3,\n intervalMs: customConfig?.requestIntervalMs ?? 1000,\n minRetryMs: 1000,\n maxRetryMs: 30000,\n };\n }\n default:\n return { concurrency: 3, intervalMs: 1000, minRetryMs: 1000, maxRetryMs: 30000 };\n }\n }\n\n private async rerankCandidatesWithApi(\n query: string,\n candidates: RankedCandidate[],\n options?: {\n definitionIntent?: boolean;\n hasIdentifierHints?: boolean;\n }\n ): Promise<RankedCandidate[]> {\n const reranker = this.config.reranker;\n if (!reranker || !reranker.enabled || candidates.length <= 1) {\n return candidates;\n }\n\n const queryTokens = Array.from(tokenizeTextForRanking(query));\n const preferSourcePaths = classifyQueryIntentRaw(query) === \"source\";\n const docIntent = classifyDocIntent(queryTokens) === \"docs\";\n\n if (options?.definitionIntent === true) {\n return candidates;\n }\n\n if (options?.hasIdentifierHints === true && preferSourcePaths && !docIntent) {\n return candidates;\n }\n\n const topN = Math.min(reranker.topN, candidates.length);\n const head = candidates.slice(0, topN);\n const tail = candidates.slice(topN);\n const grouped = new Map<ExternalRerankBand, RankedCandidate[]>([\n [\"implementation\", []],\n [\"documentation\", []],\n [\"test\", []],\n [\"other\", []],\n ]);\n\n for (const candidate of head) {\n const band = classifyExternalRerankBand(candidate, preferSourcePaths, docIntent);\n grouped.get(band)?.push(candidate);\n }\n\n const orderedBands: ExternalRerankBand[] = preferSourcePaths\n ? [\"implementation\", \"other\", \"documentation\", \"test\"]\n : docIntent\n ? [\"documentation\", \"implementation\", \"other\", \"test\"]\n : [\"implementation\", \"other\", \"documentation\", \"test\"];\n\n try {\n const rerankedHead: RankedCandidate[] = [];\n for (const band of orderedBands) {\n const bandCandidates = grouped.get(band) ?? [];\n if (bandCandidates.length <= 1) {\n rerankedHead.push(...bandCandidates);\n continue;\n }\n\n const documents = await Promise.all(\n bandCandidates.map(async (candidate) => ({\n id: candidate.id,\n text: await this.createRerankerDocumentText(candidate),\n }))\n );\n const rankedIds = await this.callExternalReranker(query, documents, reranker);\n if (rankedIds.length === 0) {\n rerankedHead.push(...bandCandidates);\n continue;\n }\n\n const order = new Map(rankedIds.map((id, index) => [id, index]));\n const bandReranked = [...bandCandidates].sort((a, b) => {\n const aRank = order.get(a.id) ?? Number.MAX_SAFE_INTEGER;\n const bRank = order.get(b.id) ?? Number.MAX_SAFE_INTEGER;\n if (aRank !== bRank) {\n return aRank - bRank;\n }\n if (b.score !== a.score) {\n return b.score - a.score;\n }\n return a.id.localeCompare(b.id);\n });\n const shouldDiversifyBand = !options?.hasIdentifierHints;\n rerankedHead.push(...diversifyCandidatesByFile(bandReranked, shouldDiversifyBand));\n }\n\n this.logger.search(\"debug\", \"Applied external reranker\", {\n provider: reranker.provider,\n model: reranker.model,\n candidateCount: head.length,\n bands: orderedBands,\n });\n\n return [...rerankedHead, ...tail];\n } catch (error) {\n this.logger.search(\"warn\", \"External reranker failed; using deterministic order\", {\n provider: reranker.provider,\n model: reranker.model,\n error: getErrorMessage(error),\n });\n return candidates;\n }\n }\n\n private async callExternalReranker(\n query: string,\n documents: RerankDocumentPayload[],\n reranker: RerankerConfig\n ): Promise<string[]> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (reranker.apiKey) {\n headers.Authorization = `Bearer ${reranker.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), reranker.timeoutMs);\n try {\n const response = await fetch(`${reranker.baseUrl}/rerank`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model: reranker.model,\n query,\n documents: documents.map((document) => document.text),\n top_n: documents.length,\n return_documents: false,\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Reranker API error: ${response.status} - ${await response.text()}`);\n }\n\n const body = await response.json() as {\n results?: Array<{ index?: number; relevance_score?: number }>;\n };\n if (!Array.isArray(body.results)) {\n throw new Error(\"Reranker API returned unexpected response format.\");\n }\n\n return body.results\n .map((result) => {\n const index = typeof result.index === \"number\" ? result.index : -1;\n return documents[index]?.id;\n })\n .filter((id): id is string => typeof id === \"string\");\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Reranker request timed out after ${reranker.timeoutMs}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async createRerankerDocumentText(candidate: RankedCandidate): Promise<string> {\n const parts = [\n `path: ${candidate.metadata.filePath}`,\n `chunk_type: ${candidate.metadata.chunkType}`,\n `language: ${candidate.metadata.language}`,\n `lines: ${candidate.metadata.startLine}-${candidate.metadata.endLine}`,\n ];\n\n if (candidate.metadata.name) {\n parts.push(`name: ${candidate.metadata.name}`);\n }\n\n const intent = isLikelyImplementationPath(candidate.metadata.filePath) ? \"implementation\" : \"doc_or_test\";\n parts.push(`intent_hint: ${intent}`);\n\n try {\n const fileContent = await fsPromises.readFile(candidate.metadata.filePath, \"utf-8\");\n const lines = fileContent.split(\"\\n\");\n const snippetStartLine = Math.max(1, candidate.metadata.startLine - 2);\n const snippetEndLine = Math.min(lines.length, candidate.metadata.endLine + 2);\n const snippet = lines.slice(snippetStartLine - 1, snippetEndLine).join(\"\\n\").trim();\n parts.push(\"snippet:\");\n parts.push(snippet.length > 0 ? snippet : \"[empty]\");\n } catch {\n parts.push(\"snippet:\");\n parts.push(\"[unavailable]\");\n }\n\n return parts.join(\"\\n\");\n }\n\n async initialize(): Promise<void> {\n if (this.config.embeddingProvider === 'custom') {\n if (!this.config.customProvider) {\n throw new Error(\"embeddingProvider is 'custom' but customProvider config is missing.\");\n }\n this.configuredProviderInfo = createCustomProviderInfo(this.config.customProvider);\n } else if (this.config.embeddingProvider === 'auto') {\n this.configuredProviderInfo = await tryDetectProvider();\n } else {\n this.configuredProviderInfo = await detectEmbeddingProvider(this.config.embeddingProvider, this.config.embeddingModel);\n }\n\n if (!this.configuredProviderInfo) {\n throw new Error(\n \"No embedding provider available. Configure GitHub Copilot, OpenAI, Google, Ollama, or a custom OpenAI-compatible endpoint.\"\n );\n }\n\n this.logger.info(\"Initializing indexer\", {\n provider: this.configuredProviderInfo.provider,\n model: this.configuredProviderInfo.modelInfo.model,\n scope: this.config.scope,\n rerankerEnabled: this.config.reranker?.enabled ?? false,\n });\n\n this.provider = createEmbeddingProvider(this.configuredProviderInfo);\n\n if (this.config.reranker?.enabled) {\n this.reranker = createReranker(this.config.reranker);\n if (this.reranker.isAvailable()) {\n this.logger.info(\"Reranker initialized\", {\n model: this.config.reranker.model,\n baseUrl: this.config.reranker.baseUrl,\n });\n }\n }\n\n await fsPromises.mkdir(this.indexPath, { recursive: true });\n\n // NOTE: Interrupted indexing recovery is deferred until after store,\n // invertedIndex, and database are initialized (see below). Running it here\n // would cause infinite recursion: recovery → healthCheck → ensureInitialized\n // → initialize (store not yet set) → recovery → ...\n\n const dimensions = this.configuredProviderInfo.modelInfo.dimensions;\n const storePath = path.join(this.indexPath, \"vectors\");\n this.store = new VectorStore(storePath, dimensions);\n\n const indexFilePath = path.join(this.indexPath, \"vectors.usearch\");\n if (existsSync(indexFilePath)) {\n this.store.load();\n }\n\n const invertedIndexPath = path.join(this.indexPath, \"inverted-index.json\");\n this.invertedIndex = new InvertedIndex(invertedIndexPath);\n try {\n this.invertedIndex.load();\n } catch {\n if (existsSync(invertedIndexPath)) {\n await fsPromises.unlink(invertedIndexPath);\n }\n this.invertedIndex = new InvertedIndex(invertedIndexPath);\n }\n\n const dbPath = path.join(this.indexPath, \"codebase.db\");\n let dbIsNew = !existsSync(dbPath);\n try {\n this.database = new Database(dbPath);\n } catch (error) {\n if (!(await this.tryResetCorruptedIndex(\"initializing index database\", error))) {\n throw error;\n }\n\n this.store = new VectorStore(storePath, dimensions);\n this.invertedIndex = new InvertedIndex(invertedIndexPath);\n this.database = new Database(dbPath);\n dbIsNew = true;\n }\n\n if (isGitRepo(this.projectRoot)) {\n this.currentBranch = getBranchOrDefault(this.projectRoot);\n this.baseBranch = getBaseBranch(this.projectRoot);\n this.logger.branch(\"info\", \"Detected git repository\", {\n currentBranch: this.currentBranch,\n baseBranch: this.baseBranch,\n });\n } else {\n this.currentBranch = \"default\";\n this.baseBranch = \"default\";\n this.logger.branch(\"debug\", \"Not a git repository, using default branch\");\n }\n\n // Recover from interrupted indexing AFTER store, invertedIndex, and database\n // are all initialized. healthCheck() calls ensureInitialized() which checks\n // these fields — if they're not set, it re-enters initialize() causing infinite\n // recursion and 70GB+ memory usage.\n if (this.checkForInterruptedIndexing()) {\n await this.recoverFromInterruptedIndexing();\n }\n\n if (dbIsNew && this.store.count() > 0) {\n this.migrateFromLegacyIndex();\n }\n\n this.loadFileHashCache();\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo);\n if (!this.indexCompatibility.compatible) {\n this.logger.warn(\"Index compatibility issue detected\", {\n reason: this.indexCompatibility.reason,\n storedMetadata: this.indexCompatibility.storedMetadata,\n configuredProviderInfo: this.configuredProviderInfo,\n });\n }\n\n // Auto-GC: Run garbage collection if enabled and interval has elapsed\n if (this.config.indexing.autoGc) {\n await this.maybeRunAutoGc();\n }\n }\n\n private async maybeRunAutoGc(): Promise<void> {\n if (!this.database) return;\n\n const lastGcTimestamp = this.database.getMetadata(\"lastGcTimestamp\");\n const now = Date.now();\n const intervalMs = this.config.indexing.gcIntervalDays * 24 * 60 * 60 * 1000;\n\n let shouldRunGc = false;\n if (!lastGcTimestamp) {\n // Never run GC before, run it now\n shouldRunGc = true;\n } else {\n const lastGcTime = parseInt(lastGcTimestamp, 10);\n if (!isNaN(lastGcTime) && now - lastGcTime > intervalMs) {\n shouldRunGc = true;\n }\n }\n\n if (shouldRunGc) {\n const result = await this.healthCheck();\n if (result.warning) {\n this.database.setMetadata(STARTUP_WARNING_METADATA_KEY, result.warning);\n } else {\n this.database.deleteMetadata(STARTUP_WARNING_METADATA_KEY);\n }\n this.database.setMetadata(\"lastGcTimestamp\", now.toString());\n }\n }\n\n private async maybeRunOrphanGc(): Promise<CorruptedIndexResetResult | null> {\n if (!this.database) return null;\n\n const stats = this.database.getStats();\n if (!stats) return null;\n\n const orphanCount = stats.embeddingCount - stats.chunkCount;\n if (orphanCount > this.config.indexing.gcOrphanThreshold) {\n try {\n this.database.gcOrphanEmbeddings();\n this.database.gcOrphanChunks();\n } catch (error) {\n if (await this.tryResetCorruptedIndex(\"running automatic orphan garbage collection\", error)) {\n return {\n resetCorruptedIndex: true,\n warning: this.getCorruptedIndexWarning(path.join(this.indexPath, \"codebase.db\")),\n };\n }\n throw error;\n }\n this.database.setMetadata(\"lastGcTimestamp\", Date.now().toString());\n }\n\n return null;\n }\n\n private rebuildVectorStoreExcludingChunkIds(\n store: VectorStore,\n database: Database,\n excludedChunkIds: Iterable<string>\n ): void {\n const excludedSet = new Set(excludedChunkIds);\n if (excludedSet.size === 0) {\n return;\n }\n\n const retainedEntries = store\n .getAllMetadata()\n .filter(({ key }) => !excludedSet.has(key));\n\n const storeBasePath = path.join(this.indexPath, \"vectors\");\n const storeIndexPath = `${storeBasePath}.usearch`;\n const storeMetadataPath = `${storeBasePath}.meta.json`;\n const backupIndexPath = `${storeIndexPath}.bak`;\n const backupMetadataPath = `${storeMetadataPath}.bak`;\n\n let backedUpIndex = false;\n let backedUpMetadata = false;\n let rebuiltCount = 0;\n let skippedCount = 0;\n\n if (existsSync(backupIndexPath)) {\n unlinkSync(backupIndexPath);\n }\n if (existsSync(backupMetadataPath)) {\n unlinkSync(backupMetadataPath);\n }\n\n try {\n if (existsSync(storeIndexPath)) {\n renameSync(storeIndexPath, backupIndexPath);\n backedUpIndex = true;\n }\n if (existsSync(storeMetadataPath)) {\n renameSync(storeMetadataPath, backupMetadataPath);\n backedUpMetadata = true;\n }\n\n store.clear();\n\n for (const { key, metadata } of retainedEntries) {\n const chunk = database.getChunk(key);\n if (!chunk) {\n skippedCount += 1;\n continue;\n }\n\n const embeddingBuffer = database.getEmbedding(chunk.contentHash);\n if (!embeddingBuffer) {\n skippedCount += 1;\n continue;\n }\n\n const vector = bufferToFloat32Array(embeddingBuffer);\n store.add(key, Array.from(vector), metadata);\n rebuiltCount += 1;\n }\n\n store.save();\n\n if (backedUpIndex && existsSync(backupIndexPath)) {\n unlinkSync(backupIndexPath);\n }\n if (backedUpMetadata && existsSync(backupMetadataPath)) {\n unlinkSync(backupMetadataPath);\n }\n\n this.logger.gc(\"info\", \"Rebuilt vector store to avoid native remove\", {\n excludedChunks: excludedSet.size,\n rebuiltChunks: rebuiltCount,\n skippedChunks: skippedCount,\n });\n } catch (error) {\n try {\n store.clear();\n } catch {\n // Ignore best-effort cleanup before restore.\n }\n\n if (existsSync(storeIndexPath)) {\n unlinkSync(storeIndexPath);\n }\n if (existsSync(storeMetadataPath)) {\n unlinkSync(storeMetadataPath);\n }\n\n if (backedUpIndex && existsSync(backupIndexPath)) {\n renameSync(backupIndexPath, storeIndexPath);\n }\n if (backedUpMetadata && existsSync(backupMetadataPath)) {\n renameSync(backupMetadataPath, storeMetadataPath);\n }\n\n if (backedUpIndex || backedUpMetadata) {\n store.load();\n }\n\n throw error;\n }\n }\n\n private getCorruptedIndexWarning(dbPath: string): string {\n if (this.config.scope === \"global\") {\n return `Detected a corrupted shared global SQLite index at ${dbPath}. Automatic repair is disabled for global scope because it may delete other projects' index data. Remove or repair the shared index manually, then rerun index_codebase with force=true.`;\n }\n\n return `Detected a corrupted local SQLite index at ${dbPath} and reset the local index. Run index_codebase to rebuild search data.`;\n }\n\n private async tryResetCorruptedIndex(stage: string, error: unknown): Promise<boolean> {\n if (!isSqliteCorruptionError(error)) {\n return false;\n }\n\n const dbPath = path.join(this.indexPath, \"codebase.db\");\n const warning = this.getCorruptedIndexWarning(dbPath);\n const errorMessage = getErrorMessage(error);\n\n if (this.config.scope === \"global\") {\n this.logger.error(\"Detected corrupted shared global index database\", {\n stage,\n dbPath,\n error: errorMessage,\n });\n throw new Error(`${warning} Original SQLite error: ${errorMessage}`);\n }\n\n this.logger.warn(\"Detected corrupted local index database, resetting local index\", {\n stage,\n dbPath,\n error: errorMessage,\n });\n\n this.store = null;\n this.invertedIndex = null;\n this.database?.close();\n this.database = null;\n this.indexCompatibility = null;\n this.fileHashCache.clear();\n\n const resetPaths = [\n path.join(this.indexPath, \"codebase.db\"),\n path.join(this.indexPath, \"codebase.db-shm\"),\n path.join(this.indexPath, \"codebase.db-wal\"),\n path.join(this.indexPath, \"vectors.usearch\"),\n path.join(this.indexPath, \"inverted-index.json\"),\n path.join(this.indexPath, \"file-hashes.json\"),\n path.join(this.indexPath, \"failed-batches.json\"),\n path.join(this.indexPath, \"indexing.lock\"),\n path.join(this.indexPath, \"vectors\"),\n ];\n\n await Promise.all(resetPaths.map(async (targetPath) => {\n try {\n await fsPromises.rm(targetPath, { recursive: true, force: true });\n } catch {\n // Best-effort cleanup. The follow-up reinitialization will recreate what it needs.\n }\n }));\n\n await fsPromises.mkdir(this.indexPath, { recursive: true });\n return true;\n }\n\n private migrateFromLegacyIndex(): void {\n if (!this.store || !this.database) return;\n\n const allMetadata = this.store.getAllMetadata();\n const chunkIds: string[] = [];\n const chunkDataBatch: ChunkData[] = [];\n\n for (const { key, metadata } of allMetadata) {\n const chunkData: ChunkData = {\n chunkId: key,\n contentHash: metadata.hash,\n filePath: metadata.filePath,\n startLine: metadata.startLine,\n endLine: metadata.endLine,\n nodeType: metadata.chunkType,\n name: metadata.name,\n language: metadata.language,\n };\n chunkDataBatch.push(chunkData);\n chunkIds.push(key);\n }\n\n if (chunkDataBatch.length > 0) {\n this.database.upsertChunksBatch(chunkDataBatch);\n }\n this.database.addChunksToBranchBatch(this.getBranchCatalogKey(), chunkIds);\n }\n\n private loadIndexMetadata(): IndexMetadata | null {\n if (!this.database) return null;\n\n const version = this.database.getMetadata(\"index.version\");\n if (!version) return null;\n\n return {\n indexVersion: version,\n embeddingProvider: this.database.getMetadata(\"index.embeddingProvider\") ?? \"\",\n embeddingModel: this.database.getMetadata(\"index.embeddingModel\") ?? \"\",\n embeddingDimensions: parseInt(this.database.getMetadata(\"index.embeddingDimensions\") ?? \"0\", 10),\n embeddingStrategyVersion: this.loadStoredEmbeddingStrategyVersion() ?? EMBEDDING_STRATEGY_VERSION,\n createdAt: this.database.getMetadata(\"index.createdAt\") ?? \"\",\n updatedAt: this.database.getMetadata(\"index.updatedAt\") ?? \"\",\n };\n }\n\n private saveIndexMetadata(provider: ConfiguredProviderInfo): void {\n if (!this.database) return;\n\n const now = new Date().toISOString();\n const existingCreatedAt = this.database.getMetadata(\"index.createdAt\");\n const completeProjectEmbeddingStrategyReset = !this.hasProjectForceReembedPending();\n\n this.database.setMetadata(\"index.version\", INDEX_METADATA_VERSION);\n this.database.setMetadata(\"index.embeddingProvider\", provider.provider);\n this.database.setMetadata(\"index.embeddingModel\", provider.modelInfo.model);\n this.database.setMetadata(\"index.embeddingDimensions\", provider.modelInfo.dimensions.toString());\n if (this.config.scope === \"global\") {\n if (completeProjectEmbeddingStrategyReset) {\n this.database.setMetadata(this.getProjectEmbeddingStrategyMetadataKey(), EMBEDDING_STRATEGY_VERSION);\n }\n this.database.setMetadata(this.getLegacyMigrationMetadataKey(), \"done\");\n if (completeProjectEmbeddingStrategyReset) {\n this.database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n }\n } else {\n this.database.setMetadata(\"index.embeddingStrategyVersion\", EMBEDDING_STRATEGY_VERSION);\n }\n this.database.setMetadata(\"index.updatedAt\", now);\n\n if (!existingCreatedAt) {\n this.database.setMetadata(\"index.createdAt\", now);\n }\n }\n\n private validateIndexCompatibility(provider: ConfiguredProviderInfo): IndexCompatibility {\n const storedMetadata = this.loadIndexMetadata();\n\n if (!storedMetadata) {\n return { compatible: true };\n }\n\n const currentProvider = provider.provider;\n const currentModel = provider.modelInfo.model;\n const currentDimensions = provider.modelInfo.dimensions;\n\n if (storedMetadata.embeddingDimensions !== currentDimensions) {\n return {\n compatible: false,\n code: IncompatibilityCode.DIMENSION_MISMATCH,\n reason: `Dimension mismatch: index has ${storedMetadata.embeddingDimensions}D vectors (${storedMetadata.embeddingProvider}/${storedMetadata.embeddingModel}), but current provider uses ${currentDimensions}D (${currentProvider}/${currentModel}). Run index_codebase with force=true to rebuild.`,\n storedMetadata,\n };\n }\n\n if (storedMetadata.embeddingModel !== currentModel) {\n return {\n compatible: false,\n code: IncompatibilityCode.MODEL_MISMATCH,\n reason: `Model mismatch: index was built with \"${storedMetadata.embeddingModel}\", but current model is \"${currentModel}\". Embeddings are incompatible. Run index_codebase with force=true to rebuild.`,\n storedMetadata,\n };\n }\n\n if (storedMetadata.embeddingStrategyVersion !== EMBEDDING_STRATEGY_VERSION) {\n return {\n compatible: false,\n code: IncompatibilityCode.EMBEDDING_STRATEGY_MISMATCH,\n reason: `Embedding strategy mismatch: index was built with embedding strategy v${storedMetadata.embeddingStrategyVersion}, but the current code requires v${EMBEDDING_STRATEGY_VERSION}. Run index_codebase with force=true to rebuild cached embeddings.`,\n storedMetadata,\n };\n }\n\n if (storedMetadata.embeddingProvider !== currentProvider) {\n this.logger.warn(\"Provider changed\", {\n storedProvider: storedMetadata.embeddingProvider,\n currentProvider,\n });\n }\n\n return {\n compatible: true,\n storedMetadata,\n };\n }\n\n checkCompatibility(): IndexCompatibility {\n if (!this.indexCompatibility) {\n if (!this.configuredProviderInfo) {\n throw new Error('No embedding provider info, you must initialize the indexer first.');\n }\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo);\n }\n return this.indexCompatibility;\n }\n\n private async ensureInitialized(): Promise<{\n store: VectorStore;\n provider: EmbeddingProviderInterface;\n invertedIndex: InvertedIndex;\n configuredProviderInfo: ConfiguredProviderInfo;\n database: Database;\n }> {\n if (!this.store || !this.provider || !this.invertedIndex || !this.configuredProviderInfo || !this.database) {\n await this.initialize();\n }\n return {\n store: this.store!,\n provider: this.provider!,\n invertedIndex: this.invertedIndex!,\n configuredProviderInfo: this.configuredProviderInfo!,\n database: this.database!,\n };\n }\n\n async estimateCost(): Promise<CostEstimate> {\n const { configuredProviderInfo } = await this.ensureInitialized();\n\n const includePatterns = [...this.config.include, ...this.config.additionalInclude];\n const { files } = await collectFiles(\n this.projectRoot,\n includePatterns,\n this.config.exclude,\n this.config.indexing.maxFileSize,\n this.config.knowledgeBases,\n { maxDepth: this.config.indexing.maxDepth, maxFilesPerDirectory: this.config.indexing.maxFilesPerDirectory }\n );\n\n return createCostEstimate(files, configuredProviderInfo);\n }\n\n async index(onProgress?: ProgressCallback): Promise<IndexStats> {\n const { store, provider, invertedIndex, database, configuredProviderInfo } = await this.ensureInitialized();\n const scopedRoots = this.config.scope === \"global\" ? this.getScopedRoots() : null;\n const branchCatalogKey = this.getBranchCatalogKey();\n const forceScopedReembed = scopedRoots !== null && database.getMetadata(this.getProjectForceReembedMetadataKey()) === \"true\";\n const failedForcedChunkIds = new Set<string>();\n\n if (!this.indexCompatibility?.compatible) {\n throw new Error(\n `${this.indexCompatibility?.reason} ` +\n `Run index_codebase with force=true to rebuild the index.`\n );\n }\n\n this.acquireIndexingLock();\n this.logger.recordIndexingStart();\n this.logger.info(\"Starting indexing\", { projectRoot: this.projectRoot });\n\n const startTime = Date.now();\n const stats: IndexStats = {\n totalFiles: 0,\n totalChunks: 0,\n indexedChunks: 0,\n failedChunks: 0,\n tokensUsed: 0,\n durationMs: 0,\n existingChunks: 0,\n removedChunks: 0,\n skippedFiles: [],\n parseFailures: [],\n };\n const failedBatchesForCurrentRun: FailedBatch[] = [];\n\n onProgress?.({\n phase: \"scanning\",\n filesProcessed: 0,\n totalFiles: 0,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n\n this.loadFileHashCache();\n\n const includePatterns = [...this.config.include, ...this.config.additionalInclude];\n const { files, skipped } = await collectFiles(\n this.projectRoot,\n includePatterns,\n this.config.exclude,\n this.config.indexing.maxFileSize,\n this.config.knowledgeBases,\n { maxDepth: this.config.indexing.maxDepth, maxFilesPerDirectory: this.config.indexing.maxFilesPerDirectory }\n );\n\n stats.totalFiles = files.length;\n stats.skippedFiles = skipped;\n\n this.logger.recordFilesScanned(files.length);\n this.logger.cache(\"debug\", \"Scanning files for changes\", {\n totalFiles: files.length,\n skippedFiles: skipped.length,\n });\n\n const changedFiles: Array<{ path: string; content: string; hash: string }> = [];\n const unchangedFilePaths = new Set<string>();\n const currentFileHashes = new Map<string, string>();\n\n for (const f of files) {\n const currentHash = hashFile(f.path);\n currentFileHashes.set(f.path, currentHash);\n\n if (this.fileHashCache.get(f.path) === currentHash) {\n unchangedFilePaths.add(f.path);\n this.logger.recordCacheHit();\n } else {\n const content = await fsPromises.readFile(f.path, \"utf-8\");\n changedFiles.push({ path: f.path, content, hash: currentHash });\n this.logger.recordCacheMiss();\n }\n }\n\n this.logger.cache(\"info\", \"File hash cache results\", {\n unchanged: unchangedFilePaths.size,\n changed: changedFiles.length,\n });\n\n onProgress?.({\n phase: \"parsing\",\n filesProcessed: 0,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n\n const parseStartTime = performance.now();\n const parsedFiles = parseFiles(changedFiles);\n const parseMs = performance.now() - parseStartTime;\n\n this.logger.recordFilesParsed(parsedFiles.length);\n this.logger.recordParseDuration(parseMs);\n this.logger.debug(\"Parsed changed files\", { parsedCount: parsedFiles.length, parseMs: parseMs.toFixed(2) });\n\n const existingChunks = new Map<string, string>();\n const existingChunksByFile = new Map<string, Set<string>>();\n for (const { key, metadata } of store.getAllMetadata()) {\n if (scopedRoots && !this.isFileInCurrentScope(metadata.filePath, scopedRoots)) {\n continue;\n }\n if (forceScopedReembed && scopedRoots && this.isFileInCurrentScope(metadata.filePath, scopedRoots)) {\n continue;\n }\n existingChunks.set(key, metadata.hash);\n const fileChunks = existingChunksByFile.get(metadata.filePath) || new Set();\n fileChunks.add(key);\n existingChunksByFile.set(metadata.filePath, fileChunks);\n }\n\n const currentChunkIds = new Set<string>();\n const currentFilePaths = new Set<string>();\n const pendingChunks: PendingChunk[] = [];\n\n for (const filePath of unchangedFilePaths) {\n currentFilePaths.add(filePath);\n const fileChunks = existingChunksByFile.get(filePath);\n if (fileChunks) {\n for (const chunkId of fileChunks) {\n currentChunkIds.add(chunkId);\n }\n }\n }\n\n const chunkDataBatch: ChunkData[] = [];\n\n for (const parsed of parsedFiles) {\n currentFilePaths.add(parsed.path);\n\n if (parsed.chunks.length === 0) {\n const relativePath = path.relative(this.projectRoot, parsed.path);\n stats.parseFailures.push(relativePath);\n }\n\n let fileChunkCount = 0;\n let chunksToProcess = parsed.chunks;\n\n if (this.config.indexing.fallbackToTextOnMaxChunks && chunksToProcess.length > this.config.indexing.maxChunksPerFile) {\n const changedFile = changedFiles.find(f => f.path === parsed.path);\n if (changedFile) {\n const textChunks = parseFileAsText(parsed.path, changedFile.content);\n chunksToProcess = textChunks;\n }\n }\n\n for (const chunk of chunksToProcess) {\n if (fileChunkCount >= this.config.indexing.maxChunksPerFile) {\n break;\n }\n\n if (this.config.indexing.semanticOnly && chunk.chunkType === \"other\") {\n continue;\n }\n\n const id = generateChunkId(parsed.path, chunk);\n const contentHash = generateChunkHash(chunk);\n currentChunkIds.add(id);\n\n chunkDataBatch.push({\n chunkId: id,\n contentHash,\n filePath: parsed.path,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n nodeType: chunk.chunkType,\n name: chunk.name,\n language: chunk.language,\n });\n\n if (existingChunks.get(id) === contentHash) {\n fileChunkCount++;\n continue;\n }\n\n const texts = createEmbeddingTexts(chunk, parsed.path, getSafeEmbeddingChunkTokenLimit(configuredProviderInfo)).map((text) => ({\n text,\n tokenCount: estimateTokens(text),\n }));\n const metadata: ChunkMetadata = {\n filePath: parsed.path,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n chunkType: chunk.chunkType,\n name: chunk.name,\n language: chunk.language,\n hash: contentHash,\n };\n\n pendingChunks.push({\n id,\n texts,\n storageText: createPendingChunkStorageText(texts),\n content: chunk.content,\n contentHash,\n metadata,\n });\n fileChunkCount++;\n }\n }\n\n const retryableFailedChunks = this.collectRetryableFailedChunks(\n currentFileHashes,\n unchangedFilePaths,\n getSafeEmbeddingChunkTokenLimit(configuredProviderInfo)\n );\n const retryableFailedAttemptCounts = new Map<string, number>();\n const retryableChunksWithExistingData = new Set<string>();\n if (retryableFailedChunks.length > 0) {\n const pendingChunkIds = new Set(pendingChunks.map((chunk) => chunk.id));\n for (const { chunk, attemptCount } of retryableFailedChunks) {\n retryableFailedAttemptCounts.set(chunk.id, attemptCount);\n if (existingChunks.has(chunk.id)) {\n retryableChunksWithExistingData.add(chunk.id);\n }\n if (!pendingChunkIds.has(chunk.id)) {\n pendingChunks.push(chunk);\n pendingChunkIds.add(chunk.id);\n currentChunkIds.add(chunk.id);\n }\n }\n }\n\n if (chunkDataBatch.length > 0) {\n database.upsertChunksBatch(chunkDataBatch);\n }\n\n const allSymbolIds = new Set<string>();\n const symbolsByFile = new Map<string, SymbolData[]>();\n\n for (let i = 0; i < parsedFiles.length; i++) {\n const parsed = parsedFiles[i];\n const changedFile = changedFiles[i];\n\n database.deleteCallEdgesByFile(parsed.path);\n database.deleteSymbolsByFile(parsed.path);\n\n const fileSymbols: SymbolData[] = [];\n\n for (const chunk of parsed.chunks) {\n if (!chunk.name || !CALL_GRAPH_SYMBOL_CHUNK_TYPES.has(chunk.chunkType)) continue;\n\n const symbolId = `sym_${hashContent(parsed.path + \":\" + chunk.name + \":\" + chunk.chunkType + \":\" + chunk.startLine).slice(0, 16)}`;\n const symbol: SymbolData = {\n id: symbolId,\n filePath: parsed.path,\n name: chunk.name,\n kind: chunk.chunkType,\n startLine: chunk.startLine,\n startCol: 0,\n endLine: chunk.endLine,\n endCol: 0,\n language: chunk.language,\n };\n fileSymbols.push(symbol);\n allSymbolIds.add(symbolId);\n }\n\n // For case-insensitive languages (e.g. Apex), the Rust call extractor\n // already lowercases non-constructor / non-import callee names, so we\n // must lowercase the symbol-map keys here too. Otherwise a declaration\n // like `MyMethod` would not match a lowercased call edge target like\n // `mymethod`, leaving same-file calls unresolved (toSymbolId = NULL).\n const fileLanguage = parsed.chunks[0]?.language;\n const isCaseInsensitiveLanguage =\n !!fileLanguage && CASE_INSENSITIVE_LANGUAGES.has(fileLanguage);\n const normalizeSymbolKey = (name: string): string =>\n isCaseInsensitiveLanguage ? name.toLowerCase() : name;\n\n const symbolsByName = new Map<string, SymbolData[]>();\n for (const symbol of fileSymbols) {\n const key = normalizeSymbolKey(symbol.name);\n const existing = symbolsByName.get(key) ?? [];\n existing.push(symbol);\n symbolsByName.set(key, existing);\n }\n\n if (fileSymbols.length > 0) {\n database.upsertSymbolsBatch(fileSymbols);\n symbolsByFile.set(parsed.path, fileSymbols);\n }\n\n if (!fileLanguage || !CALL_GRAPH_LANGUAGES.has(fileLanguage)) continue;\n\n const callSites = extractCalls(changedFile.content, fileLanguage);\n if (callSites.length === 0) continue;\n\n const edges: CallEdgeData[] = [];\n for (const site of callSites) {\n const enclosingSymbol = fileSymbols.find(\n (sym) => site.line >= sym.startLine && site.line <= sym.endLine\n );\n if (!enclosingSymbol) continue;\n\n const edgeId = `edge_${hashContent(enclosingSymbol.id + \":\" + site.calleeName + \":\" + site.line + \":\" + site.column).slice(0, 16)}`;\n edges.push({\n id: edgeId,\n fromSymbolId: enclosingSymbol.id,\n targetName: site.calleeName,\n toSymbolId: undefined,\n callType: site.callType,\n confidence: site.confidence,\n line: site.line,\n col: site.column,\n isResolved: false,\n });\n }\n\n if (edges.length > 0) {\n database.upsertCallEdgesBatch(edges);\n\n // Resolve same-file calls (with the same case-insensitivity rules\n // used to build symbolsByName above).\n for (const edge of edges) {\n const candidates = symbolsByName.get(normalizeSymbolKey(edge.targetName));\n if (candidates && candidates.length === 1) {\n database.resolveCallEdge(edge.id, candidates[0].id);\n }\n }\n }\n }\n\n for (const filePath of unchangedFilePaths) {\n const existingSymbols = database.getSymbolsByFile(filePath);\n for (const sym of existingSymbols) {\n allSymbolIds.add(sym.id);\n }\n }\n\n const removedChunkIds: string[] = [];\n for (const [chunkId] of existingChunks) {\n if (!currentChunkIds.has(chunkId)) {\n removedChunkIds.push(chunkId);\n }\n }\n\n if (removedChunkIds.length > 0) {\n this.rebuildVectorStoreExcludingChunkIds(store, database, removedChunkIds);\n for (const chunkId of removedChunkIds) {\n invertedIndex.removeChunk(chunkId);\n }\n database.deleteChunksByIds(removedChunkIds);\n }\n\n const removedCount = removedChunkIds.length;\n\n stats.totalChunks = pendingChunks.length;\n stats.existingChunks = currentChunkIds.size - pendingChunks.length;\n stats.removedChunks = removedCount;\n\n this.logger.recordChunksProcessed(currentChunkIds.size);\n this.logger.recordChunksRemoved(removedCount);\n this.logger.info(\"Chunk analysis complete\", {\n pending: pendingChunks.length,\n existing: stats.existingChunks,\n removed: removedCount,\n });\n\n if (pendingChunks.length === 0 && removedCount === 0) {\n database.clearBranch(branchCatalogKey);\n database.addChunksToBranchBatch(branchCatalogKey, Array.from(currentChunkIds));\n database.clearBranchSymbols(branchCatalogKey);\n database.addSymbolsToBranchBatch(branchCatalogKey, Array.from(allSymbolIds));\n if (scopedRoots) {\n this.replaceScopedFileHashCache(currentFileHashes, scopedRoots);\n this.clearScopedFailedBatches(scopedRoots);\n } else {\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\n this.saveFailedBatches([]);\n }\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n stats.durationMs = Date.now() - startTime;\n onProgress?.({\n phase: \"complete\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n this.releaseIndexingLock();\n return stats;\n }\n\n if (pendingChunks.length === 0) {\n database.clearBranch(branchCatalogKey);\n database.addChunksToBranchBatch(branchCatalogKey, Array.from(currentChunkIds));\n database.clearBranchSymbols(branchCatalogKey);\n database.addSymbolsToBranchBatch(branchCatalogKey, Array.from(allSymbolIds));\n store.save();\n invertedIndex.save();\n if (scopedRoots) {\n this.replaceScopedFileHashCache(currentFileHashes, scopedRoots);\n this.clearScopedFailedBatches(scopedRoots);\n } else {\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\n this.saveFailedBatches([]);\n }\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n stats.durationMs = Date.now() - startTime;\n onProgress?.({\n phase: \"complete\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: 0,\n });\n this.releaseIndexingLock();\n return stats;\n }\n\n onProgress?.({\n phase: \"embedding\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: 0,\n totalChunks: pendingChunks.length,\n });\n\n const allContentHashes = pendingChunks.map((c) => c.contentHash);\n const missingHashes = new Set(database.getMissingEmbeddings(allContentHashes));\n const forcedReembedChunkIds = forceScopedReembed\n ? new Set(pendingChunks.map((chunk) => chunk.id))\n : new Set<string>();\n\n const chunksNeedingEmbedding = pendingChunks.filter((c) => forcedReembedChunkIds.has(c.id) || missingHashes.has(c.contentHash));\n const chunksWithExistingEmbedding = pendingChunks.filter((c) => !forcedReembedChunkIds.has(c.id) && !missingHashes.has(c.contentHash));\n\n this.logger.cache(\"info\", \"Embedding cache lookup\", {\n needsEmbedding: chunksNeedingEmbedding.length,\n fromCache: chunksWithExistingEmbedding.length,\n });\n this.logger.recordChunksFromCache(chunksWithExistingEmbedding.length);\n\n for (const chunk of chunksWithExistingEmbedding) {\n const embeddingBuffer = database.getEmbedding(chunk.contentHash);\n if (embeddingBuffer) {\n const vector = bufferToFloat32Array(embeddingBuffer);\n store.add(chunk.id, Array.from(vector), chunk.metadata);\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n stats.indexedChunks++;\n }\n }\n\n const providerRateLimits = this.getProviderRateLimits(configuredProviderInfo.provider);\n const queue = new PQueue({\n concurrency: providerRateLimits.concurrency,\n interval: providerRateLimits.intervalMs,\n intervalCap: providerRateLimits.concurrency\n });\n const pendingChunksById = new Map(chunksNeedingEmbedding.map((chunk) => [chunk.id, chunk]));\n const embeddingPartsByChunk = new Map<string, Array<{ vector: number[]; tokenCount: number } | undefined>>();\n const completedChunkIds = new Set<string>();\n const failedChunkIds = new Set<string>();\n const requestBatches = createPendingEmbeddingRequestBatches(\n chunksNeedingEmbedding,\n getDynamicBatchOptions(configuredProviderInfo)\n );\n let rateLimitBackoffMs = 0;\n\n for (const requestBatch of requestBatches) {\n queue.add(async () => {\n if (rateLimitBackoffMs > 0) {\n await new Promise(resolve => setTimeout(resolve, rateLimitBackoffMs));\n }\n\n try {\n const result = await pRetry(\n async () => {\n const texts = requestBatch.map((request) => request.text);\n return provider.embedBatch(texts);\n },\n {\n retries: this.config.indexing.retries,\n minTimeout: Math.max(this.config.indexing.retryDelayMs, providerRateLimits.minRetryMs),\n maxTimeout: providerRateLimits.maxRetryMs,\n factor: 2,\n shouldRetry: (error) => !((error as { error?: Error }).error instanceof CustomProviderNonRetryableError),\n onFailedAttempt: (error) => {\n const message = getErrorMessage(error);\n if (isRateLimitError(error)) {\n rateLimitBackoffMs = Math.min(providerRateLimits.maxRetryMs, (rateLimitBackoffMs || providerRateLimits.minRetryMs) * 2);\n this.logger.embedding(\"warn\", `Rate limited, backing off`, {\n attempt: error.attemptNumber,\n retriesLeft: error.retriesLeft,\n backoffMs: rateLimitBackoffMs,\n });\n } else {\n this.logger.embedding(\"error\", `Embedding batch failed`, {\n attempt: error.attemptNumber,\n error: message,\n });\n }\n },\n }\n );\n\n if (rateLimitBackoffMs > 0) {\n rateLimitBackoffMs = Math.max(0, rateLimitBackoffMs - 2000);\n }\n\n const touchedChunkIds = new Set<string>();\n\n requestBatch.forEach((request, idx) => {\n if (failedChunkIds.has(request.chunk.id) || completedChunkIds.has(request.chunk.id)) {\n return;\n }\n\n const vector = result.embeddings[idx];\n if (!vector) {\n throw new Error(`Embedding API returned too few vectors for chunk ${request.chunk.id}`);\n }\n\n const parts = embeddingPartsByChunk.get(request.chunk.id) ?? [];\n parts[request.partIndex] = {\n vector,\n tokenCount: request.tokenCount,\n };\n embeddingPartsByChunk.set(request.chunk.id, parts);\n touchedChunkIds.add(request.chunk.id);\n });\n\n const pooledResults: Array<{ chunk: PendingChunk; vector: number[] }> = [];\n for (const chunkId of touchedChunkIds) {\n if (failedChunkIds.has(chunkId) || completedChunkIds.has(chunkId)) {\n continue;\n }\n\n const chunk = pendingChunksById.get(chunkId);\n if (!chunk) {\n continue;\n }\n\n const parts = embeddingPartsByChunk.get(chunk.id) ?? [];\n if (!hasAllEmbeddingParts(parts, chunk.texts.length)) {\n continue;\n }\n\n const orderedParts = parts as Array<{ vector: number[]; tokenCount: number }>;\n pooledResults.push({\n chunk,\n vector: poolEmbeddingVectors(\n orderedParts.map((part) => part.vector),\n orderedParts.map((part) => part.tokenCount)\n ),\n });\n }\n\n if (pooledResults.length > 0) {\n const items = pooledResults.map(({ chunk, vector }) => ({\n id: chunk.id,\n vector,\n metadata: chunk.metadata,\n }));\n\n store.addBatch(items);\n\n const embeddingBatchItems = pooledResults.map(({ chunk, vector }) => ({\n contentHash: chunk.contentHash,\n embedding: float32ArrayToBuffer(vector),\n chunkText: chunk.storageText,\n model: configuredProviderInfo.modelInfo.model,\n }));\n\n try {\n database.upsertEmbeddingsBatch(embeddingBatchItems);\n } catch (dbError) {\n this.rebuildVectorStoreExcludingChunkIds(\n store,\n database,\n pooledResults.map(({ chunk }) => chunk.id)\n );\n throw dbError;\n }\n\n for (const { chunk } of pooledResults) {\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n completedChunkIds.add(chunk.id);\n embeddingPartsByChunk.delete(chunk.id);\n }\n\n stats.indexedChunks += pooledResults.length;\n this.logger.recordChunksEmbedded(pooledResults.length);\n }\n\n stats.tokensUsed += result.totalTokensUsed;\n\n this.logger.recordEmbeddingApiCall(result.totalTokensUsed);\n this.logger.embedding(\"debug\", `Embedded batch`, {\n batchSize: pooledResults.length,\n requestCount: requestBatch.length,\n tokens: result.totalTokensUsed,\n });\n\n onProgress?.({\n phase: \"embedding\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: stats.indexedChunks,\n totalChunks: pendingChunks.length,\n });\n } catch (error) {\n const failedChunks = getUniquePendingChunksFromRequests(requestBatch)\n .filter((chunk) => !completedChunkIds.has(chunk.id));\n const failureMessage = getErrorMessage(error);\n const failureTimestamp = new Date().toISOString();\n\n for (const chunk of failedChunks) {\n if (!failedChunkIds.has(chunk.id)) {\n failedChunkIds.add(chunk.id);\n stats.failedChunks += 1;\n }\n\n if (forceScopedReembed) {\n failedForcedChunkIds.add(chunk.id);\n }\n\n embeddingPartsByChunk.delete(chunk.id);\n\n const existingFailedBatchIndex = failedBatchesForCurrentRun.findIndex(\n (failedBatch) => failedBatch.chunks[0]?.id === chunk.id\n );\n const existingFailedBatch = existingFailedBatchIndex === -1\n ? undefined\n : failedBatchesForCurrentRun[existingFailedBatchIndex];\n const failedBatch = {\n chunks: [chunk],\n error: failureMessage,\n attemptCount: (existingFailedBatch?.attemptCount ?? retryableFailedAttemptCounts.get(chunk.id) ?? 0) + 1,\n lastAttempt: failureTimestamp,\n } satisfies FailedBatch;\n\n if (existingFailedBatchIndex === -1) {\n failedBatchesForCurrentRun.push(failedBatch);\n } else {\n failedBatchesForCurrentRun[existingFailedBatchIndex] = failedBatch;\n }\n }\n\n this.logger.recordEmbeddingError();\n this.logger.embedding(\"error\", `Failed to embed batch after retries`, {\n batchSize: failedChunks.length,\n requestCount: requestBatch.length,\n error: failureMessage,\n });\n }\n });\n }\n\n await queue.onIdle();\n if (scopedRoots) {\n this.saveScopedFailedBatches(coalesceFailedBatches(failedBatchesForCurrentRun), scopedRoots);\n } else {\n this.saveFailedBatches(coalesceFailedBatches(failedBatchesForCurrentRun));\n }\n\n onProgress?.({\n phase: \"storing\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: stats.indexedChunks,\n totalChunks: pendingChunks.length,\n });\n\n const branchChunkIds = Array.from(currentChunkIds).filter(\n (chunkId) => {\n const isNewlyFailed = failedChunkIds.has(chunkId) && !retryableChunksWithExistingData.has(chunkId);\n const isForcedFailed = forceScopedReembed && failedForcedChunkIds.has(chunkId);\n return !isNewlyFailed && !isForcedFailed;\n }\n );\n database.clearBranch(branchCatalogKey);\n database.addChunksToBranchBatch(branchCatalogKey, branchChunkIds);\n database.clearBranchSymbols(branchCatalogKey);\n database.addSymbolsToBranchBatch(branchCatalogKey, Array.from(allSymbolIds));\n\n store.save();\n invertedIndex.save();\n if (scopedRoots) {\n this.replaceScopedFileHashCache(currentFileHashes, scopedRoots);\n } else {\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\n }\n\n if (this.config.indexing.autoGc && stats.removedChunks > 0) {\n const gcReset = await this.maybeRunOrphanGc();\n if (gcReset) {\n stats.durationMs = Date.now() - startTime;\n stats.warning = gcReset.warning;\n stats.resetCorruptedIndex = true;\n\n this.logger.recordIndexingEnd();\n this.logger.warn(\"Indexing ended after resetting corrupted local index during automatic GC\", {\n files: stats.totalFiles,\n indexed: stats.indexedChunks,\n existing: stats.existingChunks,\n removed: stats.removedChunks,\n failed: stats.failedChunks,\n tokens: stats.tokensUsed,\n durationMs: stats.durationMs,\n });\n\n return stats;\n }\n }\n\n stats.durationMs = Date.now() - startTime;\n\n if (forceScopedReembed && failedForcedChunkIds.size === 0) {\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n }\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n\n this.logger.recordIndexingEnd();\n this.logger.info(\"Indexing complete\", {\n files: stats.totalFiles,\n indexed: stats.indexedChunks,\n existing: stats.existingChunks,\n removed: stats.removedChunks,\n failed: stats.failedChunks,\n tokens: stats.tokensUsed,\n durationMs: stats.durationMs,\n });\n\n if (stats.failedChunks > 0) {\n stats.failedBatchesPath = this.failedBatchesPath;\n }\n\n onProgress?.({\n phase: \"complete\",\n filesProcessed: files.length,\n totalFiles: files.length,\n chunksProcessed: stats.indexedChunks,\n totalChunks: pendingChunks.length,\n });\n\n this.releaseIndexingLock();\n return stats;\n }\n\n private async getQueryEmbedding(query: string, provider: EmbeddingProviderInterface): Promise<number[]> {\n const now = Date.now();\n const cached = this.queryEmbeddingCache.get(query);\n\n if (cached && (now - cached.timestamp) < this.queryCacheTtlMs) {\n this.logger.cache(\"debug\", \"Query embedding cache hit (exact)\", { query: query.slice(0, 50) });\n this.logger.recordQueryCacheHit();\n return cached.embedding;\n }\n\n const similarMatch = this.findSimilarCachedQuery(query, now);\n if (similarMatch) {\n this.logger.cache(\"debug\", \"Query embedding cache hit (similar)\", {\n query: query.slice(0, 50),\n similarTo: similarMatch.key.slice(0, 50),\n similarity: similarMatch.similarity.toFixed(3),\n });\n this.logger.recordQueryCacheSimilarHit();\n return similarMatch.embedding;\n }\n\n this.logger.cache(\"debug\", \"Query embedding cache miss\", { query: query.slice(0, 50) });\n this.logger.recordQueryCacheMiss();\n const { embedding, tokensUsed } = await provider.embedQuery(query);\n this.logger.recordEmbeddingApiCall(tokensUsed);\n\n if (this.queryEmbeddingCache.size >= this.maxQueryCacheSize) {\n const oldestKey = this.queryEmbeddingCache.keys().next().value;\n if (oldestKey) {\n this.queryEmbeddingCache.delete(oldestKey);\n }\n }\n\n this.queryEmbeddingCache.set(query, { embedding, timestamp: now });\n return embedding;\n }\n\n private findSimilarCachedQuery(\n query: string,\n now: number\n ): { key: string; embedding: number[]; similarity: number } | null {\n const queryTokens = this.tokenize(query);\n if (queryTokens.size === 0) return null;\n\n let bestMatch: { key: string; embedding: number[]; similarity: number } | null = null;\n\n for (const [cachedQuery, { embedding, timestamp }] of this.queryEmbeddingCache) {\n if ((now - timestamp) >= this.queryCacheTtlMs) continue;\n\n const cachedTokens = this.tokenize(cachedQuery);\n const similarity = this.jaccardSimilarity(queryTokens, cachedTokens);\n\n if (similarity >= this.querySimilarityThreshold) {\n if (!bestMatch || similarity > bestMatch.similarity) {\n bestMatch = { key: cachedQuery, embedding, similarity };\n }\n }\n }\n\n return bestMatch;\n }\n\n private tokenize(text: string): Set<string> {\n return new Set(\n text\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter(t => t.length > 1)\n );\n }\n\n private jaccardSimilarity(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 1;\n if (a.size === 0 || b.size === 0) return 0;\n\n let intersection = 0;\n for (const token of a) {\n if (b.has(token)) intersection++;\n }\n\n const union = a.size + b.size - intersection;\n return intersection / union;\n }\n\n async search(\n query: string,\n limit?: number,\n options?: {\n hybridWeight?: number;\n fileType?: string;\n directory?: string;\n chunkType?: string;\n contextLines?: number;\n filterByBranch?: boolean;\n metadataOnly?: boolean;\n definitionIntent?: boolean;\n }\n ): Promise<SearchResult[]> {\n const { store, provider, database } = await this.ensureInitialized();\n\n const compatibility = this.checkCompatibility();\n if (!compatibility.compatible) {\n throw new Error(\n `${compatibility.reason ?? \"Index is incompatible with current embedding provider.\"} ` +\n `A possible solution is to run index_codebase with force=true to rebuild the index.`\n );\n }\n\n const searchStartTime = performance.now();\n\n if (store.count() === 0) {\n this.logger.search(\"debug\", \"Search on empty index\", { query });\n return [];\n }\n\n const maxResults = limit ?? this.config.search.maxResults;\n const hybridWeight = options?.hybridWeight ?? this.config.search.hybridWeight;\n const fusionStrategy = this.config.search.fusionStrategy;\n const rrfK = this.config.search.rrfK;\n const rerankTopN = this.config.search.rerankTopN;\n const filterByBranch = options?.filterByBranch ?? true;\n const sourceIntent = options?.definitionIntent === true || classifyQueryIntentRaw(query) === \"source\";\n const identifierHints = extractIdentifierHints(query);\n\n this.logger.search(\"debug\", \"Starting search\", {\n query,\n maxResults,\n hybridWeight,\n fusionStrategy,\n rrfK,\n rerankTopN,\n filterByBranch,\n });\n\n const embeddingStartTime = performance.now();\n const embeddingQuery = stripFilePathHint(query);\n const embedding = await this.getQueryEmbedding(embeddingQuery, provider);\n const embeddingMs = performance.now() - embeddingStartTime;\n\n const vectorStartTime = performance.now();\n const semanticResults = store.search(embedding, maxResults * 4);\n const vectorMs = performance.now() - vectorStartTime;\n\n const keywordStartTime = performance.now();\n const keywordResults = await this.keywordSearch(query, maxResults * 4);\n const keywordMs = performance.now() - keywordStartTime;\n\n let branchChunkIds: Set<string> | null = null;\n if (filterByBranch && (this.config.scope === \"global\" || this.currentBranch !== \"default\")) {\n branchChunkIds = new Set(\n this.getBranchCatalogKeys().flatMap((branchKey) => database.getBranchChunkIds(branchKey))\n );\n }\n\n const prefilterStartTime = performance.now();\n const shouldPrefilterByBranch = branchChunkIds !== null && (this.config.scope === \"global\" || branchChunkIds.size > 0);\n const allowBranchPrefilterFallback = this.config.scope !== \"global\";\n const prefilteredSemantic = shouldPrefilterByBranch && branchChunkIds\n ? semanticResults.filter((r) => branchChunkIds.has(r.id))\n : semanticResults;\n const prefilteredKeyword = shouldPrefilterByBranch && branchChunkIds\n ? keywordResults.filter((r) => branchChunkIds.has(r.id))\n : keywordResults;\n\n const semanticCandidates = (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0)\n ? semanticResults\n : prefilteredSemantic;\n const keywordCandidates = (allowBranchPrefilterFallback && shouldPrefilterByBranch && keywordResults.length > 0 && prefilteredKeyword.length === 0)\n ? keywordResults\n : prefilteredKeyword;\n const prefilterMs = performance.now() - prefilterStartTime;\n\n if (this.config.scope !== \"global\" && branchChunkIds && branchChunkIds.size === 0) {\n this.logger.search(\"warn\", \"Branch prefilter skipped because branch catalog is empty\", {\n branch: this.currentBranch,\n });\n }\n\n if (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0) {\n this.logger.search(\"warn\", \"Branch prefilter produced no semantic overlap, using unfiltered semantic candidates\", {\n branch: this.currentBranch,\n });\n }\n\n if (allowBranchPrefilterFallback && shouldPrefilterByBranch && keywordResults.length > 0 && prefilteredKeyword.length === 0) {\n this.logger.search(\"warn\", \"Branch prefilter produced no keyword overlap, using unfiltered keyword candidates\", {\n branch: this.currentBranch,\n });\n }\n\n const fusionStartTime = performance.now();\n const combined = rankHybridResults(query, semanticCandidates, keywordCandidates, {\n fusionStrategy,\n rrfK,\n rerankTopN,\n limit: maxResults,\n hybridWeight,\n prioritizeSourcePaths: sourceIntent,\n });\n const rerankedCombined = await this.rerankCandidatesWithApi(query, combined, {\n definitionIntent: options?.definitionIntent === true,\n hasIdentifierHints: identifierHints.length > 0,\n });\n const fusionMs = performance.now() - fusionStartTime;\n\n const rescued = promoteIdentifierMatches(\n query,\n rerankedCombined,\n semanticCandidates,\n keywordCandidates,\n database,\n branchChunkIds,\n sourceIntent\n );\n\n const union = unionCandidates(semanticCandidates, keywordCandidates);\n\n const deterministicIdentifierLane = buildDeterministicIdentifierPass(\n query,\n union,\n maxResults,\n sourceIntent\n );\n\n const identifierLane = buildIdentifierDefinitionLane(\n query,\n union,\n maxResults,\n sourceIntent\n );\n\n const symbolLane = buildSymbolDefinitionLane(\n query,\n database,\n branchChunkIds,\n maxResults,\n union,\n sourceIntent\n );\n\n const prePrimaryLane = mergeTieredResults(deterministicIdentifierLane, identifierLane, maxResults * 4);\n const primaryLane = mergeTieredResults(prePrimaryLane, symbolLane, maxResults * 4);\n const tiered = mergeTieredResults(primaryLane, rescued, maxResults * 4);\n const hasCodeHints = extractCodeTermHints(query).length > 0 || identifierHints.length > 0;\n\n const baseFiltered = tiered.filter((r) => matchesSearchFilters(r, options, this.config.search.minScore));\n\n const implementationOnly = baseFiltered.filter((r) =>\n isLikelyImplementationPath(r.metadata.filePath) &&\n isImplementationChunkType(r.metadata.chunkType)\n );\n\n const filtered = (sourceIntent && hasCodeHints && implementationOnly.length > 0\n ? implementationOnly\n : baseFiltered\n ).slice(0, maxResults);\n\n const identifierFallback = (!options?.definitionIntent && filtered.length === 0 && identifierHints.length > 0)\n ? buildSymbolDefinitionLane(query, database, branchChunkIds, maxResults, union, true)\n .filter((r) => matchesSearchFilters(r, options, this.config.search.minScore))\n .slice(0, maxResults)\n : [];\n\n const finalResults = filtered.length > 0 ? filtered : identifierFallback;\n\n const totalSearchMs = performance.now() - searchStartTime;\n this.logger.recordSearch(totalSearchMs, {\n embeddingMs,\n vectorMs,\n keywordMs,\n fusionMs,\n });\n this.logger.search(\"info\", \"Search complete\", {\n query,\n results: finalResults.length,\n totalMs: Math.round(totalSearchMs * 100) / 100,\n embeddingMs: Math.round(embeddingMs * 100) / 100,\n vectorMs: Math.round(vectorMs * 100) / 100,\n keywordMs: Math.round(keywordMs * 100) / 100,\n prefilterMs: Math.round(prefilterMs * 100) / 100,\n fusionMs: Math.round(fusionMs * 100) / 100,\n });\n\n const metadataOnly = options?.metadataOnly ?? false;\n\n return Promise.all(\n finalResults.map(async (r) => {\n let content = \"\";\n let contextStartLine = r.metadata.startLine;\n let contextEndLine = r.metadata.endLine;\n\n if (!metadataOnly && this.config.search.includeContext) {\n try {\n const fileContent = await fsPromises.readFile(\n r.metadata.filePath,\n \"utf-8\"\n );\n const lines = fileContent.split(\"\\n\");\n const contextLines = options?.contextLines ?? this.config.search.contextLines;\n\n contextStartLine = Math.max(1, r.metadata.startLine - contextLines);\n contextEndLine = Math.min(lines.length, r.metadata.endLine + contextLines);\n\n content = lines\n .slice(contextStartLine - 1, contextEndLine)\n .join(\"\\n\");\n } catch {\n content = \"[File not accessible]\";\n }\n }\n\n return {\n filePath: r.metadata.filePath,\n startLine: contextStartLine,\n endLine: contextEndLine,\n content,\n score: r.score,\n chunkType: r.metadata.chunkType,\n name: r.metadata.name,\n };\n })\n );\n }\n\n private async keywordSearch(\n query: string,\n limit: number\n ): Promise<Array<{ id: string; score: number; metadata: ChunkMetadata }>> {\n const { store, invertedIndex } = await this.ensureInitialized();\n const scores = invertedIndex.search(query);\n\n if (scores.size === 0) {\n return [];\n }\n\n // Only fetch metadata for chunks returned by BM25 (O(n) where n = result count)\n // instead of getAllMetadata() which fetches ALL chunks in the index\n const chunkIds = Array.from(scores.keys());\n const metadataMap = store.getMetadataBatch(chunkIds);\n\n const results: Array<{ id: string; score: number; metadata: ChunkMetadata }> = [];\n for (const [chunkId, score] of scores) {\n const metadata = metadataMap.get(chunkId);\n if (metadata && score > 0) {\n results.push({ id: chunkId, score, metadata });\n }\n }\n\n results.sort((a, b) => b.score - a.score);\n return results.slice(0, limit);\n }\n\n async getStatus(): Promise<StatusResult> {\n const { store, configuredProviderInfo, database } = await this.ensureInitialized();\n const failedBatchesCount = this.getFailedBatchesCount();\n\n return {\n indexed: store.count() > 0,\n vectorCount: store.count(),\n provider: configuredProviderInfo.provider,\n model: configuredProviderInfo.modelInfo.model,\n indexPath: this.indexPath,\n currentBranch: this.currentBranch,\n baseBranch: this.baseBranch,\n compatibility: this.indexCompatibility,\n failedBatchesCount,\n failedBatchesPath: failedBatchesCount > 0 ? this.failedBatchesPath : undefined,\n warning: database.getMetadata(STARTUP_WARNING_METADATA_KEY) ?? undefined,\n };\n }\n\n async clearIndex(): Promise<void> {\n const { store, invertedIndex, database } = await this.ensureInitialized();\n\n if (this.config.scope === \"global\") {\n store.load();\n invertedIndex.load();\n this.loadFileHashCache();\n const roots = this.getScopedRoots();\n const compatibility = this.checkCompatibility();\n const allMetadata = store.getAllMetadata();\n const hasForeignData =\n allMetadata.some(({ metadata }) => !this.isFileInCurrentScope(metadata.filePath, roots)) ||\n this.hasForeignScopedBranchData() ||\n this.hasForeignScopedFileHashData(roots) ||\n this.hasForeignScopedFailedBatches(roots);\n\n if (!compatibility.compatible && hasForeignData) {\n if (compatibility.code === IncompatibilityCode.EMBEDDING_STRATEGY_MISMATCH) {\n this.clearSharedIndexProjectData(store, invertedIndex, database, roots);\n this.clearScopedFileHashCache(roots);\n this.clearScopedFailedBatches(roots);\n database.setMetadata(this.getProjectForceReembedMetadataKey(), \"true\");\n database.deleteMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n this.indexCompatibility = { compatible: true };\n return;\n }\n\n throw new Error(\n `Global index compatibility reset is unsafe because the shared index contains files from other projects. ` +\n `The current global index cannot be force-rebuilt for ${this.projectRoot} without deleting other repositories' indexed data. ` +\n `Use scope=\"project\" for isolated rebuilds, or manually delete the shared global index if you intend to rebuild all projects.`\n );\n }\n\n if (!hasForeignData) {\n store.clear();\n store.save();\n invertedIndex.clear();\n invertedIndex.save();\n\n this.fileHashCache.clear();\n this.saveFileHashCache();\n\n database.clearAllIndexedData();\n this.saveFailedBatches([]);\n\n database.deleteMetadata(\"index.version\");\n database.deleteMetadata(\"index.embeddingProvider\");\n database.deleteMetadata(\"index.embeddingModel\");\n database.deleteMetadata(\"index.embeddingDimensions\");\n database.deleteMetadata(\"index.embeddingStrategyVersion\");\n database.deleteMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n database.deleteMetadata(this.getLegacyMigrationMetadataKey());\n database.deleteMetadata(\"index.createdAt\");\n database.deleteMetadata(\"index.updatedAt\");\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo!);\n return;\n }\n\n this.clearSharedIndexProjectData(store, invertedIndex, database, roots);\n this.clearScopedFileHashCache(roots);\n this.clearScopedFailedBatches(roots);\n this.indexCompatibility = compatibility;\n return;\n }\n\n const localProjectIndexPath = path.join(this.projectRoot, \".opencode\", \"index\");\n if (path.resolve(this.indexPath) !== path.resolve(localProjectIndexPath)) {\n throw new Error(\n \"Project-scoped force rebuild is unsafe while using an inherited worktree index. \" +\n \"Create a local project config boundary before clearing the index.\"\n );\n }\n\n store.clear();\n store.save();\n invertedIndex.clear();\n invertedIndex.save();\n\n // Clear file hash cache so all files are re-parsed\n this.fileHashCache.clear();\n this.saveFileHashCache();\n\n // cannot reuse stale chunks, symbols, or embeddings from a prior provider.\n database.clearAllIndexedData();\n this.saveFailedBatches([]);\n\n database.deleteMetadata(\"index.version\");\n database.deleteMetadata(\"index.embeddingProvider\");\n database.deleteMetadata(\"index.embeddingModel\");\n database.deleteMetadata(\"index.embeddingDimensions\");\n database.deleteMetadata(\"index.embeddingStrategyVersion\");\n database.deleteMetadata(this.getProjectEmbeddingStrategyMetadataKey());\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n database.deleteMetadata(this.getLegacyMigrationMetadataKey());\n database.deleteMetadata(\"index.createdAt\");\n database.deleteMetadata(\"index.updatedAt\");\n\n this.indexCompatibility = this.validateIndexCompatibility(this.configuredProviderInfo!);\n }\n\n async healthCheck(): Promise<HealthCheckResult> {\n const { store, invertedIndex, database } = await this.ensureInitialized();\n\n this.logger.gc(\"info\", \"Starting health check\");\n\n const allMetadata = store.getAllMetadata();\n const filePathsToChunkKeys = new Map<string, string[]>();\n\n for (const { key, metadata } of allMetadata) {\n const existing = filePathsToChunkKeys.get(metadata.filePath) || [];\n existing.push(key);\n filePathsToChunkKeys.set(metadata.filePath, existing);\n }\n\n const removedFilePaths: string[] = [];\n const removedChunkKeys: string[] = [];\n const chunkKeysByRemovedFile = new Map<string, string[]>();\n\n for (const [filePath, chunkKeys] of filePathsToChunkKeys) {\n if (!existsSync(filePath)) {\n chunkKeysByRemovedFile.set(filePath, chunkKeys);\n for (const key of chunkKeys) {\n removedChunkKeys.push(key);\n }\n removedFilePaths.push(filePath);\n }\n }\n\n if (removedChunkKeys.length > 0) {\n this.rebuildVectorStoreExcludingChunkIds(store, database, removedChunkKeys);\n for (const key of removedChunkKeys) {\n invertedIndex.removeChunk(key);\n }\n }\n\n for (const filePath of removedFilePaths) {\n const fileChunkKeys = chunkKeysByRemovedFile.get(filePath) ?? [];\n if (fileChunkKeys.length > 0) {\n database.deleteChunksByIds(fileChunkKeys);\n }\n database.deleteCallEdgesByFile(filePath);\n database.deleteSymbolsByFile(filePath);\n }\n\n const removedCount = removedChunkKeys.length;\n\n if (removedCount > 0) {\n store.save();\n invertedIndex.save();\n }\n\n let gcOrphanEmbeddings: number;\n let gcOrphanChunks: number;\n let gcOrphanSymbols: number;\n let gcOrphanCallEdges: number;\n\n try {\n gcOrphanEmbeddings = database.gcOrphanEmbeddings();\n gcOrphanChunks = database.gcOrphanChunks();\n gcOrphanSymbols = database.gcOrphanSymbols();\n gcOrphanCallEdges = database.gcOrphanCallEdges();\n } catch (error) {\n if (!(await this.tryResetCorruptedIndex(\"running index health check\", error))) {\n throw error;\n }\n\n await this.ensureInitialized();\n\n return {\n removed: 0,\n filePaths: [],\n gcOrphanEmbeddings: 0,\n gcOrphanChunks: 0,\n gcOrphanSymbols: 0,\n gcOrphanCallEdges: 0,\n resetCorruptedIndex: true,\n warning: this.getCorruptedIndexWarning(path.join(this.indexPath, \"codebase.db\")),\n };\n }\n\n this.logger.recordGc(removedCount, gcOrphanChunks, gcOrphanEmbeddings);\n this.logger.gc(\"info\", \"Health check complete\", {\n removedStale: removedCount,\n orphanEmbeddings: gcOrphanEmbeddings,\n orphanChunks: gcOrphanChunks,\n removedFiles: removedFilePaths.length,\n });\n\n return { removed: removedCount, filePaths: removedFilePaths, gcOrphanEmbeddings, gcOrphanChunks, gcOrphanSymbols, gcOrphanCallEdges };\n }\n\n async retryFailedBatches(): Promise<{ succeeded: number; failed: number; remaining: number }> {\n const { store, provider, invertedIndex, database, configuredProviderInfo } = await this.ensureInitialized();\n const maxChunkTokens = getSafeEmbeddingChunkTokenLimit(configuredProviderInfo);\n const providerRateLimits = this.getProviderRateLimits(configuredProviderInfo.provider);\n\n const roots = this.config.scope === \"global\" ? this.getScopedRoots() : null;\n const { scoped: scopedFailedBatches, retained: retainedFailedBatches } = roots\n ? this.partitionFailedBatches(roots, maxChunkTokens)\n : { scoped: this.loadFailedBatches(maxChunkTokens), retained: [] as FailedBatch[] };\n const failedBatches = scopedFailedBatches;\n if (failedBatches.length === 0) {\n return { succeeded: 0, failed: 0, remaining: 0 };\n }\n\n let succeeded = 0;\n let failed = 0;\n const stillFailing: FailedBatch[] = [];\n\n for (const batch of failedBatches) {\n const batchChunksById = new Map(batch.chunks.map((chunk) => [chunk.id, chunk]));\n const embeddingPartsByChunk = new Map<string, Array<{ vector: number[]; tokenCount: number } | undefined>>();\n const completedChunkIds = new Set<string>();\n const failedChunkIds = new Set<string>();\n const failedChunksForBatch = new Map<string, FailedBatch>();\n const pooledResults: Array<{ chunk: PendingChunk; vector: number[] }> = [];\n try {\n const requestBatches = createPendingEmbeddingRequestBatches(\n batch.chunks,\n getDynamicBatchOptions(configuredProviderInfo)\n );\n\n for (const requestBatch of requestBatches) {\n try {\n const result = await pRetry(\n async () => {\n const texts = requestBatch.map((request) => request.text);\n return provider.embedBatch(texts);\n },\n {\n retries: this.config.indexing.retries,\n minTimeout: Math.max(this.config.indexing.retryDelayMs, providerRateLimits.minRetryMs),\n maxTimeout: providerRateLimits.maxRetryMs,\n factor: 2,\n shouldRetry: (error) => !((error as { error?: Error }).error instanceof CustomProviderNonRetryableError),\n }\n );\n\n const touchedChunkIds = new Set<string>();\n requestBatch.forEach((request, idx) => {\n if (failedChunkIds.has(request.chunk.id) || completedChunkIds.has(request.chunk.id)) {\n return;\n }\n\n const vector = result.embeddings[idx];\n if (!vector) {\n throw new Error(`Embedding API returned too few vectors for chunk ${request.chunk.id}`);\n }\n\n const parts = embeddingPartsByChunk.get(request.chunk.id) ?? [];\n parts[request.partIndex] = {\n vector,\n tokenCount: request.tokenCount,\n };\n embeddingPartsByChunk.set(request.chunk.id, parts);\n touchedChunkIds.add(request.chunk.id);\n });\n\n for (const chunkId of touchedChunkIds) {\n if (failedChunkIds.has(chunkId) || completedChunkIds.has(chunkId)) {\n continue;\n }\n\n const chunk = batchChunksById.get(chunkId);\n if (!chunk) {\n continue;\n }\n\n const parts = embeddingPartsByChunk.get(chunk.id) ?? [];\n if (!hasAllEmbeddingParts(parts, chunk.texts.length)) {\n continue;\n }\n\n const orderedParts = parts as Array<{ vector: number[]; tokenCount: number }>;\n pooledResults.push({\n chunk,\n vector: poolEmbeddingVectors(\n orderedParts.map((part) => part.vector),\n orderedParts.map((part) => part.tokenCount)\n ),\n });\n }\n\n this.logger.recordEmbeddingApiCall(result.totalTokensUsed);\n } catch (error) {\n const failureMessage = String(error);\n const failureTimestamp = new Date().toISOString();\n const failedChunks = getUniquePendingChunksFromRequests(requestBatch)\n .filter((chunk) => !completedChunkIds.has(chunk.id) && !failedChunkIds.has(chunk.id));\n\n for (const chunk of failedChunks) {\n failedChunkIds.add(chunk.id);\n embeddingPartsByChunk.delete(chunk.id);\n failedChunksForBatch.set(chunk.id, {\n chunks: [chunk],\n attemptCount: batch.attemptCount + 1,\n lastAttempt: failureTimestamp,\n error: failureMessage,\n });\n }\n\n failed += failedChunks.length;\n this.logger.recordEmbeddingError();\n }\n }\n\n const successfulResults = pooledResults.filter(({ chunk }) => !failedChunkIds.has(chunk.id));\n\n const items = successfulResults.map(({ chunk, vector }) => ({\n id: chunk.id,\n vector,\n metadata: chunk.metadata,\n }));\n\n if (items.length > 0) {\n store.addBatch(items);\n }\n\n if (successfulResults.length > 0) {\n try {\n database.upsertEmbeddingsBatch(\n successfulResults.map(({ chunk, vector }) => ({\n contentHash: chunk.contentHash,\n embedding: float32ArrayToBuffer(vector),\n chunkText: chunk.storageText,\n model: configuredProviderInfo.modelInfo.model,\n }))\n );\n } catch (dbError) {\n this.rebuildVectorStoreExcludingChunkIds(\n store,\n database,\n successfulResults.map(({ chunk }) => chunk.id)\n );\n throw dbError;\n }\n }\n\n for (const { chunk } of successfulResults) {\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n completedChunkIds.add(chunk.id);\n embeddingPartsByChunk.delete(chunk.id);\n }\n\n database.addChunksToBranchBatch(\n this.getBranchCatalogKey(),\n successfulResults.map(({ chunk }) => chunk.id)\n );\n\n this.logger.recordChunksEmbedded(successfulResults.length);\n\n succeeded += successfulResults.length;\n stillFailing.push(...failedChunksForBatch.values());\n } catch (error) {\n const failureMessage = getErrorMessage(error);\n const failureTimestamp = new Date().toISOString();\n const unaccountedChunks = batch.chunks.filter(\n (chunk) => !failedChunksForBatch.has(chunk.id) && !completedChunkIds.has(chunk.id)\n );\n\n for (const chunk of unaccountedChunks) {\n failedChunksForBatch.set(chunk.id, {\n chunks: [chunk],\n attemptCount: batch.attemptCount + 1,\n lastAttempt: failureTimestamp,\n error: failureMessage,\n });\n }\n\n failed += unaccountedChunks.length;\n this.logger.recordEmbeddingError();\n stillFailing.push(...coalesceFailedBatches(Array.from(failedChunksForBatch.values())));\n }\n }\n\n const persistedStillFailing = coalesceFailedBatches(stillFailing);\n\n if (roots) {\n this.saveFailedBatches([...retainedFailedBatches, ...persistedStillFailing]);\n } else {\n this.saveFailedBatches(persistedStillFailing);\n }\n\n if (succeeded > 0) {\n store.save();\n invertedIndex.save();\n }\n\n if (roots && succeeded > 0 && persistedStillFailing.length === 0 && this.hasProjectForceReembedPending()) {\n database.deleteMetadata(this.getProjectForceReembedMetadataKey());\n this.saveIndexMetadata(configuredProviderInfo);\n this.indexCompatibility = { compatible: true };\n }\n\n return { succeeded, failed, remaining: persistedStillFailing.length };\n }\n\n getFailedBatchesCount(): number {\n if (this.config.scope === \"global\") {\n return this.partitionFailedBatches(this.getScopedRoots()).scoped.length;\n }\n return this.loadFailedBatches().length;\n }\n\n getCurrentBranch(): string {\n return this.currentBranch;\n }\n\n getBaseBranch(): string {\n return this.baseBranch;\n }\n\n refreshBranchInfo(): void {\n if (isGitRepo(this.projectRoot)) {\n this.currentBranch = getBranchOrDefault(this.projectRoot);\n this.baseBranch = getBaseBranch(this.projectRoot);\n }\n }\n\n async getDatabaseStats(): Promise<{ embeddingCount: number; chunkCount: number; branchChunkCount: number; branchCount: number } | null> {\n const { database } = await this.ensureInitialized();\n return database.getStats();\n }\n\n getLogger(): Logger {\n return this.logger;\n }\n\n async findSimilar(\n code: string,\n limit: number = this.config.search.maxResults,\n options?: {\n fileType?: string;\n directory?: string;\n chunkType?: string;\n excludeFile?: string;\n filterByBranch?: boolean;\n }\n ): Promise<SearchResult[]> {\n const { store, provider, database } = await this.ensureInitialized();\n\n const compatibility = this.checkCompatibility();\n if (!compatibility.compatible) {\n throw new Error(\n `${compatibility.reason ?? \"Index is incompatible with current embedding provider.\"} ` +\n `Run index_codebase with force=true to rebuild the index.`\n );\n }\n\n const searchStartTime = performance.now();\n\n if (store.count() === 0) {\n this.logger.search(\"debug\", \"Find similar on empty index\");\n return [];\n }\n\n const filterByBranch = options?.filterByBranch ?? true;\n\n this.logger.search(\"debug\", \"Starting find similar\", {\n codeLength: code.length,\n limit,\n filterByBranch,\n });\n\n const embeddingStartTime = performance.now();\n const { embedding, tokensUsed } = await provider.embedDocument(code);\n const embeddingMs = performance.now() - embeddingStartTime;\n this.logger.recordEmbeddingApiCall(tokensUsed);\n\n const vectorStartTime = performance.now();\n const semanticResults = store.search(embedding, limit * 2);\n const vectorMs = performance.now() - vectorStartTime;\n\n let branchChunkIds: Set<string> | null = null;\n if (filterByBranch && (this.config.scope === \"global\" || this.currentBranch !== \"default\")) {\n branchChunkIds = new Set(\n this.getBranchCatalogKeys().flatMap((branchKey) => database.getBranchChunkIds(branchKey))\n );\n }\n\n const prefilterStartTime = performance.now();\n const shouldPrefilterByBranch = branchChunkIds !== null && (this.config.scope === \"global\" || branchChunkIds.size > 0);\n const allowBranchPrefilterFallback = this.config.scope !== \"global\";\n const prefilteredSemantic = shouldPrefilterByBranch && branchChunkIds\n ? semanticResults.filter((r) => branchChunkIds.has(r.id))\n : semanticResults;\n const semanticCandidates = (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0)\n ? semanticResults\n : prefilteredSemantic;\n const prefilterMs = performance.now() - prefilterStartTime;\n\n if (this.config.scope !== \"global\" && branchChunkIds && branchChunkIds.size === 0) {\n this.logger.search(\"warn\", \"Branch prefilter skipped because branch catalog is empty\", {\n branch: this.currentBranch,\n });\n }\n\n if (allowBranchPrefilterFallback && shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0) {\n this.logger.search(\"warn\", \"Branch prefilter produced no semantic overlap, using unfiltered semantic candidates\", {\n branch: this.currentBranch,\n });\n }\n\n const rerankTopN = this.config.search.rerankTopN;\n\n const ranked = rankSemanticOnlyResults(code, semanticCandidates, {\n rerankTopN,\n limit,\n prioritizeSourcePaths: false,\n });\n\n const filtered = ranked.filter((r) => {\n if (r.score < this.config.search.minScore) return false;\n\n if (options?.excludeFile) {\n if (r.metadata.filePath === options.excludeFile) return false;\n }\n\n if (options?.fileType) {\n const ext = r.metadata.filePath.split(\".\").pop()?.toLowerCase();\n if (ext !== options.fileType.toLowerCase().replace(/^\\./, \"\")) return false;\n }\n\n if (options?.directory) {\n const normalizedDir = options.directory.replace(/^\\/|\\/$/g, \"\");\n if (!r.metadata.filePath.includes(`/${normalizedDir}/`) &&\n !r.metadata.filePath.includes(`${normalizedDir}/`)) return false;\n }\n\n if (options?.chunkType) {\n if (r.metadata.chunkType !== options.chunkType) return false;\n }\n\n return true;\n }).slice(0, limit);\n\n const totalSearchMs = performance.now() - searchStartTime;\n this.logger.recordSearch(totalSearchMs, {\n embeddingMs,\n vectorMs,\n keywordMs: 0,\n fusionMs: 0,\n });\n this.logger.search(\"info\", \"Find similar complete\", {\n codeLength: code.length,\n results: filtered.length,\n totalMs: Math.round(totalSearchMs * 100) / 100,\n embeddingMs: Math.round(embeddingMs * 100) / 100,\n vectorMs: Math.round(vectorMs * 100) / 100,\n prefilterMs: Math.round(prefilterMs * 100) / 100,\n });\n\n return Promise.all(\n filtered.map(async (r) => {\n let content = \"\";\n\n if (this.config.search.includeContext) {\n try {\n const fileContent = await fsPromises.readFile(\n r.metadata.filePath,\n \"utf-8\"\n );\n const lines = fileContent.split(\"\\n\");\n content = lines\n .slice(r.metadata.startLine - 1, r.metadata.endLine)\n .join(\"\\n\");\n } catch {\n content = \"[File not accessible]\";\n }\n }\n\n return {\n filePath: r.metadata.filePath,\n startLine: r.metadata.startLine,\n endLine: r.metadata.endLine,\n content,\n score: r.score,\n chunkType: r.metadata.chunkType,\n name: r.metadata.name,\n };\n })\n );\n }\n\n async getCallers(targetName: string, callTypeFilter?: string): Promise<CallEdgeData[]> {\n const { database } = await this.ensureInitialized();\n const seen = new Set<string>();\n const results: CallEdgeData[] = [];\n\n for (const branchKey of this.getBranchCatalogKeys()) {\n for (const edge of database.getCallersWithContext(targetName, branchKey, callTypeFilter)) {\n if (!seen.has(edge.id)) {\n seen.add(edge.id);\n results.push(edge);\n }\n }\n }\n\n return results;\n }\n\n async getCallees(symbolId: string, callTypeFilter?: string): Promise<CallEdgeData[]> {\n const { database } = await this.ensureInitialized();\n const seen = new Set<string>();\n const results: CallEdgeData[] = [];\n\n for (const branchKey of this.getBranchCatalogKeys()) {\n for (const edge of database.getCallees(symbolId, branchKey, callTypeFilter)) {\n if (!seen.has(edge.id)) {\n seen.add(edge.id);\n results.push(edge);\n }\n }\n }\n\n return results;\n }\n\n async findCallPath(fromName: string, toName: string, maxDepth?: number): Promise<PathHopData[]> {\n const { database } = await this.ensureInitialized();\n let shortest: PathHopData[] = [];\n\n for (const branchKey of this.getBranchCatalogKeys()) {\n const path = database.findShortestPath(fromName, toName, branchKey, maxDepth);\n if (path.length > 0 && (shortest.length === 0 || path.length < shortest.length)) {\n shortest = path;\n }\n }\n\n return shortest;\n }\n\n async close(): Promise<void> {\n await this.database?.close();\n this.database = null;\n this.store = null;\n this.invertedIndex = null;\n this.provider = null;\n this.reranker = null;\n }\n}\n","import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n","export class TimeoutError extends Error {\n\tname = 'TimeoutError';\n\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tError.captureStackTrace?.(this, TimeoutError);\n\t}\n}\n\nconst getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t\tsignal,\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (signal?.aborted) {\n\t\t\treject(getAbortedReason(signal));\n\t\t\treturn;\n\t\t}\n\n\t\tif (signal) {\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\t// Use .then() instead of async IIFE to preserve stack traces\n\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\tpromise.then(resolve, reject);\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\t});\n\n\t// eslint-disable-next-line promise/prefer-await-to-then\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && signal) {\n\t\t\tsignal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n const { priority = 0, id, } = options ?? {};\n const element = {\n priority,\n id,\n run,\n };\n if (this.size === 0 || this.#queue[this.size - 1].priority >= priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n setPriority(id, priority) {\n const index = this.#queue.findIndex((element) => element.id === id);\n if (index === -1) {\n throw new ReferenceError(`No promise function with the id \"${id}\" exists in the queue.`);\n }\n const [item] = this.#queue.splice(index, 1);\n this.enqueue(item.run, { priority, id });\n }\n remove(idOrRun) {\n const index = this.#queue.findIndex((element) => {\n if (typeof idOrRun === 'string') {\n return element.id === idOrRun;\n }\n return element.run === idOrRun;\n });\n if (index !== -1) {\n this.#queue.splice(index, 1);\n }\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n","import { EventEmitter } from 'eventemitter3';\nimport pTimeout from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverIntervalCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #rateLimitedInInterval = false;\n #rateLimitFlushScheduled = false;\n #interval;\n #intervalEnd = 0;\n #lastExecutionTime = 0;\n #intervalId;\n #timeoutId;\n #strict;\n // Circular buffer implementation for better performance\n #strictTicks = [];\n #strictTicksStartIndex = 0;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n // Track currently running tasks for debugging\n #runningTasks = new Map();\n #queueAbortListenerCleanupFunctions = new Set();\n /**\n Get or set the default timeout for all tasks. Can be changed at runtime.\n\n Operations will throw a `TimeoutError` if they don't complete within the specified time.\n\n The timeout begins when the operation is dequeued and starts execution, not while it's waiting in the queue.\n\n @example\n ```\n const queue = new PQueue({timeout: 5000});\n\n // Change timeout for all future tasks\n queue.timeout = 10000;\n ```\n */\n timeout;\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverIntervalCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n strict: false,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n if (options.strict && options.interval === 0) {\n throw new TypeError('The `strict` option requires a non-zero `interval`');\n }\n if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) {\n throw new TypeError('The `strict` option requires a finite `intervalCap`');\n }\n // TODO: Remove this fallback in the next major version\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n this.#carryoverIntervalCount = options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#strict = options.strict;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) {\n throw new TypeError(`Expected \\`timeout\\` to be a positive finite number, got \\`${options.timeout}\\` (${typeof options.timeout})`);\n }\n this.timeout = options.timeout;\n this.#isPaused = options.autoStart === false;\n this.#setupRateLimitTracking();\n }\n #cleanupStrictTicks(now) {\n // Remove ticks outside the current interval window using circular buffer approach\n while (this.#strictTicksStartIndex < this.#strictTicks.length) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n if (oldestTick !== undefined && now - oldestTick >= this.#interval) {\n this.#strictTicksStartIndex++;\n }\n else {\n break;\n }\n }\n // Compact the array when it becomes inefficient or fully consumed\n // Compact when: (start index is large AND more than half wasted) OR all ticks expired\n const shouldCompact = (this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2)\n || this.#strictTicksStartIndex === this.#strictTicks.length;\n if (shouldCompact) {\n this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex);\n this.#strictTicksStartIndex = 0;\n }\n }\n // Helper methods for interval consumption\n #consumeIntervalSlot(now) {\n if (this.#strict) {\n this.#strictTicks.push(now);\n }\n else {\n this.#intervalCount++;\n }\n }\n #rollbackIntervalSlot() {\n if (this.#strict) {\n // Pop from the end of the actual data (not from start index)\n if (this.#strictTicks.length > this.#strictTicksStartIndex) {\n this.#strictTicks.pop();\n }\n }\n else if (this.#intervalCount > 0) {\n this.#intervalCount--;\n }\n }\n #getActiveTicksCount() {\n return this.#strictTicks.length - this.#strictTicksStartIndex;\n }\n get #doesIntervalAllowAnother() {\n if (this.#isIntervalIgnored) {\n return true;\n }\n if (this.#strict) {\n // Cleanup already done by #isIntervalPausedAt before this is called\n return this.#getActiveTicksCount() < this.#intervalCap;\n }\n return this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n if (this.#pending === 0) {\n this.emit('pendingZero');\n }\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n // Clear timeout ID before processing to prevent race condition\n // Must clear before #onInterval to allow new timeouts to be scheduled\n this.#timeoutId = undefined;\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n }\n #isIntervalPausedAt(now) {\n // Strict mode: check if we need to wait for oldest tick to age out\n if (this.#strict) {\n this.#cleanupStrictTicks(now);\n // If at capacity, need to wait for oldest tick to age out\n const activeTicksCount = this.#getActiveTicksCount();\n if (activeTicksCount >= this.#intervalCap) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n // After cleanup, remaining ticks are within interval, so delay is always > 0\n const delay = this.#interval - (now - oldestTick);\n this.#createIntervalTimeout(delay);\n return true;\n }\n return false;\n }\n // Fixed window mode (original logic)\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // If the interval has expired while idle, check if we should enforce the interval\n // from the last task execution. This ensures proper spacing between tasks even\n // when the queue becomes empty and then new tasks are added.\n if (this.#lastExecutionTime > 0) {\n const timeSinceLastExecution = now - this.#lastExecutionTime;\n if (timeSinceLastExecution < this.#interval) {\n // Not enough time has passed since the last task execution\n this.#createIntervalTimeout(this.#interval - timeSinceLastExecution);\n return true;\n }\n }\n // Enough time has passed or no previous execution, allow execution\n this.#intervalCount = (this.#carryoverIntervalCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n this.#createIntervalTimeout(delay);\n return true;\n }\n }\n return false;\n }\n #createIntervalTimeout(delay) {\n if (this.#timeoutId !== undefined) {\n return;\n }\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n #clearIntervalTimer() {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n }\n #clearTimeoutTimer() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = undefined;\n }\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n this.#clearIntervalTimer();\n this.emit('empty');\n if (this.#pending === 0) {\n // Clear timeout as well when completely idle\n this.#clearTimeoutTimer();\n // Compact strict ticks when idle to free memory\n if (this.#strict && this.#strictTicksStartIndex > 0) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n }\n this.emit('idle');\n }\n return false;\n }\n let taskStarted = false;\n if (!this.#isPaused) {\n const now = Date.now();\n const canInitializeInterval = !this.#isIntervalPausedAt(now);\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!this.#isIntervalIgnored) {\n this.#consumeIntervalSlot(now);\n this.#scheduleRateLimitUpdate();\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n taskStarted = true;\n }\n }\n return taskStarted;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n // Strict mode uses timeouts instead of interval timers\n if (this.#strict) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n // Non-strict mode uses interval timers and intervalCount\n if (!this.#strict) {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n this.#clearIntervalTimer();\n }\n this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0;\n }\n this.#processQueue();\n this.#scheduleRateLimitUpdate();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n /**\n Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.\n\n For example, this can be used to prioritize a promise function to run earlier.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦀', {priority: 0, id: '🦀'});\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦄', {priority: 1});\n\n queue.setPriority('🦀', 2);\n ```\n\n In this case, the promise function with `id: '🦀'` runs second.\n\n You can also deprioritize a promise function to delay its execution:\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦀', {priority: 1, id: '🦀'});\n queue.add(async () => '🦄');\n queue.add(async () => '🦄', {priority: 0});\n\n queue.setPriority('🦀', -1);\n ```\n Here, the promise function with `id: '🦀'` executes last.\n */\n setPriority(id, priority) {\n if (typeof priority !== 'number' || !Number.isFinite(priority)) {\n throw new TypeError(`Expected \\`priority\\` to be a finite number, got \\`${priority}\\` (${typeof priority})`);\n }\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // Create a copy to avoid mutating the original options object\n options = {\n timeout: this.timeout,\n ...options,\n // Assign unique ID if not provided\n id: options.id ?? (this.#idAssigner++).toString(),\n };\n return new Promise((resolve, reject) => {\n // Create a unique symbol for tracking this task\n const taskSymbol = Symbol(`task-${options.id}`);\n let cleanupQueueAbortHandler = () => undefined;\n const run = async () => {\n // Task is now running — remove the queued-state abort listener\n cleanupQueueAbortHandler();\n this.#pending++;\n // Track this running task\n this.#runningTasks.set(taskSymbol, {\n id: options.id,\n priority: options.priority ?? 0, // Match priority-queue default\n startTime: Date.now(),\n timeout: options.timeout,\n });\n let eventListener;\n try {\n // Check abort signal - if aborted, need to decrement the counter\n // that was incremented in tryToStartAnother\n try {\n options.signal?.throwIfAborted();\n }\n catch (error) {\n this.#rollbackIntervalConsumption();\n // Clean up tracking before throwing\n this.#runningTasks.delete(taskSymbol);\n throw error;\n }\n this.#lastExecutionTime = Date.now();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), {\n milliseconds: options.timeout,\n message: `Task timed out after ${options.timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)`,\n });\n }\n if (options.signal) {\n const { signal } = options;\n operation = Promise.race([operation, new Promise((_resolve, reject) => {\n eventListener = () => {\n reject(signal.reason);\n };\n signal.addEventListener('abort', eventListener, { once: true });\n })]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n reject(error);\n this.emit('error', error);\n }\n finally {\n // Clean up abort event listener\n if (eventListener) {\n options.signal?.removeEventListener('abort', eventListener);\n }\n // Remove from running tasks\n this.#runningTasks.delete(taskSymbol);\n // Use queueMicrotask to prevent deep recursion while maintaining timing\n queueMicrotask(() => {\n this.#next();\n });\n }\n };\n this.#queue.enqueue(run, options);\n const removeQueuedTask = () => {\n if (this.#queue instanceof PriorityQueue) {\n this.#queue.remove(run);\n return;\n }\n this.#queue.remove?.(options.id); // Intentionally best-effort: queued abort removal is only supported for queue classes that implement `.remove()`.\n };\n // Handle abort while task is waiting in the queue\n if (options.signal) {\n const { signal } = options;\n const queueAbortHandler = () => {\n cleanupQueueAbortHandler();\n removeQueuedTask();\n reject(signal.reason);\n this.#tryToStartAnother();\n this.emit('next');\n };\n cleanupQueueAbortHandler = () => {\n signal.removeEventListener('abort', queueAbortHandler);\n this.#queueAbortListenerCleanupFunctions.delete(cleanupQueueAbortHandler);\n };\n if (signal.aborted) {\n queueAbortHandler();\n return;\n }\n signal.addEventListener('abort', queueAbortHandler, { once: true });\n this.#queueAbortListenerCleanupFunctions.add(cleanupQueueAbortHandler);\n }\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n for (const cleanupQueueAbortHandler of this.#queueAbortListenerCleanupFunctions) {\n cleanupQueueAbortHandler();\n }\n this.#queue = new this.#queueClass();\n // Clear interval timer since queue is now empty (consistent with #tryToStartAnother)\n this.#clearIntervalTimer();\n // Note: We preserve strict mode rate-limiting state (ticks and timeout)\n // because clear() only clears queued tasks, not rate limit history.\n // This ensures that rate limits are still enforced after clearing the queue.\n // Note: We don't clear #runningTasks as those tasks are still running\n // They will be removed when they complete in the finally block\n // Force synchronous update since clear() should have immediate effect\n this.#updateRateLimitState();\n // Emit events so waiters (onEmpty, onIdle, onSizeLessThan) can resolve\n this.emit('empty');\n if (this.#pending === 0) {\n this.#clearTimeoutTimer();\n this.emit('idle');\n }\n this.emit('next');\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n /**\n The difference with `.onIdle` is that `.onPendingZero` only waits for currently running tasks to finish, ignoring queued tasks.\n\n @returns A promise that settles when all currently running tasks have completed; `queue.pending === 0`.\n */\n async onPendingZero() {\n if (this.#pending === 0) {\n return;\n }\n await this.#onEvent('pendingZero');\n }\n /**\n @returns A promise that settles when the queue becomes rate-limited due to intervalCap.\n */\n async onRateLimit() {\n if (this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimit');\n }\n /**\n @returns A promise that settles when the queue is no longer rate-limited.\n */\n async onRateLimitCleared() {\n if (!this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimitCleared');\n }\n /**\n @returns A promise that rejects when any task in the queue errors.\n\n Use with `Promise.race([queue.onError(), queue.onIdle()])` to fail fast on the first error while still resolving normally when the queue goes idle.\n\n Important: The promise returned by `add()` still rejects. You must handle each `add()` promise (for example, `.catch(() => {})`) to avoid unhandled rejections.\n\n @example\n ```\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n queue.add(() => fetchData(1)).catch(() => {});\n queue.add(() => fetchData(2)).catch(() => {});\n queue.add(() => fetchData(3)).catch(() => {});\n\n // Stop processing on first error\n try {\n await Promise.race([\n queue.onError(),\n queue.onIdle()\n ]);\n } catch (error) {\n queue.pause(); // Stop processing remaining tasks\n console.error('Queue failed:', error);\n }\n ```\n */\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n onError() {\n return new Promise((_resolve, reject) => {\n const handleError = (error) => {\n this.off('error', handleError);\n reject(error);\n };\n this.on('error', handleError);\n });\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n #setupRateLimitTracking() {\n // Only schedule updates when rate limiting is enabled\n if (this.#isIntervalIgnored) {\n return;\n }\n // Wire up to lifecycle events that affect rate limit state\n // Only 'add' and 'next' can actually change rate limit state\n this.on('add', () => {\n if (this.#queue.size > 0) {\n this.#scheduleRateLimitUpdate();\n }\n });\n this.on('next', () => {\n this.#scheduleRateLimitUpdate();\n });\n }\n #scheduleRateLimitUpdate() {\n // Skip if rate limiting is not enabled or already scheduled\n if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) {\n return;\n }\n this.#rateLimitFlushScheduled = true;\n queueMicrotask(() => {\n this.#rateLimitFlushScheduled = false;\n this.#updateRateLimitState();\n });\n }\n #rollbackIntervalConsumption() {\n if (this.#isIntervalIgnored) {\n return;\n }\n this.#rollbackIntervalSlot();\n this.#scheduleRateLimitUpdate();\n }\n #updateRateLimitState() {\n const previous = this.#rateLimitedInInterval;\n // Early exit if rate limiting is disabled or queue is empty\n if (this.#isIntervalIgnored || this.#queue.size === 0) {\n if (previous) {\n this.#rateLimitedInInterval = false;\n this.emit('rateLimitCleared');\n }\n return;\n }\n // Get the current count based on mode\n let count;\n if (this.#strict) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n count = this.#getActiveTicksCount();\n }\n else {\n count = this.#intervalCount;\n }\n const shouldBeRateLimited = count >= this.#intervalCap;\n if (shouldBeRateLimited !== previous) {\n this.#rateLimitedInInterval = shouldBeRateLimited;\n this.emit(shouldBeRateLimited ? 'rateLimit' : 'rateLimitCleared');\n }\n }\n /**\n Whether the queue is currently rate-limited due to intervalCap.\n */\n get isRateLimited() {\n return this.#rateLimitedInInterval;\n }\n /**\n Whether the queue is saturated. Returns `true` when:\n - All concurrency slots are occupied and tasks are waiting, OR\n - The queue is rate-limited and tasks are waiting\n\n Useful for detecting backpressure and potential hanging tasks.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n // Backpressure handling\n if (queue.isSaturated) {\n console.log('Queue is saturated, waiting for capacity...');\n await queue.onSizeLessThan(queue.concurrency);\n }\n\n // Monitoring for stuck tasks\n setInterval(() => {\n if (queue.isSaturated) {\n console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);\n }\n }, 60000);\n ```\n */\n get isSaturated() {\n return (this.#pending === this.#concurrency && this.#queue.size > 0)\n || (this.isRateLimited && this.#queue.size > 0);\n }\n /**\n The tasks currently being executed. Each task includes its `id`, `priority`, `startTime`, and `timeout` (if set).\n\n Returns an array of task info objects.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n // Add tasks with IDs for better debugging\n queue.add(() => fetchUser(123), {id: 'user-123'});\n queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});\n\n // Check what's running\n console.log(queue.runningTasks);\n // => [{\n // id: 'user-123',\n // priority: 0,\n // startTime: 1759253001716,\n // timeout: undefined\n // }, {\n // id: 'posts-456',\n // priority: 1,\n // startTime: 1759253001916,\n // timeout: undefined\n // }]\n ```\n */\n get runningTasks() {\n // Return fresh array with fresh objects to prevent mutations\n return [...this.#runningTasks.values()].map(task => ({ ...task }));\n }\n}\n/**\nError thrown when a task times out.\n\n@example\n```\nimport PQueue, {TimeoutError} from 'p-queue';\n\nconst queue = new PQueue({timeout: 1000});\n\ntry {\n await queue.add(() => someTask());\n} catch (error) {\n if (error instanceof TimeoutError) {\n console.log('Task timed out');\n }\n}\n```\n*/\nexport { TimeoutError } from 'p-timeout';\n","const objectToString = Object.prototype.toString;\n\nconst isError = value => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n\t' A network error occurred.', // Bun (WebKit)\n\t'Network connection lost', // Cloudflare Workers (fetch)\n]);\n\nexport default function isNetworkError(error) {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\tconst {message, stack} = error;\n\n\t// Safari 17+ has generic message but no stack for network errors\n\tif (message === 'Load failed') {\n\t\treturn stack === undefined\n\t\t\t// Sentry adds its own stack trace to the fetch error, so also check for that\n\t\t\t|| '__sentry_captured__' in error;\n\t}\n\n\t// Deno network errors start with specific text\n\tif (message.startsWith('error sending request for url')) {\n\t\treturn true;\n\t}\n\n\t// Chrome: exact \"Failed to fetch\" or with hostname: \"Failed to fetch (example.com)\"\n\tif (message === 'Failed to fetch' || (message.startsWith('Failed to fetch (') && message.endsWith(')'))) {\n\t\treturn true;\n\t}\n\n\t// Standard network error messages\n\treturn errorMessages.has(message);\n}\n","import isNetworkError from 'is-network-error';\n\nfunction validateRetries(retries) {\n\tif (typeof retries === 'number') {\n\t\tif (retries < 0) {\n\t\t\tthrow new TypeError('Expected `retries` to be a non-negative number.');\n\t\t}\n\n\t\tif (Number.isNaN(retries)) {\n\t\t\tthrow new TypeError('Expected `retries` to be a valid number or Infinity, got NaN.');\n\t\t}\n\t} else if (retries !== undefined) {\n\t\tthrow new TypeError('Expected `retries` to be a number or Infinity.');\n\t}\n}\n\nfunction validateNumberOption(name, value, {min = 0, allowInfinity = false} = {}) {\n\tif (value === undefined) {\n\t\treturn;\n\t}\n\n\tif (typeof value !== 'number' || Number.isNaN(value)) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be a number${allowInfinity ? ' or Infinity' : ''}.`);\n\t}\n\n\tif (!allowInfinity && !Number.isFinite(value)) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be a finite number.`);\n\t}\n\n\tif (value < min) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be \\u2265 ${min}.`);\n\t}\n}\n\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nfunction calculateDelay(retriesConsumed, options) {\n\tconst attempt = Math.max(1, retriesConsumed + 1);\n\tconst random = options.randomize ? (Math.random() + 1) : 1;\n\n\tlet timeout = Math.round(random * options.minTimeout * (options.factor ** (attempt - 1)));\n\ttimeout = Math.min(timeout, options.maxTimeout);\n\n\treturn timeout;\n}\n\nfunction calculateRemainingTime(start, max) {\n\tif (!Number.isFinite(max)) {\n\t\treturn max;\n\t}\n\n\treturn max - (performance.now() - start);\n}\n\nasync function onAttemptFailure({error, attemptNumber, retriesConsumed, startTime, options}) {\n\tconst normalizedError = error instanceof Error\n\t\t? error\n\t\t: new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`);\n\n\tif (normalizedError instanceof AbortError) {\n\t\tthrow normalizedError.originalError;\n\t}\n\n\tconst retriesLeft = Number.isFinite(options.retries)\n\t\t? Math.max(0, options.retries - retriesConsumed)\n\t\t: options.retries;\n\n\tconst maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;\n\n\tconst context = Object.freeze({\n\t\terror: normalizedError,\n\t\tattemptNumber,\n\t\tretriesLeft,\n\t\tretriesConsumed,\n\t});\n\n\tawait options.onFailedAttempt(context);\n\n\tif (calculateRemainingTime(startTime, maxRetryTime) <= 0) {\n\t\tthrow normalizedError;\n\t}\n\n\tconst consumeRetry = await options.shouldConsumeRetry(context);\n\n\tconst remainingTime = calculateRemainingTime(startTime, maxRetryTime);\n\n\tif (remainingTime <= 0 || retriesLeft <= 0) {\n\t\tthrow normalizedError;\n\t}\n\n\tif (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {\n\t\tif (consumeRetry) {\n\t\t\tthrow normalizedError;\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\t\treturn false;\n\t}\n\n\tif (!await options.shouldRetry(context)) {\n\t\tthrow normalizedError;\n\t}\n\n\tif (!consumeRetry) {\n\t\toptions.signal?.throwIfAborted();\n\t\treturn false;\n\t}\n\n\tconst delayTime = calculateDelay(retriesConsumed, options);\n\tconst finalDelay = Math.min(delayTime, remainingTime);\n\n\toptions.signal?.throwIfAborted();\n\n\tif (finalDelay > 0) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tclearTimeout(timeoutToken);\n\t\t\t\toptions.signal?.removeEventListener('abort', onAbort);\n\t\t\t\treject(options.signal.reason);\n\t\t\t};\n\n\t\t\tconst timeoutToken = setTimeout(() => {\n\t\t\t\toptions.signal?.removeEventListener('abort', onAbort);\n\t\t\t\tresolve();\n\t\t\t}, finalDelay);\n\n\t\t\tif (options.unref) {\n\t\t\t\ttimeoutToken.unref?.();\n\t\t\t}\n\n\t\t\toptions.signal?.addEventListener('abort', onAbort, {once: true});\n\t\t});\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\treturn true;\n}\n\nexport default async function pRetry(input, options = {}) {\n\toptions = {...options};\n\n\tvalidateRetries(options.retries);\n\n\tif (Object.hasOwn(options, 'forever')) {\n\t\tthrow new Error('The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.');\n\t}\n\n\toptions.retries ??= 10;\n\toptions.factor ??= 2;\n\toptions.minTimeout ??= 1000;\n\toptions.maxTimeout ??= Number.POSITIVE_INFINITY;\n\toptions.maxRetryTime ??= Number.POSITIVE_INFINITY;\n\toptions.randomize ??= false;\n\toptions.onFailedAttempt ??= () => {};\n\toptions.shouldRetry ??= () => true;\n\toptions.shouldConsumeRetry ??= () => true;\n\n\t// Validate numeric options and normalize edge cases\n\tvalidateNumberOption('factor', options.factor, {min: 0, allowInfinity: false});\n\tvalidateNumberOption('minTimeout', options.minTimeout, {min: 0, allowInfinity: false});\n\tvalidateNumberOption('maxTimeout', options.maxTimeout, {min: 0, allowInfinity: true});\n\tvalidateNumberOption('maxRetryTime', options.maxRetryTime, {min: 0, allowInfinity: true});\n\n\t// Treat non-positive factor as 1 to avoid zero backoff or negative behavior\n\tif (!(options.factor > 0)) {\n\t\toptions.factor = 1;\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tlet attemptNumber = 0;\n\tlet retriesConsumed = 0;\n\tconst startTime = performance.now();\n\n\twhile (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {\n\t\tattemptNumber++;\n\n\t\ttry {\n\t\t\toptions.signal?.throwIfAborted();\n\n\t\t\tconst result = await input(attemptNumber);\n\n\t\t\toptions.signal?.throwIfAborted();\n\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tif (await onAttemptFailure({\n\t\t\t\terror,\n\t\t\t\tattemptNumber,\n\t\t\t\tretriesConsumed,\n\t\t\t\tstartTime,\n\t\t\t\toptions,\n\t\t\t})) {\n\t\t\t\tretriesConsumed++;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Should not reach here, but in case it does, throw an error\n\tthrow new Error('Retry attempts exhausted without throwing an error.');\n}\n\nexport function makeRetriable(function_, options) {\n\treturn function (...arguments_) {\n\t\treturn pRetry(() => function_.apply(this, arguments_), options);\n\t};\n}\n","import { type EmbeddingProvider, type CustomProviderConfig, type BaseModelInfo, getDefaultModelForProvider, isValidModel, autoDetectProviders, EmbeddingModelName, EMBEDDING_MODELS } from \"../config\";\nimport { existsSync, readFileSync } from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\n\nexport interface ProviderCredentials {\n provider: EmbeddingProvider | 'custom';\n apiKey?: string;\n baseUrl?: string;\n refreshToken?: string;\n accessToken?: string;\n tokenExpires?: number;\n}\n\nexport interface CustomModelInfo extends BaseModelInfo {\n provider: 'custom';\n timeoutMs: number;\n maxBatchSize?: number;\n}\n\nexport type ConfiguredProviderInfo = {\n [P in EmbeddingProvider]: {\n provider: P;\n credentials: ProviderCredentials;\n modelInfo: (typeof EMBEDDING_MODELS)[P][keyof (typeof EMBEDDING_MODELS)[P]];\n }\n}[EmbeddingProvider] | {\n provider: 'custom';\n credentials: ProviderCredentials;\n modelInfo: CustomModelInfo;\n}\n\ninterface OpenCodeAuthOAuth {\n type: \"oauth\";\n refresh: string;\n access: string;\n expires: number;\n enterpriseUrl?: string;\n}\n\ninterface OpenCodeAuthAPI {\n type: \"api\";\n key: string;\n}\n\ntype OpenCodeAuth = OpenCodeAuthOAuth | OpenCodeAuthAPI;\n\nfunction getOpenCodeAuthPath(): string {\n return path.join(os.homedir(), \".local\", \"share\", \"opencode\", \"auth.json\");\n}\n\nfunction loadOpenCodeAuth(): Record<string, OpenCodeAuth> {\n const authPath = getOpenCodeAuthPath();\n try {\n if (existsSync(authPath)) {\n return JSON.parse(readFileSync(authPath, \"utf-8\"));\n }\n } catch {\n // Ignore auth file read errors\n }\n return {};\n}\n\nexport async function detectEmbeddingProvider<P extends EmbeddingProvider>(\n preferredProvider: P, model?: EmbeddingModelName\n): Promise<ConfiguredProviderInfo> {\n const credentials = await getProviderCredentials(preferredProvider);\n if (credentials) {\n if (!model) {\n return {\n provider: preferredProvider,\n credentials,\n modelInfo: getDefaultModelForProvider(preferredProvider),\n } as ConfiguredProviderInfo;\n }\n if (!isValidModel(model, preferredProvider)) {\n throw new Error(\n `Model '${model}' is not supported by provider '${preferredProvider}'`\n );\n }\n const providerModels = EMBEDDING_MODELS[preferredProvider];\n return {\n provider: preferredProvider,\n credentials,\n modelInfo: providerModels[model],\n } as ConfiguredProviderInfo;\n }\n throw new Error(\n `Preferred provider '${preferredProvider}' is not configured or authenticated`\n );\n}\n\nexport async function tryDetectProvider(): Promise<ConfiguredProviderInfo> {\n for (const provider of autoDetectProviders) {\n const credentials = await getProviderCredentials(provider);\n if (credentials) {\n return {\n provider,\n credentials,\n modelInfo: getDefaultModelForProvider(provider),\n } as ConfiguredProviderInfo;\n }\n }\n\n throw new Error(\n `No embedding-capable provider found. Please authenticate with OpenCode using one of: ${autoDetectProviders.join(\", \")}.`\n );\n}\n\nasync function getProviderCredentials(\n provider: EmbeddingProvider\n): Promise<ProviderCredentials | null> {\n switch (provider) {\n case \"github-copilot\":\n return getGitHubCopilotCredentials();\n case \"openai\":\n return getOpenAICredentials();\n case \"google\":\n return getGoogleCredentials();\n case \"ollama\":\n return getOllamaCredentials();\n default:\n return null;\n }\n}\n\nfunction getGitHubCopilotCredentials(): ProviderCredentials | null {\n const authData = loadOpenCodeAuth();\n const copilotAuth = authData[\"github-copilot\"] || authData[\"github-copilot-enterprise\"];\n\n if (!copilotAuth || copilotAuth.type !== \"oauth\") {\n return null;\n }\n\n // Use GitHub Models API for embeddings (models.github.ai)\n // Enterprise uses different URL pattern\n const auth = copilotAuth as OpenCodeAuthOAuth;\n const baseUrl = auth.enterpriseUrl\n ? `https://copilot-api.${auth.enterpriseUrl.replace(/^https?:\\/\\//, \"\").replace(/\\/$/, \"\")}`\n : \"https://models.github.ai\";\n\n return {\n provider: \"github-copilot\",\n baseUrl,\n refreshToken: copilotAuth.refresh,\n accessToken: copilotAuth.access,\n tokenExpires: copilotAuth.expires,\n };\n}\n\nfunction getOpenAICredentials(): ProviderCredentials | null {\n const authData = loadOpenCodeAuth();\n const openaiAuth = authData[\"openai\"];\n\n if (openaiAuth?.type === \"api\") {\n return {\n provider: \"openai\",\n apiKey: openaiAuth.key,\n baseUrl: \"https://api.openai.com/v1\",\n };\n }\n\n return null;\n}\n\nfunction getGoogleCredentials(): ProviderCredentials | null {\n const authData = loadOpenCodeAuth();\n const googleAuth = authData[\"google\"] || authData[\"google-generative-ai\"];\n\n if (googleAuth?.type === \"api\") {\n return {\n provider: \"google\",\n apiKey: googleAuth.key,\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta\",\n };\n }\n\n return null;\n}\n\nasync function getOllamaCredentials(): Promise<ProviderCredentials | null> {\n const baseUrl = process.env.OLLAMA_HOST || \"http://localhost:11434\";\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 2000);\n\n const response = await fetch(`${baseUrl}/api/tags`, {\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n const data = await response.json() as { models?: Array<{ name: string }> };\n const hasEmbeddingModel = data.models?.some(\n (m: { name: string }) =>\n m.name.includes(\"nomic-embed\") ||\n m.name.includes(\"mxbai-embed\") ||\n m.name.includes(\"all-minilm\")\n );\n\n if (hasEmbeddingModel) {\n return {\n provider: \"ollama\",\n baseUrl,\n };\n }\n }\n } catch {\n return null;\n }\n\n return null;\n}\n\nexport function getProviderDisplayName(provider: EmbeddingProvider | 'custom'): string {\n switch (provider) {\n case \"github-copilot\":\n return \"GitHub Copilot\";\n case \"openai\":\n return \"OpenAI\";\n case \"google\":\n return \"Google (Gemini)\";\n case \"ollama\":\n return \"Ollama (Local)\";\n case \"custom\":\n return \"Custom (OpenAI-compatible)\";\n default:\n return provider;\n }\n}\n\nexport function createCustomProviderInfo(config: CustomProviderConfig): ConfiguredProviderInfo {\n // Normalize baseUrl defensively — parseConfig() already strips trailing slashes,\n // but direct callers (e.g. tests) may pass unnormalized URLs.\n const baseUrl = config.baseUrl.replace(/\\/+$/, '');\n return {\n provider: 'custom',\n credentials: {\n provider: 'custom',\n baseUrl,\n apiKey: config.apiKey,\n },\n modelInfo: {\n provider: 'custom',\n model: config.model,\n dimensions: config.dimensions,\n maxTokens: config.maxTokens ?? 8192,\n costPer1MTokens: 0,\n timeoutMs: config.timeoutMs ?? 30_000,\n maxBatchSize: config.maxBatchSize,\n },\n };\n}\n","import { type BaseModelInfo } from \"../config/schema.js\";\n\nimport { type ProviderCredentials } from \"./detector.js\";\n\nexport interface EmbeddingResult {\n embedding: number[];\n tokensUsed: number;\n}\n\nexport interface EmbeddingBatchResult {\n embeddings: number[][];\n totalTokensUsed: number;\n}\n\nexport interface EmbeddingProviderInterface {\n embedQuery(query: string): Promise<EmbeddingResult>;\n embedDocument(document: string): Promise<EmbeddingResult>;\n embedBatch(texts: string[]): Promise<EmbeddingBatchResult>;\n getModelInfo(): BaseModelInfo;\n}\n\nexport abstract class BaseEmbeddingProvider<TModelInfo extends BaseModelInfo>\n implements EmbeddingProviderInterface {\n public constructor(\n protected readonly credentials: ProviderCredentials,\n protected readonly modelInfo: TModelInfo\n ) { }\n\n public async embedQuery(query: string): Promise<EmbeddingResult> {\n const result = await this.embedBatch([query]);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public async embedDocument(document: string): Promise<EmbeddingResult> {\n const result = await this.embedBatch([document]);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public getModelInfo(): TModelInfo {\n return this.modelInfo;\n }\n\n public abstract embedBatch(texts: string[]): Promise<EmbeddingBatchResult>;\n}\n\n/**\n * Thrown by CustomEmbeddingProvider for HTTP 4xx errors (except 429 rate limit).\n * The Indexer's pRetry config uses instanceof to bail immediately on these errors\n * instead of retrying — preventing long retry loops on bad API keys or invalid models.\n */\nexport class CustomProviderNonRetryableError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"CustomProviderNonRetryableError\";\n }\n}\n","/**\n * URL validation utilities to prevent SSRF attacks against cloud metadata services.\n *\n * IMPORTANT: This intentionally allows localhost and private IPs because the custom\n * embedding provider is commonly used with local servers (Ollama, llama.cpp, vLLM,\n * text-embeddings-inference). The threat model is a malicious committed config file\n * targeting cloud metadata endpoints, not blocking legitimate local usage.\n *\n * KNOWN LIMITATION: This validates the hostname string only, not the resolved IP.\n * A DNS rebinding attack (hostname that resolves to 169.254.169.254) bypasses this\n * check. Full mitigation would require DNS resolution pinning (resolve → check IP →\n * connect), which needs a custom HTTP agent. Acceptable for now given the local-only\n * threat model and the low likelihood of DNS rebinding in committed config files.\n */\n\n/** Cloud metadata service IPs and hostnames that should never be contacted. */\nconst BLOCKED_METADATA_IPS = [\n /^169\\.254\\.169\\.254$/, // AWS/Azure/GCP metadata\n /^169\\.254\\.170\\.2$/, // AWS ECS task metadata\n /^fd00:ec2::254$/, // AWS IMDSv2 IPv6\n];\n\nconst BLOCKED_HOSTNAMES = new Set([\n \"metadata.google.internal\",\n \"metadata.google\",\n \"metadata.goog\",\n \"kubernetes.default.svc\",\n]);\n\nexport interface UrlValidationResult {\n valid: boolean;\n reason?: string;\n}\n\n/**\n * Validates that a URL does not point to cloud metadata services or use dangerous protocols.\n * Allows localhost and private IPs for local embedding servers.\n * Returns { valid: true } if the URL is safe, or { valid: false, reason } if blocked.\n */\nexport function validateExternalUrl(urlString: string): UrlValidationResult {\n let parsed: URL;\n try {\n parsed = new URL(urlString);\n } catch {\n return { valid: false, reason: `Invalid URL: ${sanitizeUrlForError(urlString)}` };\n }\n\n // Block non-HTTP protocols (file://, gopher://, ftp://, etc.)\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return { valid: false, reason: `Blocked protocol: ${parsed.protocol}` };\n }\n\n const hostname = parsed.hostname.toLowerCase();\n\n // Block known cloud metadata hostnames\n if (BLOCKED_HOSTNAMES.has(hostname)) {\n return { valid: false, reason: `Blocked: cloud metadata service (${hostname})` };\n }\n\n // Block cloud metadata IPs\n for (const pattern of BLOCKED_METADATA_IPS) {\n if (pattern.test(hostname)) {\n return { valid: false, reason: `Blocked: cloud metadata IP (${hostname})` };\n }\n }\n\n // Block link-local range (169.254.x.x) — used exclusively for metadata/APIPA, not user servers\n if (/^169\\.254\\./.test(hostname)) {\n return { valid: false, reason: `Blocked: link-local address (${hostname})` };\n }\n\n return { valid: true };\n}\n\n/**\n * Strips credentials and sensitive parts from a URL for safe inclusion in error messages.\n */\nexport function sanitizeUrlForError(url: string): string {\n try {\n const parsed = new URL(url);\n // Remove username:password from URL\n parsed.username = \"\";\n parsed.password = \"\";\n return parsed.toString();\n } catch {\n // If URL can't be parsed, truncate and mask\n const maxLen = 80;\n if (url.length > maxLen) {\n return url.slice(0, maxLen) + \"...\";\n }\n return url;\n }\n}\n","import { type CustomModelInfo, type ProviderCredentials } from \"../detector.js\";\nimport {\n BaseEmbeddingProvider,\n CustomProviderNonRetryableError,\n type EmbeddingBatchResult,\n} from \"../provider-types.js\";\nimport { sanitizeUrlForError, validateExternalUrl } from \"../../utils/url-validation.js\";\n\nexport class CustomEmbeddingProvider extends BaseEmbeddingProvider<CustomModelInfo> {\n public constructor(credentials: ProviderCredentials, modelInfo: CustomModelInfo) {\n super(credentials, modelInfo);\n }\n\n private splitIntoRequestBatches(texts: string[]): string[][] {\n const maxBatchSize = this.modelInfo.maxBatchSize;\n\n if (!maxBatchSize || texts.length <= maxBatchSize) {\n return [texts];\n }\n\n const batches: string[][] = [];\n for (let i = 0; i < texts.length; i += maxBatchSize) {\n batches.push(texts.slice(i, i + maxBatchSize));\n }\n return batches;\n }\n\n private async embedRequest(texts: string[]): Promise<EmbeddingBatchResult> {\n if (texts.length === 0) {\n return {\n embeddings: [],\n totalTokensUsed: 0,\n };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (this.credentials.apiKey) {\n headers.Authorization = `Bearer ${this.credentials.apiKey}`;\n }\n\n const baseUrl = this.credentials.baseUrl ?? \"\";\n const fullUrl = `${baseUrl}/embeddings`;\n\n const urlCheck = validateExternalUrl(fullUrl);\n if (!urlCheck.valid) {\n throw new CustomProviderNonRetryableError(\n `Custom embedding provider URL blocked (SSRF protection): ${urlCheck.reason}`\n );\n }\n\n const timeoutMs = this.modelInfo.timeoutMs;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n let response: Response;\n try {\n response = await fetch(fullUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model: this.modelInfo.model,\n input: texts,\n }),\n signal: controller.signal,\n });\n } catch (error: unknown) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Custom embedding API request timed out after ${timeoutMs}ms for ${sanitizeUrlForError(fullUrl)}`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n\n if (!response.ok) {\n const errorText = (await response.text()).slice(0, 500);\n if (response.status >= 400 && response.status < 500 && response.status !== 429) {\n throw new CustomProviderNonRetryableError(`Custom embedding API error (non-retryable): ${response.status} - ${errorText}`);\n }\n throw new Error(`Custom embedding API error: ${response.status} - ${errorText}`);\n }\n\n const data = await response.json() as {\n data?: Array<{ embedding: number[] }>;\n usage?: { total_tokens: number };\n };\n\n if (data.data && Array.isArray(data.data)) {\n if (data.data.length > 0) {\n const actualDims = data.data[0].embedding.length;\n if (actualDims !== this.modelInfo.dimensions) {\n throw new Error(\n `Dimension mismatch: customProvider.dimensions is ${this.modelInfo.dimensions}, ` +\n `but the API returned vectors with ${actualDims} dimensions. ` +\n `Update your config to match the model's actual output dimensions.`\n );\n }\n }\n\n if (data.data.length !== texts.length) {\n throw new Error(\n `Embedding count mismatch: sent ${texts.length} texts but received ${data.data.length} embeddings. ` +\n `The custom embedding server may not support batch input.`\n );\n }\n\n return {\n embeddings: data.data.map((d) => d.embedding),\n totalTokensUsed: data.usage?.total_tokens ?? texts.reduce((sum, t) => sum + Math.ceil(t.length / 4), 0),\n };\n }\n\n throw new Error(\"Custom embedding API returned unexpected response format. Expected OpenAI-compatible format with data[].embedding.\");\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const requestBatches = this.splitIntoRequestBatches(texts);\n const embeddings: number[][] = [];\n let totalTokensUsed = 0;\n\n for (const batch of requestBatches) {\n const result = await this.embedRequest(batch);\n embeddings.push(...result.embeddings);\n totalTokensUsed += result.totalTokensUsed;\n }\n\n return {\n embeddings,\n totalTokensUsed,\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport { BaseEmbeddingProvider, type EmbeddingBatchResult } from \"../provider-types.js\";\n\nexport class GitHubCopilotEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"github-copilot\"]> {\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"github-copilot\"]\n ) {\n super(credentials, modelInfo);\n }\n\n private getToken(): string {\n if (!this.credentials.refreshToken) {\n throw new Error(\"No OAuth token available for GitHub\");\n }\n return this.credentials.refreshToken;\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const token = this.getToken();\n\n const response = await fetch(`${this.credentials.baseUrl}/inference/embeddings`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n body: JSON.stringify({\n model: `openai/${this.modelInfo.model}`,\n input: texts,\n }),\n });\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`GitHub Copilot embedding API error: ${response.status} - ${error}`);\n }\n\n const data = await response.json() as {\n data: Array<{ embedding: number[] }>;\n usage: { total_tokens: number };\n };\n\n return {\n embeddings: data.data.map((d) => d.embedding),\n totalTokensUsed: data.usage.total_tokens,\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport {\n BaseEmbeddingProvider,\n type EmbeddingBatchResult,\n type EmbeddingResult,\n} from \"../provider-types.js\";\n\nexport class GoogleEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"google\"]> {\n private static readonly BATCH_SIZE = 20;\n\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"google\"]\n ) {\n super(credentials, modelInfo);\n }\n\n public async embedQuery(query: string): Promise<EmbeddingResult> {\n const taskType = this.modelInfo.taskAble ? \"CODE_RETRIEVAL_QUERY\" : undefined;\n const result = await this.embedWithTaskType([query], taskType);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public async embedDocument(document: string): Promise<EmbeddingResult> {\n const taskType = this.modelInfo.taskAble ? \"RETRIEVAL_DOCUMENT\" : undefined;\n const result = await this.embedWithTaskType([document], taskType);\n return {\n embedding: result.embeddings[0],\n tokensUsed: result.totalTokensUsed,\n };\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const taskType = this.modelInfo.taskAble ? \"RETRIEVAL_DOCUMENT\" : undefined;\n return this.embedWithTaskType(texts, taskType);\n }\n\n private async embedWithTaskType(\n texts: string[],\n taskType?: string\n ): Promise<EmbeddingBatchResult> {\n const batches: string[][] = [];\n for (let i = 0; i < texts.length; i += GoogleEmbeddingProvider.BATCH_SIZE) {\n batches.push(texts.slice(i, i + GoogleEmbeddingProvider.BATCH_SIZE));\n }\n\n const batchResults = await Promise.all(\n batches.map(async (batch) => {\n const requests = batch.map((text) => ({\n model: `models/${this.modelInfo.model}`,\n content: {\n parts: [{ text }],\n },\n taskType,\n outputDimensionality: this.modelInfo.dimensions,\n }));\n\n const response = await fetch(\n `${this.credentials.baseUrl}/models/${this.modelInfo.model}:batchEmbedContents`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(this.credentials.apiKey && { \"x-goog-api-key\": this.credentials.apiKey }),\n },\n body: JSON.stringify({ requests }),\n }\n );\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`Google embedding API error: ${response.status} - ${error}`);\n }\n\n const data = (await response.json()) as {\n embeddings: Array<{ values: number[] }>;\n };\n\n return {\n embeddings: data.embeddings.map((e) => e.values),\n tokensUsed: batch.reduce((sum, text) => sum + Math.ceil(text.length / 4), 0),\n };\n })\n );\n\n return {\n embeddings: batchResults.flatMap((r) => r.embeddings),\n totalTokensUsed: batchResults.reduce((sum, r) => sum + r.tokensUsed, 0),\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport { BaseEmbeddingProvider, type EmbeddingBatchResult } from \"../provider-types.js\";\n\nexport class OllamaEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"ollama\"]> {\n private static readonly MIN_TRUNCATION_CHARS = 512;\n\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"ollama\"]\n ) {\n super(credentials, modelInfo);\n }\n\n private estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n }\n\n private truncateToCharLimit(text: string, maxChars: number): string {\n if (text.length <= maxChars) {\n return text;\n }\n\n return `${text.slice(0, Math.max(0, maxChars - 17))}\\n... [truncated]`;\n }\n\n private isContextLengthError(error: unknown): boolean {\n const message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n return (message.includes(\"context length\") && (message.includes(\"exceed\") || message.includes(\"exceeded\") || message.includes(\"too long\")))\n || message.includes(\"input length exceeds the context length\")\n || message.includes(\"context length exceeded\");\n }\n\n private buildTruncationCandidates(text: string): string[] {\n const baseMaxChars = Math.max(1, this.modelInfo.maxTokens * 4);\n const candidateLimits = new Set<number>();\n const baselineLimit = text.length > baseMaxChars\n ? baseMaxChars\n : Math.max(\n OllamaEmbeddingProvider.MIN_TRUNCATION_CHARS,\n Math.floor(text.length * 0.9)\n );\n\n if (baselineLimit < text.length) {\n candidateLimits.add(baselineLimit);\n }\n\n for (const factor of [0.75, 0.6, 0.45, 0.35, 0.25]) {\n const scaledLimit = Math.max(\n OllamaEmbeddingProvider.MIN_TRUNCATION_CHARS,\n Math.floor(baselineLimit * factor)\n );\n if (scaledLimit < text.length) {\n candidateLimits.add(scaledLimit);\n }\n }\n\n candidateLimits.add(Math.min(text.length - 1, OllamaEmbeddingProvider.MIN_TRUNCATION_CHARS));\n\n const candidates: string[] = [];\n const seen = new Set<string>();\n for (const limit of [...candidateLimits].sort((a, b) => b - a)) {\n if (limit <= 0 || limit >= text.length) {\n continue;\n }\n\n const truncated = this.truncateToCharLimit(text, limit);\n if (truncated === text || seen.has(truncated)) {\n continue;\n }\n\n seen.add(truncated);\n candidates.push(truncated);\n }\n\n return candidates;\n }\n\n private async embedSingleWithFallback(text: string): Promise<{ embedding: number[]; tokensUsed: number }> {\n try {\n return await this.embedSingle(text);\n } catch (error) {\n if (!this.isContextLengthError(error)) {\n throw error;\n }\n\n let lastError: unknown = error;\n for (const truncated of this.buildTruncationCandidates(text)) {\n try {\n return await this.embedSingle(truncated);\n } catch (retryError) {\n if (!this.isContextLengthError(retryError)) {\n throw retryError;\n }\n lastError = retryError;\n }\n }\n\n throw lastError;\n }\n }\n\n private async embedSingle(text: string): Promise<{ embedding: number[]; tokensUsed: number }> {\n const response = await fetch(`${this.credentials.baseUrl}/api/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: this.modelInfo.model,\n prompt: text,\n truncate: false,\n }),\n });\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`Ollama embedding API error: ${response.status} - ${error}`);\n }\n\n const data = (await response.json()) as {\n embedding: number[];\n };\n\n return {\n embedding: data.embedding,\n tokensUsed: this.estimateTokens(text),\n };\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const results: Array<{ embedding: number[]; tokensUsed: number }> = [];\n\n for (const text of texts) {\n results.push(await this.embedSingleWithFallback(text));\n }\n\n return {\n embeddings: results.map((r) => r.embedding),\n totalTokensUsed: results.reduce((sum, r) => sum + r.tokensUsed, 0),\n };\n }\n}\n","import { type EmbeddingProviderModelInfo } from \"../../config/schema.js\";\n\nimport { type ProviderCredentials } from \"../detector.js\";\nimport { BaseEmbeddingProvider, type EmbeddingBatchResult } from \"../provider-types.js\";\n\nexport class OpenAIEmbeddingProvider extends BaseEmbeddingProvider<EmbeddingProviderModelInfo[\"openai\"]> {\n public constructor(\n credentials: ProviderCredentials,\n modelInfo: EmbeddingProviderModelInfo[\"openai\"]\n ) {\n super(credentials, modelInfo);\n }\n\n public async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const response = await fetch(`${this.credentials.baseUrl}/embeddings`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.credentials.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: this.modelInfo.model,\n input: texts,\n }),\n });\n\n if (!response.ok) {\n const error = (await response.text()).slice(0, 500);\n throw new Error(`OpenAI embedding API error: ${response.status} - ${error}`);\n }\n\n const data = await response.json() as {\n data: Array<{ embedding: number[] }>;\n usage: { total_tokens: number };\n };\n\n return {\n embeddings: data.data.map((d) => d.embedding),\n totalTokensUsed: data.usage.total_tokens,\n };\n }\n}\n","import { type ConfiguredProviderInfo } from \"./detector.js\";\nimport { CustomEmbeddingProvider } from \"./providers/custom.js\";\nimport { GitHubCopilotEmbeddingProvider } from \"./providers/github-copilot.js\";\nimport { GoogleEmbeddingProvider } from \"./providers/google.js\";\nimport { OllamaEmbeddingProvider } from \"./providers/ollama.js\";\nimport { OpenAIEmbeddingProvider } from \"./providers/openai.js\";\n\nexport {\n BaseEmbeddingProvider,\n CustomProviderNonRetryableError,\n type EmbeddingBatchResult,\n type EmbeddingProviderInterface,\n type EmbeddingResult,\n} from \"./provider-types.js\";\n\nexport function createEmbeddingProvider(\n configuredProviderInfo: ConfiguredProviderInfo,\n): import(\"./provider-types.js\").EmbeddingProviderInterface {\n switch (configuredProviderInfo.provider) {\n case \"github-copilot\":\n return new GitHubCopilotEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"openai\":\n return new OpenAIEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"google\":\n return new GoogleEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"ollama\":\n return new OllamaEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n case \"custom\":\n return new CustomEmbeddingProvider(configuredProviderInfo.credentials, configuredProviderInfo.modelInfo);\n default: {\n const _exhaustive: never = configuredProviderInfo;\n throw new Error(`Unsupported embedding provider: ${(_exhaustive as ConfiguredProviderInfo).provider}`);\n }\n }\n}\n","import { RerankerConfig } from \"../config/schema.js\";\n\nexport interface RerankResult {\n index: number;\n relevanceScore: number;\n document?: string;\n}\n\nexport interface RerankResponse {\n results: RerankResult[];\n tokensUsed?: number;\n}\n\nexport interface RerankerInterface {\n isAvailable(): boolean;\n rerank(query: string, documents: string[], topN?: number): Promise<RerankResponse>;\n}\n\nexport function createReranker(config: RerankerConfig): RerankerInterface {\n if (!config.enabled) {\n return new NoOpReranker();\n }\n return new SiliconFlowReranker(config);\n}\n\nclass NoOpReranker implements RerankerInterface {\n isAvailable(): boolean {\n return false;\n }\n\n async rerank(_query: string, documents: string[], _topN?: number): Promise<RerankResponse> {\n return {\n results: documents.map((_, index) => ({ index, relevanceScore: 0 })),\n };\n }\n}\n\nclass SiliconFlowReranker implements RerankerInterface {\n private config: RerankerConfig;\n\n constructor(config: RerankerConfig) {\n this.config = config;\n }\n\n isAvailable(): boolean {\n return this.config.enabled && !!this.config.baseUrl && !!this.config.model;\n }\n\n async rerank(query: string, documents: string[], topN?: number): Promise<RerankResponse> {\n if (documents.length === 0) {\n return { results: [] };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (this.config.apiKey) {\n headers[\"Authorization\"] = `Bearer ${this.config.apiKey}`;\n }\n\n const baseUrl = this.config.baseUrl;\n if (!baseUrl) {\n throw new Error(\"Reranker baseUrl is required. Configure reranker.baseUrl in your codebase-index.json.\");\n }\n const timeoutMs = this.config.timeoutMs ?? 30000;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(`${baseUrl}/rerank`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model: this.config.model,\n query,\n documents,\n top_n: topN ?? this.config.topN ?? 20,\n return_documents: false,\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Rerank API error: ${response.status} - ${errorText}`);\n }\n\n const data = await response.json() as {\n results: Array<{\n index: number;\n relevance_score: number;\n document?: { text: string };\n }>;\n meta?: {\n tokens?: {\n input_tokens: number;\n output_tokens: number;\n };\n };\n };\n\n return {\n results: data.results.map((r) => ({\n index: r.index,\n relevanceScore: r.relevance_score,\n document: r.document?.text,\n })),\n tokensUsed: data.meta?.tokens?.input_tokens,\n };\n } catch (error: unknown) {\n clearTimeout(timeout);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`Rerank API request timed out after ${timeoutMs}ms`);\n }\n throw error;\n }\n }\n}\n","import { BaseModelInfo } from \"../config/schema.js\";\nimport { getProviderDisplayName, ConfiguredProviderInfo } from \"../embeddings/detector.js\";\n\nexport interface CostEstimate {\n filesCount: number;\n totalSizeBytes: number;\n estimatedChunks: number;\n estimatedTokens: number;\n estimatedCost: number;\n provider: string;\n model: string;\n isFree: boolean;\n}\n\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nexport function estimateChunksFromFiles(\n files: Array<{ path: string; size: number }>\n): number {\n let totalChunks = 0;\n\n for (const file of files) {\n const avgChunkSize = 400;\n const chunksPerFile = Math.max(1, Math.ceil(file.size / avgChunkSize));\n totalChunks += chunksPerFile;\n }\n\n return totalChunks;\n}\n\nexport function estimateCost(\n estimatedTokens: number,\n modelInfo: BaseModelInfo\n): number {\n return (estimatedTokens / 1_000_000) * modelInfo.costPer1MTokens;\n}\n\nexport function createCostEstimate(\n files: Array<{ path: string; size: number }>,\n provider: ConfiguredProviderInfo\n): CostEstimate {\n const filesCount = files.length;\n const totalSizeBytes = files.reduce((sum, f) => sum + f.size, 0);\n const estimatedChunks = estimateChunksFromFiles(files);\n const avgTokensPerChunk = 150;\n const estimatedTokens = estimatedChunks * avgTokensPerChunk;\n const estimatedCost = estimateCost(estimatedTokens, provider.modelInfo);\n\n return {\n filesCount,\n totalSizeBytes,\n estimatedChunks,\n estimatedTokens,\n estimatedCost,\n provider: getProviderDisplayName(provider.provider),\n model: provider.modelInfo.model,\n isFree: provider.modelInfo.costPer1MTokens === 0,\n };\n}\n\nexport function formatCostEstimate(estimate: CostEstimate): string {\n const sizeFormatted = formatBytes(estimate.totalSizeBytes);\n const filesFormatted = `${estimate.filesCount.toLocaleString()} files`;\n const costFormatted = estimate.isFree\n ? \"Free\"\n : `~$${estimate.estimatedCost.toFixed(4)}`;\n\n return `\n┌─────────────────────────────────────────────────────────────────┐\n│ 📊 Indexing Estimate │\n├─────────────────────────────────────────────────────────────────┤\n│ │\n│ Files to index: ${filesFormatted.padEnd(40)}│\n│ Total size: ${sizeFormatted.padEnd(40)}│\n│ Estimated chunks: ${(\"~\" + estimate.estimatedChunks.toLocaleString() + \" chunks\").padEnd(40)}│\n│ Estimated tokens: ${(\"~\" + estimate.estimatedTokens.toLocaleString() + \" tokens\").padEnd(40)}│\n│ │\n│ Provider: ${estimate.provider.padEnd(52)}│\n│ Model: ${estimate.model.padEnd(52)}│\n│ Cost: ${costFormatted.padEnd(52)}│\n│ │\n└─────────────────────────────────────────────────────────────────┘\n`;\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return \"0 B\";\n const k = 1024;\n const sizes = [\"B\", \"KB\", \"MB\", \"GB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + \" \" + sizes[i];\n}\n\n\nexport interface ConfirmationResult {\n confirmed: boolean;\n rememberChoice: boolean;\n}\n\nexport function formatConfirmationPrompt(): string {\n return `\nProceed with indexing? [Y/n/always]\n\n Y - Index now\n n - Cancel\n always - Index now and don't ask again for this project\n`;\n}\n\nexport function parseConfirmationResponse(response: string): ConfirmationResult {\n const normalized = response.toLowerCase().trim();\n\n if (normalized === \"\" || normalized === \"y\" || normalized === \"yes\") {\n return { confirmed: true, rememberChoice: false };\n }\n\n if (normalized === \"always\" || normalized === \"a\") {\n return { confirmed: true, rememberChoice: true };\n }\n\n return { confirmed: false, rememberChoice: false };\n}\n","import type { DebugConfig, LogLevel } from \"../config/schema.js\";\n\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nexport interface Metrics {\n indexingStartTime?: number;\n indexingEndTime?: number;\n filesScanned: number;\n filesParsed: number;\n parseMs: number;\n chunksProcessed: number;\n chunksEmbedded: number;\n chunksFromCache: number;\n chunksRemoved: number;\n embeddingApiCalls: number;\n embeddingTokensUsed: number;\n embeddingErrors: number;\n \n searchCount: number;\n searchTotalMs: number;\n searchAvgMs: number;\n searchLastMs: number;\n embeddingCallMs: number;\n vectorSearchMs: number;\n keywordSearchMs: number;\n fusionMs: number;\n \n cacheHits: number;\n cacheMisses: number;\n \n queryCacheHits: number;\n queryCacheSimilarHits: number;\n queryCacheMisses: number;\n \n gcRuns: number;\n gcOrphansRemoved: number;\n gcChunksRemoved: number;\n gcEmbeddingsRemoved: number;\n}\n\nexport interface LogEntry {\n timestamp: string;\n level: LogLevel;\n category: string;\n message: string;\n data?: Record<string, unknown>;\n}\n\nfunction createEmptyMetrics(): Metrics {\n return {\n filesScanned: 0,\n filesParsed: 0,\n parseMs: 0,\n chunksProcessed: 0,\n chunksEmbedded: 0,\n chunksFromCache: 0,\n chunksRemoved: 0,\n embeddingApiCalls: 0,\n embeddingTokensUsed: 0,\n embeddingErrors: 0,\n searchCount: 0,\n searchTotalMs: 0,\n searchAvgMs: 0,\n searchLastMs: 0,\n embeddingCallMs: 0,\n vectorSearchMs: 0,\n keywordSearchMs: 0,\n fusionMs: 0,\n cacheHits: 0,\n cacheMisses: 0,\n queryCacheHits: 0,\n queryCacheSimilarHits: 0,\n queryCacheMisses: 0,\n gcRuns: 0,\n gcOrphansRemoved: 0,\n gcChunksRemoved: 0,\n gcEmbeddingsRemoved: 0,\n };\n}\n\nexport class Logger {\n private config: DebugConfig;\n private metrics: Metrics;\n private logs: LogEntry[] = [];\n private maxLogs = 1000;\n\n constructor(config: DebugConfig) {\n this.config = config;\n this.metrics = createEmptyMetrics();\n }\n\n private shouldLog(level: LogLevel): boolean {\n if (!this.config.enabled) return false;\n return LOG_LEVEL_PRIORITY[level] <= LOG_LEVEL_PRIORITY[this.config.logLevel];\n }\n\n private log(level: LogLevel, category: string, message: string, data?: Record<string, unknown>): void {\n if (!this.shouldLog(level)) return;\n\n const entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n category,\n message,\n data,\n };\n\n this.logs.push(entry);\n if (this.logs.length > this.maxLogs) {\n this.logs.shift();\n }\n }\n\n private withMetrics(fn: () => void): void {\n if (!this.config.metrics) return;\n fn();\n }\n\n search(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logSearch) {\n this.log(level, \"search\", message, data);\n }\n }\n\n embedding(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logEmbedding) {\n this.log(level, \"embedding\", message, data);\n }\n }\n\n cache(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logCache) {\n this.log(level, \"cache\", message, data);\n }\n }\n\n gc(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logGc) {\n this.log(level, \"gc\", message, data);\n }\n }\n\n branch(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (this.config.logBranch) {\n this.log(level, \"branch\", message, data);\n }\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.log(\"info\", \"general\", message, data);\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.log(\"warn\", \"general\", message, data);\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.log(\"error\", \"general\", message, data);\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.log(\"debug\", \"general\", message, data);\n }\n\n recordIndexingStart(): void {\n this.withMetrics(() => {\n this.metrics.indexingStartTime = Date.now();\n });\n }\n\n recordIndexingEnd(): void {\n this.withMetrics(() => {\n this.metrics.indexingEndTime = Date.now();\n });\n }\n\n recordFilesScanned(count: number): void {\n this.withMetrics(() => {\n this.metrics.filesScanned = count;\n });\n }\n\n recordFilesParsed(count: number): void {\n this.withMetrics(() => {\n this.metrics.filesParsed = count;\n });\n }\n\n recordParseDuration(durationMs: number): void {\n this.withMetrics(() => {\n this.metrics.parseMs = durationMs;\n });\n }\n\n recordChunksProcessed(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksProcessed += count;\n });\n }\n\n recordChunksEmbedded(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksEmbedded += count;\n });\n }\n\n recordChunksFromCache(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksFromCache += count;\n });\n }\n\n recordChunksRemoved(count: number): void {\n this.withMetrics(() => {\n this.metrics.chunksRemoved += count;\n });\n }\n\n recordEmbeddingApiCall(tokens: number): void {\n this.withMetrics(() => {\n this.metrics.embeddingApiCalls++;\n this.metrics.embeddingTokensUsed += tokens;\n });\n }\n\n recordEmbeddingError(): void {\n this.withMetrics(() => {\n this.metrics.embeddingErrors++;\n });\n }\n\n recordSearch(durationMs: number, breakdown?: { embeddingMs: number; vectorMs: number; keywordMs: number; fusionMs: number }): void {\n this.withMetrics(() => {\n this.metrics.searchCount++;\n this.metrics.searchTotalMs += durationMs;\n this.metrics.searchLastMs = durationMs;\n this.metrics.searchAvgMs = this.metrics.searchTotalMs / this.metrics.searchCount;\n\n if (breakdown) {\n this.metrics.embeddingCallMs = breakdown.embeddingMs;\n this.metrics.vectorSearchMs = breakdown.vectorMs;\n this.metrics.keywordSearchMs = breakdown.keywordMs;\n this.metrics.fusionMs = breakdown.fusionMs;\n }\n });\n }\n\n recordCacheHit(): void {\n this.withMetrics(() => {\n this.metrics.cacheHits++;\n });\n }\n\n recordCacheMiss(): void {\n this.withMetrics(() => {\n this.metrics.cacheMisses++;\n });\n }\n\n recordQueryCacheHit(): void {\n this.withMetrics(() => {\n this.metrics.queryCacheHits++;\n });\n }\n\n recordQueryCacheSimilarHit(): void {\n this.withMetrics(() => {\n this.metrics.queryCacheSimilarHits++;\n });\n }\n\n recordQueryCacheMiss(): void {\n this.withMetrics(() => {\n this.metrics.queryCacheMisses++;\n });\n }\n\n recordGc(orphans: number, chunks: number, embeddings: number): void {\n this.withMetrics(() => {\n this.metrics.gcRuns++;\n this.metrics.gcOrphansRemoved += orphans;\n this.metrics.gcChunksRemoved += chunks;\n this.metrics.gcEmbeddingsRemoved += embeddings;\n });\n }\n\n getMetrics(): Metrics {\n return { ...this.metrics };\n }\n\n getLogs(limit?: number): LogEntry[] {\n const logs = [...this.logs];\n if (limit) {\n return logs.slice(-limit);\n }\n return logs;\n }\n\n getLogsByCategory(category: string, limit?: number): LogEntry[] {\n const filtered = this.logs.filter(l => l.category === category);\n if (limit) {\n return filtered.slice(-limit);\n }\n return filtered;\n }\n\n getLogsByLevel(level: LogLevel, limit?: number): LogEntry[] {\n const filtered = this.logs.filter(l => l.level === level);\n if (limit) {\n return filtered.slice(-limit);\n }\n return filtered;\n }\n\n resetMetrics(): void {\n this.metrics = createEmptyMetrics();\n }\n\n clearLogs(): void {\n this.logs = [];\n }\n\n formatMetrics(): string {\n const m = this.metrics;\n const lines: string[] = [];\n \n if (m.indexingStartTime && m.indexingEndTime) {\n const duration = m.indexingEndTime - m.indexingStartTime;\n lines.push(`Indexing duration: ${(duration / 1000).toFixed(2)}s`);\n }\n \n lines.push(\"\");\n lines.push(\"Indexing:\");\n lines.push(` Files scanned: ${m.filesScanned}`);\n lines.push(` Files parsed: ${m.filesParsed}`);\n lines.push(` Chunks processed: ${m.chunksProcessed}`);\n lines.push(` Chunks embedded: ${m.chunksEmbedded}`);\n lines.push(` Chunks from cache: ${m.chunksFromCache}`);\n lines.push(` Chunks removed: ${m.chunksRemoved}`);\n \n lines.push(\"\");\n lines.push(\"Embedding API:\");\n lines.push(` API calls: ${m.embeddingApiCalls}`);\n lines.push(` Tokens used: ${m.embeddingTokensUsed.toLocaleString()}`);\n lines.push(` Errors: ${m.embeddingErrors}`);\n \n if (m.searchCount > 0) {\n lines.push(\"\");\n lines.push(\"Search:\");\n lines.push(` Total searches: ${m.searchCount}`);\n lines.push(` Average time: ${m.searchAvgMs.toFixed(2)}ms`);\n lines.push(` Last search: ${m.searchLastMs.toFixed(2)}ms`);\n if (m.embeddingCallMs > 0) {\n lines.push(` - Embedding: ${m.embeddingCallMs.toFixed(2)}ms`);\n lines.push(` - Vector search: ${m.vectorSearchMs.toFixed(2)}ms`);\n lines.push(` - Keyword search: ${m.keywordSearchMs.toFixed(2)}ms`);\n lines.push(` - Fusion: ${m.fusionMs.toFixed(2)}ms`);\n }\n }\n \n const totalCacheOps = m.cacheHits + m.cacheMisses;\n if (totalCacheOps > 0) {\n lines.push(\"\");\n lines.push(\"Cache:\");\n lines.push(` Hits: ${m.cacheHits}`);\n lines.push(` Misses: ${m.cacheMisses}`);\n lines.push(` Hit rate: ${((m.cacheHits / totalCacheOps) * 100).toFixed(1)}%`);\n }\n \n if (m.gcRuns > 0) {\n lines.push(\"\");\n lines.push(\"Garbage Collection:\");\n lines.push(` GC runs: ${m.gcRuns}`);\n lines.push(` Orphans removed: ${m.gcOrphansRemoved}`);\n lines.push(` Chunks removed: ${m.gcChunksRemoved}`);\n lines.push(` Embeddings removed: ${m.gcEmbeddingsRemoved}`);\n }\n \n return lines.join(\"\\n\");\n }\n\n formatRecentLogs(limit = 20): string {\n const logs = this.getLogs(limit);\n if (logs.length === 0) {\n return \"No logs recorded.\";\n }\n \n return logs.map(l => {\n const dataStr = l.data ? ` ${JSON.stringify(l.data)}` : \"\";\n return `[${l.timestamp}] [${l.level.toUpperCase()}] [${l.category}] ${l.message}${dataStr}`;\n }).join(\"\\n\");\n }\n\n isEnabled(): boolean {\n return this.config.enabled;\n }\n\n isMetricsEnabled(): boolean {\n return this.config.enabled && this.config.metrics;\n }\n}\n\nlet globalLogger: Logger | null = null;\n\nexport function initializeLogger(config: DebugConfig): Logger {\n globalLogger = new Logger(config);\n return globalLogger;\n}\n\nexport function getLogger(): Logger | null {\n return globalLogger;\n}\n","import * as path from \"path\";\nimport * as os from \"os\";\nimport * as module from \"module\";\nimport { fileURLToPath } from \"url\";\n\nfunction getNativeBinding() {\n const platform = os.platform();\n const arch = os.arch();\n\n let bindingName: string;\n \n if (platform === \"darwin\" && arch === \"arm64\") {\n bindingName = \"codebase-index-native.darwin-arm64.node\";\n } else if (platform === \"darwin\" && arch === \"x64\") {\n bindingName = \"codebase-index-native.darwin-x64.node\";\n } else if (platform === \"linux\" && arch === \"x64\") {\n bindingName = \"codebase-index-native.linux-x64-gnu.node\";\n } else if (platform === \"linux\" && arch === \"arm64\") {\n bindingName = \"codebase-index-native.linux-arm64-gnu.node\";\n } else if (platform === \"win32\" && arch === \"x64\") {\n bindingName = \"codebase-index-native.win32-x64-msvc.node\";\n } else {\n throw new Error(`Unsupported platform: ${platform}-${arch}`);\n }\n\n // Determine the current directory - handle ESM, CJS, and bundled contexts\n let currentDir: string;\n let requireTarget: string;\n \n // Check for ESM context with valid import.meta.url\n if (typeof import.meta !== 'undefined' && import.meta.url) {\n currentDir = path.dirname(fileURLToPath(import.meta.url));\n requireTarget = import.meta.url;\n } \n // Fallback to __dirname for CJS/bundled contexts\n else if (typeof __dirname !== 'undefined') {\n currentDir = __dirname;\n requireTarget = __filename;\n }\n // Last resort: use process.cwd() - shouldn't normally hit this\n else {\n currentDir = process.cwd();\n requireTarget = path.join(currentDir, \"index.js\");\n }\n \n // The native module is in the 'native' folder at package root\n // From dist/index.js, we go up one level to package root, then into native/\n // From src/native/index.ts (dev/test), we go up two levels to package root\n const normalizedDir = currentDir.replace(/\\\\/g, '/');\n const isDevMode = normalizedDir.includes('/src/native') || currentDir.includes(path.join('src', 'native'));\n const packageRoot = isDevMode\n ? path.resolve(currentDir, '../..')\n : path.resolve(currentDir, '..');\n const nativePath = path.join(packageRoot, 'native', bindingName);\n \n // Load the native module - use standard require for .node files\n const require = module.createRequire(requireTarget);\n return require(nativePath);\n}\n\nfunction createMockNativeBinding() {\n const error = new Error(\"Native module not available. Please rebuild with 'npm run build:native'.\");\n \n return {\n parseFile: () => { throw error; },\n parseFiles: () => { throw error; },\n hashContent: () => { throw error; },\n hashFile: () => { throw error; },\n extractCalls: () => { throw error; },\n VectorStore: class {\n constructor() { throw error; }\n },\n InvertedIndex: class {\n constructor() { throw error; }\n serialize() { throw error; }\n deserialize() { throw error; }\n },\n Database: class {\n constructor() { throw error; }\n close() { throw error; }\n },\n };\n}\n\nlet native: any;\ntry {\n native = getNativeBinding();\n} catch (e) {\n console.error(\"[codebase-index] Failed to load native module:\", e);\n native = createMockNativeBinding();\n}\n\nexport interface FileInput {\n path: string;\n content: string;\n}\n\nexport interface CodeChunk {\n content: string;\n startLine: number;\n endLine: number;\n chunkType: ChunkType;\n name?: string;\n language: string;\n}\n\nexport type ChunkType =\n | \"function\"\n | \"class\"\n | \"method\"\n | \"interface\"\n | \"type\"\n | \"enum\"\n | \"struct\"\n | \"impl\"\n | \"trait\"\n | \"module\"\n | \"import\"\n | \"export\"\n | \"comment\"\n | \"other\";\n\nexport interface ParsedFile {\n path: string;\n chunks: CodeChunk[];\n hash: string;\n}\n\n\nexport type Confidence = \"Direct\" | \"Inferred\";\n\nexport type CallType = \"Call\" | \"MethodCall\" | \"Constructor\" | \"Import\" | \"Inherits\" | \"Implements\";\n\nexport interface CallSiteData {\n calleeName: string;\n line: number;\n column: number;\n callType: CallType;\n confidence: Confidence;\n}\n\nexport interface SymbolData {\n id: string;\n filePath: string;\n name: string;\n kind: string;\n startLine: number;\n startCol: number;\n endLine: number;\n endCol: number;\n language: string;\n}\n\nexport interface CallEdgeData {\n id: string;\n fromSymbolId: string;\n fromSymbolName?: string;\n fromSymbolFilePath?: string;\n targetName: string;\n toSymbolId?: string;\n callType: string;\n confidence: string;\n line: number;\n col: number;\n isResolved: boolean;\n}\n\nexport interface PathHopData {\n symbolId: string;\n symbolName: string;\n filePath: string;\n line: number;\n callType: string;\n}\n\nexport interface SearchResult {\n id: string;\n score: number;\n metadata: ChunkMetadata;\n}\n\nexport interface ChunkMetadata {\n filePath: string;\n startLine: number;\n endLine: number;\n chunkType: ChunkType;\n name?: string;\n language: string;\n hash: string;\n}\n\nexport function parseFile(filePath: string, content: string): CodeChunk[] {\n const result = native.parseFile(filePath, content);\n return result.map(mapChunk);\n}\n\nexport function parseFileAsText(filePath: string, content: string): CodeChunk[] {\n const result = native.parseFileAsText(filePath, content);\n return result.map(mapChunk);\n}\n\nexport function parseFiles(files: FileInput[]): ParsedFile[] {\n const result = native.parseFiles(files);\n return result.map((f: any) => ({\n path: f.path,\n chunks: f.chunks.map(mapChunk),\n hash: f.hash,\n }));\n}\n\nfunction mapChunk(c: any): CodeChunk {\n return {\n content: c.content,\n startLine: c.startLine ?? c.start_line,\n endLine: c.endLine ?? c.end_line,\n chunkType: (c.chunkType ?? c.chunk_type) as ChunkType,\n name: c.name ?? undefined,\n language: c.language,\n };\n}\n\nexport function hashContent(content: string): string {\n return native.hashContent(content);\n}\n\nexport function hashFile(filePath: string): string {\n return native.hashFile(filePath);\n}\n\n\nexport function extractCalls(content: string, language: string): CallSiteData[] {\n return native.extractCalls(content, language);\n}\n\nexport class VectorStore {\n private inner: any;\n private dimensions: number;\n\n constructor(indexPath: string, dimensions: number) {\n this.inner = new native.VectorStore(indexPath, dimensions);\n this.dimensions = dimensions;\n }\n\n add(id: string, vector: number[], metadata: ChunkMetadata): void {\n if (vector.length !== this.dimensions) {\n throw new Error(\n `Vector dimension mismatch: expected ${this.dimensions}, got ${vector.length}`\n );\n }\n this.inner.add(id, vector, JSON.stringify(metadata));\n }\n\n addBatch(\n items: Array<{ id: string; vector: number[]; metadata: ChunkMetadata }>\n ): void {\n const ids = items.map((i) => i.id);\n const vectors = items.map((i) => {\n if (i.vector.length !== this.dimensions) {\n throw new Error(\n `Vector dimension mismatch for ${i.id}: expected ${this.dimensions}, got ${i.vector.length}`\n );\n }\n return i.vector;\n });\n const metadata = items.map((i) => JSON.stringify(i.metadata));\n this.inner.addBatch(ids, vectors, metadata);\n }\n\n search(queryVector: number[], limit: number = 10): SearchResult[] {\n if (queryVector.length !== this.dimensions) {\n throw new Error(\n `Query vector dimension mismatch: expected ${this.dimensions}, got ${queryVector.length}`\n );\n }\n const results = this.inner.search(queryVector, limit);\n return results.map((r: any) => ({\n id: r.id,\n score: r.score,\n metadata: JSON.parse(r.metadata) as ChunkMetadata,\n }));\n }\n\n remove(id: string): boolean {\n return this.inner.remove(id);\n }\n\n save(): void {\n this.inner.save();\n }\n\n load(): void {\n this.inner.load();\n }\n\n count(): number {\n return this.inner.count();\n }\n\n clear(): void {\n this.inner.clear();\n }\n\n getDimensions(): number {\n return this.dimensions;\n }\n\n getAllKeys(): string[] {\n return this.inner.getAllKeys();\n }\n\n getAllMetadata(): Array<{ key: string; metadata: ChunkMetadata }> {\n const results = this.inner.getAllMetadata();\n return results.map((r: { key: string; metadata: string }) => ({\n key: r.key,\n metadata: JSON.parse(r.metadata) as ChunkMetadata,\n }));\n }\n\n getMetadata(id: string): ChunkMetadata | undefined {\n const result = this.inner.getMetadata(id);\n if (result === null || result === undefined) {\n return undefined;\n }\n return JSON.parse(result) as ChunkMetadata;\n }\n\n getMetadataBatch(ids: string[]): Map<string, ChunkMetadata> {\n const results = this.inner.getMetadataBatch(ids);\n const map = new Map<string, ChunkMetadata>();\n for (const { key, metadata } of results) {\n map.set(key, JSON.parse(metadata) as ChunkMetadata);\n }\n return map;\n }\n}\n\n// Token estimation: ~4 chars per token for code (conservative)\nconst CHARS_PER_TOKEN = 4;\nconst MAX_BATCH_TOKENS = 7500; // Leave buffer under 8192 API limit\nconst MAX_SINGLE_CHUNK_TOKENS = 2000; // Default truncation cap for individual chunks\n\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nfunction getEmbeddingHeaderParts(chunk: CodeChunk, filePath: string): string[] {\n const parts: string[] = [];\n\n const fileName = filePath.split(\"/\").pop() || filePath;\n const dirPath = filePath.split(\"/\").slice(-3, -1).join(\"/\");\n\n const langDescriptors: Record<string, string> = {\n typescript: \"TypeScript\",\n javascript: \"JavaScript\",\n python: \"Python\",\n rust: \"Rust\",\n go: \"Go\",\n java: \"Java\",\n };\n\n const typeDescriptors: Record<string, string> = {\n function_declaration: \"function\",\n function: \"function\",\n arrow_function: \"arrow function\",\n method_definition: \"method\",\n class_declaration: \"class\",\n interface_declaration: \"interface\",\n type_alias_declaration: \"type alias\",\n enum_declaration: \"enum\",\n export_statement: \"export\",\n lexical_declaration: \"variable declaration\",\n function_definition: \"function\",\n class_definition: \"class\",\n function_item: \"function\",\n impl_item: \"implementation\",\n struct_item: \"struct\",\n enum_item: \"enum\",\n trait_item: \"trait\",\n };\n\n const lang = langDescriptors[chunk.language] || chunk.language;\n const typeDesc = typeDescriptors[chunk.chunkType] || chunk.chunkType;\n\n if (chunk.name) {\n parts.push(`${lang} ${typeDesc} \"${chunk.name}\"`);\n } else {\n parts.push(`${lang} ${typeDesc}`);\n }\n\n if (dirPath) {\n parts.push(`in ${dirPath}/${fileName}`);\n } else {\n parts.push(`in ${fileName}`);\n }\n\n const semanticHints = extractSemanticHints(chunk.name || \"\", chunk.content);\n if (semanticHints.length > 0) {\n parts.push(`Purpose: ${semanticHints.join(\", \")}`);\n }\n\n return parts;\n}\n\nfunction buildEmbeddingText(headerParts: string[], content: string, partIndex?: number, partCount?: number): string {\n const parts = [...headerParts];\n if (partCount && partCount > 1 && partIndex) {\n parts.push(`Part ${partIndex}/${partCount}`);\n }\n parts.push(\"\");\n parts.push(content);\n return parts.join(\"\\n\");\n}\n\nfunction splitOversizedContent(content: string, maxContentChars: number): string[] {\n if (content.length <= maxContentChars) {\n return [content];\n }\n\n const overlapChars = Math.max(CHARS_PER_TOKEN * 32, Math.min(Math.floor(maxContentChars * 0.15), CHARS_PER_TOKEN * 128));\n const stepChars = Math.max(1, maxContentChars - overlapChars);\n const segments: string[] = [];\n\n for (let start = 0; start < content.length; start += stepChars) {\n const end = Math.min(content.length, start + maxContentChars);\n segments.push(content.slice(start, end));\n if (end >= content.length) {\n break;\n }\n }\n\n return segments;\n}\n\nexport function createEmbeddingTexts(chunk: CodeChunk, filePath: string, maxChunkTokens = MAX_SINGLE_CHUNK_TOKENS): string[] {\n const headerParts = getEmbeddingHeaderParts(chunk, filePath);\n const headerLength = buildEmbeddingText(headerParts, \"\", 1, 9).length;\n const maxContentChars = Math.max(1, (maxChunkTokens * CHARS_PER_TOKEN) - headerLength);\n const segments = splitOversizedContent(chunk.content, maxContentChars);\n\n if (segments.length === 1) {\n return [buildEmbeddingText(headerParts, segments[0])];\n }\n\n return segments.map((segment, index) => buildEmbeddingText(headerParts, segment, index + 1, segments.length));\n}\n\nexport function createEmbeddingText(chunk: CodeChunk, filePath: string, maxChunkTokens = MAX_SINGLE_CHUNK_TOKENS): string {\n const text = createEmbeddingTexts(chunk, filePath, maxChunkTokens)[0];\n if (!text) {\n return \"\";\n }\n\n const maxChars = maxChunkTokens * CHARS_PER_TOKEN;\n if (text.length <= maxChars) {\n return text;\n }\n\n return text.slice(0, Math.max(0, maxChars - 17)) + \"\\n... [truncated]\";\n}\n\nexport interface DynamicBatchOptions {\n maxBatchTokens?: number;\n maxBatchItems?: number;\n}\n\nexport function createDynamicBatches<T extends { text: string; tokenCount?: number }>(chunks: T[], options: DynamicBatchOptions = {}): T[][] {\n const batches: T[][] = [];\n let currentBatch: T[] = [];\n let currentTokens = 0;\n const maxBatchTokens = Math.max(1, options.maxBatchTokens ?? MAX_BATCH_TOKENS);\n const maxBatchItems = Math.max(1, options.maxBatchItems ?? Number.MAX_SAFE_INTEGER);\n \n for (const chunk of chunks) {\n const chunkTokens = chunk.tokenCount ?? estimateTokens(chunk.text);\n\n if (\n currentBatch.length > 0\n && (currentTokens + chunkTokens > maxBatchTokens || currentBatch.length >= maxBatchItems)\n ) {\n batches.push(currentBatch);\n currentBatch = [];\n currentTokens = 0;\n }\n \n currentBatch.push(chunk);\n currentTokens += chunkTokens;\n }\n \n if (currentBatch.length > 0) {\n batches.push(currentBatch);\n }\n \n return batches;\n}\n\nfunction extractSemanticHints(name: string, content: string): string[] {\n const hints: string[] = [];\n const combined = `${name} ${content}`.toLowerCase();\n \n const signature = extractFunctionSignature(content);\n if (signature) {\n hints.push(signature);\n }\n \n const patterns: Array<[RegExp, string]> = [\n [/auth|login|logout|signin|signout|credential/i, \"authentication\"],\n [/password|hash|bcrypt|argon/i, \"password handling\"],\n [/token|jwt|bearer|oauth/i, \"token management\"],\n [/user|account|profile|member/i, \"user management\"],\n [/permission|role|access|authorize/i, \"authorization\"],\n [/validate|verify|check|assert/i, \"validation\"],\n [/error|exception|throw|catch/i, \"error handling\"],\n [/log|debug|trace|info|warn/i, \"logging\"],\n [/cache|memoize|store/i, \"caching\"],\n [/fetch|request|response|api|http/i, \"HTTP/API\"],\n [/database|db|query|sql|mongo/i, \"database\"],\n [/file|read|write|stream|path/i, \"file operations\"],\n [/parse|serialize|json|xml/i, \"data parsing\"],\n [/encrypt|decrypt|crypto|secret|cipher|cryptographic/i, \"encryption/cryptography\"],\n [/test|spec|mock|stub|expect/i, \"testing\"],\n [/config|setting|option|env/i, \"configuration\"],\n [/route|endpoint|handler|controller|middleware/i, \"routing/middleware\"],\n [/render|component|view|template/i, \"UI rendering\"],\n [/state|redux|store|dispatch/i, \"state management\"],\n [/hook|effect|memo|callback/i, \"React hooks\"],\n ];\n \n for (const [pattern, hint] of patterns) {\n if (pattern.test(combined) && !hints.includes(hint)) {\n hints.push(hint);\n }\n }\n \n return hints.slice(0, 6);\n}\n\nfunction extractFunctionSignature(content: string): string | null {\n const tsJsPatterns = [\n /(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*(?:<[^>]+>)?\\s*\\(([^)]*)\\)\\s*(?::\\s*([^{]+))?/,\n /(?:export\\s+)?const\\s+(\\w+)\\s*(?::\\s*[^=]+)?\\s*=\\s*(?:async\\s+)?\\(([^)]*)\\)\\s*(?::\\s*([^=>{]+))?\\s*=>/,\n /(?:export\\s+)?const\\s+(\\w+)\\s*(?::\\s*[^=]+)?\\s*=\\s*(?:async\\s+)?function\\s*\\(([^)]*)\\)/,\n ];\n \n const pyPatterns = [\n /def\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*(?:->\\s*([^:]+))?:/,\n /async\\s+def\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*(?:->\\s*([^:]+))?:/,\n ];\n \n const goPatterns = [\n /func\\s+(?:\\([^)]+\\)\\s+)?(\\w+)\\s*\\(([^)]*)\\)\\s*(?:\\(([^)]+)\\)|([^{\\n]+))?/,\n ];\n \n const rustPatterns = [\n /(?:pub\\s+)?(?:async\\s+)?fn\\s+(\\w+)\\s*(?:<[^>]+>)?\\s*\\(([^)]*)\\)\\s*(?:->\\s*([^{]+))?/,\n ];\n \n for (const pattern of [...tsJsPatterns, ...pyPatterns, ...goPatterns, ...rustPatterns]) {\n const match = content.match(pattern);\n if (match) {\n const funcName = match[1];\n const params = match[2]?.trim() || \"\";\n const returnType = (match[3] || match[4])?.trim();\n \n const paramNames = extractParamNames(params);\n \n let sig = `${funcName}(${paramNames.join(\", \")})`;\n if (returnType && returnType.length < 50) {\n sig += ` -> ${returnType.replace(/\\s+/g, \" \").trim()}`;\n }\n \n if (sig.length < 100) {\n return sig;\n }\n }\n }\n \n return null;\n}\n\nfunction extractParamNames(params: string): string[] {\n if (!params.trim()) return [];\n \n const names: string[] = [];\n const parts = params.split(\",\");\n \n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed) continue;\n \n const tsMatch = trimmed.match(/^(\\w+)\\s*[?:]?/);\n const pyMatch = trimmed.match(/^(\\w+)\\s*(?::|=)/);\n const goMatch = trimmed.match(/^(\\w+)\\s+\\w/);\n const rustMatch = trimmed.match(/^(\\w+)\\s*:/);\n \n const match = tsMatch || pyMatch || goMatch || rustMatch;\n if (match && match[1] !== \"self\" && match[1] !== \"this\") {\n names.push(match[1]);\n }\n }\n \n return names.slice(0, 5);\n}\n\nexport function generateChunkId(filePath: string, chunk: CodeChunk): string {\n const hash = hashContent(`${filePath}:${chunk.startLine}:${chunk.endLine}:${chunk.content}`);\n return `chunk_${hash.slice(0, 16)}`;\n}\n\nexport function generateChunkHash(chunk: CodeChunk): string {\n return hashContent(chunk.content);\n}\n\nexport interface KeywordSearchResult {\n chunkId: string;\n score: number;\n}\n\nexport class InvertedIndex {\n private inner: any;\n\n constructor(indexPath: string) {\n this.inner = new native.InvertedIndex(indexPath);\n }\n\n load(): void {\n this.inner.load();\n }\n\n save(): void {\n this.inner.save();\n }\n\n serialize(): string {\n return this.inner.serialize();\n }\n\n deserialize(json: string): void {\n this.inner.deserialize(json);\n }\n\n addChunk(chunkId: string, content: string): void {\n this.inner.addChunk(chunkId, content);\n }\n\n removeChunk(chunkId: string): boolean {\n return this.inner.removeChunk(chunkId);\n }\n\n search(query: string, limit?: number): Map<string, number> {\n const results = this.inner.search(query, limit ?? 100);\n const map = new Map<string, number>();\n for (const r of results) {\n map.set(r.chunkId, r.score);\n }\n return map;\n }\n\n hasChunk(chunkId: string): boolean {\n return this.inner.hasChunk(chunkId);\n }\n\n clear(): void {\n this.inner.clear();\n }\n\n getDocumentCount(): number {\n return this.inner.documentCount();\n }\n}\n\nexport interface ChunkData {\n chunkId: string;\n contentHash: string;\n filePath: string;\n startLine: number;\n endLine: number;\n nodeType?: string;\n name?: string;\n language: string;\n}\n\nexport interface BranchDelta {\n added: string[];\n removed: string[];\n}\n\nexport interface DatabaseStats {\n embeddingCount: number;\n chunkCount: number;\n branchChunkCount: number;\n branchCount: number;\n symbolCount: number;\n callEdgeCount: number;\n}\n\nexport class Database {\n private inner: any;\n private closed = false;\n\n constructor(dbPath: string) {\n this.inner = new native.Database(dbPath);\n }\n\n private throwIfClosed(): void {\n if (this.closed) {\n throw new Error(\"Database is closed\");\n }\n }\n\n close(): void {\n if (this.closed) {\n return;\n }\n\n if (typeof this.inner.close === \"function\") {\n this.inner.close();\n }\n\n this.closed = true;\n }\n\n embeddingExists(contentHash: string): boolean {\n this.throwIfClosed();\n return this.inner.embeddingExists(contentHash);\n }\n\n getEmbedding(contentHash: string): Buffer | null {\n this.throwIfClosed();\n return this.inner.getEmbedding(contentHash) ?? null;\n }\n\n upsertEmbedding(\n contentHash: string,\n embedding: Buffer,\n chunkText: string,\n model: string\n ): void {\n this.throwIfClosed();\n this.inner.upsertEmbedding(contentHash, embedding, chunkText, model);\n }\n\n upsertEmbeddingsBatch(\n items: Array<{\n contentHash: string;\n embedding: Buffer;\n chunkText: string;\n model: string;\n }>\n ): void {\n this.throwIfClosed();\n if (items.length === 0) return;\n this.inner.upsertEmbeddingsBatch(items);\n }\n\n getMissingEmbeddings(contentHashes: string[]): string[] {\n this.throwIfClosed();\n return this.inner.getMissingEmbeddings(contentHashes);\n }\n\n upsertChunk(chunk: ChunkData): void {\n this.throwIfClosed();\n this.inner.upsertChunk(chunk);\n }\n\n upsertChunksBatch(chunks: ChunkData[]): void {\n this.throwIfClosed();\n if (chunks.length === 0) return;\n this.inner.upsertChunksBatch(chunks);\n }\n\n getChunk(chunkId: string): ChunkData | null {\n this.throwIfClosed();\n return this.inner.getChunk(chunkId) ?? null;\n }\n\n getChunksByFile(filePath: string): ChunkData[] {\n this.throwIfClosed();\n return this.inner.getChunksByFile(filePath);\n }\n\n getChunksByName(name: string): ChunkData[] {\n this.throwIfClosed();\n return this.inner.getChunksByName(name);\n }\n\n getChunksByNameCi(name: string): ChunkData[] {\n this.throwIfClosed();\n return this.inner.getChunksByNameCi(name);\n }\n\n deleteChunksByFile(filePath: string): number {\n this.throwIfClosed();\n return this.inner.deleteChunksByFile(filePath);\n }\n\n deleteChunksByIds(chunkIds: string[]): number {\n this.throwIfClosed();\n if (chunkIds.length === 0) return 0;\n return this.inner.deleteChunksByIds(chunkIds);\n }\n\n addChunksToBranch(branch: string, chunkIds: string[]): void {\n this.throwIfClosed();\n this.inner.addChunksToBranch(branch, chunkIds);\n }\n\n addChunksToBranchBatch(branch: string, chunkIds: string[]): void {\n this.throwIfClosed();\n if (chunkIds.length === 0) return;\n this.inner.addChunksToBranchBatch(branch, chunkIds);\n }\n\n clearBranch(branch: string): number {\n this.throwIfClosed();\n return this.inner.clearBranch(branch);\n }\n\n deleteBranchChunksByChunkIds(chunkIds: string[]): number {\n this.throwIfClosed();\n if (chunkIds.length === 0) return 0;\n return this.inner.deleteBranchChunksByChunkIds(chunkIds);\n }\n\n deleteBranchChunksForBranch(branch: string, chunkIds: string[]): number {\n this.throwIfClosed();\n if (chunkIds.length === 0) return 0;\n return this.inner.deleteBranchChunksForBranch(branch, chunkIds);\n }\n\n getBranchChunkIds(branch: string): string[] {\n this.throwIfClosed();\n return this.inner.getBranchChunkIds(branch);\n }\n\n getBranchDelta(branch: string, baseBranch: string): BranchDelta {\n this.throwIfClosed();\n return this.inner.getBranchDelta(branch, baseBranch);\n }\n\n getReferencedChunkIds(chunkIds: string[]): string[] {\n this.throwIfClosed();\n if (chunkIds.length === 0) return [];\n return this.inner.getReferencedChunkIds(chunkIds);\n }\n\n chunkExistsOnBranch(branch: string, chunkId: string): boolean {\n this.throwIfClosed();\n return this.inner.chunkExistsOnBranch(branch, chunkId);\n }\n\n getAllBranches(): string[] {\n this.throwIfClosed();\n return this.inner.getAllBranches();\n }\n\n getMetadata(key: string): string | null {\n this.throwIfClosed();\n return this.inner.getMetadata(key) ?? null;\n }\n\n setMetadata(key: string, value: string): void {\n this.throwIfClosed();\n this.inner.setMetadata(key, value);\n }\n\n deleteMetadata(key: string): boolean {\n this.throwIfClosed();\n return this.inner.deleteMetadata(key);\n }\n\n clearAllIndexedData(): void {\n this.throwIfClosed();\n this.inner.clearAllIndexedData();\n }\n\n clearCallEdgeTargetsForSymbols(symbolIds: string[]): number {\n this.throwIfClosed();\n if (symbolIds.length === 0) return 0;\n return this.inner.clearCallEdgeTargetsForSymbols(symbolIds);\n }\n\n gcOrphanEmbeddings(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanEmbeddings();\n }\n\n gcOrphanChunks(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanChunks();\n }\n\n getStats(): DatabaseStats {\n this.throwIfClosed();\n return this.inner.getStats();\n }\n\n\n\n upsertSymbol(symbol: SymbolData): void {\n this.throwIfClosed();\n this.inner.upsertSymbol(symbol);\n }\n\n upsertSymbolsBatch(symbols: SymbolData[]): void {\n this.throwIfClosed();\n if (symbols.length === 0) return;\n this.inner.upsertSymbolsBatch(symbols);\n }\n\n getSymbolsByFile(filePath: string): SymbolData[] {\n this.throwIfClosed();\n return this.inner.getSymbolsByFile(filePath);\n }\n\n getSymbolByName(name: string, filePath: string): SymbolData | null {\n this.throwIfClosed();\n return this.inner.getSymbolByName(name, filePath) ?? null;\n }\n\n getSymbolsByName(name: string): SymbolData[] {\n this.throwIfClosed();\n return this.inner.getSymbolsByName(name);\n }\n\n getSymbolsByNameCi(name: string): SymbolData[] {\n this.throwIfClosed();\n return this.inner.getSymbolsByNameCi(name);\n }\n\n deleteSymbolsByFile(filePath: string): number {\n this.throwIfClosed();\n return this.inner.deleteSymbolsByFile(filePath);\n }\n\n\n\n upsertCallEdge(edge: CallEdgeData): void {\n this.throwIfClosed();\n this.inner.upsertCallEdge(edge);\n }\n\n upsertCallEdgesBatch(edges: CallEdgeData[]): void {\n this.throwIfClosed();\n if (edges.length === 0) return;\n this.inner.upsertCallEdgesBatch(edges);\n }\n\n getCallers(targetName: string, branch: string, callTypeFilter?: string): CallEdgeData[] {\n this.throwIfClosed();\n return this.inner.getCallers(targetName, branch, callTypeFilter ?? null);\n }\n\n getCallersWithContext(targetName: string, branch: string, callTypeFilter?: string): CallEdgeData[] {\n this.throwIfClosed();\n return this.inner.getCallersWithContext(targetName, branch, callTypeFilter ?? null);\n }\n\n getCallees(symbolId: string, branch: string, callTypeFilter?: string): CallEdgeData[] {\n this.throwIfClosed();\n return this.inner.getCallees(symbolId, branch, callTypeFilter ?? null);\n }\n\n deleteCallEdgesByFile(filePath: string): number {\n this.throwIfClosed();\n return this.inner.deleteCallEdgesByFile(filePath);\n }\n\n resolveCallEdge(edgeId: string, toSymbolId: string): void {\n this.throwIfClosed();\n this.inner.resolveCallEdge(edgeId, toSymbolId);\n }\n\n findShortestPath(fromName: string, toName: string, branch: string, maxDepth?: number): PathHopData[] {\n this.throwIfClosed();\n return this.inner.findShortestPath(fromName, toName, branch, maxDepth ?? null);\n }\n\n\n\n addSymbolsToBranch(branch: string, symbolIds: string[]): void {\n this.throwIfClosed();\n this.inner.addSymbolsToBranch(branch, symbolIds);\n }\n\n addSymbolsToBranchBatch(branch: string, symbolIds: string[]): void {\n this.throwIfClosed();\n if (symbolIds.length === 0) return;\n this.inner.addSymbolsToBranchBatch(branch, symbolIds);\n }\n\n getBranchSymbolIds(branch: string): string[] {\n this.throwIfClosed();\n return this.inner.getBranchSymbolIds(branch);\n }\n\n clearBranchSymbols(branch: string): number {\n this.throwIfClosed();\n return this.inner.clearBranchSymbols(branch);\n }\n\n getReferencedSymbolIds(symbolIds: string[]): string[] {\n this.throwIfClosed();\n if (symbolIds.length === 0) return [];\n return this.inner.getReferencedSymbolIds(symbolIds);\n }\n\n deleteBranchSymbolsBySymbolIds(symbolIds: string[]): number {\n this.throwIfClosed();\n if (symbolIds.length === 0) return 0;\n return this.inner.deleteBranchSymbolsBySymbolIds(symbolIds);\n }\n\n deleteBranchSymbolsForBranch(branch: string, symbolIds: string[]): number {\n this.throwIfClosed();\n if (symbolIds.length === 0) return 0;\n return this.inner.deleteBranchSymbolsForBranch(branch, symbolIds);\n }\n\n\n\n gcOrphanSymbols(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanSymbols();\n }\n\n gcOrphanCallEdges(): number {\n this.throwIfClosed();\n return this.inner.gcOrphanCallEdges();\n }\n}\n","import { IndexStats, IndexProgress, SearchResult, HealthCheckResult, StatusResult } from \"../indexer/index.js\";\nimport type { LogEntry } from \"../utils/logger.js\";\n\nconst MAX_CONTENT_LINES = 30;\n\nfunction truncateContent(content: string): string {\n const lines = content.split(\"\\n\");\n if (lines.length <= MAX_CONTENT_LINES) return content;\n return (\n lines.slice(0, MAX_CONTENT_LINES).join(\"\\n\") +\n `\\n// ... (${lines.length - MAX_CONTENT_LINES} more lines)`\n );\n}\n\nexport function formatIndexStats(stats: IndexStats, verbose: boolean = false): string {\n if (stats.resetCorruptedIndex) {\n return stats.warning ?? \"Detected a corrupted local index and reset it during indexing. Run index_codebase again to rebuild search data.\";\n }\n\n const lines: string[] = [];\n\n if (stats.failedChunks > 0) {\n lines.push(`INDEXING WARNING: ${stats.failedChunks} chunks failed to embed.`);\n if (stats.failedBatchesPath) {\n lines.push(`Inspect failed batches at: ${stats.failedBatchesPath}`);\n }\n lines.push(\"\");\n }\n \n if (stats.indexedChunks === 0 && stats.removedChunks === 0) {\n lines.push(`${stats.totalFiles} files processed, ${stats.existingChunks} code chunks already up to date.`);\n } else if (stats.indexedChunks === 0) {\n lines.push(`${stats.totalFiles} files, removed ${stats.removedChunks} stale chunks, ${stats.existingChunks} chunks remain.`);\n } else {\n let main = `${stats.totalFiles} files processed, ${stats.indexedChunks} new chunks embedded.`;\n if (stats.existingChunks > 0) {\n main += ` ${stats.existingChunks} unchanged chunks skipped.`;\n }\n lines.push(main);\n\n if (stats.removedChunks > 0) {\n lines.push(`Removed ${stats.removedChunks} stale chunks.`);\n }\n\n if (stats.failedChunks > 0) {\n lines.push(`Failed: ${stats.failedChunks} chunks.`);\n }\n\n lines.push(`Tokens: ${stats.tokensUsed.toLocaleString()}, Duration: ${(stats.durationMs / 1000).toFixed(1)}s`);\n }\n\n if (verbose) {\n if (stats.skippedFiles.length > 0) {\n const tooLarge = stats.skippedFiles.filter(f => f.reason === \"too_large\");\n const excluded = stats.skippedFiles.filter(f => f.reason === \"excluded\");\n const gitignored = stats.skippedFiles.filter(f => f.reason === \"gitignore\");\n \n lines.push(\"\");\n lines.push(`Skipped files: ${stats.skippedFiles.length}`);\n if (tooLarge.length > 0) {\n lines.push(` Too large (${tooLarge.length}): ${tooLarge.slice(0, 5).map(f => f.path).join(\", \")}${tooLarge.length > 5 ? \"...\" : \"\"}`);\n }\n if (excluded.length > 0) {\n lines.push(` Excluded (${excluded.length}): ${excluded.slice(0, 5).map(f => f.path).join(\", \")}${excluded.length > 5 ? \"...\" : \"\"}`);\n }\n if (gitignored.length > 0) {\n lines.push(` Gitignored (${gitignored.length}): ${gitignored.slice(0, 5).map(f => f.path).join(\", \")}${gitignored.length > 5 ? \"...\" : \"\"}`);\n }\n }\n\n if (stats.parseFailures.length > 0) {\n lines.push(\"\");\n lines.push(`Files with no extractable chunks (${stats.parseFailures.length}): ${stats.parseFailures.slice(0, 10).join(\", \")}${stats.parseFailures.length > 10 ? \"...\" : \"\"}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatStatus(status: StatusResult): string {\n if (!status.indexed) {\n if (status.warning) {\n return status.warning;\n }\n\n if (status.failedBatchesCount > 0) {\n const lines = [\n \"Codebase is not indexed. The last indexing run left failed embedding batches.\",\n \"Fix the provider/model configuration, then rerun index_codebase normally to retry the saved failed batches. Use force=true only for a full rebuild or compatibility reset.\",\n ];\n\n if (status.failedBatchesPath) {\n lines.push(`Failed batches: ${status.failedBatchesPath}`);\n }\n\n return lines.join(\"\\n\");\n }\n\n return \"Codebase is not indexed. Run index_codebase to create an index.\";\n }\n\n const lines = [\n `Indexed chunks: ${status.vectorCount.toLocaleString()}`,\n `Provider: ${status.provider}`,\n `Model: ${status.model}`,\n `Location: ${status.indexPath}`,\n ];\n\n if (status.currentBranch !== \"default\") {\n lines.push(`Current branch: ${status.currentBranch}`);\n lines.push(`Base branch: ${status.baseBranch}`);\n }\n\n if (status.failedBatchesCount > 0) {\n lines.push(\"\");\n lines.push(`INDEXING WARNING: ${status.failedBatchesCount} failed embedding batch${status.failedBatchesCount === 1 ? \" remains\" : \"es remain\"}.`);\n if (status.failedBatchesPath) {\n lines.push(`Failed batches: ${status.failedBatchesPath}`);\n }\n }\n\n if (status.compatibility && !status.compatibility.compatible) {\n lines.push(\"\");\n lines.push(`COMPATIBILITY WARNING: ${status.compatibility.reason}`);\n if (status.compatibility.storedMetadata) {\n const stored = status.compatibility.storedMetadata;\n lines.push(`Index was built with: ${stored.embeddingProvider}/${stored.embeddingModel} (${stored.embeddingDimensions}D)`);\n lines.push(`Current config: ${status.provider}/${status.model}`);\n }\n } else if (!status.compatibility) {\n lines.push(`Compatibility: No compatibility information found. Maybe the index is not initialized yet, try running index_codebase.`);\n } else {\n lines.push(`Compatibility: Index is compatible with the current provider and model.`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatProgressTitle(progress: IndexProgress): string {\n switch (progress.phase) {\n case \"scanning\":\n return \"Scanning files...\";\n case \"parsing\":\n return `Parsing: ${progress.filesProcessed}/${progress.totalFiles} files`;\n case \"embedding\":\n return `Embedding: ${progress.chunksProcessed}/${progress.totalChunks} chunks`;\n case \"storing\":\n return \"Storing index...\";\n case \"complete\":\n return \"Indexing complete\";\n default:\n return \"Indexing...\";\n }\n}\n\nexport function calculatePercentage(progress: IndexProgress): number {\n if (progress.phase === \"scanning\") return 0;\n if (progress.phase === \"complete\") return 100;\n \n if (progress.phase === \"parsing\") {\n if (progress.totalFiles === 0) return 5;\n return Math.round(5 + (progress.filesProcessed / progress.totalFiles) * 15);\n }\n \n if (progress.phase === \"embedding\") {\n if (progress.totalChunks === 0) return 20;\n return Math.round(20 + (progress.chunksProcessed / progress.totalChunks) * 70);\n }\n \n if (progress.phase === \"storing\") return 95;\n \n return 0;\n}\n\nexport function formatCodebasePeek(results: SearchResult[]): string {\n if (results.length === 0) {\n return \"No matching code found. Try a different query or run index_codebase first.\";\n }\n\n const formatted = results.map((r, idx) => {\n const location = `${r.filePath}:${r.startLine}-${r.endLine}`;\n const name = r.name ? `\"${r.name}\"` : \"(anonymous)\";\n return `[${idx + 1}] ${r.chunkType} ${name} at ${location} (score: ${r.score.toFixed(2)})`;\n });\n\n return formatted.join(\"\\n\");\n}\n\nexport function formatHealthCheck(result: HealthCheckResult): string {\n if (result.resetCorruptedIndex) {\n return result.warning ?? \"Detected a corrupted local index and reset it. Run index_codebase to rebuild search data.\";\n }\n\n if (result.removed === 0 && result.gcOrphanEmbeddings === 0 && result.gcOrphanChunks === 0 && result.gcOrphanSymbols === 0 && result.gcOrphanCallEdges === 0) {\n return \"Index is healthy. No stale entries found.\";\n }\n\n const lines: string[] = [];\n \n if (result.removed > 0) {\n lines.push(`Removed stale entries: ${result.removed}`);\n }\n \n if (result.gcOrphanEmbeddings > 0) {\n lines.push(`Garbage collected orphan embeddings: ${result.gcOrphanEmbeddings}`);\n }\n \n if (result.gcOrphanChunks > 0) {\n lines.push(`Garbage collected orphan chunks: ${result.gcOrphanChunks}`);\n }\n\n if (result.gcOrphanSymbols > 0) {\n lines.push(`Garbage collected orphan symbols: ${result.gcOrphanSymbols}`);\n }\n\n if (result.gcOrphanCallEdges > 0) {\n lines.push(`Garbage collected orphan call edges: ${result.gcOrphanCallEdges}`);\n }\n\n if (result.filePaths.length > 0) {\n lines.push(`Cleaned paths: ${result.filePaths.join(\", \")}`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatLogs(logs: LogEntry[]): string {\n if (logs.length === 0) {\n return \"No logs recorded yet. Logs are captured during indexing and search operations.\";\n }\n\n return logs.map(l => {\n const dataStr = l.data ? ` ${JSON.stringify(l.data)}` : \"\";\n return `[${l.timestamp}] [${l.level.toUpperCase()}] [${l.category}] ${l.message}${dataStr}`;\n }).join(\"\\n\");\n}\n\nfunction formatResultHeader(result: SearchResult, index: number): string {\n return result.name\n ? `[${index + 1}] ${result.chunkType} \"${result.name}\" in ${result.filePath}:${result.startLine}-${result.endLine}`\n : `[${index + 1}] ${result.chunkType} in ${result.filePath}:${result.startLine}-${result.endLine}`;\n}\n\nexport function formatDefinitionLookup(results: SearchResult[], query: string): string {\n if (results.length === 0) {\n return `No definition found for \"${query}\". Try codebase_search for broader discovery, or verify the symbol name.`;\n }\n\n const formatted = results.map((r, idx) => {\n const header = formatResultHeader(r, idx);\n return `${header} (score: ${r.score.toFixed(2)})\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return formatted.join(\"\\n\\n\");\n}\n\nexport type ScoreFormat = \"score\" | \"similarity\";\n\nexport function formatSearchResults(results: SearchResult[], scoreFormat: ScoreFormat = \"similarity\"): string {\n const formatted = results.map((r, idx) => {\n const header = formatResultHeader(r, idx);\n\n const scoreLabel = scoreFormat === \"similarity\"\n ? `(similarity: ${(r.score * 100).toFixed(1)}%)`\n : `(score: ${r.score.toFixed(2)})`;\n\n return `${header} ${scoreLabel}\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return formatted.join(\"\\n\\n\");\n}\n","import * as path from \"path\";\n\nimport { normalizePathSeparators } from \"../utils/paths.js\";\n\nexport function resolveConfigPathValue(value: string, baseDir: string): string {\n const trimmed = value.trim();\n if (!trimmed) {\n return trimmed;\n }\n\n const absolutePath = path.isAbsolute(trimmed) ? trimmed : path.resolve(baseDir, trimmed);\n return path.normalize(absolutePath);\n}\n\nexport function serializeConfigPathValue(value: string, baseDir: string): string {\n const trimmed = value.trim();\n if (!trimmed) {\n return trimmed;\n }\n\n if (!path.isAbsolute(trimmed)) {\n return normalizePathSeparators(path.normalize(trimmed));\n }\n\n const relativePath = path.relative(baseDir, trimmed);\n if (!relativePath || (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath))) {\n return normalizePathSeparators(path.normalize(relativePath || \".\"));\n }\n\n return path.normalize(trimmed);\n}\n\nexport function resolveKnowledgeBasePath(value: string, projectRoot: string): string {\n return path.isAbsolute(value) ? value : path.resolve(projectRoot, value);\n}\n\nexport function normalizeKnowledgeBasePath(value: string, projectRoot: string): string {\n return path.normalize(resolveKnowledgeBasePath(value, projectRoot));\n}\n\nexport function hasMatchingKnowledgeBasePath(\n knowledgeBases: string[],\n inputPath: string,\n projectRoot: string,\n): boolean {\n const normalizedInput = path.normalize(inputPath);\n return knowledgeBases.some((kb) => normalizeKnowledgeBasePath(kb, projectRoot) === normalizedInput);\n}\n\nexport function findKnowledgeBasePathIndex(\n knowledgeBases: string[],\n inputPath: string,\n projectRoot: string,\n): number {\n const normalizedInput = path.normalize(inputPath);\n return knowledgeBases.findIndex(\n (kb) => path.normalize(kb) === normalizedInput || normalizeKnowledgeBasePath(kb, projectRoot) === normalizedInput\n );\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"fs\";\nimport * as path from \"path\";\n\nimport { loadMergedConfig, loadProjectConfigLayer } from \"../config/merger.js\";\nimport { resolveWritableProjectConfigPath } from \"../config/paths.js\";\nimport { resolveConfigPathValue, serializeConfigPathValue } from \"./knowledge-base-paths.js\";\n\nfunction normalizeKnowledgeBasePaths(\n config: Record<string, unknown>,\n projectRoot: string,\n): Record<string, unknown> {\n const normalized = { ...config };\n\n if (Array.isArray(normalized.knowledgeBases)) {\n normalized.knowledgeBases = (normalized.knowledgeBases as string[]).map((kb) =>\n resolveConfigPathValue(kb, projectRoot)\n );\n }\n\n return normalized;\n}\n\nfunction toConfigRecord(rawConfig: unknown): Record<string, unknown> {\n if (!rawConfig || typeof rawConfig !== \"object\") {\n return {};\n }\n\n return { ...(rawConfig as Record<string, unknown>) };\n}\n\nexport function getConfigPath(projectRoot: string): string {\n return resolveWritableProjectConfigPath(projectRoot);\n}\n\nexport function loadRuntimeConfig(projectRoot: string): Record<string, unknown> {\n return normalizeKnowledgeBasePaths(toConfigRecord(loadMergedConfig(projectRoot)), projectRoot);\n}\n\nexport function loadEditableConfig(projectRoot: string): Record<string, unknown> {\n return normalizeKnowledgeBasePaths(toConfigRecord(loadProjectConfigLayer(projectRoot)), projectRoot);\n}\n\nexport function saveConfig(projectRoot: string, config: Record<string, unknown>): void {\n const configPath = getConfigPath(projectRoot);\n const configDir = path.dirname(configPath);\n const configBaseDir = path.dirname(configDir);\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true });\n }\n\n const serializableConfig: Record<string, unknown> = { ...config };\n\n if (Array.isArray(serializableConfig.knowledgeBases)) {\n serializableConfig.knowledgeBases = (serializableConfig.knowledgeBases as string[]).map((kb) =>\n serializeConfigPathValue(kb, configBaseDir)\n );\n }\n\n writeFileSync(configPath, JSON.stringify(serializableConfig, null, 2) + \"\\n\", \"utf-8\");\n}\n","import { existsSync, readdirSync, readFileSync } from \"fs\";\nimport * as path from \"path\";\n\nexport interface CommandDefinition {\n description: string;\n template: string;\n}\n\nfunction parseFrontmatter(content: string): { frontmatter: Record<string, string>; body: string } {\n const frontmatterRegex = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n const match = content.match(frontmatterRegex);\n \n if (!match) {\n return { frontmatter: {}, body: content.trim() };\n }\n\n const frontmatterLines = match[1].split(\"\\n\");\n const frontmatter: Record<string, string> = {};\n \n for (const line of frontmatterLines) {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const value = line.slice(colonIndex + 1).trim();\n frontmatter[key] = value;\n }\n }\n\n return { frontmatter, body: match[2].trim() };\n}\n\nexport function loadCommandsFromDirectory(commandsDir: string): Map<string, CommandDefinition> {\n const commands = new Map<string, CommandDefinition>();\n\n if (!existsSync(commandsDir)) {\n return commands;\n }\n\n const files = readdirSync(commandsDir).filter((f) => f.endsWith(\".md\"));\n\n for (const file of files) {\n const filePath = path.join(commandsDir, file);\n let content: string;\n\n try {\n content = readFileSync(filePath, \"utf-8\");\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load command file ${filePath}: ${message}`);\n }\n\n const { frontmatter, body } = parseFrontmatter(content);\n \n const name = path.basename(file, \".md\");\n const description = frontmatter.description || `Run the ${name} command`;\n\n commands.set(name, {\n description,\n template: body,\n });\n }\n\n return commands;\n}\n","const EXTERNAL_HINTS = [\n \"docs\",\n \"documentation\",\n \"official docs\",\n \"github example\",\n \"github examples\",\n \"github repo\",\n \"github repository\",\n \"web search\",\n \"website\",\n \"url\",\n \"npm\",\n \"pypi\",\n \"crate\",\n \"library\",\n \"package\",\n \"framework\",\n \"context7\",\n \"stackoverflow\",\n];\n\nconst NON_DISCOVERY_HINTS = [\n \"commit\",\n \"rebase\",\n \"push\",\n \"pull request\",\n \"pr\",\n \"lint\",\n \"typecheck\",\n \"build\",\n \"test\",\n \"release\",\n \"deploy\",\n \"screenshot\",\n \"browser\",\n \"open the website\",\n];\n\nconst CONCEPTUAL_DISCOVERY_HINTS = [\n \"where is\",\n \"where are\",\n \"which file\",\n \"what file\",\n \"how does\",\n \"how do we\",\n \"how is\",\n \"find the code\",\n \"find code\",\n \"find where\",\n \"find logic\",\n \"implementation\",\n \"implements\",\n \"handler\",\n \"flow\",\n \"logic\",\n \"middleware\",\n \"parser\",\n \"validation\",\n \"rate limiting\",\n \"error handling\",\n \"auth flow\",\n \"responsible for\",\n \"similar code\",\n \"pattern\",\n \"code that\",\n];\n\nconst DEFINITION_HINTS = [\n \"defined\",\n \"definition\",\n \"jump to\",\n \"definition site\",\n \"authoritative definition\",\n];\n\nconst EXACT_MATCH_HINTS = [\n \"exact\",\n \"all references\",\n \"all occurrences\",\n \"literal\",\n \"regex\",\n \"grep\",\n \"identifier\",\n \"symbol\",\n \"named\",\n \"definition of\",\n];\n\nconst FILE_PATH_PATTERN = /(?:^|\\s)(?:\\.?\\.?\\/)?[\\w.-]+(?:\\/[\\w.-]+)+/;\nconst URL_PATTERN = /https?:\\/\\//;\nconst CAMEL_OR_PASCAL_PATTERN = /\\b[A-Za-z_$][A-Za-z0-9_$]*\\b/g;\nconst SNAKE_PATTERN = /\\b[a-z0-9]+_[a-z0-9_]+\\b/g;\nconst KEBAB_PATTERN = /\\b[a-z0-9]+-[a-z0-9-]+\\b/g;\nconst BACKTICK_IDENTIFIER_PATTERN = /`([^`]+)`/g;\nconst BACKTICK_IDENTIFIER_PRESENCE_PATTERN = /`([^`]+)`/;\nconst DOUBLE_QUOTED_PATTERN = /\"[^\"]+\"/;\nconst SINGLE_QUOTED_PATTERN = /'[^']+'/;\n\nexport function normalizeText(text: string): string {\n return text.trim().replace(/\\s+/g, \" \");\n}\n\nfunction includesHint(text: string, hints: string[]): boolean {\n return hints.some((hint) => text.includes(hint));\n}\n\nexport function countWords(text: string): number {\n if (!text) {\n return 0;\n }\n\n return text.split(/\\s+/).filter(Boolean).length;\n}\n\nexport function isExternalLookup(text: string): boolean {\n return URL_PATTERN.test(text) || includesHint(text, EXTERNAL_HINTS);\n}\n\nexport function hasConceptualDiscoveryHint(text: string): boolean {\n return includesHint(text, CONCEPTUAL_DISCOVERY_HINTS);\n}\n\nexport function hasDefinitionHint(text: string): boolean {\n return includesHint(text, DEFINITION_HINTS);\n}\n\nexport function hasExactMatchHint(text: string): boolean {\n return includesHint(text, EXACT_MATCH_HINTS);\n}\n\nexport function hasNonDiscoveryHint(text: string): boolean {\n return includesHint(text, NON_DISCOVERY_HINTS);\n}\n\nexport function hasIdentifierShape(text: string): boolean {\n const matches = [\n ...(text.match(CAMEL_OR_PASCAL_PATTERN) ?? []),\n ...(text.match(SNAKE_PATTERN) ?? []),\n ...(text.match(KEBAB_PATTERN) ?? []),\n ...Array.from(text.matchAll(BACKTICK_IDENTIFIER_PATTERN), (match) => match[1]),\n ];\n\n return matches.some((match) => {\n if (match.length < 3) {\n return false;\n }\n\n return /[A-Z]/.test(match) || match.includes(\"_\") || match.includes(\"-\") || /`/.test(match);\n });\n}\n\nexport function containsQuotedIdentifier(text: string): boolean {\n return BACKTICK_IDENTIFIER_PRESENCE_PATTERN.test(text) || DOUBLE_QUOTED_PATTERN.test(text) || SINGLE_QUOTED_PATTERN.test(text);\n}\n\nexport function looksLikeDirectPath(text: string): boolean {\n return FILE_PATH_PATTERN.test(text) || /\\b[a-z0-9_-]+\\.(ts|tsx|js|jsx|rs|py|go|java|json|md|yaml|yml)\\b/i.test(text);\n}\n","import type { StatusResult } from \"./indexer/index.js\";\nimport {\n containsQuotedIdentifier,\n countWords,\n hasConceptualDiscoveryHint,\n hasDefinitionHint,\n hasExactMatchHint,\n hasIdentifierShape,\n hasNonDiscoveryHint,\n isExternalLookup,\n looksLikeDirectPath,\n normalizeText,\n} from \"./routing-hints-patterns.js\";\n\nexport type RoutingIntent =\n | \"local_conceptual\"\n | \"definition_lookup\"\n | \"exact_identifier\"\n | \"external\"\n | \"direct_path\"\n | \"other\";\n\nexport interface RoutingAssessment {\n intent: RoutingIntent;\n text: string;\n reason: string;\n}\n\nexport interface RoutingSessionState {\n assessment: RoutingAssessment;\n pendingHint: boolean;\n updatedAt: number;\n}\n\ninterface TextPartLike {\n type?: string;\n text?: string;\n}\n\nexport function extractUserText(parts: TextPartLike[]): string {\n return normalizeText(\n parts\n .filter((part) => part.type === \"text\" && typeof part.text === \"string\")\n .map((part) => part.text ?? \"\")\n .join(\" \"),\n );\n}\n\nexport function assessRoutingIntent(text: string): RoutingAssessment {\n const normalizedText = normalizeText(text);\n const lowered = normalizedText.toLowerCase();\n\n if (!lowered) {\n return {\n intent: \"other\",\n text: normalizedText,\n reason: \"empty_text\",\n };\n }\n\n if (isExternalLookup(lowered)) {\n return {\n intent: \"external\",\n text: normalizedText,\n reason: \"external_lookup\",\n };\n }\n\n const matchedConceptualHint = hasConceptualDiscoveryHint(lowered);\n const matchedDefinitionHint = hasDefinitionHint(lowered);\n const matchedExactMatchHint = hasExactMatchHint(lowered);\n const matchedNonDiscoveryHint = hasNonDiscoveryHint(lowered);\n const hasIdentifier = hasIdentifierShape(normalizedText);\n const hasQuotedIdentifier = containsQuotedIdentifier(normalizedText);\n const shortQuery = countWords(lowered) <= 10;\n\n if (matchedNonDiscoveryHint && !matchedConceptualHint) {\n return {\n intent: \"other\",\n text: normalizedText,\n reason: \"non_discovery_task\",\n };\n }\n\n if (looksLikeDirectPath(normalizedText)) {\n return {\n intent: \"direct_path\",\n text: normalizedText,\n reason: \"direct_path_reference\",\n };\n }\n\n if ((matchedDefinitionHint || lowered.includes(\"where is\") || lowered.includes(\"where are\")) && (lowered.includes(\"defined\") || lowered.includes(\"definition\"))) {\n return {\n intent: \"definition_lookup\",\n text: normalizedText,\n reason: \"definition_lookup_request\",\n };\n }\n\n if ((matchedExactMatchHint || hasQuotedIdentifier || hasIdentifier) && !matchedConceptualHint && shortQuery) {\n return {\n intent: \"exact_identifier\",\n text: normalizedText,\n reason: matchedExactMatchHint || hasQuotedIdentifier ? \"exact_match_request\" : \"identifier_shaped_query\",\n };\n }\n\n if (matchedConceptualHint) {\n return {\n intent: \"local_conceptual\",\n text: normalizedText,\n reason: \"conceptual_local_discovery\",\n };\n }\n\n return {\n intent: \"other\",\n text: normalizedText,\n reason: \"no_local_discovery_signal\",\n };\n}\n\nexport function buildRoutingHint(\n assessment: RoutingAssessment,\n status: Pick<StatusResult, \"indexed\" | \"compatibility\"> | null,\n): string | null {\n if (assessment.intent === \"definition_lookup\") {\n if (!status || !status.indexed || status.compatibility?.compatible === false) {\n return \"For this turn, if you need a symbol definition, check `index_status` first and run `index_codebase` if the index is missing or incompatible. Then use `implementation_lookup` for the definition site. Use `grep` for exhaustive literal matches.\";\n }\n\n return \"For this turn, prefer `implementation_lookup` to find the authoritative definition site. Use `codebase_search` only if no definition is found, and use `grep` for exhaustive literal matches.\";\n }\n\n if (assessment.intent !== \"local_conceptual\") {\n return null;\n }\n\n if (!status || !status.indexed || status.compatibility?.compatible === false) {\n return \"For this turn, if local code discovery by behavior is needed, check `index_status` first and run `index_codebase` if the index is missing or incompatible. Use `grep` for exact identifiers or exhaustive matches.\";\n }\n\n return \"For this turn, prefer `codebase_peek` for local code discovery by behavior or likely location, then use `codebase_search` when you need implementation content. Use `grep` for exact identifiers or exhaustive matches.\";\n}\n\nexport class RoutingHintController {\n private readonly sessionState = new Map<string, RoutingSessionState>();\n\n constructor(\n private readonly getStatus: () => Promise<Pick<StatusResult, \"indexed\" | \"compatibility\">>,\n private readonly maxSessions: number = 200,\n ) {}\n\n observeUserMessage(sessionID: string, parts: TextPartLike[]): RoutingAssessment {\n const assessment = assessRoutingIntent(extractUserText(parts));\n\n this.compactSessions();\n this.sessionState.set(sessionID, {\n assessment,\n pendingHint: assessment.intent === \"local_conceptual\" || assessment.intent === \"definition_lookup\",\n updatedAt: Date.now(),\n });\n\n return assessment;\n }\n\n async getSystemHints(sessionID?: string): Promise<string[]> {\n if (!sessionID) {\n return [];\n }\n\n const state = this.sessionState.get(sessionID);\n if (!state || !state.pendingHint) {\n return [];\n }\n\n const status = await this.safeGetStatus();\n const hint = buildRoutingHint(state.assessment, status);\n\n return hint ? [hint] : [];\n }\n\n markToolUsed(sessionID: string, toolName: string): void {\n const state = this.sessionState.get(sessionID);\n if (!state || !state.pendingHint) {\n return;\n }\n\n if (\n toolName === \"codebase_peek\"\n || toolName === \"codebase_search\"\n || toolName === \"implementation_lookup\"\n || toolName === \"index_status\"\n || toolName === \"index_codebase\"\n ) {\n state.pendingHint = false;\n state.updatedAt = Date.now();\n this.sessionState.set(sessionID, state);\n }\n }\n\n getSessionState(sessionID: string): RoutingSessionState | undefined {\n return this.sessionState.get(sessionID);\n }\n\n private async safeGetStatus(): Promise<Pick<StatusResult, \"indexed\" | \"compatibility\"> | null> {\n try {\n return await this.getStatus();\n } catch {\n return null;\n }\n }\n\n private compactSessions(): void {\n if (this.sessionState.size < this.maxSessions) {\n return;\n }\n\n const oldestSession = [...this.sessionState.entries()]\n .sort((left, right) => left[1].updatedAt - right[1].updatedAt)\n .at(0);\n\n if (oldestSession) {\n this.sessionState.delete(oldestSession[0]);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0CAAAA,SAAA;AAAA;AACA,aAAS,UAAW,SAAS;AAC3B,aAAO,MAAM,QAAQ,OAAO,IACxB,UACA,CAAC,OAAO;AAAA,IACd;AAEA,QAAM,YAAY;AAClB,QAAM,QAAQ;AACd,QAAM,QAAQ;AACd,QAAM,SAAS;AACf,QAAM,wBAAwB;AAC9B,QAAM,mCAAmC;AACzC,QAAM,4CAA4C;AAClD,QAAM,qCAAqC;AAC3C,QAAM,sBAAsB;AAU5B,QAAM,0BAA0B;AAEhC,QAAM,4BAA4B;AAElC,QAAMC,SAAQ;AAGd,QAAI,iBAAiB;AAErB,QAAI,OAAO,WAAW,aAAa;AACjC,uBAAiB,uBAAO,IAAI,aAAa;AAAA,IAC3C;AACA,QAAM,aAAa;AAEnB,QAAM,SAAS,CAAC,QAAQ,KAAK,UAAU;AACrC,aAAO,eAAe,QAAQ,KAAK,EAAC,MAAK,CAAC;AAC1C,aAAO;AAAA,IACT;AAEA,QAAM,qBAAqB;AAE3B,QAAM,eAAe,MAAM;AAI3B,QAAM,gBAAgB,WAAS,MAAM;AAAA,MACnC;AAAA,MACA,CAAC,OAAO,MAAM,OAAO,KAAK,WAAW,CAAC,KAAK,GAAG,WAAW,CAAC,IACtD,QAGA;AAAA,IACN;AAGA,QAAM,sBAAsB,aAAW;AACrC,YAAM,EAA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AoB,UAAU;AAC9C;AAAA,QACF;AAEA,cAAM,QAAQ,MAAM,cAAc,eAAe,MAAM,SAAS,KAAK,CAAC;AACtE,2BAAmB,QAAQ,OAAO,QAAQ;AAAA,MAC5C;AAAA,MAEA,MAAM,wCAAwC,OAA2B,QAA6B;AACpG,YAAI,OAAO,OAAO,oBAAoB,aAAa;AACjD;AAAA,QACF;AAEA,cAAM,QAAQ,MAAM,cAAc,eAAe,MAAM,SAAS,KAAK,CAAC;AACtE,2BAAmB,QAAQ,OAAO,WAAW;AAAA,MAC/C;AAAA,MAEA,MAAM,qBAAqB,OAAO;AAChC,sBAAc,aAAa,MAAM,WAAW,MAAM,IAAI;AAAA,MACxD;AAAA,MAEA,MAAM,OAAO,KAAK;AAChB,YAAI,UAAU,IAAI,WAAW,CAAC;AAE9B,cAAM,cAAc,eAAe;AACnC,cAAM,WAAW,0BAA0B,WAAW;AAEtD,mBAAW,CAAC,MAAM,UAAU,KAAK,UAAU;AACzC,cAAI,QAAQ,IAAI,IAAI;AAAA,QACtB;AAAA,MACF;AAAA,IACF;AAAA,EACF,QAAQ;AACN,YAAQ,MAAM,yEAAyE;AAEvF,WAAO;AAAA,MACL,MAAM;AAAA,MACN,MAAM,SAAS;AAAA,MAAC;AAAA,IAClB;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;","names":["module","SLASH","path","Ignore","module","EventEmitter","os","path","fileURLToPath","existsSync","readFileSync","os","path","existsSync","path","existsSync","readFileSync","statSync","path","existsSync","stat","statSync","readFileSync","existsSync","existsSync","path","path","isStringArray","existsSync","readFileSync","readdir","stat","sp","path","basename","lstat","stat","lstat","stat","path","rawEmitter","listener","basename","dirname","newStats","closer","resolve","realpath","stats","relative","path","testString","readdir","stats","stat","now","path","existsSync","readFileSync","path","existsSync","ignore","readFileSync","stat","path","path","existsSync","readFileSync","writeFileSync","mkdirSync","fsPromises","path","performance","resolve","EventEmitter","resolve","reject","resolve","existsSync","readFileSync","path","os","path","os","platform","arch","require","existsSync","readFileSync","mkdirSync","writeFileSync","fsPromises","performance","resolve","failedBatch","path","lines","path","normalizeKnowledgeBasePath","existsSync","statSync","path","existsSync","mkdirSync","writeFileSync","path","existsSync","mkdirSync","writeFileSync","os","existsSync","formatted","path","stat","statSync","result","existsSync","readdirSync","readFileSync","path","fileURLToPath"]}
|