opencode-codebase-index 0.8.1 → 0.9.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 +28 -11
- package/dist/cli.cjs +1520 -1288
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1519 -1287
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1107 -921
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1076 -890
- 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 +8 -2
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/eventemitter3/index.js","../node_modules/ignore/index.js","../src/cli.ts","../src/config/constants.ts","../src/config/env-substitution.ts","../src/config/schema.ts","../src/eval/cli.ts","../src/eval/compare.ts","../src/eval/reports.ts","../src/eval/runner.ts","../src/config/merger.ts","../src/config/paths.ts","../src/git/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.ts","../src/rerank/index.ts","../src/utils/files.ts","../src/utils/cost.ts","../src/utils/logger.ts","../src/native/index.ts","../src/eval/budget.ts","../src/eval/metrics.ts","../src/eval/schema.ts","../src/mcp-server.ts","../src/tools/utils.ts"],"sourcesContent":["'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","// 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","#!/usr/bin/env node\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport * as path from \"path\";\n\nimport { parseConfig } from \"./config/schema.js\";\nimport { handleEvalCommand } from \"./eval/cli.js\";\nimport { createMcpServer } from \"./mcp-server.js\";\nimport { loadMergedConfig } from \"./config/merger.js\";\n\nfunction parseArgs(argv: string[]): { project: string; config?: string } {\n let project = process.cwd();\n let config: string | undefined;\n\n for (let i = 2; i < argv.length; i++) {\n if (argv[i] === \"--project\" && argv[i + 1]) {\n project = path.resolve(argv[++i]);\n } else if (argv[i] === \"--config\" && argv[i + 1]) {\n config = path.resolve(argv[++i]);\n }\n }\n\n return { project, config };\n}\n\nasync function main(): Promise<void> {\n if (process.argv[2] === \"eval\") {\n const exitCode = await handleEvalCommand(process.argv.slice(3), process.cwd());\n process.exit(exitCode);\n }\n\n const args = parseArgs(process.argv);\n const rawConfig = loadMergedConfig(args.project);\n const config = parseConfig(rawConfig);\n\n const server = createMcpServer(args.project, config);\n const transport = new StdioServerTransport();\n\n await server.connect(transport);\n\n const shutdown = (): void => {\n server.close().catch(() => {});\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n}\n\nmain().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Fatal: ${message}`);\n process.exit(1);\n});\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];\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\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","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","// 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 { substituteEnvString } from \"./env-substitution.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\nfunction 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\nfunction 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\nfunction isValidFusionStrategy(value: unknown): value is SearchConfig[\"fusionStrategy\"] {\n return value === \"weighted\" || value === \"rrf\";\n}\n\nfunction isValidRerankerProvider(value: unknown): value is RerankerProvider {\n return value === \"cohere\" || value === \"jina\" || value === \"custom\";\n}\n\nfunction 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\nfunction 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\nconst VALID_SCOPES: IndexScope[] = [\"project\", \"global\"];\nconst VALID_LOG_LEVELS: LogLevel[] = [\"error\", \"warn\", \"info\", \"debug\"];\n\nfunction 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\nfunction isValidScope(value: unknown): value is IndexScope {\n return typeof value === \"string\" && VALID_SCOPES.includes(value as IndexScope);\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every(item => typeof item === \"string\");\n}\n\nfunction getResolvedString(value: unknown, keyPath: string): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n return substituteEnvString(value, keyPath);\n}\n\nfunction 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\nfunction isValidLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && VALID_LOG_LEVELS.includes(value as LogLevel);\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.filter(p => typeof p === \"string\" && p.trim().length > 0).map(p => p.trim())\n : [];\n\n let embeddingProvider: EmbeddingProvider | 'custom' | 'auto';\n let embeddingModel: EmbeddingModelName | undefined = undefined;\n let customProvider: CustomProviderConfig | undefined = undefined;\n let reranker: RerankerConfig | undefined = undefined;\n \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 = substituteEnvString(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 * as path from \"path\";\n\nimport { compareSummaries } from \"./compare.js\";\nimport { createSummaryMarkdown, createRunDirectory, loadSummary, writeJson, writeText } from \"./reports.js\";\nimport { runEvaluation, runSweep } from \"./runner.js\";\nimport type { EvalRunOptions, SweepDefinition } from \"./types.js\";\n\ninterface ParsedArgs {\n projectRoot: string;\n configPath?: string;\n datasetPath: string;\n currentPath?: string;\n outputRoot: string;\n againstPath?: string;\n budgetPath?: string;\n ciMode: boolean;\n reindex: boolean;\n fusionStrategy?: \"rrf\" | \"weighted\";\n hybridWeight?: number;\n rrfK?: number;\n rerankTopN?: number;\n sweep: SweepDefinition;\n}\n\ninterface EvalSubcommandOptions {\n parsed: ParsedArgs;\n explicitAgainst?: string;\n}\n\nfunction printUsage(): void {\n console.log(`\nUsage:\n opencode-codebase-index-mcp eval run [options]\n opencode-codebase-index-mcp eval compare --against <summary.json> [options]\n opencode-codebase-index-mcp eval diff --current <summary.json> --against <summary.json> [options]\n\nOptions:\n --project <path> Project root (default: cwd)\n --config <path> Config JSON path\n --dataset <path> Golden dataset path (default: benchmarks/golden/small.json)\n --current <path> Current summary.json path (required for eval diff)\n --output <path> Output root dir (default: benchmarks/results)\n --against <path> Baseline summary.json to compare against\n --budget <path> Budget file for CI mode (default: benchmarks/budgets/default.json)\n --ci Enable CI gate mode\n --reindex Force reindex before eval\n\nSearch overrides:\n --fusionStrategy <rrf|weighted>\n --hybridWeight <0-1>\n --rrfK <number>\n --rerankTopN <number>\n\nSweep options (comma-separated values):\n --sweepFusionStrategy <rrf,weighted>\n --sweepHybridWeight <0.3,0.5,0.7>\n --sweepRrfK <30,60,90>\n --sweepRerankTopN <10,20,40>\n`);\n}\n\nfunction parseNumber(value: string, flag: string): number {\n const parsed = Number(value);\n if (Number.isNaN(parsed)) {\n throw new Error(`${flag} must be a number`);\n }\n return parsed;\n}\n\nfunction parseCsvNumbers(value: string, flag: string): number[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0)\n .map((item) => parseNumber(item, flag));\n}\n\nfunction parseCsvFusion(value: string): Array<\"rrf\" | \"weighted\"> {\n const values = value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n\n const parsed: Array<\"rrf\" | \"weighted\"> = [];\n for (const candidate of values) {\n if (candidate !== \"rrf\" && candidate !== \"weighted\") {\n throw new Error(\"--sweepFusionStrategy accepts only rrf,weighted\");\n }\n parsed.push(candidate);\n }\n return parsed;\n}\n\nfunction hasSweepOptions(sweep: SweepDefinition): boolean {\n return Boolean(\n (sweep.fusionStrategy && sweep.fusionStrategy.length > 0) ||\n (sweep.hybridWeight && sweep.hybridWeight.length > 0) ||\n (sweep.rrfK && sweep.rrfK.length > 0) ||\n (sweep.rerankTopN && sweep.rerankTopN.length > 0)\n );\n}\n\nfunction parseEvalArgs(argv: string[], cwd: string): ParsedArgs {\n const parsed: ParsedArgs = {\n projectRoot: cwd,\n datasetPath: \"benchmarks/golden/small.json\",\n outputRoot: \"benchmarks/results\",\n budgetPath: \"benchmarks/budgets/default.json\",\n ciMode: false,\n reindex: false,\n sweep: {},\n };\n\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n const next = argv[i + 1];\n\n if (arg === \"--project\" && next) {\n parsed.projectRoot = path.resolve(cwd, next);\n i += 1;\n continue;\n }\n if (arg === \"--config\" && next) {\n parsed.configPath = path.resolve(cwd, next);\n i += 1;\n continue;\n }\n if (arg === \"--dataset\" && next) {\n parsed.datasetPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--current\" && next) {\n parsed.currentPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--output\" && next) {\n parsed.outputRoot = next;\n i += 1;\n continue;\n }\n if (arg === \"--against\" && next) {\n parsed.againstPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--budget\" && next) {\n parsed.budgetPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--ci\") {\n parsed.ciMode = true;\n continue;\n }\n if (arg === \"--reindex\") {\n parsed.reindex = true;\n continue;\n }\n if (arg === \"--fusionStrategy\" && next) {\n if (next !== \"rrf\" && next !== \"weighted\") {\n throw new Error(\"--fusionStrategy must be rrf or weighted\");\n }\n parsed.fusionStrategy = next;\n i += 1;\n continue;\n }\n if (arg === \"--hybridWeight\" && next) {\n parsed.hybridWeight = parseNumber(next, \"--hybridWeight\");\n i += 1;\n continue;\n }\n if (arg === \"--rrfK\" && next) {\n parsed.rrfK = parseNumber(next, \"--rrfK\");\n i += 1;\n continue;\n }\n if (arg === \"--rerankTopN\" && next) {\n parsed.rerankTopN = parseNumber(next, \"--rerankTopN\");\n i += 1;\n continue;\n }\n if (arg === \"--sweepFusionStrategy\" && next) {\n parsed.sweep.fusionStrategy = parseCsvFusion(next);\n i += 1;\n continue;\n }\n if (arg === \"--sweepHybridWeight\" && next) {\n parsed.sweep.hybridWeight = parseCsvNumbers(next, \"--sweepHybridWeight\");\n i += 1;\n continue;\n }\n if (arg === \"--sweepRrfK\" && next) {\n parsed.sweep.rrfK = parseCsvNumbers(next, \"--sweepRrfK\");\n i += 1;\n continue;\n }\n if (arg === \"--sweepRerankTopN\" && next) {\n parsed.sweep.rerankTopN = parseCsvNumbers(next, \"--sweepRerankTopN\");\n i += 1;\n continue;\n }\n }\n\n return parsed;\n}\n\nfunction parseEvalSubcommandOptions(argv: string[], cwd: string): EvalSubcommandOptions {\n let explicitAgainst: string | undefined;\n const filtered: string[] = [];\n\n for (let i = 0; i < argv.length; i += 1) {\n const current = argv[i];\n const next = argv[i + 1];\n\n if (current === \"--against\" && next) {\n explicitAgainst = next;\n i += 1;\n continue;\n }\n\n filtered.push(current);\n }\n\n return {\n parsed: parseEvalArgs(filtered, cwd),\n explicitAgainst,\n };\n}\n\nfunction toRunOptions(parsed: ParsedArgs): EvalRunOptions {\n return {\n projectRoot: parsed.projectRoot,\n configPath: parsed.configPath,\n datasetPath: parsed.datasetPath,\n outputRoot: parsed.outputRoot,\n againstPath: parsed.againstPath,\n budgetPath: parsed.budgetPath,\n ciMode: parsed.ciMode,\n reindex: parsed.reindex,\n searchOverrides: {\n ...(parsed.fusionStrategy !== undefined ? { fusionStrategy: parsed.fusionStrategy } : {}),\n ...(parsed.hybridWeight !== undefined ? { hybridWeight: parsed.hybridWeight } : {}),\n ...(parsed.rrfK !== undefined ? { rrfK: parsed.rrfK } : {}),\n ...(parsed.rerankTopN !== undefined ? { rerankTopN: parsed.rerankTopN } : {}),\n },\n };\n}\n\nexport async function handleEvalCommand(args: string[], cwd: string): Promise<number> {\n const subcommand = args[0];\n\n if (!subcommand || subcommand === \"--help\" || subcommand === \"-h\") {\n printUsage();\n return 0;\n }\n\n if (subcommand === \"run\") {\n const { parsed, explicitAgainst } = parseEvalSubcommandOptions(args.slice(1), cwd);\n if (explicitAgainst) {\n parsed.againstPath = explicitAgainst;\n }\n const runOptions = toRunOptions(parsed);\n\n if (hasSweepOptions(parsed.sweep)) {\n const sweep = await runSweep(runOptions, parsed.sweep);\n console.log(`Eval sweep complete. Artifacts: ${sweep.outputDir}`);\n console.log(`Sweep runs: ${sweep.aggregate.runCount}`);\n if (parsed.ciMode && sweep.aggregate.gatePassed === false) {\n console.error(\n `[CI-GATE] Sweep failed: ${sweep.aggregate.failedGateRuns ?? 0} run(s) violated budget/baseline gates`\n );\n return 1;\n }\n return 0;\n }\n\n const result = await runEvaluation(runOptions);\n console.log(`Eval run complete. Artifacts: ${result.outputDir}`);\n console.log(\n `Hit@5=${(result.summary.metrics.hitAt5 * 100).toFixed(2)}% MRR@10=${result.summary.metrics.mrrAt10.toFixed(4)} p95=${result.summary.metrics.latencyMs.p95.toFixed(3)}ms`\n );\n\n if (result.gate && !result.gate.passed) {\n for (const violation of result.gate.violations) {\n console.error(`[CI-GATE] ${violation.metric}: ${violation.message}`);\n }\n return 1;\n }\n\n return 0;\n }\n\n if (subcommand === \"compare\") {\n const { parsed, explicitAgainst } = parseEvalSubcommandOptions(args.slice(1), cwd);\n\n if (!explicitAgainst) {\n throw new Error(\"eval compare requires --against <baseline summary.json>\");\n }\n parsed.againstPath = explicitAgainst;\n\n const runOptions = toRunOptions(parsed);\n\n if (hasSweepOptions(parsed.sweep)) {\n const sweep = await runSweep(runOptions, parsed.sweep);\n console.log(`Eval compare sweep complete. Artifacts: ${sweep.outputDir}`);\n if (parsed.ciMode && sweep.aggregate.gatePassed === false) {\n console.error(\n `[CI-GATE] Sweep failed: ${sweep.aggregate.failedGateRuns ?? 0} run(s) violated budget/baseline gates`\n );\n return 1;\n }\n return 0;\n }\n\n const result = await runEvaluation(runOptions);\n console.log(`Eval compare complete. Artifacts: ${result.outputDir}`);\n return 0;\n }\n\n if (subcommand === \"diff\") {\n const { parsed, explicitAgainst } = parseEvalSubcommandOptions(args.slice(1), cwd);\n if (!explicitAgainst) {\n throw new Error(\"eval diff requires --against <baseline summary.json>\");\n }\n if (!parsed.currentPath) {\n throw new Error(\"eval diff requires --current <current summary.json>\");\n }\n parsed.againstPath = explicitAgainst;\n\n const currentPath = parsed.currentPath;\n if (!currentPath.endsWith(\".json\")) {\n throw new Error(\"eval diff --current must point to a summary JSON file\");\n }\n if (!parsed.againstPath.endsWith(\".json\")) {\n throw new Error(\"eval diff --against must point to a summary JSON file\");\n }\n const currentSummary = loadSummary(path.resolve(parsed.projectRoot, currentPath), {\n allowLegacyDiversityMetrics: true,\n });\n const baselineSummary = loadSummary(path.resolve(parsed.projectRoot, parsed.againstPath), {\n allowLegacyDiversityMetrics: true,\n });\n const comparison = compareSummaries(\n currentSummary,\n baselineSummary,\n path.resolve(parsed.projectRoot, parsed.againstPath)\n );\n\n const outputDir = createRunDirectory(path.resolve(parsed.projectRoot, parsed.outputRoot));\n const summaryMd = createSummaryMarkdown(currentSummary, comparison);\n writeJson(path.join(outputDir, \"compare.json\"), comparison);\n writeText(path.join(outputDir, \"summary.md\"), summaryMd);\n writeJson(path.join(outputDir, \"summary.json\"), currentSummary);\n console.log(`Eval diff complete. Artifacts: ${outputDir}`);\n return 0;\n }\n\n throw new Error(`Unknown eval subcommand: ${subcommand}`);\n}\n","import type { EvalComparison, EvalSummary, MetricDelta } from \"./types.js\";\n\nfunction metricDelta(current: number, baseline: number): MetricDelta {\n const absolute = current - baseline;\n const relativePct = baseline === 0 ? (current === 0 ? 0 : 100) : (absolute / baseline) * 100;\n return {\n current,\n baseline,\n absolute,\n relativePct,\n };\n}\n\nexport function compareSummaries(current: EvalSummary, baseline: EvalSummary, againstPath: string): EvalComparison {\n return {\n againstPath,\n deltas: {\n hitAt1: metricDelta(current.metrics.hitAt1, baseline.metrics.hitAt1),\n hitAt3: metricDelta(current.metrics.hitAt3, baseline.metrics.hitAt3),\n hitAt5: metricDelta(current.metrics.hitAt5, baseline.metrics.hitAt5),\n hitAt10: metricDelta(current.metrics.hitAt10, baseline.metrics.hitAt10),\n mrrAt10: metricDelta(current.metrics.mrrAt10, baseline.metrics.mrrAt10),\n ndcgAt10: metricDelta(current.metrics.ndcgAt10, baseline.metrics.ndcgAt10),\n distinctTop3Ratio: metricDelta(current.metrics.distinctTop3Ratio, baseline.metrics.distinctTop3Ratio),\n rawDistinctTop3Ratio: metricDelta(current.metrics.rawDistinctTop3Ratio, baseline.metrics.rawDistinctTop3Ratio),\n latencyP50Ms: metricDelta(current.metrics.latencyMs.p50, baseline.metrics.latencyMs.p50),\n latencyP95Ms: metricDelta(current.metrics.latencyMs.p95, baseline.metrics.latencyMs.p95),\n latencyP99Ms: metricDelta(current.metrics.latencyMs.p99, baseline.metrics.latencyMs.p99),\n embeddingCallCount: metricDelta(\n current.metrics.embedding.callCount,\n baseline.metrics.embedding.callCount\n ),\n estimatedCostUsd: metricDelta(\n current.metrics.embedding.estimatedCostUsd,\n baseline.metrics.embedding.estimatedCostUsd\n ),\n },\n };\n}\n","import { mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport * as path from \"path\";\n\nimport type {\n EvalComparison,\n EvalGateResult,\n EvalSummary,\n PerQueryEvalResult,\n SweepAggregateReport,\n} from \"./types.js\";\n\ninterface LoadSummaryOptions {\n allowLegacyDiversityMetrics?: boolean;\n}\n\nfunction assertFiniteNumber(value: unknown, path: string): number {\n if (typeof value !== \"number\" || Number.isNaN(value) || !Number.isFinite(value)) {\n throw new Error(`${path} must be a finite number`);\n }\n return value;\n}\n\nfunction validateSummary(\n summary: EvalSummary,\n summaryPath: string,\n options?: LoadSummaryOptions\n): EvalSummary {\n assertFiniteNumber(summary.metrics.hitAt1, `${summaryPath}.metrics.hitAt1`);\n assertFiniteNumber(summary.metrics.hitAt3, `${summaryPath}.metrics.hitAt3`);\n assertFiniteNumber(summary.metrics.hitAt5, `${summaryPath}.metrics.hitAt5`);\n assertFiniteNumber(summary.metrics.hitAt10, `${summaryPath}.metrics.hitAt10`);\n assertFiniteNumber(summary.metrics.mrrAt10, `${summaryPath}.metrics.mrrAt10`);\n assertFiniteNumber(summary.metrics.ndcgAt10, `${summaryPath}.metrics.ndcgAt10`);\n\n const metrics = summary.metrics as EvalSummary[\"metrics\"] & {\n distinctTop3Ratio?: number;\n rawDistinctTop3Ratio?: number;\n };\n\n if (metrics.distinctTop3Ratio === undefined && options?.allowLegacyDiversityMetrics) {\n metrics.distinctTop3Ratio = 0;\n }\n if (metrics.rawDistinctTop3Ratio === undefined && options?.allowLegacyDiversityMetrics) {\n metrics.rawDistinctTop3Ratio = 0;\n }\n\n assertFiniteNumber(metrics.distinctTop3Ratio, `${summaryPath}.metrics.distinctTop3Ratio`);\n assertFiniteNumber(metrics.rawDistinctTop3Ratio, `${summaryPath}.metrics.rawDistinctTop3Ratio`);\n assertFiniteNumber(summary.metrics.latencyMs.p50, `${summaryPath}.metrics.latencyMs.p50`);\n assertFiniteNumber(summary.metrics.latencyMs.p95, `${summaryPath}.metrics.latencyMs.p95`);\n assertFiniteNumber(summary.metrics.latencyMs.p99, `${summaryPath}.metrics.latencyMs.p99`);\n assertFiniteNumber(summary.metrics.embedding.callCount, `${summaryPath}.metrics.embedding.callCount`);\n assertFiniteNumber(summary.metrics.embedding.estimatedCostUsd, `${summaryPath}.metrics.embedding.estimatedCostUsd`);\n\n return summary;\n}\n\nfunction formatPct(value: number): string {\n return `${(value * 100).toFixed(2)}%`;\n}\n\nfunction formatMs(value: number): string {\n return `${value.toFixed(3)}ms`;\n}\n\nfunction formatUsd(value: number): string {\n return `$${value.toFixed(6)}`;\n}\n\nfunction signed(value: number, digits = 4): string {\n const formatted = value.toFixed(digits);\n return value > 0 ? `+${formatted}` : formatted;\n}\n\nexport function loadSummary(summaryPath: string, options?: LoadSummaryOptions): EvalSummary {\n const raw = readFileSync(summaryPath, \"utf-8\");\n return validateSummary(JSON.parse(raw) as EvalSummary, summaryPath, options);\n}\n\nexport function createRunDirectory(outputRoot: string, timestampOverride?: string): string {\n const timestamp = (timestampOverride ?? new Date().toISOString()).replace(/[:.]/g, \"-\");\n const dir = path.join(outputRoot, timestamp);\n mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nexport function writeJson(filePath: string, value: unknown): void {\n writeFileSync(filePath, JSON.stringify(value, null, 2), \"utf-8\");\n}\n\nexport function writeText(filePath: string, value: string): void {\n writeFileSync(filePath, value, \"utf-8\");\n}\n\nexport function createSummaryMarkdown(\n summary: EvalSummary,\n comparison?: EvalComparison,\n gate?: EvalGateResult,\n sweep?: SweepAggregateReport\n): string {\n const lines: string[] = [];\n\n lines.push(\"# Evaluation Summary\");\n lines.push(\"\");\n lines.push(`- Generated: ${summary.generatedAt}`);\n lines.push(`- Dataset: ${summary.datasetName} (v${summary.datasetVersion})`);\n lines.push(`- Query count: ${summary.queryCount}`);\n lines.push(\n `- Search config: fusion=${summary.searchConfig.fusionStrategy}, hybridWeight=${summary.searchConfig.hybridWeight}, rrfK=${summary.searchConfig.rrfK}, rerankTopN=${summary.searchConfig.rerankTopN}`\n );\n lines.push(\"\");\n\n lines.push(\"## Metrics\");\n lines.push(\"\");\n lines.push(\"| Metric | Value |\");\n lines.push(\"|---|---:|\");\n lines.push(`| Hit@1 | ${formatPct(summary.metrics.hitAt1)} |`);\n lines.push(`| Hit@3 | ${formatPct(summary.metrics.hitAt3)} |`);\n lines.push(`| Hit@5 | ${formatPct(summary.metrics.hitAt5)} |`);\n lines.push(`| Hit@10 | ${formatPct(summary.metrics.hitAt10)} |`);\n lines.push(`| MRR@10 | ${summary.metrics.mrrAt10.toFixed(4)} |`);\n lines.push(`| nDCG@10 | ${summary.metrics.ndcgAt10.toFixed(4)} |`);\n lines.push(`| Distinct Top@3 | ${formatPct(summary.metrics.distinctTop3Ratio)} |`);\n lines.push(`| Raw Distinct Top@3 | ${formatPct(summary.metrics.rawDistinctTop3Ratio)} |`);\n lines.push(`| Latency p50 | ${formatMs(summary.metrics.latencyMs.p50)} |`);\n lines.push(`| Latency p95 | ${formatMs(summary.metrics.latencyMs.p95)} |`);\n lines.push(`| Latency p99 | ${formatMs(summary.metrics.latencyMs.p99)} |`);\n lines.push(`| Embedding calls | ${summary.metrics.embedding.callCount} |`);\n lines.push(`| Embedding tokens | ${summary.metrics.tokenEstimate.embeddingTokensUsed} |`);\n lines.push(`| Estimated embedding cost | ${formatUsd(summary.metrics.embedding.estimatedCostUsd)} |`);\n lines.push(\"\");\n\n lines.push(\"## Failure Buckets\");\n lines.push(\"\");\n lines.push(\"| Bucket | Count |\");\n lines.push(\"|---|---:|\");\n lines.push(\n `| wrong-file | ${summary.metrics.failureBuckets[\"wrong-file\"]} |`\n );\n lines.push(\n `| wrong-symbol | ${summary.metrics.failureBuckets[\"wrong-symbol\"]} |`\n );\n lines.push(\n `| docs/tests outranking source | ${summary.metrics.failureBuckets[\"docs-tests-outranking-source\"]} |`\n );\n lines.push(\n `| no relevant hit in top-k | ${summary.metrics.failureBuckets[\"no-relevant-hit-top-k\"]} |`\n );\n lines.push(\"\");\n\n if (comparison) {\n lines.push(\"## Comparison vs Baseline\");\n lines.push(\"\");\n lines.push(`- Against: ${comparison.againstPath}`);\n lines.push(\"\");\n lines.push(\"| Metric | Baseline | Current | Delta |\");\n lines.push(\"|---|---:|---:|---:|\");\n lines.push(\n `| Hit@5 | ${formatPct(comparison.deltas.hitAt5.baseline)} | ${formatPct(comparison.deltas.hitAt5.current)} | ${signed(comparison.deltas.hitAt5.absolute)} |`\n );\n lines.push(\n `| MRR@10 | ${comparison.deltas.mrrAt10.baseline.toFixed(4)} | ${comparison.deltas.mrrAt10.current.toFixed(4)} | ${signed(comparison.deltas.mrrAt10.absolute)} |`\n );\n lines.push(\n `| nDCG@10 | ${comparison.deltas.ndcgAt10.baseline.toFixed(4)} | ${comparison.deltas.ndcgAt10.current.toFixed(4)} | ${signed(comparison.deltas.ndcgAt10.absolute)} |`\n );\n lines.push(\n `| Distinct Top@3 | ${formatPct(comparison.deltas.distinctTop3Ratio.baseline)} | ${formatPct(comparison.deltas.distinctTop3Ratio.current)} | ${signed(comparison.deltas.distinctTop3Ratio.absolute)} |`\n );\n lines.push(\n `| Raw Distinct Top@3 | ${formatPct(comparison.deltas.rawDistinctTop3Ratio.baseline)} | ${formatPct(comparison.deltas.rawDistinctTop3Ratio.current)} | ${signed(comparison.deltas.rawDistinctTop3Ratio.absolute)} |`\n );\n lines.push(\n `| p95 latency (ms) | ${comparison.deltas.latencyP95Ms.baseline.toFixed(3)} | ${comparison.deltas.latencyP95Ms.current.toFixed(3)} | ${signed(comparison.deltas.latencyP95Ms.absolute, 3)} |`\n );\n lines.push(\"\");\n }\n\n if (gate) {\n lines.push(\"## CI Gate\");\n lines.push(\"\");\n lines.push(`- Result: ${gate.passed ? \"PASS ✅\" : \"FAIL ❌\"}`);\n if (gate.violations.length > 0) {\n lines.push(\"- Violations:\");\n for (const violation of gate.violations) {\n lines.push(` - ${violation.metric}: ${violation.message}`);\n }\n }\n lines.push(\"\");\n }\n\n if (sweep) {\n lines.push(\"## Parameter Sweep\");\n lines.push(\"\");\n lines.push(`- Run count: ${sweep.runCount}`);\n if (sweep.bestByHitAt5) {\n lines.push(\n `- Best Hit@5: ${formatPct(sweep.bestByHitAt5.summary.metrics.hitAt5)} with fusion=${sweep.bestByHitAt5.searchConfig.fusionStrategy}, hybridWeight=${sweep.bestByHitAt5.searchConfig.hybridWeight}, rrfK=${sweep.bestByHitAt5.searchConfig.rrfK}, rerankTopN=${sweep.bestByHitAt5.searchConfig.rerankTopN}`\n );\n }\n if (sweep.bestByMrrAt10) {\n lines.push(\n `- Best MRR@10: ${sweep.bestByMrrAt10.summary.metrics.mrrAt10.toFixed(4)} with fusion=${sweep.bestByMrrAt10.searchConfig.fusionStrategy}, hybridWeight=${sweep.bestByMrrAt10.searchConfig.hybridWeight}, rrfK=${sweep.bestByMrrAt10.searchConfig.rrfK}, rerankTopN=${sweep.bestByMrrAt10.searchConfig.rerankTopN}`\n );\n }\n if (sweep.bestByP95Latency) {\n lines.push(\n `- Best p95 latency: ${formatMs(sweep.bestByP95Latency.summary.metrics.latencyMs.p95)} with fusion=${sweep.bestByP95Latency.searchConfig.fusionStrategy}, hybridWeight=${sweep.bestByP95Latency.searchConfig.hybridWeight}, rrfK=${sweep.bestByP95Latency.searchConfig.rrfK}, rerankTopN=${sweep.bestByP95Latency.searchConfig.rerankTopN}`\n );\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport function buildPerQueryArtifact(perQuery: PerQueryEvalResult[]): {\n queryCount: number;\n queries: PerQueryEvalResult[];\n} {\n return {\n queryCount: perQuery.length,\n queries: [...perQuery].sort((a, b) => a.id.localeCompare(b.id)),\n };\n}\n","import { existsSync } from \"fs\";\nimport { mkdirSync } from \"fs\";\nimport { readFileSync } from \"fs\";\nimport { rmSync } from \"fs\";\nimport { writeFileSync } from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { performance } from \"perf_hooks\";\n\nimport { rebasePathEntries, resolveInheritedKnowledgeBaseEntries } from \"../config/merger.js\";\nimport { parseConfig } from \"../config/schema.js\";\nimport type { SearchConfig as ConfigSearchConfig } from \"../config/schema.js\";\nimport { getDefaultModelForProvider } from \"../config/index.js\";\nimport { getGlobalIndexPath, resolveProjectConfigPath, resolveProjectIndexPath } from \"../config/paths.js\";\nimport { Indexer } from \"../indexer/index.js\";\n\nimport { evaluateBudgetGate } from \"./budget.js\";\nimport { compareSummaries } from \"./compare.js\";\nimport { buildPerQueryResult, computeEvalMetrics } from \"./metrics.js\";\nimport {\n createSummaryMarkdown,\n createRunDirectory,\n loadSummary,\n writeJson,\n writeText,\n buildPerQueryArtifact,\n} from \"./reports.js\";\nimport { loadBudget, loadGoldenDataset } from \"./schema.js\";\nimport type {\n EvalComparison,\n EvalGateResult,\n EvalRunOptions,\n EvalSummary,\n PerQueryEvalResult,\n SweepAggregateReport,\n SweepDefinition,\n SweepRunSummary,\n} from \"./types.js\";\n\nfunction toAbsolute(projectRoot: string, maybeRelative: string): string {\n return path.isAbsolute(maybeRelative) ? maybeRelative : path.join(projectRoot, maybeRelative);\n}\n\nfunction isProjectScopedConfigPath(configPath: string): boolean {\n return path.basename(configPath) === \"codebase-index.json\"\n && path.basename(path.dirname(configPath)) === \".opencode\";\n}\n\nfunction normalizeEvalConfigKnowledgeBases(\n rawConfig: unknown,\n projectRoot: string,\n resolvedConfigPath: string,\n): Record<string, unknown> {\n const config = rawConfig && typeof rawConfig === \"object\"\n ? { ...(rawConfig as Record<string, unknown>) }\n : {};\n\n if (!Array.isArray(config.knowledgeBases)) {\n return config;\n }\n\n config.knowledgeBases = isProjectScopedConfigPath(resolvedConfigPath)\n ? resolveInheritedKnowledgeBaseEntries(\n config.knowledgeBases,\n path.dirname(path.dirname(resolvedConfigPath)),\n projectRoot,\n )\n : rebasePathEntries(\n config.knowledgeBases,\n path.dirname(resolvedConfigPath),\n projectRoot,\n );\n\n return config;\n}\n\nfunction loadRawConfig(projectRoot: string, configPath?: string): unknown {\n const fromPath = configPath ? toAbsolute(projectRoot, configPath) : null;\n if (fromPath && existsSync(fromPath)) {\n return normalizeEvalConfigKnowledgeBases(\n JSON.parse(readFileSync(fromPath, \"utf-8\")),\n projectRoot,\n fromPath,\n );\n }\n\n const projectConfig = resolveProjectConfigPath(projectRoot);\n if (existsSync(projectConfig)) {\n return normalizeEvalConfigKnowledgeBases(\n JSON.parse(readFileSync(projectConfig, \"utf-8\")),\n projectRoot,\n projectConfig,\n );\n }\n\n const globalConfig = path.join(os.homedir(), \".config\", \"opencode\", \"codebase-index.json\");\n if (existsSync(globalConfig)) {\n return JSON.parse(readFileSync(globalConfig, \"utf-8\"));\n }\n\n return {};\n}\n\nfunction getIndexRootPath(projectRoot: string, scope: \"project\" | \"global\"): string {\n return scope === \"global\"\n ? getGlobalIndexPath()\n : resolveProjectIndexPath(projectRoot, scope);\n}\n\nfunction getLocalProjectIndexRoot(projectRoot: string): string {\n return path.join(projectRoot, \".opencode\", \"index\");\n}\n\nfunction getLocalProjectConfigPath(projectRoot: string): string {\n return path.join(projectRoot, \".opencode\", \"codebase-index.json\");\n}\n\nfunction clearIndexRoot(projectRoot: string, scope: \"project\" | \"global\"): void {\n const indexRoot = scope === \"global\"\n ? getIndexRootPath(projectRoot, scope)\n : getLocalProjectIndexRoot(projectRoot);\n if (existsSync(indexRoot)) {\n rmSync(indexRoot, { recursive: true, force: true });\n }\n}\n\nfunction ensureLocalEvalProjectConfig(projectRoot: string, configPath?: string): string | undefined {\n const localConfigPath = getLocalProjectConfigPath(projectRoot);\n const resolvedConfigPath = configPath\n ? toAbsolute(projectRoot, configPath)\n : resolveProjectConfigPath(projectRoot);\n\n if (!configPath && existsSync(localConfigPath)) {\n return localConfigPath;\n }\n\n if (!existsSync(resolvedConfigPath) || resolvedConfigPath === localConfigPath) {\n return resolvedConfigPath;\n }\n\n const sourceConfig = normalizeEvalConfigKnowledgeBases(\n JSON.parse(readFileSync(resolvedConfigPath, \"utf-8\")),\n projectRoot,\n resolvedConfigPath,\n );\n\n mkdirSync(path.dirname(localConfigPath), { recursive: true });\n writeFileSync(localConfigPath, JSON.stringify(sourceConfig, null, 2), \"utf-8\");\n return localConfigPath;\n}\n\nfunction loadParsedConfig(projectRoot: string, configPath?: string) {\n const raw = loadRawConfig(projectRoot, configPath);\n return parseConfig(raw);\n}\n\nfunction resolveSearchConfig(\n parsedConfig: ReturnType<typeof parseConfig>,\n overrides?: Partial<Pick<ConfigSearchConfig, \"fusionStrategy\" | \"hybridWeight\" | \"rrfK\" | \"rerankTopN\">>\n) {\n const nextSearch: ConfigSearchConfig = {\n ...parsedConfig.search,\n };\n\n if (overrides?.fusionStrategy !== undefined) {\n nextSearch.fusionStrategy = overrides.fusionStrategy;\n }\n if (overrides?.hybridWeight !== undefined) {\n nextSearch.hybridWeight = overrides.hybridWeight;\n }\n if (overrides?.rrfK !== undefined) {\n nextSearch.rrfK = overrides.rrfK;\n }\n if (overrides?.rerankTopN !== undefined) {\n nextSearch.rerankTopN = overrides.rerankTopN;\n }\n\n return {\n ...parsedConfig,\n search: nextSearch,\n };\n}\n\nexport interface EvalRunResult {\n outputDir: string;\n summary: EvalSummary;\n perQuery: PerQueryEvalResult[];\n comparison?: EvalComparison;\n gate?: EvalGateResult;\n}\n\nexport async function runEvaluation(options: EvalRunOptions): Promise<EvalRunResult> {\n const datasetPath = toAbsolute(options.projectRoot, options.datasetPath);\n const againstPath = options.againstPath ? toAbsolute(options.projectRoot, options.againstPath) : undefined;\n const budgetPath = options.budgetPath ? toAbsolute(options.projectRoot, options.budgetPath) : undefined;\n\n const dataset = loadGoldenDataset(datasetPath);\n\n const resolvedEvalConfigPath = options.reindex\n ? ensureLocalEvalProjectConfig(options.projectRoot, options.configPath)\n : options.configPath;\n\n const parsedConfig = loadParsedConfig(options.projectRoot, resolvedEvalConfigPath);\n const effectiveConfig = resolveSearchConfig(parsedConfig, options.searchOverrides);\n\n if (options.reindex) {\n clearIndexRoot(options.projectRoot, effectiveConfig.scope);\n }\n\n const indexer = new Indexer(options.projectRoot, effectiveConfig);\n\n try {\n await indexer.index();\n\n const perQuery: PerQueryEvalResult[] = [];\n\n for (const query of dataset.queries) {\n if (query.expected.branch && query.expected.branch !== indexer.getCurrentBranch()) {\n throw new Error(\n `Query '${query.id}' expects branch '${query.expected.branch}', but current branch is '${indexer.getCurrentBranch()}'. Switch branch before running this dataset.`\n );\n }\n\n const start = performance.now();\n const result = await indexer.search(query.query, 10, {\n metadataOnly: true,\n filterByBranch: query.expected.branch ? true : false,\n });\n const elapsed = performance.now() - start;\n\n const materialized = result.map((item) => ({\n filePath: item.filePath,\n startLine: item.startLine,\n endLine: item.endLine,\n score: item.score,\n chunkType: item.chunkType,\n name: item.name,\n }));\n\n perQuery.push(buildPerQueryResult(query, materialized, elapsed, 10));\n }\n\n const logger = indexer.getLogger();\n const metricSnapshot = logger.getMetrics();\n\n const costPer1MTokensUsd =\n effectiveConfig.embeddingProvider === \"custom\" || effectiveConfig.embeddingProvider === \"auto\"\n ? 0\n : getDefaultModelForProvider(effectiveConfig.embeddingProvider).costPer1MTokens;\n\n const summary: EvalSummary = {\n generatedAt: new Date().toISOString(),\n projectRoot: options.projectRoot,\n datasetPath,\n datasetName: dataset.name,\n datasetVersion: dataset.version,\n queryCount: dataset.queries.length,\n topK: 10,\n searchConfig: {\n fusionStrategy: effectiveConfig.search.fusionStrategy,\n hybridWeight: effectiveConfig.search.hybridWeight,\n rrfK: effectiveConfig.search.rrfK,\n rerankTopN: effectiveConfig.search.rerankTopN,\n },\n metrics: computeEvalMetrics(\n dataset.queries,\n perQuery,\n metricSnapshot.embeddingApiCalls,\n metricSnapshot.embeddingTokensUsed,\n costPer1MTokensUsd\n ),\n };\n\n const outputDir = createRunDirectory(toAbsolute(options.projectRoot, options.outputRoot));\n const perQueryArtifact = buildPerQueryArtifact(perQuery);\n\n writeJson(path.join(outputDir, \"summary.json\"), summary);\n writeJson(path.join(outputDir, \"per-query.json\"), perQueryArtifact);\n\n let comparison: EvalComparison | undefined;\n if (againstPath) {\n const baseline = loadSummary(againstPath);\n comparison = compareSummaries(summary, baseline, againstPath);\n writeJson(path.join(outputDir, \"compare.json\"), comparison);\n }\n\n let gate: EvalGateResult | undefined;\n if (options.ciMode) {\n if (!budgetPath) {\n throw new Error(\"CI mode requires --budget path\");\n }\n const budget = loadBudget(budgetPath);\n\n if (!comparison && budget.baselinePath) {\n const resolvedBaseline = toAbsolute(options.projectRoot, budget.baselinePath);\n if (existsSync(resolvedBaseline)) {\n const baselineSummary = loadSummary(resolvedBaseline);\n comparison = compareSummaries(summary, baselineSummary, resolvedBaseline);\n writeJson(path.join(outputDir, \"compare.json\"), comparison);\n } else if (budget.failOnMissingBaseline) {\n throw new Error(\n `Budget baseline is missing: ${resolvedBaseline}. Set failOnMissingBaseline=false to allow CI run without baseline.`\n );\n }\n }\n\n gate = evaluateBudgetGate(budget, summary, comparison);\n }\n\n const markdown = createSummaryMarkdown(summary, comparison, gate);\n writeText(path.join(outputDir, \"summary.md\"), markdown);\n\n return { outputDir, summary, perQuery, comparison, gate };\n } finally {\n await indexer.close();\n }\n}\n\nexport async function runSweep(\n options: EvalRunOptions,\n sweep: SweepDefinition\n): Promise<{ outputDir: string; aggregate: SweepAggregateReport }> {\n const fusionValues: Array<\"rrf\" | \"weighted\" | undefined> =\n sweep.fusionStrategy && sweep.fusionStrategy.length > 0\n ? [...sweep.fusionStrategy]\n : [undefined];\n const weightValues: Array<number | undefined> =\n sweep.hybridWeight && sweep.hybridWeight.length > 0 ? [...sweep.hybridWeight] : [undefined];\n const rrfValues: Array<number | undefined> =\n sweep.rrfK && sweep.rrfK.length > 0 ? [...sweep.rrfK] : [undefined];\n const rerankValues: Array<number | undefined> =\n sweep.rerankTopN && sweep.rerankTopN.length > 0 ? [...sweep.rerankTopN] : [undefined];\n\n const runs: SweepRunSummary[] = [];\n\n for (const fusion of fusionValues) {\n for (const hybridWeight of weightValues) {\n for (const rrfK of rrfValues) {\n for (const rerankTopN of rerankValues) {\n const run = await runEvaluation({\n ...options,\n searchOverrides: {\n ...(fusion !== undefined ? { fusionStrategy: fusion } : {}),\n ...(hybridWeight !== undefined ? { hybridWeight } : {}),\n ...(rrfK !== undefined ? { rrfK } : {}),\n ...(rerankTopN !== undefined ? { rerankTopN } : {}),\n },\n });\n\n runs.push({\n searchConfig: run.summary.searchConfig,\n summary: run.summary,\n comparison: run.comparison,\n gate: run.gate,\n });\n }\n }\n }\n }\n\n const bestByHitAt5 = [...runs].sort(\n (a, b) => b.summary.metrics.hitAt5 - a.summary.metrics.hitAt5\n )[0];\n const bestByMrrAt10 = [...runs].sort(\n (a, b) => b.summary.metrics.mrrAt10 - a.summary.metrics.mrrAt10\n )[0];\n const bestByP95Latency = [...runs].sort(\n (a, b) => a.summary.metrics.latencyMs.p95 - b.summary.metrics.latencyMs.p95\n )[0];\n\n const outputDir = createRunDirectory(toAbsolute(options.projectRoot, options.outputRoot));\n const failedGateRuns = runs.filter((run) => run.gate && !run.gate.passed).length;\n const gatePassed = failedGateRuns === 0;\n const aggregate: SweepAggregateReport = {\n generatedAt: new Date().toISOString(),\n againstPath: options.againstPath,\n runCount: runs.length,\n runs,\n gatePassed,\n failedGateRuns,\n bestByHitAt5,\n bestByMrrAt10,\n bestByP95Latency,\n };\n\n writeJson(path.join(outputDir, \"compare.json\"), aggregate);\n const md = createSummaryMarkdown(\n bestByHitAt5?.summary ?? runs[0].summary,\n bestByHitAt5?.comparison,\n undefined,\n aggregate\n );\n writeText(path.join(outputDir, \"summary.md\"), md);\n writeJson(path.join(outputDir, \"summary.json\"), bestByHitAt5?.summary ?? runs[0].summary);\n\n return { outputDir, aggregate };\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { resolveProjectConfigPath } from \"./paths.js\";\n\nfunction loadJsonFile(filePath: string): unknown {\n try {\n if (existsSync(filePath)) {\n const content = readFileSync(filePath, \"utf-8\");\n return JSON.parse(content);\n }\n } catch { /* ignore */ }\n return null;\n}\n\nfunction normalizeRelativeConfigPath(candidate: string): string {\n return candidate.replace(/\\\\/g, \"/\");\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 normalizeRelativeConfigPath(path.normalize(path.relative(toDir, path.resolve(fromDir, trimmed))));\n })\n .filter(Boolean);\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 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 normalizeRelativeConfigPath(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 normalizeRelativeConfigPath(path.normalize(trimmed));\n }\n\n return normalizeRelativeConfigPath(path.normalize(path.relative(targetRoot, resolvedFromSource)));\n })\n .filter(Boolean);\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 globalConfig = loadJsonFile(globalConfigPath) as Record<string, unknown> | null;\n const projectConfigPath = resolveProjectConfigPath(projectRoot);\n const projectConfig = loadJsonFile(projectConfigPath) as Record<string, unknown> | null;\n const normalizedProjectConfig = loadProjectConfigLayer(projectRoot);\n\n // If neither exists, return empty\n if (!globalConfig && !projectConfig) {\n return {};\n }\n\n // If only global exists, return it\n if (!projectConfig && globalConfig) {\n return globalConfig;\n }\n\n // If only project exists, return it\n if (!globalConfig && projectConfig) {\n return normalizedProjectConfig;\n }\n\n // Both exist - start with global config as base\n const merged: Record<string, unknown> = { ...globalConfig };\n\n // For embeddingProvider: project overrides if set, otherwise use global\n if (projectConfig && \"embeddingProvider\" in normalizedProjectConfig) {\n merged.embeddingProvider = normalizedProjectConfig.embeddingProvider;\n } else if (globalConfig && globalConfig.embeddingProvider) {\n merged.embeddingProvider = globalConfig.embeddingProvider;\n }\n\n // For customProvider: project overrides if set, otherwise use global\n if (projectConfig && \"customProvider\" in normalizedProjectConfig) {\n merged.customProvider = normalizedProjectConfig.customProvider;\n } else if (globalConfig && globalConfig.customProvider) {\n merged.customProvider = globalConfig.customProvider;\n }\n\n // For embeddingModel: project overrides if set, otherwise use global\n if (projectConfig && \"embeddingModel\" in normalizedProjectConfig) {\n merged.embeddingModel = normalizedProjectConfig.embeddingModel;\n } else if (globalConfig && globalConfig.embeddingModel) {\n merged.embeddingModel = globalConfig.embeddingModel;\n }\n\n // For reranker: project overrides if set, otherwise use global\n if (projectConfig && \"reranker\" in normalizedProjectConfig) {\n merged.reranker = normalizedProjectConfig.reranker;\n } else if (globalConfig && globalConfig.reranker) {\n merged.reranker = globalConfig.reranker;\n }\n\n // For include: project overrides if set, otherwise use global\n if (projectConfig && \"include\" in normalizedProjectConfig) {\n merged.include = normalizedProjectConfig.include;\n } else if (globalConfig && globalConfig.include) {\n merged.include = globalConfig.include;\n }\n\n // For exclude: project overrides if set, otherwise use global\n if (projectConfig && \"exclude\" in normalizedProjectConfig) {\n merged.exclude = normalizedProjectConfig.exclude;\n } else if (globalConfig && globalConfig.exclude) {\n merged.exclude = globalConfig.exclude;\n }\n\n // For indexing: project overrides if set, otherwise use global\n if (projectConfig && \"indexing\" in normalizedProjectConfig) {\n merged.indexing = normalizedProjectConfig.indexing;\n } else if (globalConfig && globalConfig.indexing) {\n merged.indexing = globalConfig.indexing;\n }\n\n // For search: project overrides if set, otherwise use global\n if (projectConfig && \"search\" in normalizedProjectConfig) {\n merged.search = normalizedProjectConfig.search;\n } else if (globalConfig && globalConfig.search) {\n merged.search = globalConfig.search;\n }\n\n // For debug: project overrides if set, otherwise use global\n if (projectConfig && \"debug\" in normalizedProjectConfig) {\n merged.debug = normalizedProjectConfig.debug;\n } else if (globalConfig && globalConfig.debug) {\n merged.debug = globalConfig.debug;\n }\n\n // For scope: project overrides if set, otherwise use global\n if (projectConfig && \"scope\" in normalizedProjectConfig) {\n merged.scope = normalizedProjectConfig.scope;\n } else if (globalConfig && \"scope\" in globalConfig) {\n merged.scope = globalConfig.scope;\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 key === \"embeddingProvider\" ||\n key === \"customProvider\" ||\n key === \"embeddingModel\" ||\n key === \"reranker\" ||\n key === \"include\" ||\n key === \"exclude\" ||\n key === \"indexing\" ||\n key === \"search\" ||\n key === \"debug\" ||\n key === \"scope\" ||\n key === \"knowledgeBases\" ||\n key === \"additionalInclude\"\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 const uniqueKbs = [...new Set(allKbs.map(p => String(p).trim()))];\n merged.knowledgeBases = uniqueKbs;\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 const uniqueAdditional = [...new Set(allAdditional.map(p => String(p).trim()))];\n merged.additionalInclude = uniqueAdditional;\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, readdirSync, statSync } from \"fs\";\nimport * as path from \"path\";\n\nfunction 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\nfunction 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 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\nfunction 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\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 // Normal repo: .git is a directory\n return gitPath;\n }\n \n if (stat.isFile()) {\n // Worktree: .git is a file with gitdir pointer\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\nfunction 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\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, 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\"]);\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]);\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 try {\n if (existsSync(this.fileHashCachePath)) {\n const data = readFileSync(this.fileHashCachePath, \"utf-8\");\n const parsed = JSON.parse(data);\n this.fileHashCache = new Map(Object.entries(parsed));\n }\n } catch {\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 {\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 // Initialize reranker if configured\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\n // ── Call Graph Extraction ────────────────────────────────────────\n // Extract symbols and call edges from changed files.\n const allSymbolIds = new Set<string>();\n const symbolsByFile = new Map<string, SymbolData[]>();\n\n // For changed files: delete old symbols/edges, extract new ones\n for (let i = 0; i < parsedFiles.length; i++) {\n const parsed = parsedFiles[i];\n const changedFile = changedFiles[i];\n\n // Clean up old call graph data for this file\n database.deleteCallEdgesByFile(parsed.path);\n database.deleteSymbolsByFile(parsed.path);\n\n // Build symbols from parsed chunks\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 // Extract call sites from file content (only for supported languages)\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 // Map each call site to its enclosing symbol\n const edges: CallEdgeData[] = [];\n for (const site of callSites) {\n // Find the enclosing symbol (function/method that contains this call)\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 // Collect symbol IDs from unchanged files for branch association\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 // Auto-GC after indexing: check if orphan count exceeds threshold\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 // Clear persisted index data across all branches so force rebuilds\n // cannot reuse stale chunks, symbols, or embeddings from a prior provider.\n database.clearAllIndexedData();\n this.saveFailedBatches([]);\n\n // Clear index metadata so compatibility is re-evaluated from scratch\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 // Re-validate compatibility (no stored metadata = compatible)\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 baseUrl = (copilotAuth as OpenCodeAuthOAuth).enterpriseUrl\n ? `https://copilot-api.${(copilotAuth as OpenCodeAuthOAuth).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 { EmbeddingProviderModelInfo, BaseModelInfo } from \"../config/schema.js\";\nimport { ConfiguredProviderInfo, CustomModelInfo, 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\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 constructor(message: string) {\n super(message);\n this.name = 'CustomProviderNonRetryableError';\n }\n}\n\nexport function createEmbeddingProvider(\n configuredProviderInfo: ConfiguredProviderInfo,\n): 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\nclass GitHubCopilotEmbeddingProvider implements EmbeddingProviderInterface {\n constructor(\n private credentials: ProviderCredentials,\n private modelInfo: EmbeddingProviderModelInfo['github-copilot']\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 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 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 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();\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 getModelInfo(): BaseModelInfo {\n return this.modelInfo;\n }\n}\n\nclass OpenAIEmbeddingProvider implements EmbeddingProviderInterface {\n constructor(\n private credentials: ProviderCredentials,\n private modelInfo: EmbeddingProviderModelInfo['openai']\n ) { }\n\n 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 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 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();\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 getModelInfo(): BaseModelInfo {\n return this.modelInfo;\n }\n}\n\nclass GoogleEmbeddingProvider implements EmbeddingProviderInterface {\n private static readonly BATCH_SIZE = 20;\n\n constructor(\n private credentials: ProviderCredentials,\n private modelInfo: EmbeddingProviderModelInfo['google']\n ) { }\n\n 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 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 async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const taskType = this.modelInfo.taskAble ? \"RETRIEVAL_DOCUMENT\" : undefined;\n return this.embedWithTaskType(texts, taskType);\n }\n\n /**\n * Embeds texts using the Google embedContent API.\n * Sends multiple texts as parts in batched requests (up to BATCH_SIZE per call).\n * When taskType is provided (gemini-embedding-001), includes it in the request\n * for task-specific embedding optimization.\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?key=${this.credentials.apiKey}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ requests }),\n }\n );\n\n if (!response.ok) {\n const error = await response.text();\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 getModelInfo(): BaseModelInfo {\n return this.modelInfo;\n }\n}\n\nclass OllamaEmbeddingProvider implements EmbeddingProviderInterface {\n private static readonly MIN_TRUNCATION_CHARS = 512;\n\n constructor(\n private credentials: ProviderCredentials,\n private modelInfo: EmbeddingProviderModelInfo['ollama']\n ) { }\n\n 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 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 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();\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 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 getModelInfo(): BaseModelInfo {\n return this.modelInfo;\n }\n}\n\n/**\n * Custom OpenAI-compatible embedding provider.\n * Works with any server that implements the OpenAI /v1/embeddings API format\n * (llama.cpp, vLLM, text-embeddings-inference, LiteLLM, etc.).\n */\nclass CustomEmbeddingProvider implements EmbeddingProviderInterface {\n constructor(\n private credentials: ProviderCredentials,\n private modelInfo: CustomModelInfo\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 // baseUrl is already normalized (trailing slashes stripped) by parseConfig().\n const baseUrl = this.credentials.baseUrl ?? '';\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(`${baseUrl}/embeddings`, {\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 ${baseUrl}/embeddings`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n\n if (!response.ok) {\n const errorText = await response.text();\n // Throw non-retryable error for client errors (4xx) except 429 (rate limit).\n // The Indexer uses pRetry which retries all errors by default; marking 4xx as\n // non-retryable prevents long retry loops on bad API keys or invalid models.\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 // Always validate dimensions — the vector store is initialized with a fixed\n // dimension count, so mismatched vectors will corrupt the index or crash usearch.\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 // Validate the server returned exactly as many embeddings as we sent texts.\n // A mismatch would cause undefined vectors in store.addBatch, corrupting the index.\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 // Rough estimate: ~4 chars per token. Used as fallback when the server\n // doesn't return usage.total_tokens (e.g. llama.cpp, some vLLM configs).\n totalTokensUsed: data.usage?.total_tokens ?? texts.reduce((sum, t) => sum + Math.ceil(t.length / 4), 0),\n };\n }\n\n // Fallback: some servers return a flat embedding array for single inputs\n throw new Error(\"Custom embedding API returned unexpected response format. Expected OpenAI-compatible format with data[].embedding.\");\n }\n\n 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 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 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 getModelInfo(): CustomModelInfo {\n return this.modelInfo;\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 ?? \"https://api.siliconflow.cn/v1\";\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 ignore, { Ignore } from \"ignore\";\nimport { existsSync, readFileSync, promises as fsPromises } from \"fs\";\nimport * as path from \"path\";\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 // Exclude hidden files/folders (starting with .)\n const pathParts = relativePath.split(path.sep);\n for (const part of pathParts) {\n if (part.startsWith(\".\") && part !== \".\" && part !== \"..\") {\n return false;\n }\n // Exclude folders containing \"build\" in their name\n if (part.toLowerCase().includes(\"build\")) {\n return false;\n }\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 // Skip hidden files/folders (starting with .)\n if (entry.name.startsWith(\".\") && entry.name !== \".\" && entry.name !== \"..\") {\n if (entry.isDirectory()) {\n skipped.push({ path: relativePath, reason: \"excluded\" });\n }\n continue;\n }\n\n // Skip folders containing \"build\" in their name\n if (entry.isDirectory() && entry.name.toLowerCase().includes(\"build\")) {\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 // Sort by size ascending, keep only the smallest maxFilesPerDirectory files\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 // Recurse into subdirectories respecting depth limit\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 // Collect from project root\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 // Collect from additional knowledge base directories\n if (additionalRoots && additionalRoots.length > 0) {\n // Normalize and deduplicate knowledge base paths\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 { 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 costFormatted = estimate.isFree\n ? \"Free\"\n : `~$${estimate.estimatedCost.toFixed(4)}`;\n\n return `\n┌─────────────────────────────────────────────────────────────────┐\n│ 📊 Indexing Estimate │\n├─────────────────────────────────────────────────────────────────┤\n│ │\n│ Files to index: ${padRight(estimate.filesCount.toLocaleString() + \" files\", 40)}│\n│ Total size: ${padRight(sizeFormatted, 40)}│\n│ Estimated chunks: ${padRight(\"~\" + estimate.estimatedChunks.toLocaleString() + \" chunks\", 40)}│\n│ Estimated tokens: ${padRight(\"~\" + estimate.estimatedTokens.toLocaleString() + \" tokens\", 40)}│\n│ │\n│ Provider: ${padRight(estimate.provider, 52)}│\n│ Model: ${padRight(estimate.model, 52)}│\n│ Cost: ${padRight(costFormatted, 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\nfunction padRight(str: string, length: number): string {\n return str.padEnd(length);\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 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 if (!this.config.metrics) return;\n this.metrics.indexingStartTime = Date.now();\n }\n\n recordIndexingEnd(): void {\n if (!this.config.metrics) return;\n this.metrics.indexingEndTime = Date.now();\n }\n\n recordFilesScanned(count: number): void {\n if (!this.config.metrics) return;\n this.metrics.filesScanned = count;\n }\n\n recordFilesParsed(count: number): void {\n if (!this.config.metrics) return;\n this.metrics.filesParsed = count;\n }\n\n recordParseDuration(durationMs: number): void {\n if (!this.config.metrics) return;\n this.metrics.parseMs = durationMs;\n }\n\n recordChunksProcessed(count: number): void {\n if (!this.config.metrics) return;\n this.metrics.chunksProcessed += count;\n }\n\n recordChunksEmbedded(count: number): void {\n if (!this.config.metrics) return;\n this.metrics.chunksEmbedded += count;\n }\n\n recordChunksFromCache(count: number): void {\n if (!this.config.metrics) return;\n this.metrics.chunksFromCache += count;\n }\n\n recordChunksRemoved(count: number): void {\n if (!this.config.metrics) return;\n this.metrics.chunksRemoved += count;\n }\n\n recordEmbeddingApiCall(tokens: number): void {\n if (!this.config.metrics) return;\n this.metrics.embeddingApiCalls++;\n this.metrics.embeddingTokensUsed += tokens;\n }\n\n recordEmbeddingError(): void {\n if (!this.config.metrics) return;\n this.metrics.embeddingErrors++;\n }\n\n recordSearch(durationMs: number, breakdown?: { embeddingMs: number; vectorMs: number; keywordMs: number; fusionMs: number }): void {\n if (!this.config.metrics) return;\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 recordCacheHit(): void {\n if (!this.config.metrics) return;\n this.metrics.cacheHits++;\n }\n\n recordCacheMiss(): void {\n if (!this.config.metrics) return;\n this.metrics.cacheMisses++;\n }\n\n recordQueryCacheHit(): void {\n if (!this.config.metrics) return;\n this.metrics.queryCacheHits++;\n }\n\n recordQueryCacheSimilarHit(): void {\n if (!this.config.metrics) return;\n this.metrics.queryCacheSimilarHits++;\n }\n\n recordQueryCacheMiss(): void {\n if (!this.config.metrics) return;\n this.metrics.queryCacheMisses++;\n }\n\n recordGc(orphans: number, chunks: number, embeddings: number): void {\n if (!this.config.metrics) return;\n this.metrics.gcRuns++;\n this.metrics.gcOrphansRemoved += orphans;\n this.metrics.gcChunksRemoved += chunks;\n this.metrics.gcEmbeddingsRemoved += embeddings;\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 // ── Symbol methods ──────────────────────────────────────────────\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 // ── Call Edge methods ────────────────────────────────────────────\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 // ── Branch Symbol methods ────────────────────────────────────────\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 // ── GC methods for symbols/edges ─────────────────────────────────\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 type { EvalBudget, EvalComparison, EvalGateResult, EvalSummary } from \"./types.js\";\n\nexport function evaluateBudgetGate(\n budget: EvalBudget,\n summary: EvalSummary,\n comparison?: EvalComparison\n): EvalGateResult {\n const BASELINE_P95_EPSILON_MS = 0.001;\n const violations: EvalGateResult[\"violations\"] = [];\n\n const { thresholds } = budget;\n\n if (thresholds.minHitAt5 !== undefined && summary.metrics.hitAt5 < thresholds.minHitAt5) {\n violations.push({\n metric: \"minHitAt5\",\n message: `Hit@5 ${summary.metrics.hitAt5.toFixed(4)} is below minimum ${thresholds.minHitAt5.toFixed(4)}`,\n });\n }\n\n if (thresholds.minMrrAt10 !== undefined && summary.metrics.mrrAt10 < thresholds.minMrrAt10) {\n violations.push({\n metric: \"minMrrAt10\",\n message: `MRR@10 ${summary.metrics.mrrAt10.toFixed(4)} is below minimum ${thresholds.minMrrAt10.toFixed(4)}`,\n });\n }\n\n if (\n thresholds.minRawDistinctTop3Ratio !== undefined &&\n summary.metrics.rawDistinctTop3Ratio < thresholds.minRawDistinctTop3Ratio\n ) {\n violations.push({\n metric: \"minRawDistinctTop3Ratio\",\n message: `Raw Distinct Top@3 ${summary.metrics.rawDistinctTop3Ratio.toFixed(4)} is below minimum ${thresholds.minRawDistinctTop3Ratio.toFixed(4)}`,\n });\n }\n\n if (comparison) {\n if (\n thresholds.hitAt5MaxDrop !== undefined &&\n comparison.deltas.hitAt5.absolute < -thresholds.hitAt5MaxDrop\n ) {\n violations.push({\n metric: \"hitAt5MaxDrop\",\n message: `Hit@5 drop ${comparison.deltas.hitAt5.absolute.toFixed(4)} exceeds allowed -${thresholds.hitAt5MaxDrop.toFixed(4)}`,\n });\n }\n\n if (\n thresholds.mrrAt10MaxDrop !== undefined &&\n comparison.deltas.mrrAt10.absolute < -thresholds.mrrAt10MaxDrop\n ) {\n violations.push({\n metric: \"mrrAt10MaxDrop\",\n message: `MRR@10 drop ${comparison.deltas.mrrAt10.absolute.toFixed(4)} exceeds allowed -${thresholds.mrrAt10MaxDrop.toFixed(4)}`,\n });\n }\n\n if (\n thresholds.rawDistinctTop3RatioMaxDrop !== undefined &&\n comparison.deltas.rawDistinctTop3Ratio.absolute < -thresholds.rawDistinctTop3RatioMaxDrop\n ) {\n violations.push({\n metric: \"rawDistinctTop3RatioMaxDrop\",\n message: `Raw Distinct Top@3 drop ${comparison.deltas.rawDistinctTop3Ratio.absolute.toFixed(4)} exceeds allowed -${thresholds.rawDistinctTop3RatioMaxDrop.toFixed(4)}`,\n });\n }\n\n if (thresholds.p95LatencyMaxMultiplier !== undefined) {\n const baselineP95 = comparison.deltas.latencyP95Ms.baseline;\n if (baselineP95 > BASELINE_P95_EPSILON_MS) {\n const allowed = baselineP95 * thresholds.p95LatencyMaxMultiplier;\n if (summary.metrics.latencyMs.p95 > allowed) {\n violations.push({\n metric: \"p95LatencyMaxMultiplier\",\n message: `p95 latency ${summary.metrics.latencyMs.p95.toFixed(3)}ms exceeds allowed ${allowed.toFixed(3)}ms (${thresholds.p95LatencyMaxMultiplier.toFixed(2)}x baseline)`,\n });\n }\n }\n }\n }\n\n if (\n thresholds.p95LatencyMaxAbsoluteMs !== undefined &&\n summary.metrics.latencyMs.p95 > thresholds.p95LatencyMaxAbsoluteMs\n ) {\n violations.push({\n metric: \"p95LatencyMaxAbsoluteMs\",\n message: `p95 latency ${summary.metrics.latencyMs.p95.toFixed(3)}ms exceeds absolute maximum ${thresholds.p95LatencyMaxAbsoluteMs.toFixed(3)}ms`,\n });\n }\n\n return {\n passed: violations.length === 0,\n budgetName: budget.name,\n violations,\n };\n}\n","import { estimateTokens } from \"../utils/cost.js\";\n\nimport type {\n EvalMetrics,\n FailureBucket,\n GoldenQuery,\n PerQueryEvalResult,\n} from \"./types.js\";\n\nfunction percentile(values: number[], p: number): number {\n if (values.length === 0) return 0;\n if (values.length === 1) return values[0];\n const sorted = [...values].sort((a, b) => a - b);\n const x = p * (sorted.length - 1);\n const lowerIndex = Math.floor(x);\n const upperIndex = Math.ceil(x);\n if (lowerIndex === upperIndex) {\n return sorted[lowerIndex];\n }\n const fraction = x - lowerIndex;\n return sorted[lowerIndex] + fraction * (sorted[upperIndex] - sorted[lowerIndex]);\n}\n\nfunction normalizePath(input: string): string {\n return input.replace(/\\\\/g, \"/\");\n}\n\nfunction uniqueResultsByPath(results: PerQueryEvalResult[\"results\"]): PerQueryEvalResult[\"results\"] {\n const seen = new Set<string>();\n const unique: PerQueryEvalResult[\"results\"] = [];\n\n for (const result of results) {\n const normalized = normalizePath(result.filePath);\n if (seen.has(normalized)) continue;\n seen.add(normalized);\n unique.push(result);\n }\n\n return unique;\n}\n\nfunction distinctTopKRatio(results: PerQueryEvalResult[\"results\"], k: number): number {\n const top = results.slice(0, k);\n if (top.length === 0) return 0;\n const distinct = new Set(top.map((result) => normalizePath(result.filePath))).size;\n return distinct / top.length;\n}\n\nexport function pathMatchesExpected(actualPath: string, expectedPath: string): boolean {\n const actual = normalizePath(actualPath);\n const expected = normalizePath(expectedPath);\n if (actual === expected) return true;\n return actual.endsWith(`/${expected}`) || expected.endsWith(`/${actual}`);\n}\n\nexport function getRelevantPaths(query: GoldenQuery): string[] {\n const fromExact = query.expected.filePath ? [query.expected.filePath] : [];\n const fromAcceptable = query.expected.acceptableFiles ?? [];\n return Array.from(new Set([...fromExact, ...fromAcceptable]));\n}\n\nfunction isRelevantResult(filePath: string, relevantPaths: string[]): boolean {\n return relevantPaths.some((expected) => pathMatchesExpected(filePath, expected));\n}\n\nfunction reciprocalRankAtK(results: PerQueryEvalResult[\"results\"], relevantPaths: string[], k: number): number {\n const top = uniqueResultsByPath(results).slice(0, k);\n for (let i = 0; i < top.length; i += 1) {\n if (isRelevantResult(top[i].filePath, relevantPaths)) {\n return 1 / (i + 1);\n }\n }\n return 0;\n}\n\nfunction ndcgAtK(results: PerQueryEvalResult[\"results\"], relevantPaths: string[], k: number): number {\n const top = uniqueResultsByPath(results).slice(0, k);\n const dcg = top.reduce((sum, result, i) => {\n const rel = isRelevantResult(result.filePath, relevantPaths) ? 1 : 0;\n return sum + rel / Math.log2(i + 2);\n }, 0);\n\n const idealLen = Math.min(k, relevantPaths.length);\n const idcg = Array.from({ length: idealLen }, (_, i) => 1 / Math.log2(i + 2)).reduce(\n (sum, value) => sum + value,\n 0\n );\n\n return idcg === 0 ? 0 : dcg / idcg;\n}\n\nfunction isDocsOrTestsPath(filePath: string): boolean {\n const lowered = normalizePath(filePath).toLowerCase();\n return (\n lowered.includes(\"/docs/\") ||\n lowered.includes(\"/test/\") ||\n lowered.includes(\"/tests/\") ||\n lowered.includes(\"readme\") ||\n lowered.includes(\"/benchmarks/\")\n );\n}\n\nexport function classifyFailureBucket(\n query: GoldenQuery,\n results: PerQueryEvalResult[\"results\"],\n k: number\n): FailureBucket | undefined {\n const relevantPaths = getRelevantPaths(query);\n const top = uniqueResultsByPath(results).slice(0, k);\n const hasRelevantTopK = top.some((result) => isRelevantResult(result.filePath, relevantPaths));\n\n if (!hasRelevantTopK) {\n return \"no-relevant-hit-top-k\";\n }\n\n if (query.expected.symbol) {\n const hasSymbol = top.some(\n (result) =>\n isRelevantResult(result.filePath, relevantPaths) && result.name === query.expected.symbol\n );\n if (!hasSymbol) return \"wrong-symbol\";\n }\n\n const top1 = top[0];\n if (top1 && !isRelevantResult(top1.filePath, relevantPaths) && isDocsOrTestsPath(top1.filePath)) {\n return \"docs-tests-outranking-source\";\n }\n\n if (top1 && !isRelevantResult(top1.filePath, relevantPaths)) {\n return \"wrong-file\";\n }\n\n return undefined;\n}\n\nexport function buildPerQueryResult(\n query: GoldenQuery,\n results: PerQueryEvalResult[\"results\"],\n latencyMs: number,\n k: number\n): PerQueryEvalResult {\n const relevantPaths = getRelevantPaths(query);\n const deduped = uniqueResultsByPath(results);\n const hitAt = (cutoff: number): boolean =>\n deduped.slice(0, cutoff).some((result) => isRelevantResult(result.filePath, relevantPaths));\n\n const perQuery: PerQueryEvalResult = {\n id: query.id,\n query: query.query,\n queryType: query.queryType,\n latencyMs,\n hitAt1: hitAt(1),\n hitAt3: hitAt(3),\n hitAt5: hitAt(5),\n hitAt10: hitAt(10),\n reciprocalRankAt10: reciprocalRankAtK(deduped, relevantPaths, 10),\n ndcgAt10: ndcgAtK(deduped, relevantPaths, 10),\n failureBucket: classifyFailureBucket(query, results, k),\n rawTop3DistinctRatio: distinctTopKRatio(results, 3),\n results: deduped,\n };\n\n return perQuery;\n}\n\nexport function computeEvalMetrics(\n queries: GoldenQuery[],\n perQuery: PerQueryEvalResult[],\n embeddingCallCount: number,\n embeddingTokensUsed: number,\n costPer1MTokensUsd: number\n): EvalMetrics {\n const count = perQuery.length;\n const safeDiv = (value: number): number => (count === 0 ? 0 : value / count);\n\n const sum = {\n hitAt1: 0,\n hitAt3: 0,\n hitAt5: 0,\n hitAt10: 0,\n mrrAt10: 0,\n ndcgAt10: 0,\n distinctTop3Ratio: 0,\n rawDistinctTop3Ratio: 0,\n };\n\n const failureBuckets: Record<FailureBucket, number> = {\n \"wrong-file\": 0,\n \"wrong-symbol\": 0,\n \"docs-tests-outranking-source\": 0,\n \"no-relevant-hit-top-k\": 0,\n };\n\n const latencies = perQuery.map((item) => item.latencyMs);\n\n for (const query of perQuery) {\n if (query.hitAt1) sum.hitAt1 += 1;\n if (query.hitAt3) sum.hitAt3 += 1;\n if (query.hitAt5) sum.hitAt5 += 1;\n if (query.hitAt10) sum.hitAt10 += 1;\n sum.mrrAt10 += query.reciprocalRankAt10;\n sum.ndcgAt10 += query.ndcgAt10;\n sum.distinctTop3Ratio += distinctTopKRatio(query.results, 3);\n sum.rawDistinctTop3Ratio += query.rawTop3DistinctRatio;\n if (query.failureBucket) {\n failureBuckets[query.failureBucket] += 1;\n }\n }\n\n const queryTokens = queries.reduce((acc, q) => acc + estimateTokens(q.query), 0);\n\n return {\n hitAt1: safeDiv(sum.hitAt1),\n hitAt3: safeDiv(sum.hitAt3),\n hitAt5: safeDiv(sum.hitAt5),\n hitAt10: safeDiv(sum.hitAt10),\n mrrAt10: safeDiv(sum.mrrAt10),\n ndcgAt10: safeDiv(sum.ndcgAt10),\n distinctTop3Ratio: safeDiv(sum.distinctTop3Ratio),\n rawDistinctTop3Ratio: safeDiv(sum.rawDistinctTop3Ratio),\n latencyMs: {\n p50: percentile(latencies, 0.5),\n p95: percentile(latencies, 0.95),\n p99: percentile(latencies, 0.99),\n },\n tokenEstimate: {\n queryTokens,\n embeddingTokensUsed,\n },\n embedding: {\n callCount: embeddingCallCount,\n estimatedCostUsd: (embeddingTokensUsed / 1_000_000) * costPer1MTokensUsd,\n costPer1MTokensUsd,\n },\n failureBuckets,\n };\n}\n","import { readFileSync } from \"fs\";\n\nimport type {\n EvalBudget,\n GoldenDataset,\n GoldenExpected,\n GoldenQuery,\n GoldenQueryType,\n} from \"./types.js\";\n\nfunction parseJsonFile(filePath: string): unknown {\n const content = readFileSync(filePath, \"utf-8\");\n return JSON.parse(content);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\nfunction asPositiveNumber(value: unknown, path: string): number {\n if (typeof value !== \"number\" || Number.isNaN(value) || value < 0) {\n throw new Error(`${path} must be a non-negative number`);\n }\n return value;\n}\n\nfunction parseQueryType(value: unknown, path: string): GoldenQueryType {\n if (\n value === \"definition\" ||\n value === \"implementation-intent\" ||\n value === \"similarity\" ||\n value === \"keyword-heavy\"\n ) {\n return value;\n }\n throw new Error(\n `${path} must be one of: definition, implementation-intent, similarity, keyword-heavy`\n );\n}\n\nfunction parseExpected(input: unknown, path: string): GoldenExpected {\n if (!isRecord(input)) {\n throw new Error(`${path} must be an object`);\n }\n\n const filePathRaw = input.filePath;\n const acceptableFilesRaw = input.acceptableFiles;\n const symbolRaw = input.symbol;\n const branchRaw = input.branch;\n\n const filePath = typeof filePathRaw === \"string\" ? filePathRaw : undefined;\n const acceptableFiles = isStringArray(acceptableFilesRaw) ? acceptableFilesRaw : undefined;\n\n if (!filePath && (!acceptableFiles || acceptableFiles.length === 0)) {\n throw new Error(`${path} must include either expected.filePath or expected.acceptableFiles`);\n }\n\n if (acceptableFilesRaw !== undefined && !isStringArray(acceptableFilesRaw)) {\n throw new Error(`${path}.acceptableFiles must be an array of strings`);\n }\n\n if (symbolRaw !== undefined && typeof symbolRaw !== \"string\") {\n throw new Error(`${path}.symbol must be a string when provided`);\n }\n\n if (branchRaw !== undefined && typeof branchRaw !== \"string\") {\n throw new Error(`${path}.branch must be a string when provided`);\n }\n\n return {\n filePath,\n acceptableFiles,\n symbol: typeof symbolRaw === \"string\" ? symbolRaw : undefined,\n branch: typeof branchRaw === \"string\" ? branchRaw : undefined,\n };\n}\n\nfunction parseQuery(input: unknown, index: number): GoldenQuery {\n const path = `queries[${index}]`;\n if (!isRecord(input)) {\n throw new Error(`${path} must be an object`);\n }\n\n const id = input.id;\n const query = input.query;\n const queryType = input.queryType;\n const expected = input.expected;\n\n if (typeof id !== \"string\" || id.trim().length === 0) {\n throw new Error(`${path}.id must be a non-empty string`);\n }\n\n if (typeof query !== \"string\" || query.trim().length === 0) {\n throw new Error(`${path}.query must be a non-empty string`);\n }\n\n return {\n id,\n query,\n queryType: parseQueryType(queryType, `${path}.queryType`),\n expected: parseExpected(expected, `${path}.expected`),\n };\n}\n\nexport function parseGoldenDataset(raw: unknown, sourceLabel: string): GoldenDataset {\n if (!isRecord(raw)) {\n throw new Error(`${sourceLabel} must be a JSON object`);\n }\n\n const version = raw.version;\n const name = raw.name;\n const description = raw.description;\n const queriesRaw = raw.queries;\n\n if (typeof version !== \"string\" || version.trim().length === 0) {\n throw new Error(`${sourceLabel}.version must be a non-empty string`);\n }\n\n if (typeof name !== \"string\" || name.trim().length === 0) {\n throw new Error(`${sourceLabel}.name must be a non-empty string`);\n }\n\n if (description !== undefined && typeof description !== \"string\") {\n throw new Error(`${sourceLabel}.description must be a string when provided`);\n }\n\n if (!Array.isArray(queriesRaw)) {\n throw new Error(`${sourceLabel}.queries must be an array`);\n }\n\n if (queriesRaw.length === 0) {\n throw new Error(`${sourceLabel}.queries must contain at least one query`);\n }\n\n const queries = queriesRaw.map((query, idx) => parseQuery(query, idx));\n const idSet = new Set<string>();\n\n for (const query of queries) {\n if (idSet.has(query.id)) {\n throw new Error(`${sourceLabel}.queries has duplicate id: ${query.id}`);\n }\n idSet.add(query.id);\n }\n\n return {\n version,\n name,\n description: typeof description === \"string\" ? description : undefined,\n queries,\n };\n}\n\nexport function loadGoldenDataset(datasetPath: string): GoldenDataset {\n const parsed = parseJsonFile(datasetPath);\n return parseGoldenDataset(parsed, datasetPath);\n}\n\nexport function parseBudget(raw: unknown, sourceLabel: string): EvalBudget {\n if (!isRecord(raw)) {\n throw new Error(`${sourceLabel} must be a JSON object`);\n }\n\n const name = raw.name;\n const baselinePath = raw.baselinePath;\n const failOnMissingBaseline = raw.failOnMissingBaseline;\n const thresholds = raw.thresholds;\n\n if (typeof name !== \"string\" || name.trim().length === 0) {\n throw new Error(`${sourceLabel}.name must be a non-empty string`);\n }\n\n if (baselinePath !== undefined && typeof baselinePath !== \"string\") {\n throw new Error(`${sourceLabel}.baselinePath must be a string when provided`);\n }\n\n if (!isRecord(thresholds)) {\n throw new Error(`${sourceLabel}.thresholds must be an object`);\n }\n\n return {\n name,\n baselinePath: typeof baselinePath === \"string\" ? baselinePath : undefined,\n failOnMissingBaseline:\n typeof failOnMissingBaseline === \"boolean\" ? failOnMissingBaseline : true,\n thresholds: {\n hitAt5MaxDrop:\n thresholds.hitAt5MaxDrop === undefined\n ? undefined\n : asPositiveNumber(thresholds.hitAt5MaxDrop, `${sourceLabel}.thresholds.hitAt5MaxDrop`),\n mrrAt10MaxDrop:\n thresholds.mrrAt10MaxDrop === undefined\n ? undefined\n : asPositiveNumber(thresholds.mrrAt10MaxDrop, `${sourceLabel}.thresholds.mrrAt10MaxDrop`),\n rawDistinctTop3RatioMaxDrop:\n thresholds.rawDistinctTop3RatioMaxDrop === undefined\n ? undefined\n : asPositiveNumber(\n thresholds.rawDistinctTop3RatioMaxDrop,\n `${sourceLabel}.thresholds.rawDistinctTop3RatioMaxDrop`\n ),\n p95LatencyMaxMultiplier:\n thresholds.p95LatencyMaxMultiplier === undefined\n ? undefined\n : asPositiveNumber(\n thresholds.p95LatencyMaxMultiplier,\n `${sourceLabel}.thresholds.p95LatencyMaxMultiplier`\n ),\n p95LatencyMaxAbsoluteMs:\n thresholds.p95LatencyMaxAbsoluteMs === undefined\n ? undefined\n : asPositiveNumber(\n thresholds.p95LatencyMaxAbsoluteMs,\n `${sourceLabel}.thresholds.p95LatencyMaxAbsoluteMs`\n ),\n minHitAt5:\n thresholds.minHitAt5 === undefined\n ? undefined\n : asPositiveNumber(thresholds.minHitAt5, `${sourceLabel}.thresholds.minHitAt5`),\n minMrrAt10:\n thresholds.minMrrAt10 === undefined\n ? undefined\n : asPositiveNumber(thresholds.minMrrAt10, `${sourceLabel}.thresholds.minMrrAt10`),\n minRawDistinctTop3Ratio:\n thresholds.minRawDistinctTop3Ratio === undefined\n ? undefined\n : asPositiveNumber(\n thresholds.minRawDistinctTop3Ratio,\n `${sourceLabel}.thresholds.minRawDistinctTop3Ratio`\n ),\n },\n };\n}\n\nexport function loadBudget(budgetPath: string): EvalBudget {\n const parsed = parseJsonFile(budgetPath);\n return parseBudget(parsed, budgetPath);\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport * as path from \"path\";\nimport { existsSync } from \"fs\";\n\nimport { Indexer } from \"./indexer/index.js\";\nimport type { ParsedCodebaseIndexConfig, LogLevel } from \"./config/schema.js\";\nimport { loadProjectConfigLayer, materializeLocalProjectConfig } from \"./config/merger.js\";\nimport { formatDefinitionLookup, formatHealthCheck, formatIndexStats, formatStatus } from \"./tools/utils.js\";\nimport { formatCostEstimate } from \"./utils/cost.js\";\nimport type { LogEntry } from \"./utils/logger.js\";\nimport { resolveWorktreeMainRepoRoot } from \"./git/index.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\nconst CHUNK_TYPE_ENUM = [\n \"function\", \"class\", \"method\", \"interface\", \"type\",\n \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\",\n] as const;\n\nexport function createMcpServer(projectRoot: string, config: ParsedCodebaseIndexConfig): McpServer {\n const server = new McpServer({\n name: \"opencode-codebase-index\",\n version: \"0.5.1\",\n });\n\n const runtimeConfig = config;\n let indexer = new Indexer(projectRoot, runtimeConfig);\n let initialized = false;\n\n function refreshIndexerFromConfig(): void {\n indexer = new Indexer(projectRoot, runtimeConfig);\n initialized = false;\n }\n\n function shouldForceLocalizeProjectIndex(): boolean {\n if (runtimeConfig.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\n async function ensureInitialized(): Promise<void> {\n if (!initialized) {\n await indexer.initialize();\n initialized = true;\n }\n }\n\n // --- Tools ---\n\n server.tool(\n \"codebase_search\",\n \"Search codebase by MEANING, not keywords. Returns full code content. For just finding WHERE code is (saves ~90% tokens), use codebase_peek instead.\",\n {\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(CHUNK_TYPE_ENUM).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 (args) => {\n await ensureInitialized();\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 { content: [{ type: \"text\", text: \"No matching code found. Try a different query or run index_codebase first.\" }] };\n }\n\n const formatted = results.map((r, idx) => {\n const header = r.name\n ? `[${idx + 1}] ${r.chunkType} \"${r.name}\" in ${r.filePath}:${r.startLine}-${r.endLine}`\n : `[${idx + 1}] ${r.chunkType} in ${r.filePath}:${r.startLine}-${r.endLine}`;\n return `${header} (score: ${r.score.toFixed(2)})\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return { content: [{ type: \"text\", text: `Found ${results.length} results for \"${args.query}\":\\n\\n${formatted.join(\"\\n\\n\")}` }] };\n },\n );\n\n server.tool(\n \"codebase_peek\",\n \"Quick lookup of code locations by meaning. Returns only metadata (file, line, name, type) WITHOUT code content. Saves ~90% tokens vs codebase_search.\",\n {\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(CHUNK_TYPE_ENUM).optional().describe(\"Filter by code chunk type\"),\n },\n async (args) => {\n await ensureInitialized();\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 if (results.length === 0) {\n return { content: [{ type: \"text\", text: \"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 { content: [{ type: \"text\", text: `Found ${results.length} locations for \"${args.query}\":\\n\\n${formatted.join(\"\\n\")}\\n\\nUse Read tool to examine specific files.` }] };\n },\n );\n\n server.tool(\n \"index_codebase\",\n \"Index the codebase for semantic search. Creates vector embeddings of code chunks. Incremental - only re-indexes changed files. Run before first codebase_search.\",\n {\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 (args) => {\n if (args.estimateOnly) {\n await ensureInitialized();\n const estimate = await indexer.estimateCost();\n return { content: [{ type: \"text\", text: formatCostEstimate(estimate) }] };\n }\n\n if (args.force) {\n if (shouldForceLocalizeProjectIndex()) {\n materializeLocalProjectConfig(projectRoot, loadProjectConfigLayer(projectRoot));\n refreshIndexerFromConfig();\n }\n await ensureInitialized();\n await indexer.clearIndex();\n refreshIndexerFromConfig();\n await ensureInitialized();\n } else {\n await ensureInitialized();\n }\n\n const stats = await indexer.index();\n return { content: [{ type: \"text\", text: formatIndexStats(stats, args.verbose ?? false) }] };\n },\n );\n\n server.tool(\n \"index_status\",\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 {},\n async () => {\n await ensureInitialized();\n const status = await indexer.getStatus();\n return { content: [{ type: \"text\", text: formatStatus(status) }] };\n },\n );\n\n server.tool(\n \"index_health_check\",\n \"Check index health and remove stale entries from deleted files. Run this to clean up the index after files have been deleted.\",\n {},\n async () => {\n await ensureInitialized();\n const result = await indexer.healthCheck();\n return { content: [{ type: \"text\", text: formatHealthCheck(result) }] };\n },\n );\n\n server.tool(\n \"index_metrics\",\n \"Get metrics and performance statistics for the codebase index. Requires debug.enabled=true and debug.metrics=true in config.\",\n {},\n async () => {\n await ensureInitialized();\n const logger = indexer.getLogger();\n\n if (!logger.isEnabled()) {\n return { content: [{ type: \"text\", text: \"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 { content: [{ type: \"text\", text: \"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 { content: [{ type: \"text\", text: logger.formatMetrics() }] };\n },\n );\n\n server.tool(\n \"index_logs\",\n \"Get recent debug logs from the codebase indexer. Requires debug.enabled=true in config.\",\n {\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 (args) => {\n await ensureInitialized();\n const logger = indexer.getLogger();\n\n if (!logger.isEnabled()) {\n return { content: [{ type: \"text\", text: \"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 if (logs.length === 0) {\n return { content: [{ type: \"text\", text: \"No logs recorded yet. Logs are captured during indexing and search operations.\" }] };\n }\n\n const text = 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 return { content: [{ type: \"text\", text }] };\n },\n );\n\n server.tool(\n \"find_similar\",\n \"Find code similar to a given snippet. Use for duplicate detection, pattern discovery, or refactoring prep.\",\n {\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(CHUNK_TYPE_ENUM).optional().describe(\"Filter by code chunk type\"),\n excludeFile: z.string().optional().describe(\"Exclude results from this file path\"),\n },\n async (args) => {\n await ensureInitialized();\n const results = await indexer.findSimilar(args.code, args.limit ?? 10, {\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 { content: [{ type: \"text\", text: \"No similar code found. Try a different snippet or run index_codebase first.\" }] };\n }\n\n const formatted = results.map((r, idx) => {\n const header = r.name\n ? `[${idx + 1}] ${r.chunkType} \"${r.name}\" in ${r.filePath}:${r.startLine}-${r.endLine}`\n : `[${idx + 1}] ${r.chunkType} in ${r.filePath}:${r.startLine}-${r.endLine}`;\n return `${header} (similarity: ${(r.score * 100).toFixed(1)}%)\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return { content: [{ type: \"text\", text: `Found ${results.length} similar code blocks:\\n\\n${formatted.join(\"\\n\\n\")}` }] };\n },\n );\n\n server.tool(\n \"implementation_lookup\",\n \"Jump to symbol definition. Find WHERE something is defined. Returns the authoritative source location(s). Prefers real implementation files over tests, docs, examples, and fixtures.\",\n {\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 (args) => {\n await ensureInitialized();\n const results = await indexer.search(args.query, args.limit ?? 5, {\n fileType: args.fileType,\n directory: args.directory,\n definitionIntent: true,\n });\n\n return { content: [{ type: \"text\", text: formatDefinitionLookup(results, args.query) }] };\n },\n );\n\n server.tool(\n \"call_graph\",\n \"Query the call graph to find callers or callees of a function/method. Use to understand code flow and dependencies.\",\n {\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)\"),\n },\n async (args) => {\n await ensureInitialized();\n if (args.direction === \"callees\") {\n if (!args.symbolId) {\n return { content: [{ type: \"text\", text: \"Error: 'symbolId' is required when direction is 'callees'.\" }] };\n }\n const callees = await indexer.getCallees(args.symbolId);\n if (callees.length === 0) {\n return { content: [{ type: \"text\", text: `No callees found for symbol ${args.symbolId}.` }] };\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 { content: [{ type: \"text\", text: `Callees (${callees.length}):\\n\\n${formatted.join(\"\\n\")}` }] };\n }\n const callers = await indexer.getCallers(args.name);\n if (callers.length === 0) {\n return { content: [{ type: \"text\", text: `No callers found for \"${args.name}\".` }] };\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 { content: [{ type: \"text\", text: `\"${args.name}\" is called by ${callers.length} function(s):\\n\\n${formatted.join(\"\\n\")}` }] };\n },\n );\n\n // --- Prompts ---\n\n server.prompt(\n \"search\",\n \"Search codebase by meaning using semantic search\",\n { query: z.string().describe(\"What to search for in the codebase\") },\n (args) => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: `Search the codebase for: \"${args.query}\"\\n\\nUse the codebase_search tool with this query. If you need just locations first, use codebase_peek instead to save tokens.`,\n },\n }],\n }),\n );\n\n server.prompt(\n \"find\",\n \"Find code using hybrid approach (semantic + grep)\",\n { query: z.string().describe(\"What to find in the codebase\") },\n (args) => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: `Find code related to: \"${args.query}\"\\n\\nUse a hybrid approach:\\n1. First use codebase_peek to find semantic matches by meaning\\n2. Then use grep for exact identifier matches\\n3. Combine results for comprehensive coverage`,\n },\n }],\n }),\n );\n\n server.prompt(\n \"index\",\n \"Index the codebase for semantic search\",\n { options: z.string().optional().describe(\"Options: 'force' to rebuild, 'estimate' to check costs\") },\n (args) => {\n const opts = args.options?.toLowerCase() ?? \"\";\n let instruction = \"Use the index_codebase tool to index the codebase for semantic search.\";\n if (opts.includes(\"force\")) {\n instruction = \"Use the index_codebase tool with force=true to rebuild the entire index from scratch.\";\n } else if (opts.includes(\"estimate\")) {\n instruction = \"Use the index_codebase tool with estimateOnly=true to check the cost estimate before indexing.\";\n }\n return {\n messages: [{\n role: \"user\",\n content: { type: \"text\", text: instruction },\n }],\n };\n },\n );\n\n server.prompt(\n \"status\",\n \"Check if the codebase is indexed and ready\",\n {},\n () => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: \"Use the index_status tool to check if the codebase index is ready and show its current state.\",\n },\n }],\n }),\n );\n\n server.prompt(\n \"definition\",\n \"Find where a symbol is defined in the codebase\",\n { query: z.string().describe(\"Symbol name or description to find the definition of\") },\n (args) => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: `Find the definition of: \"${args.query}\"\\n\\nUse the implementation_lookup tool to find where this symbol is defined. This prioritizes real implementation files over tests, docs, and examples. If no definition is found, fall back to codebase_search for broader discovery.`,\n },\n }],\n }),\n );\n\n return server;\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\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 = r.name\n ? `[${idx + 1}] ${r.chunkType} \"${r.name}\" in ${r.filePath}:${r.startLine}-${r.endLine}`\n : `[${idx + 1}] ${r.chunkType} in ${r.filePath}:${r.startLine}-${r.endLine}`;\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 = r.name\n ? `[${idx + 1}] ${r.chunkType} \"${r.name}\" in ${r.filePath}:${r.startLine}-${r.endLine}`\n : `[${idx + 1}] ${r.chunkType} in ${r.filePath}:${r.startLine}-${r.endLine}`;\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)}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kdirSync","readFileSync","writeFileSync","os","path","performance","existsSync","mkdirSync","readFileSync","writeFileSync","os","path","existsSync","path","readFileSync","path","readFileSync","existsSync","existsSync","existsSync","readFileSync","mkdirSync","writeFileSync","existsSync","readFileSync","writeFileSync","mkdirSync","fsPromises","path","performance","resolve","EventEmitter","resolve","reject","resolve","existsSync","readFileSync","path","os","existsSync","readFileSync","path","ignore","existsSync","readFileSync","path","os","platform","arch","require","estimateTokens","estimateTokens","estimateTokens","existsSync","readFileSync","mkdirSync","writeFileSync","fsPromises","performance","resolve","failedBatch","readFileSync","isStringArray","path","existsSync","readFileSync","mkdirSync","writeFileSync","performance","path","existsSync","main","lines","MAX_CONTENT_LINES","truncateContent","existsSync","formatted"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/eventemitter3/index.js","../node_modules/ignore/index.js","../src/cli.ts","../src/config/constants.ts","../src/config/defaults.ts","../src/config/env-substitution.ts","../src/config/validators.ts","../src/config/schema.ts","../src/eval/compare.ts","../src/eval/reports.ts","../src/eval/report-formatters.ts","../src/eval/runner.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/files.ts","../src/utils/paths.ts","../src/utils/cost.ts","../src/utils/logger.ts","../src/native/index.ts","../src/git/index.ts","../src/git/refs.ts","../src/config/paths.ts","../src/eval/budget.ts","../src/eval/metrics.ts","../src/eval/runner-config.ts","../src/config/rebase.ts","../src/eval/schema.ts","../src/eval/cli.ts","../src/eval/cli-parser.ts","../src/mcp-server.ts","../src/mcp-server/register-prompts.ts","../src/mcp-server/register-tools.ts","../src/config/merger.ts","../src/tools/utils.ts","../src/mcp-server/shared.ts"],"sourcesContent":["'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","// 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","#!/usr/bin/env node\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport * as path from \"path\";\n\nimport { parseConfig } from \"./config/schema.js\";\nimport { handleEvalCommand } from \"./eval/cli.js\";\nimport { createMcpServer } from \"./mcp-server.js\";\nimport { loadMergedConfig } from \"./config/merger.js\";\n\nfunction parseArgs(argv: string[]): { project: string; config?: string } {\n let project = process.cwd();\n let config: string | undefined;\n\n for (let i = 2; i < argv.length; i++) {\n if (argv[i] === \"--project\" && argv[i + 1]) {\n project = path.resolve(argv[++i]);\n } else if (argv[i] === \"--config\" && argv[i + 1]) {\n config = path.resolve(argv[++i]);\n }\n }\n\n return { project, config };\n}\n\nasync function main(): Promise<void> {\n if (process.argv[2] === \"eval\") {\n const exitCode = await handleEvalCommand(process.argv.slice(3), process.cwd());\n process.exit(exitCode);\n }\n\n const args = parseArgs(process.argv);\n const rawConfig = loadMergedConfig(args.project);\n const config = parseConfig(rawConfig);\n\n const server = createMcpServer(args.project, config);\n const transport = new StdioServerTransport();\n\n await server.connect(transport);\n\n const shutdown = (): void => {\n server.close().catch(() => {});\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n}\n\nmain().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Fatal: ${message}`);\n process.exit(1);\n});\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 type { EvalComparison, EvalSummary, MetricDelta } from \"./types.js\";\n\nfunction metricDelta(current: number, baseline: number): MetricDelta {\n const absolute = current - baseline;\n const relativePct = baseline === 0 ? (current === 0 ? 0 : 100) : (absolute / baseline) * 100;\n return {\n current,\n baseline,\n absolute,\n relativePct,\n };\n}\n\nexport function compareSummaries(current: EvalSummary, baseline: EvalSummary, againstPath: string): EvalComparison {\n return {\n againstPath,\n deltas: {\n hitAt1: metricDelta(current.metrics.hitAt1, baseline.metrics.hitAt1),\n hitAt3: metricDelta(current.metrics.hitAt3, baseline.metrics.hitAt3),\n hitAt5: metricDelta(current.metrics.hitAt5, baseline.metrics.hitAt5),\n hitAt10: metricDelta(current.metrics.hitAt10, baseline.metrics.hitAt10),\n mrrAt10: metricDelta(current.metrics.mrrAt10, baseline.metrics.mrrAt10),\n ndcgAt10: metricDelta(current.metrics.ndcgAt10, baseline.metrics.ndcgAt10),\n distinctTop3Ratio: metricDelta(current.metrics.distinctTop3Ratio, baseline.metrics.distinctTop3Ratio),\n rawDistinctTop3Ratio: metricDelta(current.metrics.rawDistinctTop3Ratio, baseline.metrics.rawDistinctTop3Ratio),\n latencyP50Ms: metricDelta(current.metrics.latencyMs.p50, baseline.metrics.latencyMs.p50),\n latencyP95Ms: metricDelta(current.metrics.latencyMs.p95, baseline.metrics.latencyMs.p95),\n latencyP99Ms: metricDelta(current.metrics.latencyMs.p99, baseline.metrics.latencyMs.p99),\n embeddingCallCount: metricDelta(\n current.metrics.embedding.callCount,\n baseline.metrics.embedding.callCount\n ),\n estimatedCostUsd: metricDelta(\n current.metrics.embedding.estimatedCostUsd,\n baseline.metrics.embedding.estimatedCostUsd\n ),\n },\n };\n}\n","import { mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport * as path from \"path\";\n\nimport {\n formatMs,\n formatPct,\n formatUsd,\n signed,\n type LoadSummaryOptions,\n validateSummary,\n} from \"./report-formatters.js\";\nimport type {\n EvalComparison,\n EvalGateResult,\n EvalSummary,\n PerQueryEvalResult,\n SweepAggregateReport,\n} from \"./types.js\";\n\nexport function loadSummary(summaryPath: string, options?: LoadSummaryOptions): EvalSummary {\n try {\n const raw = readFileSync(summaryPath, \"utf-8\");\n const parsed = JSON.parse(raw) as EvalSummary;\n return validateSummary(parsed, summaryPath, options);\n } catch (error: unknown) {\n if (error instanceof SyntaxError) {\n const message = error.message;\n throw new Error(`Failed to parse eval summary JSON at ${summaryPath}: ${message}`);\n }\n\n if (error instanceof Error) {\n throw error;\n }\n\n throw new Error(`Failed to load eval summary at ${summaryPath}: ${String(error)}`);\n }\n}\n\nexport function createRunDirectory(outputRoot: string, timestampOverride?: string): string {\n const timestamp = (timestampOverride ?? new Date().toISOString()).replace(/[:.]/g, \"-\");\n const dir = path.join(outputRoot, timestamp);\n mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nexport function writeJson(filePath: string, value: unknown): void {\n writeFileSync(filePath, JSON.stringify(value, null, 2), \"utf-8\");\n}\n\nexport function writeText(filePath: string, value: string): void {\n writeFileSync(filePath, value, \"utf-8\");\n}\n\nexport function createSummaryMarkdown(\n summary: EvalSummary,\n comparison?: EvalComparison,\n gate?: EvalGateResult,\n sweep?: SweepAggregateReport\n): string {\n const lines: string[] = [];\n\n lines.push(\"# Evaluation Summary\");\n lines.push(\"\");\n lines.push(`- Generated: ${summary.generatedAt}`);\n lines.push(`- Dataset: ${summary.datasetName} (v${summary.datasetVersion})`);\n lines.push(`- Query count: ${summary.queryCount}`);\n lines.push(\n `- Search config: fusion=${summary.searchConfig.fusionStrategy}, hybridWeight=${summary.searchConfig.hybridWeight}, rrfK=${summary.searchConfig.rrfK}, rerankTopN=${summary.searchConfig.rerankTopN}`\n );\n lines.push(\"\");\n\n lines.push(\"## Metrics\");\n lines.push(\"\");\n lines.push(\"| Metric | Value |\");\n lines.push(\"|---|---:|\");\n lines.push(`| Hit@1 | ${formatPct(summary.metrics.hitAt1)} |`);\n lines.push(`| Hit@3 | ${formatPct(summary.metrics.hitAt3)} |`);\n lines.push(`| Hit@5 | ${formatPct(summary.metrics.hitAt5)} |`);\n lines.push(`| Hit@10 | ${formatPct(summary.metrics.hitAt10)} |`);\n lines.push(`| MRR@10 | ${summary.metrics.mrrAt10.toFixed(4)} |`);\n lines.push(`| nDCG@10 | ${summary.metrics.ndcgAt10.toFixed(4)} |`);\n lines.push(`| Distinct Top@3 | ${formatPct(summary.metrics.distinctTop3Ratio)} |`);\n lines.push(`| Raw Distinct Top@3 | ${formatPct(summary.metrics.rawDistinctTop3Ratio)} |`);\n lines.push(`| Latency p50 | ${formatMs(summary.metrics.latencyMs.p50)} |`);\n lines.push(`| Latency p95 | ${formatMs(summary.metrics.latencyMs.p95)} |`);\n lines.push(`| Latency p99 | ${formatMs(summary.metrics.latencyMs.p99)} |`);\n lines.push(`| Embedding calls | ${summary.metrics.embedding.callCount} |`);\n lines.push(`| Embedding tokens | ${summary.metrics.tokenEstimate.embeddingTokensUsed} |`);\n lines.push(`| Estimated embedding cost | ${formatUsd(summary.metrics.embedding.estimatedCostUsd)} |`);\n lines.push(\"\");\n\n lines.push(\"## Failure Buckets\");\n lines.push(\"\");\n lines.push(\"| Bucket | Count |\");\n lines.push(\"|---|---:|\");\n lines.push(\n `| wrong-file | ${summary.metrics.failureBuckets[\"wrong-file\"]} |`\n );\n lines.push(\n `| wrong-symbol | ${summary.metrics.failureBuckets[\"wrong-symbol\"]} |`\n );\n lines.push(\n `| docs/tests outranking source | ${summary.metrics.failureBuckets[\"docs-tests-outranking-source\"]} |`\n );\n lines.push(\n `| no relevant hit in top-k | ${summary.metrics.failureBuckets[\"no-relevant-hit-top-k\"]} |`\n );\n lines.push(\"\");\n\n if (comparison) {\n lines.push(\"## Comparison vs Baseline\");\n lines.push(\"\");\n lines.push(`- Against: ${comparison.againstPath}`);\n lines.push(\"\");\n lines.push(\"| Metric | Baseline | Current | Delta |\");\n lines.push(\"|---|---:|---:|---:|\");\n lines.push(\n `| Hit@5 | ${formatPct(comparison.deltas.hitAt5.baseline)} | ${formatPct(comparison.deltas.hitAt5.current)} | ${signed(comparison.deltas.hitAt5.absolute)} |`\n );\n lines.push(\n `| MRR@10 | ${comparison.deltas.mrrAt10.baseline.toFixed(4)} | ${comparison.deltas.mrrAt10.current.toFixed(4)} | ${signed(comparison.deltas.mrrAt10.absolute)} |`\n );\n lines.push(\n `| nDCG@10 | ${comparison.deltas.ndcgAt10.baseline.toFixed(4)} | ${comparison.deltas.ndcgAt10.current.toFixed(4)} | ${signed(comparison.deltas.ndcgAt10.absolute)} |`\n );\n lines.push(\n `| Distinct Top@3 | ${formatPct(comparison.deltas.distinctTop3Ratio.baseline)} | ${formatPct(comparison.deltas.distinctTop3Ratio.current)} | ${signed(comparison.deltas.distinctTop3Ratio.absolute)} |`\n );\n lines.push(\n `| Raw Distinct Top@3 | ${formatPct(comparison.deltas.rawDistinctTop3Ratio.baseline)} | ${formatPct(comparison.deltas.rawDistinctTop3Ratio.current)} | ${signed(comparison.deltas.rawDistinctTop3Ratio.absolute)} |`\n );\n lines.push(\n `| p95 latency (ms) | ${comparison.deltas.latencyP95Ms.baseline.toFixed(3)} | ${comparison.deltas.latencyP95Ms.current.toFixed(3)} | ${signed(comparison.deltas.latencyP95Ms.absolute, 3)} |`\n );\n lines.push(\"\");\n }\n\n if (gate) {\n lines.push(\"## CI Gate\");\n lines.push(\"\");\n lines.push(`- Result: ${gate.passed ? \"PASS ✅\" : \"FAIL ❌\"}`);\n if (gate.violations.length > 0) {\n lines.push(\"- Violations:\");\n for (const violation of gate.violations) {\n lines.push(` - ${violation.metric}: ${violation.message}`);\n }\n }\n lines.push(\"\");\n }\n\n if (sweep) {\n lines.push(\"## Parameter Sweep\");\n lines.push(\"\");\n lines.push(`- Run count: ${sweep.runCount}`);\n if (sweep.bestByHitAt5) {\n lines.push(\n `- Best Hit@5: ${formatPct(sweep.bestByHitAt5.summary.metrics.hitAt5)} with fusion=${sweep.bestByHitAt5.searchConfig.fusionStrategy}, hybridWeight=${sweep.bestByHitAt5.searchConfig.hybridWeight}, rrfK=${sweep.bestByHitAt5.searchConfig.rrfK}, rerankTopN=${sweep.bestByHitAt5.searchConfig.rerankTopN}`\n );\n }\n if (sweep.bestByMrrAt10) {\n lines.push(\n `- Best MRR@10: ${sweep.bestByMrrAt10.summary.metrics.mrrAt10.toFixed(4)} with fusion=${sweep.bestByMrrAt10.searchConfig.fusionStrategy}, hybridWeight=${sweep.bestByMrrAt10.searchConfig.hybridWeight}, rrfK=${sweep.bestByMrrAt10.searchConfig.rrfK}, rerankTopN=${sweep.bestByMrrAt10.searchConfig.rerankTopN}`\n );\n }\n if (sweep.bestByP95Latency) {\n lines.push(\n `- Best p95 latency: ${formatMs(sweep.bestByP95Latency.summary.metrics.latencyMs.p95)} with fusion=${sweep.bestByP95Latency.searchConfig.fusionStrategy}, hybridWeight=${sweep.bestByP95Latency.searchConfig.hybridWeight}, rrfK=${sweep.bestByP95Latency.searchConfig.rrfK}, rerankTopN=${sweep.bestByP95Latency.searchConfig.rerankTopN}`\n );\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport function buildPerQueryArtifact(perQuery: PerQueryEvalResult[]): {\n queryCount: number;\n queries: PerQueryEvalResult[];\n} {\n return {\n queryCount: perQuery.length,\n queries: [...perQuery].sort((a, b) => a.id.localeCompare(b.id)),\n };\n}\n","import type { EvalSummary } from \"./types.js\";\n\nexport interface LoadSummaryOptions {\n allowLegacyDiversityMetrics?: boolean;\n}\n\nexport function assertFiniteNumber(value: unknown, path: string): number {\n if (typeof value !== \"number\" || Number.isNaN(value) || !Number.isFinite(value)) {\n throw new Error(`${path} must be a finite number`);\n }\n return value;\n}\n\nexport function validateSummary(\n summary: EvalSummary,\n summaryPath: string,\n options?: LoadSummaryOptions\n): EvalSummary {\n assertFiniteNumber(summary.metrics.hitAt1, `${summaryPath}.metrics.hitAt1`);\n assertFiniteNumber(summary.metrics.hitAt3, `${summaryPath}.metrics.hitAt3`);\n assertFiniteNumber(summary.metrics.hitAt5, `${summaryPath}.metrics.hitAt5`);\n assertFiniteNumber(summary.metrics.hitAt10, `${summaryPath}.metrics.hitAt10`);\n assertFiniteNumber(summary.metrics.mrrAt10, `${summaryPath}.metrics.mrrAt10`);\n assertFiniteNumber(summary.metrics.ndcgAt10, `${summaryPath}.metrics.ndcgAt10`);\n\n const metrics = summary.metrics as EvalSummary[\"metrics\"] & {\n distinctTop3Ratio?: number;\n rawDistinctTop3Ratio?: number;\n };\n\n if (metrics.distinctTop3Ratio === undefined && options?.allowLegacyDiversityMetrics) {\n metrics.distinctTop3Ratio = 0;\n }\n if (metrics.rawDistinctTop3Ratio === undefined && options?.allowLegacyDiversityMetrics) {\n metrics.rawDistinctTop3Ratio = 0;\n }\n\n assertFiniteNumber(metrics.distinctTop3Ratio, `${summaryPath}.metrics.distinctTop3Ratio`);\n assertFiniteNumber(metrics.rawDistinctTop3Ratio, `${summaryPath}.metrics.rawDistinctTop3Ratio`);\n assertFiniteNumber(summary.metrics.latencyMs.p50, `${summaryPath}.metrics.latencyMs.p50`);\n assertFiniteNumber(summary.metrics.latencyMs.p95, `${summaryPath}.metrics.latencyMs.p95`);\n assertFiniteNumber(summary.metrics.latencyMs.p99, `${summaryPath}.metrics.latencyMs.p99`);\n assertFiniteNumber(summary.metrics.embedding.callCount, `${summaryPath}.metrics.embedding.callCount`);\n assertFiniteNumber(summary.metrics.embedding.estimatedCostUsd, `${summaryPath}.metrics.embedding.estimatedCostUsd`);\n\n return summary;\n}\n\nexport function formatPct(value: number): string {\n return `${(value * 100).toFixed(2)}%`;\n}\n\nexport function formatMs(value: number): string {\n return `${value.toFixed(3)}ms`;\n}\n\nexport function formatUsd(value: number): string {\n return `$${value.toFixed(6)}`;\n}\n\nexport function signed(value: number, digits = 4): string {\n const formatted = value.toFixed(digits);\n return value > 0 ? `+${formatted}` : formatted;\n}\n","import { existsSync } from \"fs\";\nimport * as path from \"path\";\nimport { performance } from \"perf_hooks\";\n\nimport { Indexer } from \"../indexer/index.js\";\n\nimport { evaluateBudgetGate } from \"./budget.js\";\nimport { compareSummaries } from \"./compare.js\";\nimport { buildPerQueryResult, computeEvalMetrics } from \"./metrics.js\";\nimport {\n clearIndexRoot,\n ensureLocalEvalProjectConfig,\n getEmbeddingCostPer1MTokens,\n loadParsedConfig,\n resolveSearchConfig,\n toAbsolute,\n} from \"./runner-config.js\";\nimport {\n createSummaryMarkdown,\n createRunDirectory,\n loadSummary,\n writeJson,\n writeText,\n buildPerQueryArtifact,\n} from \"./reports.js\";\nimport { loadBudget, loadGoldenDataset } from \"./schema.js\";\nimport type {\n EvalComparison,\n EvalGateResult,\n EvalRunOptions,\n EvalSummary,\n PerQueryEvalResult,\n SweepAggregateReport,\n SweepDefinition,\n SweepRunSummary,\n} from \"./types.js\";\n\nexport interface EvalRunResult {\n outputDir: string;\n summary: EvalSummary;\n perQuery: PerQueryEvalResult[];\n comparison?: EvalComparison;\n gate?: EvalGateResult;\n}\n\nexport async function runEvaluation(options: EvalRunOptions): Promise<EvalRunResult> {\n const datasetPath = toAbsolute(options.projectRoot, options.datasetPath);\n const againstPath = options.againstPath ? toAbsolute(options.projectRoot, options.againstPath) : undefined;\n const budgetPath = options.budgetPath ? toAbsolute(options.projectRoot, options.budgetPath) : undefined;\n\n const dataset = loadGoldenDataset(datasetPath);\n\n const resolvedEvalConfigPath = options.reindex\n ? ensureLocalEvalProjectConfig(options.projectRoot, options.configPath)\n : options.configPath;\n\n const parsedConfig = loadParsedConfig(options.projectRoot, resolvedEvalConfigPath);\n const effectiveConfig = resolveSearchConfig(parsedConfig, options.searchOverrides);\n\n if (options.reindex) {\n clearIndexRoot(options.projectRoot, effectiveConfig.scope);\n }\n\n const indexer = new Indexer(options.projectRoot, effectiveConfig);\n\n try {\n await indexer.index();\n\n const perQuery: PerQueryEvalResult[] = [];\n\n for (const query of dataset.queries) {\n if (query.expected.branch && query.expected.branch !== indexer.getCurrentBranch()) {\n throw new Error(\n `Query '${query.id}' expects branch '${query.expected.branch}', but current branch is '${indexer.getCurrentBranch()}'. Switch branch before running this dataset.`\n );\n }\n\n const start = performance.now();\n const result = await indexer.search(query.query, 10, {\n metadataOnly: true,\n filterByBranch: !!query.expected.branch,\n });\n const elapsed = performance.now() - start;\n\n const materialized = result.map((item) => ({\n filePath: item.filePath,\n startLine: item.startLine,\n endLine: item.endLine,\n score: item.score,\n chunkType: item.chunkType,\n name: item.name,\n }));\n\n perQuery.push(buildPerQueryResult(query, materialized, elapsed, 10));\n }\n\n const logger = indexer.getLogger();\n const metricSnapshot = logger.getMetrics();\n\n const costPer1MTokensUsd = getEmbeddingCostPer1MTokens(effectiveConfig.embeddingProvider);\n\n const summary: EvalSummary = {\n generatedAt: new Date().toISOString(),\n projectRoot: options.projectRoot,\n datasetPath,\n datasetName: dataset.name,\n datasetVersion: dataset.version,\n queryCount: dataset.queries.length,\n topK: 10,\n searchConfig: {\n fusionStrategy: effectiveConfig.search.fusionStrategy,\n hybridWeight: effectiveConfig.search.hybridWeight,\n rrfK: effectiveConfig.search.rrfK,\n rerankTopN: effectiveConfig.search.rerankTopN,\n },\n metrics: computeEvalMetrics(\n dataset.queries,\n perQuery,\n metricSnapshot.embeddingApiCalls,\n metricSnapshot.embeddingTokensUsed,\n costPer1MTokensUsd\n ),\n };\n\n const outputDir = createRunDirectory(toAbsolute(options.projectRoot, options.outputRoot));\n const perQueryArtifact = buildPerQueryArtifact(perQuery);\n\n writeJson(path.join(outputDir, \"summary.json\"), summary);\n writeJson(path.join(outputDir, \"per-query.json\"), perQueryArtifact);\n\n let comparison: EvalComparison | undefined;\n if (againstPath) {\n const baseline = loadSummary(againstPath);\n comparison = compareSummaries(summary, baseline, againstPath);\n writeJson(path.join(outputDir, \"compare.json\"), comparison);\n }\n\n let gate: EvalGateResult | undefined;\n if (options.ciMode) {\n if (!budgetPath) {\n throw new Error(\"CI mode requires --budget path\");\n }\n const budget = loadBudget(budgetPath);\n\n if (!comparison && budget.baselinePath) {\n const resolvedBaseline = toAbsolute(options.projectRoot, budget.baselinePath);\n if (existsSync(resolvedBaseline)) {\n const baselineSummary = loadSummary(resolvedBaseline);\n comparison = compareSummaries(summary, baselineSummary, resolvedBaseline);\n writeJson(path.join(outputDir, \"compare.json\"), comparison);\n } else if (budget.failOnMissingBaseline) {\n throw new Error(\n `Budget baseline is missing: ${resolvedBaseline}. Set failOnMissingBaseline=false to allow CI run without baseline.`\n );\n }\n }\n\n gate = evaluateBudgetGate(budget, summary, comparison);\n }\n\n const markdown = createSummaryMarkdown(summary, comparison, gate);\n writeText(path.join(outputDir, \"summary.md\"), markdown);\n\n return { outputDir, summary, perQuery, comparison, gate };\n } finally {\n await indexer.close();\n }\n}\n\nexport async function runSweep(\n options: EvalRunOptions,\n sweep: SweepDefinition\n): Promise<{ outputDir: string; aggregate: SweepAggregateReport }> {\n const fusionValues: Array<\"rrf\" | \"weighted\" | undefined> =\n sweep.fusionStrategy && sweep.fusionStrategy.length > 0\n ? [...sweep.fusionStrategy]\n : [undefined];\n const weightValues: Array<number | undefined> =\n sweep.hybridWeight && sweep.hybridWeight.length > 0 ? [...sweep.hybridWeight] : [undefined];\n const rrfValues: Array<number | undefined> =\n sweep.rrfK && sweep.rrfK.length > 0 ? [...sweep.rrfK] : [undefined];\n const rerankValues: Array<number | undefined> =\n sweep.rerankTopN && sweep.rerankTopN.length > 0 ? [...sweep.rerankTopN] : [undefined];\n\n const runs: SweepRunSummary[] = [];\n\n for (const fusion of fusionValues) {\n for (const hybridWeight of weightValues) {\n for (const rrfK of rrfValues) {\n for (const rerankTopN of rerankValues) {\n const run = await runEvaluation({\n ...options,\n searchOverrides: {\n ...(fusion !== undefined ? { fusionStrategy: fusion } : {}),\n ...(hybridWeight !== undefined ? { hybridWeight } : {}),\n ...(rrfK !== undefined ? { rrfK } : {}),\n ...(rerankTopN !== undefined ? { rerankTopN } : {}),\n },\n });\n\n runs.push({\n searchConfig: run.summary.searchConfig,\n summary: run.summary,\n comparison: run.comparison,\n gate: run.gate,\n });\n }\n }\n }\n }\n\n const bestByHitAt5 = [...runs].sort(\n (a, b) => b.summary.metrics.hitAt5 - a.summary.metrics.hitAt5\n )[0];\n const bestByMrrAt10 = [...runs].sort(\n (a, b) => b.summary.metrics.mrrAt10 - a.summary.metrics.mrrAt10\n )[0];\n const bestByP95Latency = [...runs].sort(\n (a, b) => a.summary.metrics.latencyMs.p95 - b.summary.metrics.latencyMs.p95\n )[0];\n\n const outputDir = createRunDirectory(toAbsolute(options.projectRoot, options.outputRoot));\n const failedGateRuns = runs.filter((run) => run.gate && !run.gate.passed).length;\n const gatePassed = failedGateRuns === 0;\n const aggregate: SweepAggregateReport = {\n generatedAt: new Date().toISOString(),\n againstPath: options.againstPath,\n runCount: runs.length,\n runs,\n gatePassed,\n failedGateRuns,\n bestByHitAt5,\n bestByMrrAt10,\n bestByP95Latency,\n };\n\n writeJson(path.join(outputDir, \"compare.json\"), aggregate);\n const md = createSummaryMarkdown(\n bestByHitAt5?.summary ?? runs[0].summary,\n bestByHitAt5?.comparison,\n undefined,\n aggregate\n );\n writeText(path.join(outputDir, \"summary.md\"), md);\n writeJson(path.join(outputDir, \"summary.json\"), bestByHitAt5?.summary ?? runs[0].summary);\n\n return { outputDir, aggregate };\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 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 * 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","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 { 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 { 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 type { EvalBudget, EvalComparison, EvalGateResult, EvalSummary } from \"./types.js\";\n\nexport function evaluateBudgetGate(\n budget: EvalBudget,\n summary: EvalSummary,\n comparison?: EvalComparison\n): EvalGateResult {\n const BASELINE_P95_EPSILON_MS = 0.001;\n const violations: EvalGateResult[\"violations\"] = [];\n\n const { thresholds } = budget;\n\n if (thresholds.minHitAt5 !== undefined && summary.metrics.hitAt5 < thresholds.minHitAt5) {\n violations.push({\n metric: \"minHitAt5\",\n message: `Hit@5 ${summary.metrics.hitAt5.toFixed(4)} is below minimum ${thresholds.minHitAt5.toFixed(4)}`,\n });\n }\n\n if (thresholds.minMrrAt10 !== undefined && summary.metrics.mrrAt10 < thresholds.minMrrAt10) {\n violations.push({\n metric: \"minMrrAt10\",\n message: `MRR@10 ${summary.metrics.mrrAt10.toFixed(4)} is below minimum ${thresholds.minMrrAt10.toFixed(4)}`,\n });\n }\n\n if (\n thresholds.minRawDistinctTop3Ratio !== undefined &&\n summary.metrics.rawDistinctTop3Ratio < thresholds.minRawDistinctTop3Ratio\n ) {\n violations.push({\n metric: \"minRawDistinctTop3Ratio\",\n message: `Raw Distinct Top@3 ${summary.metrics.rawDistinctTop3Ratio.toFixed(4)} is below minimum ${thresholds.minRawDistinctTop3Ratio.toFixed(4)}`,\n });\n }\n\n if (comparison) {\n if (\n thresholds.hitAt5MaxDrop !== undefined &&\n comparison.deltas.hitAt5.absolute < -thresholds.hitAt5MaxDrop\n ) {\n violations.push({\n metric: \"hitAt5MaxDrop\",\n message: `Hit@5 drop ${comparison.deltas.hitAt5.absolute.toFixed(4)} exceeds allowed -${thresholds.hitAt5MaxDrop.toFixed(4)}`,\n });\n }\n\n if (\n thresholds.mrrAt10MaxDrop !== undefined &&\n comparison.deltas.mrrAt10.absolute < -thresholds.mrrAt10MaxDrop\n ) {\n violations.push({\n metric: \"mrrAt10MaxDrop\",\n message: `MRR@10 drop ${comparison.deltas.mrrAt10.absolute.toFixed(4)} exceeds allowed -${thresholds.mrrAt10MaxDrop.toFixed(4)}`,\n });\n }\n\n if (\n thresholds.rawDistinctTop3RatioMaxDrop !== undefined &&\n comparison.deltas.rawDistinctTop3Ratio.absolute < -thresholds.rawDistinctTop3RatioMaxDrop\n ) {\n violations.push({\n metric: \"rawDistinctTop3RatioMaxDrop\",\n message: `Raw Distinct Top@3 drop ${comparison.deltas.rawDistinctTop3Ratio.absolute.toFixed(4)} exceeds allowed -${thresholds.rawDistinctTop3RatioMaxDrop.toFixed(4)}`,\n });\n }\n\n if (thresholds.p95LatencyMaxMultiplier !== undefined) {\n const baselineP95 = comparison.deltas.latencyP95Ms.baseline;\n if (baselineP95 > BASELINE_P95_EPSILON_MS) {\n const allowed = baselineP95 * thresholds.p95LatencyMaxMultiplier;\n if (summary.metrics.latencyMs.p95 > allowed) {\n violations.push({\n metric: \"p95LatencyMaxMultiplier\",\n message: `p95 latency ${summary.metrics.latencyMs.p95.toFixed(3)}ms exceeds allowed ${allowed.toFixed(3)}ms (${thresholds.p95LatencyMaxMultiplier.toFixed(2)}x baseline)`,\n });\n }\n }\n }\n }\n\n if (\n thresholds.p95LatencyMaxAbsoluteMs !== undefined &&\n summary.metrics.latencyMs.p95 > thresholds.p95LatencyMaxAbsoluteMs\n ) {\n violations.push({\n metric: \"p95LatencyMaxAbsoluteMs\",\n message: `p95 latency ${summary.metrics.latencyMs.p95.toFixed(3)}ms exceeds absolute maximum ${thresholds.p95LatencyMaxAbsoluteMs.toFixed(3)}ms`,\n });\n }\n\n return {\n passed: violations.length === 0,\n budgetName: budget.name,\n violations,\n };\n}\n","import { estimateTokens } from \"../utils/cost.js\";\nimport { normalizePathSeparators } from \"../utils/paths.js\";\n\nimport type {\n EvalMetrics,\n FailureBucket,\n GoldenQuery,\n PerQueryEvalResult,\n} from \"./types.js\";\n\nfunction percentile(values: number[], p: number): number {\n if (values.length === 0) return 0;\n if (values.length === 1) return values[0];\n const sorted = [...values].sort((a, b) => a - b);\n const x = p * (sorted.length - 1);\n const lowerIndex = Math.floor(x);\n const upperIndex = Math.ceil(x);\n if (lowerIndex === upperIndex) {\n return sorted[lowerIndex];\n }\n const fraction = x - lowerIndex;\n return sorted[lowerIndex] + fraction * (sorted[upperIndex] - sorted[lowerIndex]);\n}\n\nfunction normalizePath(input: string): string {\n return normalizePathSeparators(input);\n}\n\nfunction uniqueResultsByPath(results: PerQueryEvalResult[\"results\"]): PerQueryEvalResult[\"results\"] {\n const seen = new Set<string>();\n const unique: PerQueryEvalResult[\"results\"] = [];\n\n for (const result of results) {\n const normalized = normalizePath(result.filePath);\n if (seen.has(normalized)) continue;\n seen.add(normalized);\n unique.push(result);\n }\n\n return unique;\n}\n\nfunction distinctTopKRatio(results: PerQueryEvalResult[\"results\"], k: number): number {\n const top = results.slice(0, k);\n if (top.length === 0) return 0;\n const distinct = new Set(top.map((result) => normalizePath(result.filePath))).size;\n return distinct / top.length;\n}\n\nexport function pathMatchesExpected(actualPath: string, expectedPath: string): boolean {\n const actual = normalizePath(actualPath);\n const expected = normalizePath(expectedPath);\n if (actual === expected) return true;\n return actual.endsWith(`/${expected}`) || expected.endsWith(`/${actual}`);\n}\n\nexport function getRelevantPaths(query: GoldenQuery): string[] {\n const fromExact = query.expected.filePath ? [query.expected.filePath] : [];\n const fromAcceptable = query.expected.acceptableFiles ?? [];\n return Array.from(new Set([...fromExact, ...fromAcceptable]));\n}\n\nfunction isRelevantResult(filePath: string, relevantPaths: string[]): boolean {\n return relevantPaths.some((expected) => pathMatchesExpected(filePath, expected));\n}\n\nfunction reciprocalRankAtK(results: PerQueryEvalResult[\"results\"], relevantPaths: string[], k: number): number {\n const top = uniqueResultsByPath(results).slice(0, k);\n for (let i = 0; i < top.length; i += 1) {\n if (isRelevantResult(top[i].filePath, relevantPaths)) {\n return 1 / (i + 1);\n }\n }\n return 0;\n}\n\nfunction ndcgAtK(results: PerQueryEvalResult[\"results\"], relevantPaths: string[], k: number): number {\n const top = uniqueResultsByPath(results).slice(0, k);\n const dcg = top.reduce((sum, result, i) => {\n const rel = isRelevantResult(result.filePath, relevantPaths) ? 1 : 0;\n return sum + rel / Math.log2(i + 2);\n }, 0);\n\n const idealLen = Math.min(k, relevantPaths.length);\n const idcg = Array.from({ length: idealLen }, (_, i) => 1 / Math.log2(i + 2)).reduce(\n (sum, value) => sum + value,\n 0\n );\n\n return idcg === 0 ? 0 : dcg / idcg;\n}\n\nfunction isDocsOrTestsPath(filePath: string): boolean {\n const lowered = normalizePath(filePath).toLowerCase();\n return (\n lowered.includes(\"/docs/\") ||\n lowered.includes(\"/test/\") ||\n lowered.includes(\"/tests/\") ||\n lowered.includes(\"readme\") ||\n lowered.includes(\"/benchmarks/\")\n );\n}\n\nexport function classifyFailureBucket(\n query: GoldenQuery,\n results: PerQueryEvalResult[\"results\"],\n k: number\n): FailureBucket | undefined {\n const relevantPaths = getRelevantPaths(query);\n const top = uniqueResultsByPath(results).slice(0, k);\n const hasRelevantTopK = top.some((result) => isRelevantResult(result.filePath, relevantPaths));\n\n if (!hasRelevantTopK) {\n return \"no-relevant-hit-top-k\";\n }\n\n if (query.expected.symbol) {\n const hasSymbol = top.some(\n (result) =>\n isRelevantResult(result.filePath, relevantPaths) && result.name === query.expected.symbol\n );\n if (!hasSymbol) return \"wrong-symbol\";\n }\n\n const top1 = top[0];\n if (top1 && !isRelevantResult(top1.filePath, relevantPaths) && isDocsOrTestsPath(top1.filePath)) {\n return \"docs-tests-outranking-source\";\n }\n\n if (top1 && !isRelevantResult(top1.filePath, relevantPaths)) {\n return \"wrong-file\";\n }\n\n return undefined;\n}\n\nexport function buildPerQueryResult(\n query: GoldenQuery,\n results: PerQueryEvalResult[\"results\"],\n latencyMs: number,\n k: number\n): PerQueryEvalResult {\n const relevantPaths = getRelevantPaths(query);\n const deduped = uniqueResultsByPath(results);\n const hitAt = (cutoff: number): boolean =>\n deduped.slice(0, cutoff).some((result) => isRelevantResult(result.filePath, relevantPaths));\n\n const perQuery: PerQueryEvalResult = {\n id: query.id,\n query: query.query,\n queryType: query.queryType,\n latencyMs,\n hitAt1: hitAt(1),\n hitAt3: hitAt(3),\n hitAt5: hitAt(5),\n hitAt10: hitAt(10),\n reciprocalRankAt10: reciprocalRankAtK(deduped, relevantPaths, 10),\n ndcgAt10: ndcgAtK(deduped, relevantPaths, 10),\n failureBucket: classifyFailureBucket(query, results, k),\n rawTop3DistinctRatio: distinctTopKRatio(results, 3),\n results: deduped,\n };\n\n return perQuery;\n}\n\nexport function computeEvalMetrics(\n queries: GoldenQuery[],\n perQuery: PerQueryEvalResult[],\n embeddingCallCount: number,\n embeddingTokensUsed: number,\n costPer1MTokensUsd: number\n): EvalMetrics {\n const count = perQuery.length;\n const safeDiv = (value: number): number => (count === 0 ? 0 : value / count);\n\n const sum = {\n hitAt1: 0,\n hitAt3: 0,\n hitAt5: 0,\n hitAt10: 0,\n mrrAt10: 0,\n ndcgAt10: 0,\n distinctTop3Ratio: 0,\n rawDistinctTop3Ratio: 0,\n };\n\n const failureBuckets: Record<FailureBucket, number> = {\n \"wrong-file\": 0,\n \"wrong-symbol\": 0,\n \"docs-tests-outranking-source\": 0,\n \"no-relevant-hit-top-k\": 0,\n };\n\n const latencies = perQuery.map((item) => item.latencyMs);\n\n for (const query of perQuery) {\n if (query.hitAt1) sum.hitAt1 += 1;\n if (query.hitAt3) sum.hitAt3 += 1;\n if (query.hitAt5) sum.hitAt5 += 1;\n if (query.hitAt10) sum.hitAt10 += 1;\n sum.mrrAt10 += query.reciprocalRankAt10;\n sum.ndcgAt10 += query.ndcgAt10;\n sum.distinctTop3Ratio += distinctTopKRatio(query.results, 3);\n sum.rawDistinctTop3Ratio += query.rawTop3DistinctRatio;\n if (query.failureBucket) {\n failureBuckets[query.failureBucket] += 1;\n }\n }\n\n const queryTokens = queries.reduce((acc, q) => acc + estimateTokens(q.query), 0);\n\n return {\n hitAt1: safeDiv(sum.hitAt1),\n hitAt3: safeDiv(sum.hitAt3),\n hitAt5: safeDiv(sum.hitAt5),\n hitAt10: safeDiv(sum.hitAt10),\n mrrAt10: safeDiv(sum.mrrAt10),\n ndcgAt10: safeDiv(sum.ndcgAt10),\n distinctTop3Ratio: safeDiv(sum.distinctTop3Ratio),\n rawDistinctTop3Ratio: safeDiv(sum.rawDistinctTop3Ratio),\n latencyMs: {\n p50: percentile(latencies, 0.5),\n p95: percentile(latencies, 0.95),\n p99: percentile(latencies, 0.99),\n },\n tokenEstimate: {\n queryTokens,\n embeddingTokensUsed,\n },\n embedding: {\n callCount: embeddingCallCount,\n estimatedCostUsd: (embeddingTokensUsed / 1_000_000) * costPer1MTokensUsd,\n costPer1MTokensUsd,\n },\n failureBuckets,\n };\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { getDefaultModelForProvider } from \"../config/index.js\";\nimport { getGlobalIndexPath, resolveProjectConfigPath, resolveProjectIndexPath } from \"../config/paths.js\";\nimport { rebasePathEntries, resolveInheritedKnowledgeBaseEntries } from \"../config/rebase.js\";\nimport { parseConfig, type SearchConfig as ConfigSearchConfig } from \"../config/schema.js\";\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 validateEvalConfigShape(rawConfig: unknown, filePath: string): Record<string, unknown> {\n if (!isRecord(rawConfig)) {\n throw new Error(`Eval config at ${filePath} must contain a JSON object at the root.`);\n }\n\n const config = rawConfig;\n\n if (config.knowledgeBases !== undefined && !isStringArray(config.knowledgeBases)) {\n throw new Error(`Eval config at ${filePath} field 'knowledgeBases' must be an array of strings.`);\n }\n if (config.additionalInclude !== undefined && !isStringArray(config.additionalInclude)) {\n throw new Error(`Eval config at ${filePath} field 'additionalInclude' must be an array of strings.`);\n }\n if (config.include !== undefined && !isStringArray(config.include)) {\n throw new Error(`Eval config at ${filePath} field 'include' must be an array of strings.`);\n }\n if (config.exclude !== undefined && !isStringArray(config.exclude)) {\n throw new Error(`Eval config at ${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 = config[section];\n if (value !== undefined && !isRecord(value)) {\n throw new Error(`Eval config at ${filePath} field '${section}' must be an object.`);\n }\n }\n\n return config;\n}\n\nfunction parseJsonConfigFile(filePath: string): unknown {\n try {\n return validateEvalConfigShape(JSON.parse(readFileSync(filePath, \"utf-8\")), filePath);\n } catch (error: unknown) {\n if (error instanceof Error && error.message.startsWith(\"Eval config at \")) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to parse eval config JSON at ${filePath}: ${message}`);\n }\n}\n\nexport function toAbsolute(projectRoot: string, maybeRelative: string): string {\n return path.isAbsolute(maybeRelative) ? maybeRelative : path.join(projectRoot, maybeRelative);\n}\n\nfunction isProjectScopedConfigPath(configPath: string): boolean {\n return path.basename(configPath) === \"codebase-index.json\"\n && path.basename(path.dirname(configPath)) === \".opencode\";\n}\n\nfunction normalizeEvalConfigKnowledgeBases(\n rawConfig: unknown,\n projectRoot: string,\n resolvedConfigPath: string,\n): Record<string, unknown> {\n const config = rawConfig && typeof rawConfig === \"object\"\n ? { ...(rawConfig as Record<string, unknown>) }\n : {};\n\n const rebaseEntries = (values: unknown): string[] => isProjectScopedConfigPath(resolvedConfigPath)\n ? resolveInheritedKnowledgeBaseEntries(\n values,\n path.dirname(path.dirname(resolvedConfigPath)),\n projectRoot,\n )\n : rebasePathEntries(\n values,\n path.dirname(resolvedConfigPath),\n projectRoot,\n );\n\n if (Array.isArray(config.knowledgeBases)) {\n config.knowledgeBases = rebaseEntries(config.knowledgeBases);\n }\n\n if (Array.isArray(config.additionalInclude)) {\n config.additionalInclude = rebaseEntries(config.additionalInclude);\n }\n\n return config;\n}\n\nfunction loadRawConfig(projectRoot: string, configPath?: string): unknown {\n const fromPath = configPath ? toAbsolute(projectRoot, configPath) : null;\n if (fromPath && existsSync(fromPath)) {\n return normalizeEvalConfigKnowledgeBases(\n parseJsonConfigFile(fromPath),\n projectRoot,\n fromPath,\n );\n }\n\n const projectConfig = resolveProjectConfigPath(projectRoot);\n if (existsSync(projectConfig)) {\n return normalizeEvalConfigKnowledgeBases(\n parseJsonConfigFile(projectConfig),\n projectRoot,\n projectConfig,\n );\n }\n\n const globalConfig = path.join(os.homedir(), \".config\", \"opencode\", \"codebase-index.json\");\n if (existsSync(globalConfig)) {\n return parseJsonConfigFile(globalConfig);\n }\n\n return {};\n}\n\nfunction getIndexRootPath(projectRoot: string, scope: \"project\" | \"global\"): string {\n return scope === \"global\"\n ? getGlobalIndexPath()\n : resolveProjectIndexPath(projectRoot, scope);\n}\n\nfunction getLocalProjectIndexRoot(projectRoot: string): string {\n return path.join(projectRoot, \".opencode\", \"index\");\n}\n\nfunction getLocalProjectConfigPath(projectRoot: string): string {\n return path.join(projectRoot, \".opencode\", \"codebase-index.json\");\n}\n\nexport function clearIndexRoot(projectRoot: string, scope: \"project\" | \"global\"): void {\n const indexRoot = scope === \"global\"\n ? getIndexRootPath(projectRoot, scope)\n : getLocalProjectIndexRoot(projectRoot);\n if (existsSync(indexRoot)) {\n rmSync(indexRoot, { recursive: true, force: true });\n }\n}\n\nexport function ensureLocalEvalProjectConfig(projectRoot: string, configPath?: string): string | undefined {\n const localConfigPath = getLocalProjectConfigPath(projectRoot);\n const resolvedConfigPath = configPath\n ? toAbsolute(projectRoot, configPath)\n : resolveProjectConfigPath(projectRoot);\n\n if (!configPath && existsSync(localConfigPath)) {\n return localConfigPath;\n }\n\n if (!existsSync(resolvedConfigPath) || resolvedConfigPath === localConfigPath) {\n return resolvedConfigPath;\n }\n\n const sourceConfig = normalizeEvalConfigKnowledgeBases(\n parseJsonConfigFile(resolvedConfigPath),\n projectRoot,\n resolvedConfigPath,\n );\n\n mkdirSync(path.dirname(localConfigPath), { recursive: true });\n writeFileSync(localConfigPath, JSON.stringify(sourceConfig, null, 2), \"utf-8\");\n return localConfigPath;\n}\n\nexport function loadParsedConfig(projectRoot: string, configPath?: string): ReturnType<typeof parseConfig> {\n const raw = loadRawConfig(projectRoot, configPath);\n return parseConfig(raw);\n}\n\nexport function resolveSearchConfig(\n parsedConfig: ReturnType<typeof parseConfig>,\n overrides?: Partial<Pick<ConfigSearchConfig, \"fusionStrategy\" | \"hybridWeight\" | \"rrfK\" | \"rerankTopN\">>\n): ReturnType<typeof parseConfig> {\n const nextSearch: ConfigSearchConfig = {\n ...parsedConfig.search,\n };\n\n if (overrides?.fusionStrategy !== undefined) {\n nextSearch.fusionStrategy = overrides.fusionStrategy;\n }\n if (overrides?.hybridWeight !== undefined) {\n nextSearch.hybridWeight = overrides.hybridWeight;\n }\n if (overrides?.rrfK !== undefined) {\n nextSearch.rrfK = overrides.rrfK;\n }\n if (overrides?.rerankTopN !== undefined) {\n nextSearch.rerankTopN = overrides.rerankTopN;\n }\n\n return {\n ...parsedConfig,\n search: nextSearch,\n };\n}\n\nexport function getEmbeddingCostPer1MTokens(\n embeddingProvider: ReturnType<typeof parseConfig>[\"embeddingProvider\"],\n): number {\n return embeddingProvider === \"custom\" || embeddingProvider === \"auto\"\n ? 0\n : getDefaultModelForProvider(embeddingProvider).costPer1MTokens;\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 { readFileSync } from \"fs\";\n\nimport type {\n EvalBudget,\n GoldenDataset,\n GoldenExpected,\n GoldenQuery,\n GoldenQueryType,\n} from \"./types.js\";\n\nfunction parseJsonFile(filePath: string): unknown {\n const content = readFileSync(filePath, \"utf-8\");\n\n try {\n return JSON.parse(content);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to parse JSON from ${filePath}: ${message}`);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\nfunction asPositiveNumber(value: unknown, path: string): number {\n if (typeof value !== \"number\" || Number.isNaN(value) || value < 0) {\n throw new Error(`${path} must be a non-negative number`);\n }\n return value;\n}\n\nfunction parseQueryType(value: unknown, path: string): GoldenQueryType {\n if (\n value === \"definition\" ||\n value === \"implementation-intent\" ||\n value === \"similarity\" ||\n value === \"keyword-heavy\"\n ) {\n return value;\n }\n throw new Error(\n `${path} must be one of: definition, implementation-intent, similarity, keyword-heavy`\n );\n}\n\nfunction parseExpected(input: unknown, path: string): GoldenExpected {\n if (!isRecord(input)) {\n throw new Error(`${path} must be an object`);\n }\n\n const filePathRaw = input.filePath;\n const acceptableFilesRaw = input.acceptableFiles;\n const symbolRaw = input.symbol;\n const branchRaw = input.branch;\n\n const filePath = typeof filePathRaw === \"string\" ? filePathRaw : undefined;\n const acceptableFiles = isStringArray(acceptableFilesRaw) ? acceptableFilesRaw : undefined;\n\n if (!filePath && (!acceptableFiles || acceptableFiles.length === 0)) {\n throw new Error(`${path} must include either expected.filePath or expected.acceptableFiles`);\n }\n\n if (acceptableFilesRaw !== undefined && !isStringArray(acceptableFilesRaw)) {\n throw new Error(`${path}.acceptableFiles must be an array of strings`);\n }\n\n if (symbolRaw !== undefined && typeof symbolRaw !== \"string\") {\n throw new Error(`${path}.symbol must be a string when provided`);\n }\n\n if (branchRaw !== undefined && typeof branchRaw !== \"string\") {\n throw new Error(`${path}.branch must be a string when provided`);\n }\n\n\n\n\n return {\n filePath,\n acceptableFiles,\n symbol: typeof symbolRaw === \"string\" ? symbolRaw : undefined,\n branch: typeof branchRaw === \"string\" ? branchRaw : undefined,\n };\n}\n\nfunction parseQuery(input: unknown, index: number): GoldenQuery {\n const path = `queries[${index}]`;\n if (!isRecord(input)) {\n throw new Error(`${path} must be an object`);\n }\n\n const id = input.id;\n const query = input.query;\n const queryType = input.queryType;\n const expected = input.expected;\n\n if (typeof id !== \"string\" || id.trim().length === 0) {\n throw new Error(`${path}.id must be a non-empty string`);\n }\n\n if (typeof query !== \"string\" || query.trim().length === 0) {\n throw new Error(`${path}.query must be a non-empty string`);\n }\n\n return {\n id,\n query,\n queryType: parseQueryType(queryType, `${path}.queryType`),\n expected: parseExpected(expected, `${path}.expected`),\n };\n}\n\nexport function parseGoldenDataset(raw: unknown, sourceLabel: string): GoldenDataset {\n if (!isRecord(raw)) {\n throw new Error(`${sourceLabel} must be a JSON object`);\n }\n\n const version = raw.version;\n const name = raw.name;\n const description = raw.description;\n const queriesRaw = raw.queries;\n\n if (typeof version !== \"string\" || version.trim().length === 0) {\n throw new Error(`${sourceLabel}.version must be a non-empty string`);\n }\n\n if (typeof name !== \"string\" || name.trim().length === 0) {\n throw new Error(`${sourceLabel}.name must be a non-empty string`);\n }\n\n if (description !== undefined && typeof description !== \"string\") {\n throw new Error(`${sourceLabel}.description must be a string when provided`);\n }\n\n if (!Array.isArray(queriesRaw)) {\n throw new Error(`${sourceLabel}.queries must be an array`);\n }\n\n if (queriesRaw.length === 0) {\n throw new Error(`${sourceLabel}.queries must contain at least one query`);\n }\n\n const queries = queriesRaw.map((query, idx) => parseQuery(query, idx));\n const idSet = new Set<string>();\n\n for (const query of queries) {\n if (idSet.has(query.id)) {\n throw new Error(`${sourceLabel}.queries has duplicate id: ${query.id}`);\n }\n idSet.add(query.id);\n }\n\n return {\n version,\n name,\n description: typeof description === \"string\" ? description : undefined,\n queries,\n };\n}\n\nexport function loadGoldenDataset(datasetPath: string): GoldenDataset {\n const parsed = parseJsonFile(datasetPath);\n return parseGoldenDataset(parsed, datasetPath);\n}\n\nfunction parseThresholdValue(\n value: unknown,\n fieldName: string,\n sourceLabel: string\n): number | undefined {\n return value === undefined\n ? undefined\n : asPositiveNumber(value, `${sourceLabel}.thresholds.${fieldName}`);\n}\n\nexport function parseBudget(raw: unknown, sourceLabel: string): EvalBudget {\n if (!isRecord(raw)) {\n throw new Error(`${sourceLabel} must be a JSON object`);\n }\n\n const name = raw.name;\n const baselinePath = raw.baselinePath;\n const failOnMissingBaseline = raw.failOnMissingBaseline;\n const thresholds = raw.thresholds;\n\n if (typeof name !== \"string\" || name.trim().length === 0) {\n throw new Error(`${sourceLabel}.name must be a non-empty string`);\n }\n\n if (baselinePath !== undefined && typeof baselinePath !== \"string\") {\n throw new Error(`${sourceLabel}.baselinePath must be a string when provided`);\n }\n\n if (!isRecord(thresholds)) {\n throw new Error(`${sourceLabel}.thresholds must be an object`);\n }\n\n return {\n name,\n baselinePath: typeof baselinePath === \"string\" ? baselinePath : undefined,\n failOnMissingBaseline:\n typeof failOnMissingBaseline === \"boolean\" ? failOnMissingBaseline : true,\n thresholds: {\n hitAt5MaxDrop: parseThresholdValue(\n thresholds.hitAt5MaxDrop,\n \"hitAt5MaxDrop\",\n sourceLabel\n ),\n mrrAt10MaxDrop: parseThresholdValue(\n thresholds.mrrAt10MaxDrop,\n \"mrrAt10MaxDrop\",\n sourceLabel\n ),\n rawDistinctTop3RatioMaxDrop: parseThresholdValue(\n thresholds.rawDistinctTop3RatioMaxDrop,\n \"rawDistinctTop3RatioMaxDrop\",\n sourceLabel\n ),\n p95LatencyMaxMultiplier: parseThresholdValue(\n thresholds.p95LatencyMaxMultiplier,\n \"p95LatencyMaxMultiplier\",\n sourceLabel\n ),\n p95LatencyMaxAbsoluteMs: parseThresholdValue(\n thresholds.p95LatencyMaxAbsoluteMs,\n \"p95LatencyMaxAbsoluteMs\",\n sourceLabel\n ),\n minHitAt5: parseThresholdValue(\n thresholds.minHitAt5,\n \"minHitAt5\",\n sourceLabel\n ),\n minMrrAt10: parseThresholdValue(\n thresholds.minMrrAt10,\n \"minMrrAt10\",\n sourceLabel\n ),\n minRawDistinctTop3Ratio: parseThresholdValue(\n thresholds.minRawDistinctTop3Ratio,\n \"minRawDistinctTop3Ratio\",\n sourceLabel\n ),\n },\n };\n}\n\nexport function loadBudget(budgetPath: string): EvalBudget {\n const parsed = parseJsonFile(budgetPath);\n return parseBudget(parsed, budgetPath);\n}\n","import { compareSummaries } from \"./compare.js\";\nimport { createSummaryMarkdown, createRunDirectory, loadSummary, writeJson, writeText } from \"./reports.js\";\nimport { runEvaluation, runSweep } from \"./runner.js\";\nimport * as path from \"path\";\n\nimport {\n hasSweepOptions,\n parseEvalSubcommandOptions,\n printUsage,\n toRunOptions,\n} from \"./cli-parser.js\";\n\nexport async function handleEvalCommand(args: string[], cwd: string): Promise<number> {\n const subcommand = args[0];\n\n if (!subcommand || subcommand === \"--help\" || subcommand === \"-h\") {\n printUsage();\n return 0;\n }\n\n if (subcommand === \"run\") {\n const { parsed, explicitAgainst } = parseEvalSubcommandOptions(args.slice(1), cwd);\n if (explicitAgainst) {\n parsed.againstPath = explicitAgainst;\n }\n const runOptions = toRunOptions(parsed);\n\n if (hasSweepOptions(parsed.sweep)) {\n const sweep = await runSweep(runOptions, parsed.sweep);\n console.log(`Eval sweep complete. Artifacts: ${sweep.outputDir}`);\n console.log(`Sweep runs: ${sweep.aggregate.runCount}`);\n if (parsed.ciMode && sweep.aggregate.gatePassed === false) {\n console.error(\n `[CI-GATE] Sweep failed: ${sweep.aggregate.failedGateRuns ?? 0} run(s) violated budget/baseline gates`\n );\n return 1;\n }\n return 0;\n }\n\n const result = await runEvaluation(runOptions);\n console.log(`Eval run complete. Artifacts: ${result.outputDir}`);\n console.log(\n `Hit@5=${(result.summary.metrics.hitAt5 * 100).toFixed(2)}% MRR@10=${result.summary.metrics.mrrAt10.toFixed(4)} p95=${result.summary.metrics.latencyMs.p95.toFixed(3)}ms`\n );\n\n if (result.gate && !result.gate.passed) {\n for (const violation of result.gate.violations) {\n console.error(`[CI-GATE] ${violation.metric}: ${violation.message}`);\n }\n return 1;\n }\n\n return 0;\n }\n\n if (subcommand === \"compare\") {\n const { parsed, explicitAgainst } = parseEvalSubcommandOptions(args.slice(1), cwd);\n\n if (!explicitAgainst) {\n throw new Error(\"eval compare requires --against <baseline summary.json>\");\n }\n parsed.againstPath = explicitAgainst;\n\n const runOptions = toRunOptions(parsed);\n\n if (hasSweepOptions(parsed.sweep)) {\n const sweep = await runSweep(runOptions, parsed.sweep);\n console.log(`Eval compare sweep complete. Artifacts: ${sweep.outputDir}`);\n if (parsed.ciMode && sweep.aggregate.gatePassed === false) {\n console.error(\n `[CI-GATE] Sweep failed: ${sweep.aggregate.failedGateRuns ?? 0} run(s) violated budget/baseline gates`\n );\n return 1;\n }\n return 0;\n }\n\n const result = await runEvaluation(runOptions);\n console.log(`Eval compare complete. Artifacts: ${result.outputDir}`);\n return 0;\n }\n\n if (subcommand === \"diff\") {\n const { parsed, explicitAgainst } = parseEvalSubcommandOptions(args.slice(1), cwd);\n if (!explicitAgainst) {\n throw new Error(\"eval diff requires --against <baseline summary.json>\");\n }\n if (!parsed.currentPath) {\n throw new Error(\"eval diff requires --current <current summary.json>\");\n }\n parsed.againstPath = explicitAgainst;\n\n const currentPath = parsed.currentPath;\n if (!currentPath.endsWith(\".json\")) {\n throw new Error(\"eval diff --current must point to a summary JSON file\");\n }\n if (!parsed.againstPath.endsWith(\".json\")) {\n throw new Error(\"eval diff --against must point to a summary JSON file\");\n }\n const currentSummary = loadSummary(path.resolve(parsed.projectRoot, currentPath), {\n allowLegacyDiversityMetrics: true,\n });\n const baselineSummary = loadSummary(path.resolve(parsed.projectRoot, parsed.againstPath), {\n allowLegacyDiversityMetrics: true,\n });\n const comparison = compareSummaries(\n currentSummary,\n baselineSummary,\n path.resolve(parsed.projectRoot, parsed.againstPath)\n );\n\n const outputDir = createRunDirectory(path.resolve(parsed.projectRoot, parsed.outputRoot));\n const summaryMd = createSummaryMarkdown(currentSummary, comparison);\n writeJson(path.join(outputDir, \"compare.json\"), comparison);\n writeText(path.join(outputDir, \"summary.md\"), summaryMd);\n writeJson(path.join(outputDir, \"summary.json\"), currentSummary);\n console.log(`Eval diff complete. Artifacts: ${outputDir}`);\n return 0;\n }\n\n throw new Error(`Unknown eval subcommand: ${subcommand}`);\n}\n","import * as path from \"path\";\n\nimport type { EvalRunOptions, SweepDefinition } from \"./types.js\";\n\nexport interface ParsedArgs {\n projectRoot: string;\n configPath?: string;\n datasetPath: string;\n currentPath?: string;\n outputRoot: string;\n againstPath?: string;\n budgetPath?: string;\n ciMode: boolean;\n reindex: boolean;\n fusionStrategy?: \"rrf\" | \"weighted\";\n hybridWeight?: number;\n rrfK?: number;\n rerankTopN?: number;\n sweep: SweepDefinition;\n}\n\nexport interface EvalSubcommandOptions {\n parsed: ParsedArgs;\n explicitAgainst?: string;\n}\n\nexport function printUsage(): void {\n console.log(`\nUsage:\n opencode-codebase-index-mcp eval run [options]\n opencode-codebase-index-mcp eval compare --against <summary.json> [options]\n opencode-codebase-index-mcp eval diff --current <summary.json> --against <summary.json> [options]\n\nOptions:\n --project <path> Project root (default: cwd)\n --config <path> Config JSON path\n --dataset <path> Golden dataset path (default: benchmarks/golden/small.json)\n --current <path> Current summary.json path (required for eval diff)\n --output <path> Output root dir (default: benchmarks/results)\n --against <path> Baseline summary.json to compare against\n --budget <path> Budget file for CI mode (default: benchmarks/budgets/default.json)\n --ci Enable CI gate mode\n --reindex Force reindex before eval\n\nSearch overrides:\n --fusionStrategy <rrf|weighted>\n --hybridWeight <0-1>\n --rrfK <number>\n --rerankTopN <number>\n\nSweep options (comma-separated values):\n --sweepFusionStrategy <rrf,weighted>\n --sweepHybridWeight <0.3,0.5,0.7>\n --sweepRrfK <30,60,90>\n --sweepRerankTopN <10,20,40>\n`);\n}\n\nfunction parseNumber(value: string, flag: string): number {\n const parsed = Number(value);\n if (Number.isNaN(parsed)) {\n throw new Error(`${flag} must be a number`);\n }\n return parsed;\n}\n\nfunction parseCsvNumbers(value: string, flag: string): number[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0)\n .map((item) => parseNumber(item, flag));\n}\n\nfunction parseCsvFusion(value: string): Array<\"rrf\" | \"weighted\"> {\n const values = value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n\n const parsed: Array<\"rrf\" | \"weighted\"> = [];\n for (const candidate of values) {\n if (candidate !== \"rrf\" && candidate !== \"weighted\") {\n throw new Error(\"--sweepFusionStrategy accepts only rrf,weighted\");\n }\n parsed.push(candidate);\n }\n return parsed;\n}\n\nexport function hasSweepOptions(sweep: SweepDefinition): boolean {\n return Boolean(\n (sweep.fusionStrategy && sweep.fusionStrategy.length > 0) ||\n (sweep.hybridWeight && sweep.hybridWeight.length > 0) ||\n (sweep.rrfK && sweep.rrfK.length > 0) ||\n (sweep.rerankTopN && sweep.rerankTopN.length > 0)\n );\n}\n\nexport function parseEvalArgs(argv: string[], cwd: string): ParsedArgs {\n const parsed: ParsedArgs = {\n projectRoot: cwd,\n datasetPath: \"benchmarks/golden/small.json\",\n outputRoot: \"benchmarks/results\",\n budgetPath: \"benchmarks/budgets/default.json\",\n ciMode: false,\n reindex: false,\n sweep: {},\n };\n\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n const next = argv[i + 1];\n\n if (arg === \"--project\" && next) {\n parsed.projectRoot = path.resolve(cwd, next);\n i += 1;\n continue;\n }\n if (arg === \"--config\" && next) {\n parsed.configPath = path.resolve(cwd, next);\n i += 1;\n continue;\n }\n if (arg === \"--dataset\" && next) {\n parsed.datasetPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--current\" && next) {\n parsed.currentPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--output\" && next) {\n parsed.outputRoot = next;\n i += 1;\n continue;\n }\n if (arg === \"--against\" && next) {\n parsed.againstPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--budget\" && next) {\n parsed.budgetPath = next;\n i += 1;\n continue;\n }\n if (arg === \"--ci\") {\n parsed.ciMode = true;\n continue;\n }\n if (arg === \"--reindex\") {\n parsed.reindex = true;\n continue;\n }\n if (arg === \"--fusionStrategy\" && next) {\n if (next !== \"rrf\" && next !== \"weighted\") {\n throw new Error(\"--fusionStrategy must be rrf or weighted\");\n }\n parsed.fusionStrategy = next;\n i += 1;\n continue;\n }\n if (arg === \"--hybridWeight\" && next) {\n parsed.hybridWeight = parseNumber(next, \"--hybridWeight\");\n i += 1;\n continue;\n }\n if (arg === \"--rrfK\" && next) {\n parsed.rrfK = parseNumber(next, \"--rrfK\");\n i += 1;\n continue;\n }\n if (arg === \"--rerankTopN\" && next) {\n parsed.rerankTopN = parseNumber(next, \"--rerankTopN\");\n i += 1;\n continue;\n }\n if (arg === \"--sweepFusionStrategy\" && next) {\n parsed.sweep.fusionStrategy = parseCsvFusion(next);\n i += 1;\n continue;\n }\n if (arg === \"--sweepHybridWeight\" && next) {\n parsed.sweep.hybridWeight = parseCsvNumbers(next, \"--sweepHybridWeight\");\n i += 1;\n continue;\n }\n if (arg === \"--sweepRrfK\" && next) {\n parsed.sweep.rrfK = parseCsvNumbers(next, \"--sweepRrfK\");\n i += 1;\n continue;\n }\n if (arg === \"--sweepRerankTopN\" && next) {\n parsed.sweep.rerankTopN = parseCsvNumbers(next, \"--sweepRerankTopN\");\n i += 1;\n continue;\n }\n }\n\n return parsed;\n}\n\nexport function parseEvalSubcommandOptions(argv: string[], cwd: string): EvalSubcommandOptions {\n let explicitAgainst: string | undefined;\n const filtered: string[] = [];\n\n for (let i = 0; i < argv.length; i += 1) {\n const current = argv[i];\n const next = argv[i + 1];\n\n if (current === \"--against\" && next) {\n explicitAgainst = next;\n i += 1;\n continue;\n }\n\n filtered.push(current);\n }\n\n return {\n parsed: parseEvalArgs(filtered, cwd),\n explicitAgainst,\n };\n}\n\nexport function toRunOptions(parsed: ParsedArgs): EvalRunOptions {\n return {\n projectRoot: parsed.projectRoot,\n configPath: parsed.configPath,\n datasetPath: parsed.datasetPath,\n outputRoot: parsed.outputRoot,\n againstPath: parsed.againstPath,\n budgetPath: parsed.budgetPath,\n ciMode: parsed.ciMode,\n reindex: parsed.reindex,\n searchOverrides: {\n ...(parsed.fusionStrategy !== undefined ? { fusionStrategy: parsed.fusionStrategy } : {}),\n ...(parsed.hybridWeight !== undefined ? { hybridWeight: parsed.hybridWeight } : {}),\n ...(parsed.rrfK !== undefined ? { rrfK: parsed.rrfK } : {}),\n ...(parsed.rerankTopN !== undefined ? { rerankTopN: parsed.rerankTopN } : {}),\n },\n };\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport * as path from \"path\";\nimport { existsSync } from \"fs\";\n\nimport { Indexer } from \"./indexer/index.js\";\nimport type { ParsedCodebaseIndexConfig } from \"./config/schema.js\";\nimport { resolveWorktreeMainRepoRoot } from \"./git/index.js\";\nimport { registerMcpPrompts } from \"./mcp-server/register-prompts.js\";\nimport { registerMcpTools } from \"./mcp-server/register-tools.js\";\n\nexport function createMcpServer(projectRoot: string, config: ParsedCodebaseIndexConfig): McpServer {\n const server = new McpServer({\n name: \"opencode-codebase-index\",\n version: \"0.5.1\",\n });\n\n let indexer = new Indexer(projectRoot, config);\n let initialized = false;\n\n function refreshIndexerFromConfig(): void {\n indexer = new Indexer(projectRoot, config);\n initialized = false;\n }\n\n function shouldForceLocalizeProjectIndex(): boolean {\n if (config.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\n async function ensureInitialized(): Promise<void> {\n if (!initialized) {\n await indexer.initialize();\n initialized = true;\n }\n }\n\n registerMcpTools(server, {\n projectRoot,\n ensureInitialized,\n getIndexer: () => indexer,\n refreshIndexerFromConfig,\n shouldForceLocalizeProjectIndex,\n });\n\n registerMcpPrompts(server);\n\n return server;\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nexport function registerMcpPrompts(server: McpServer): void {\n server.prompt(\n \"search\",\n \"Search codebase by meaning using semantic search\",\n { query: z.string().describe(\"What to search for in the codebase\") },\n (args) => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: `Search the codebase for: \"${args.query}\"\\n\\nUse the codebase_search tool with this query. If you need just locations first, use codebase_peek instead to save tokens.`,\n },\n }],\n }),\n );\n\n server.prompt(\n \"find\",\n \"Find code using hybrid approach (semantic + grep)\",\n { query: z.string().describe(\"What to find in the codebase\") },\n (args) => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: `Find code related to: \"${args.query}\"\\n\\nUse a hybrid approach:\\n1. First use codebase_peek to find semantic matches by meaning\\n2. Then use grep for exact identifier matches\\n3. Combine results for comprehensive coverage`,\n },\n }],\n }),\n );\n\n server.prompt(\n \"index\",\n \"Index the codebase for semantic search\",\n { options: z.string().optional().describe(\"Options: 'force' to rebuild, 'estimate' to check costs\") },\n (args) => {\n const opts = args.options?.toLowerCase() ?? \"\";\n let instruction = \"Use the index_codebase tool to index the codebase for semantic search.\";\n if (opts.includes(\"force\")) {\n instruction = \"Use the index_codebase tool with force=true to rebuild the entire index from scratch.\";\n } else if (opts.includes(\"estimate\")) {\n instruction = \"Use the index_codebase tool with estimateOnly=true to check the cost estimate before indexing.\";\n }\n return {\n messages: [{\n role: \"user\",\n content: { type: \"text\", text: instruction },\n }],\n };\n },\n );\n\n server.prompt(\n \"status\",\n \"Check if the codebase is indexed and ready\",\n {},\n () => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: \"Use the index_status tool to check if the codebase index is ready and show its current state.\",\n },\n }],\n }),\n );\n\n server.prompt(\n \"definition\",\n \"Find where a symbol is defined in the codebase\",\n { query: z.string().describe(\"Symbol name or description to find the definition of\") },\n (args) => ({\n messages: [{\n role: \"user\",\n content: {\n type: \"text\",\n text: `Find the definition of: \"${args.query}\"\\n\\nUse the implementation_lookup tool to find where this symbol is defined. This prioritizes real implementation files over tests, docs, and examples. If no definition is found, fall back to codebase_search for broader discovery.`,\n },\n }],\n }),\n );\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport { loadProjectConfigLayer, materializeLocalProjectConfig } from \"../config/merger.js\";\nimport type { LogLevel } from \"../config/schema.js\";\nimport { formatCostEstimate } from \"../utils/cost.js\";\nimport type { LogEntry } from \"../utils/logger.js\";\nimport { formatDefinitionLookup, formatHealthCheck, formatIndexStats, formatStatus } from \"../tools/utils.js\";\nimport { CHUNK_TYPE_ENUM, type McpServerRuntime, truncateContent } from \"./shared.js\";\n\nexport function registerMcpTools(server: McpServer, runtime: McpServerRuntime): void {\n server.tool(\n \"codebase_search\",\n \"Search codebase by MEANING, not keywords. Returns full code content. For just finding WHERE code is (saves ~90% tokens), use codebase_peek instead.\",\n {\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(CHUNK_TYPE_ENUM).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 (args) => {\n await runtime.ensureInitialized();\n const results = await runtime.getIndexer().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 { content: [{ type: \"text\", text: \"No matching code found. Try a different query or run index_codebase first.\" }] };\n }\n\n const formatted = results.map((r, idx) => {\n const header = r.name\n ? `[${idx + 1}] ${r.chunkType} \"${r.name}\" in ${r.filePath}:${r.startLine}-${r.endLine}`\n : `[${idx + 1}] ${r.chunkType} in ${r.filePath}:${r.startLine}-${r.endLine}`;\n return `${header} (score: ${r.score.toFixed(2)})\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return { content: [{ type: \"text\", text: `Found ${results.length} results for \"${args.query}\":\\n\\n${formatted.join(\"\\n\\n\")}` }] };\n },\n );\n\n server.tool(\n \"codebase_peek\",\n \"Quick lookup of code locations by meaning. Returns only metadata (file, line, name, type) WITHOUT code content. Saves ~90% tokens vs codebase_search.\",\n {\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(CHUNK_TYPE_ENUM).optional().describe(\"Filter by code chunk type\"),\n },\n async (args) => {\n await runtime.ensureInitialized();\n const results = await runtime.getIndexer().search(args.query, args.limit ?? 10, {\n fileType: args.fileType,\n directory: args.directory,\n chunkType: args.chunkType,\n metadataOnly: true,\n });\n\n if (results.length === 0) {\n return { content: [{ type: \"text\", text: \"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 { content: [{ type: \"text\", text: `Found ${results.length} locations for \"${args.query}\":\\n\\n${formatted.join(\"\\n\")}\\n\\nUse Read tool to examine specific files.` }] };\n },\n );\n\n server.tool(\n \"index_codebase\",\n \"Index the codebase for semantic search. Creates vector embeddings of code chunks. Incremental - only re-indexes changed files. Run before first codebase_search.\",\n {\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 (args) => {\n if (args.estimateOnly) {\n await runtime.ensureInitialized();\n const estimate = await runtime.getIndexer().estimateCost();\n return { content: [{ type: \"text\", text: formatCostEstimate(estimate) }] };\n }\n\n if (args.force) {\n if (runtime.shouldForceLocalizeProjectIndex()) {\n materializeLocalProjectConfig(runtime.projectRoot, loadProjectConfigLayer(runtime.projectRoot));\n runtime.refreshIndexerFromConfig();\n }\n await runtime.ensureInitialized();\n await runtime.getIndexer().clearIndex();\n runtime.refreshIndexerFromConfig();\n await runtime.ensureInitialized();\n } else {\n await runtime.ensureInitialized();\n }\n\n const stats = await runtime.getIndexer().index();\n return { content: [{ type: \"text\", text: formatIndexStats(stats, args.verbose ?? false) }] };\n },\n );\n\n server.tool(\n \"index_status\",\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 {},\n async () => {\n await runtime.ensureInitialized();\n const status = await runtime.getIndexer().getStatus();\n return { content: [{ type: \"text\", text: formatStatus(status) }] };\n },\n );\n\n server.tool(\n \"index_health_check\",\n \"Check index health and remove stale entries from deleted files. Run this to clean up the index after files have been deleted.\",\n {},\n async () => {\n await runtime.ensureInitialized();\n const result = await runtime.getIndexer().healthCheck();\n return { content: [{ type: \"text\", text: formatHealthCheck(result) }] };\n },\n );\n\n server.tool(\n \"index_metrics\",\n \"Get metrics and performance statistics for the codebase index. Requires debug.enabled=true and debug.metrics=true in config.\",\n {},\n async () => {\n await runtime.ensureInitialized();\n const logger = runtime.getIndexer().getLogger();\n\n if (!logger.isEnabled()) {\n return { content: [{ type: \"text\", text: \"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 { content: [{ type: \"text\", text: \"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 { content: [{ type: \"text\", text: logger.formatMetrics() }] };\n },\n );\n\n server.tool(\n \"index_logs\",\n \"Get recent debug logs from the codebase indexer. Requires debug.enabled=true in config.\",\n {\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 (args) => {\n await runtime.ensureInitialized();\n const logger = runtime.getIndexer().getLogger();\n\n if (!logger.isEnabled()) {\n return { content: [{ type: \"text\", text: \"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 if (logs.length === 0) {\n return { content: [{ type: \"text\", text: \"No logs recorded yet. Logs are captured during indexing and search operations.\" }] };\n }\n\n const text = 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 return { content: [{ type: \"text\", text }] };\n },\n );\n\n server.tool(\n \"find_similar\",\n \"Find code similar to a given snippet. Use for duplicate detection, pattern discovery, or refactoring prep.\",\n {\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(CHUNK_TYPE_ENUM).optional().describe(\"Filter by code chunk type\"),\n excludeFile: z.string().optional().describe(\"Exclude results from this file path\"),\n },\n async (args) => {\n await runtime.ensureInitialized();\n const results = await runtime.getIndexer().findSimilar(args.code, args.limit ?? 10, {\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 { content: [{ type: \"text\", text: \"No similar code found. Try a different snippet or run index_codebase first.\" }] };\n }\n\n const formatted = results.map((r, idx) => {\n const header = r.name\n ? `[${idx + 1}] ${r.chunkType} \"${r.name}\" in ${r.filePath}:${r.startLine}-${r.endLine}`\n : `[${idx + 1}] ${r.chunkType} in ${r.filePath}:${r.startLine}-${r.endLine}`;\n return `${header} (similarity: ${(r.score * 100).toFixed(1)}%)\\n\\`\\`\\`\\n${truncateContent(r.content)}\\n\\`\\`\\``;\n });\n\n return { content: [{ type: \"text\", text: `Found ${results.length} similar code blocks:\\n\\n${formatted.join(\"\\n\\n\")}` }] };\n },\n );\n\n server.tool(\n \"implementation_lookup\",\n \"Jump to symbol definition. Find WHERE something is defined. Returns the authoritative source location(s). Prefers real implementation files over tests, docs, examples, and fixtures.\",\n {\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 (args) => {\n await runtime.ensureInitialized();\n const results = await runtime.getIndexer().search(args.query, args.limit ?? 5, {\n fileType: args.fileType,\n directory: args.directory,\n definitionIntent: true,\n });\n\n return { content: [{ type: \"text\", text: formatDefinitionLookup(results, args.query) }] };\n },\n );\n\n server.tool(\n \"call_graph\",\n \"Query the call graph to find callers or callees of a function/method. Use to understand code flow and dependencies.\",\n {\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)\"),\n },\n async (args) => {\n await runtime.ensureInitialized();\n const indexer = runtime.getIndexer();\n\n if (args.direction === \"callees\") {\n if (!args.symbolId) {\n return { content: [{ type: \"text\", text: \"Error: 'symbolId' is required when direction is 'callees'.\" }] };\n }\n const callees = await indexer.getCallees(args.symbolId);\n if (callees.length === 0) {\n return { content: [{ type: \"text\", text: `No callees found for symbol ${args.symbolId}.` }] };\n }\n const formatted = callees.map((e, i) =>\n `[${i + 1}] → ${e.targetName} (${e.callType}) at line ${e.line}${e.isResolved ? ` [resolved: ${e.toSymbolId}]` : \" [unresolved]\"}`\n );\n return { content: [{ type: \"text\", text: `Callees (${callees.length}):\\n\\n${formatted.join(\"\\n\")}` }] };\n }\n\n const callers = await indexer.getCallers(args.name);\n if (callers.length === 0) {\n return { content: [{ type: \"text\", text: `No callers found for \"${args.name}\".` }] };\n }\n const formatted = callers.map((e, i) =>\n `[${i + 1}] ← from ${e.fromSymbolName ?? \"<unknown>\"} in ${e.fromSymbolFilePath ?? \"<unknown file>\"} [${e.fromSymbolId}] (${e.callType}) at line ${e.line}${e.isResolved ? \" [resolved]\" : \" [unresolved]\"}`\n );\n return { content: [{ type: \"text\", text: `\"${args.name}\" is called by ${callers.length} function(s):\\n\\n${formatted.join(\"\\n\")}` }] };\n },\n );\n}\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 { 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 type { Indexer } from \"../indexer/index.js\";\n\nexport const MAX_CONTENT_LINES = 30;\n\nexport function 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 const CHUNK_TYPE_ENUM = [\n \"function\", \"class\", \"method\", \"interface\", \"type\",\n \"enum\", \"struct\", \"impl\", \"trait\", \"module\", \"other\",\n] as const;\n\nexport interface McpServerRuntime {\n projectRoot: string;\n ensureInitialized(): Promise<void>;\n getIndexer(): Indexer;\n refreshIndexerFromConfig(): void;\n shouldForceLocalizeProjectIndex(): boolean;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,iDAAAA,SAAA;AAAA;AAEA,QAAI,MAAM,OAAO,UAAU;AAA3B,QACI,SAAS;AASb,aAAS,SAAS;AAAA,IAAC;AASnB,QAAI,OAAO,QAAQ;AACjB,aAAO,YAAY,uBAAO,OAAO,IAAI;AAMrC,UAAI,CAAC,IAAI,OAAO,EAAE,UAAW,UAAS;AAAA,IACxC;AAWA,aAAS,GAAG,IAAI,SAAS,MAAM;AAC7B,WAAK,KAAK;AACV,WAAK,UAAU;AACf,WAAK,OAAO,QAAQ;AAAA,IACtB;AAaA,aAAS,YAAY,SAAS,OAAO,IAAI,SAAS,MAAM;AACtD,UAAI,OAAO,OAAO,YAAY;AAC5B,cAAM,IAAI,UAAU,iCAAiC;AAAA,MACvD;AAEA,UAAI,WAAW,IAAI,GAAG,IAAI,WAAW,SAAS,IAAI,GAC9C,MAAM,SAAS,SAAS,QAAQ;AAEpC,UAAI,CAAC,QAAQ,QAAQ,GAAG,EAAG,SAAQ,QAAQ,GAAG,IAA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IAAC,CAAC;AAC7B,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,UAAQ,GAAG,UAAU,QAAQ;AAC7B,UAAQ,GAAG,WAAW,QAAQ;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAmB;AAC/B,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,UAAQ,MAAM,UAAU,OAAO,EAAE;AACjC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["module","EventEmitter","module","path","Ignore","path","path","existsSync","path","performance","existsSync","readFileSync","writeFileSync","mkdirSync","fsPromises","path","performance","resolve","EventEmitter","resolve","reject","resolve","readFileSync","path","existsSync","readFileSync","path","path","ignore","existsSync","readFileSync","path","os","platform","arch","require","estimateTokens","estimateTokens","existsSync","readFileSync","statSync","path","existsSync","readFileSync","path","existsSync","statSync","readFileSync","existsSync","existsSync","os","path","existsSync","existsSync","estimateTokens","existsSync","readFileSync","mkdirSync","writeFileSync","fsPromises","performance","resolve","failedBatch","existsSync","mkdirSync","readFileSync","writeFileSync","os","path","path","isStringArray","readFileSync","existsSync","mkdirSync","writeFileSync","readFileSync","isRecord","isStringArray","path","performance","existsSync","path","path","path","existsSync","z","existsSync","mkdirSync","readFileSync","writeFileSync","os","path","isRecord","isStringArray","existsSync","readFileSync","mkdirSync","writeFileSync","main","lines","MAX_CONTENT_LINES","truncateContent","z","truncateContent","formatted","existsSync"]}
|