@khivi/opencode-codebase-index 0.5.2
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/LICENSE +21 -0
- package/README.md +658 -0
- package/commands/call-graph.md +24 -0
- package/commands/find.md +25 -0
- package/commands/index.md +21 -0
- package/commands/search.md +24 -0
- package/commands/status.md +15 -0
- package/dist/cli.cjs +6208 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.js +6213 -0
- package/dist/cli.js.map +1 -0
- package/dist/git-cli.cjs +6006 -0
- package/dist/git-cli.cjs.map +1 -0
- package/dist/git-cli.js +6011 -0
- package/dist/git-cli.js.map +1 -0
- package/dist/index.cjs +8224 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +8221 -0
- package/dist/index.js.map +1 -0
- package/native/codebase-index-native.darwin-arm64.node +0 -0
- package/package.json +103 -0
- package/skill/SKILL.md +78 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../node_modules/eventemitter3/index.js","../node_modules/ignore/index.js","../src/cli.ts","../src/config/constants.ts","../src/config/schema.ts","../src/mcp-server.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/utils/files.ts","../src/utils/cost.ts","../src/utils/logger.ts","../src/native/index.ts","../src/git/index.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 { existsSync, readFileSync } from \"fs\";\nimport * as path from \"path\";\nimport * as os from \"os\";\n\nimport { parseConfig } from \"./config/schema.js\";\nimport { createMcpServer } from \"./mcp-server.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 loadPluginConfig(projectRoot: string, configPath?: string): unknown {\n if (configPath) {\n const config = loadJsonFile(configPath);\n if (config) return config;\n }\n\n const projectConfig = loadJsonFile(path.join(projectRoot, \".opencode\", \"codebase-index.json\"));\n if (projectConfig) return projectConfig;\n\n const globalConfig = loadJsonFile(path.join(os.homedir(), \".config\", \"opencode\", \"codebase-index.json\"));\n if (globalConfig) return globalConfig;\n\n return {};\n}\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 const args = parseArgs(process.argv);\n const rawConfig = loadPluginConfig(args.project, args.config);\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,swift}\",\n \"**/*.{vue,svelte,astro}\",\n \"**/*.{sql,graphql,proto}\",\n \"**/*.{yaml,yml,toml}\",\n \"**/*.{md,mdx}\",\n \"**/*.{sh,bash,zsh}\",\n];\n\nexport const DEFAULT_EXCLUDE = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/dist/**\",\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\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: 8192,\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\": \"text-embedding-005\",\n \"ollama\": \"nomic-embed-text\",\n} as const\n","// Config schema without zod dependency to avoid version conflicts with OpenCode SDK\n\nimport { DEFAULT_INCLUDE, DEFAULT_EXCLUDE, EMBEDDING_MODELS, DEFAULT_PROVIDER_MODELS } from \"./constants.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 * This prevents accidentally watching/indexing large non-project directories like home.\n * Set to false to allow indexing any directory.\n */\n requireProjectMarker: 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}\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}\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 include: string[];\n exclude: string[];\n}\n\nexport type ParsedCodebaseIndexConfig = CodebaseIndexConfig & {\n indexing: IndexingConfig;\n search: SearchConfig;\n debug: DebugConfig;\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 };\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 };\n}\n\nfunction isValidFusionStrategy(value: unknown): value is SearchConfig[\"fusionStrategy\"] {\n return value === \"weighted\" || value === \"rrf\";\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 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\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 };\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 };\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 let embeddingProvider: EmbeddingProvider | 'custom' | 'auto';\n let embeddingModel: EmbeddingModelName | undefined = undefined;\n let customProvider: CustomProviderConfig | undefined = undefined;\n \n if (input.embeddingProvider === 'custom') {\n embeddingProvider = 'custom';\n const rawCustom = (input.customProvider && typeof input.customProvider === 'object' ? input.customProvider : null) as Record<string, unknown> | null;\n if (rawCustom && typeof rawCustom.baseUrl === 'string' && rawCustom.baseUrl.trim().length > 0 && typeof rawCustom.model === 'string' && rawCustom.model.trim().length > 0 && typeof rawCustom.dimensions === 'number' && Number.isInteger(rawCustom.dimensions) && rawCustom.dimensions > 0) {\n customProvider = {\n baseUrl: rawCustom.baseUrl.trim().replace(/\\/+$/, ''),\n model: rawCustom.model,\n dimensions: rawCustom.dimensions,\n apiKey: typeof rawCustom.apiKey === 'string' ? rawCustom.apiKey : undefined,\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 };\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(input.embeddingProvider)) {\n embeddingProvider = input.embeddingProvider;\n if (input.embeddingModel) {\n embeddingModel = isValidModel(input.embeddingModel, embeddingProvider) ? input.embeddingModel : DEFAULT_PROVIDER_MODELS[embeddingProvider];\n }\n } else {\n embeddingProvider = 'auto';\n }\n\n return {\n embeddingProvider,\n embeddingModel,\n customProvider,\n scope: isValidScope(input.scope) ? input.scope : \"project\",\n include: isStringArray(input.include) ? input.include : DEFAULT_INCLUDE,\n exclude: isStringArray(input.exclude) ? input.exclude : DEFAULT_EXCLUDE,\n indexing,\n search,\n debug,\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 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 { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport { Indexer, type IndexStats } from \"./indexer/index.js\";\nimport type { ParsedCodebaseIndexConfig, LogLevel } from \"./config/schema.js\";\nimport { formatCostEstimate } from \"./utils/cost.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\nfunction formatIndexStats(stats: IndexStats, verbose: boolean = false): string {\n const lines: string[] = [];\n\n if (stats.indexedChunks === 0 && stats.removedChunks === 0) {\n lines.push(`Indexed. ${stats.totalFiles} files processed, ${stats.existingChunks} code chunks already up to date.`);\n } else if (stats.indexedChunks === 0) {\n lines.push(`Indexed. ${stats.totalFiles} files, removed ${stats.removedChunks} stale chunks, ${stats.existingChunks} chunks remain.`);\n } else {\n let main = `Indexed. ${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\nfunction formatStatus(status: {\n indexed: boolean;\n vectorCount: number;\n provider: string;\n model: string;\n indexPath: string;\n currentBranch: string;\n baseBranch: string;\n}): string {\n if (!status.indexed) {\n return \"Codebase is not indexed. Run index_codebase to create an index.\";\n }\n\n const lines = [\n `Index status:`,\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 return lines.join(\"\\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 indexer = new Indexer(projectRoot, config);\n let initialized = false;\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 await ensureInitialized();\n\n if (args.estimateOnly) {\n const estimate = await indexer.estimateCost();\n return { content: [{ type: \"text\", text: formatCostEstimate(estimate) }] };\n }\n\n if (args.force) {\n await indexer.clearIndex();\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\n if (result.removed === 0 && result.gcOrphanEmbeddings === 0 && result.gcOrphanChunks === 0 && result.gcOrphanSymbols === 0 && result.gcOrphanCallEdges === 0) {\n return { content: [{ type: \"text\", text: \"Index is healthy. No stale entries found.\" }] };\n }\n\n const lines = [`Health check complete:`];\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 { content: [{ type: \"text\", text: lines.join(\"\\n\") }] };\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\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 return server;\n}\n","import { existsSync, readFileSync, writeFileSync, renameSync, unlinkSync, 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 } 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 { 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 createEmbeddingText,\n generateChunkId,\n generateChunkHash,\n ChunkMetadata,\n ChunkData,\n createDynamicBatches,\n hashFile,\n hashContent,\n extractCalls,\n} from \"../native/index.js\";\nimport type { SymbolData, CallEdgeData } from \"../native/index.js\";\nimport { getBranchOrDefault, getBaseBranch, isGitRepo } from \"../git/index.js\";\n\nconst CALL_GRAPH_LANGUAGES = new Set([\"typescript\", \"tsx\", \"javascript\", \"jsx\", \"python\", \"go\", \"rust\"]);\nconst 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]);\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\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}\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}\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}\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 text: string;\n content: string;\n contentHash: string;\n metadata: ChunkMetadata;\n}\n\ninterface FailedBatch {\n chunks: PendingChunk[];\n error: string;\n attemptCount: number;\n lastAttempt: string;\n}\n\ntype RankedCandidate = { id: string; score: number; metadata: ChunkMetadata };\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 createdAt: string;\n updatedAt: string;\n}\n\nenum IncompatibilityCode {\n DIMENSION_MISMATCH = \"DIMENSION_MISMATCH\",\n MODEL_MISMATCH = \"MODEL_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 RANKING_TOKEN_CACHE_LIMIT = 4096;\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>>();\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 classifyQueryIntent(tokens: string[]): \"source\" | \"doc_test\" {\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 return sourceIntentHits >= docTestIntentHits ? \"source\" : \"doc_test\";\n}\n\nfunction classifyQueryIntentRaw(query: string): \"source\" | \"doc_test\" {\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) {\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): RankedCandidate[] {\n if (classifyQueryIntentRaw(query) !== \"source\") {\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 intent = classifyQueryIntentRaw(query);\n const docIntent = classifyDocIntent(queryTokenList);\n const preferSourcePaths = options?.prioritizeSourcePaths ?? intent === \"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 tail = candidates.slice(topN);\n return [...head.map((entry) => entry.candidate), ...tail];\n}\n\nexport function rankHybridResults(\n query: string,\n semanticResults: RankedCandidate[],\n keywordResults: RankedCandidate[],\n options: HybridRankOptions\n): RankedCandidate[] {\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 intent = classifyQueryIntentRaw(query);\n return rerankResults(query, rerankPool, options.rerankTopN, {\n prioritizeSourcePaths: intent === \"source\",\n });\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): RankedCandidate[] {\n if (combined.length === 0) {\n return combined;\n }\n\n if (classifyQueryIntentRaw(query) !== \"source\") {\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): RankedCandidate[] {\n if (classifyQueryIntentRaw(query) !== \"source\") {\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): RankedCandidate[] {\n if (classifyQueryIntentRaw(query) !== \"source\") {\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 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 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 if (this.config.scope === \"global\") {\n const homeDir = process.env.HOME || process.env.USERPROFILE || \"\";\n return path.join(homeDir, \".opencode\", \"global-index\");\n }\n return path.join(this.projectRoot, \".opencode\", \"index\");\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 writeFileSync(tempPath, data);\n renameSync(tempPath, targetPath);\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(): FailedBatch[] {\n try {\n if (existsSync(this.failedBatchesPath)) {\n const data = readFileSync(this.failedBatchesPath, \"utf-8\");\n return JSON.parse(data) as FailedBatch[];\n }\n } catch {\n return [];\n }\n return [];\n }\n\n private saveFailedBatches(batches: FailedBatch[]): void {\n if (batches.length === 0) {\n if (existsSync(this.failedBatchesPath)) {\n fsPromises.unlink(this.failedBatchesPath).catch(() => { });\n }\n return;\n }\n writeFileSync(this.failedBatchesPath, JSON.stringify(batches, null, 2));\n }\n\n private addFailedBatch(batch: PendingChunk[], error: string): void {\n const existing = this.loadFailedBatches();\n existing.push({\n chunks: batch,\n error,\n attemptCount: 1,\n lastAttempt: new Date().toISOString(),\n });\n this.saveFailedBatches(existing);\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 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 });\n\n this.provider = createEmbeddingProvider(this.configuredProviderInfo);\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 const dbIsNew = !existsSync(dbPath);\n this.database = new Database(dbPath);\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.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 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 // 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 await this.healthCheck();\n this.database.setMetadata(\"lastGcTimestamp\", now.toString());\n }\n }\n\n private async maybeRunOrphanGc(): Promise<void> {\n if (!this.database) return;\n\n const stats = this.database.getStats();\n if (!stats) return;\n\n const orphanCount = stats.embeddingCount - stats.chunkCount;\n if (orphanCount > this.config.indexing.gcOrphanThreshold) {\n this.database.gcOrphanEmbeddings();\n this.database.gcOrphanChunks();\n this.database.setMetadata(\"lastGcTimestamp\", Date.now().toString());\n }\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.currentBranch || \"default\", 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 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\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 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.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 { files } = await collectFiles(\n this.projectRoot,\n this.config.include,\n this.config.exclude,\n this.config.indexing.maxFileSize\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\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\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 { files, skipped } = await collectFiles(\n this.projectRoot,\n this.config.include,\n this.config.exclude,\n this.config.indexing.maxFileSize\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 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 for (const chunk of parsed.chunks) {\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 text = createEmbeddingText(chunk, parsed.path);\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({ id, text, content: chunk.content, contentHash, metadata });\n fileChunkCount++;\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 const symbolsByName = new Map<string, SymbolData[]>();\n for (const symbol of fileSymbols) {\n const existing = symbolsByName.get(symbol.name) ?? [];\n existing.push(symbol);\n symbolsByName.set(symbol.name, 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 const fileLanguage = parsed.chunks[0]?.language;\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\n for (const edge of edges) {\n const candidates = symbolsByName.get(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 let removedCount = 0;\n for (const [chunkId] of existingChunks) {\n if (!currentChunkIds.has(chunkId)) {\n store.remove(chunkId);\n invertedIndex.removeChunk(chunkId);\n removedCount++;\n }\n }\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(this.currentBranch);\n database.addChunksToBranchBatch(this.currentBranch, Array.from(currentChunkIds));\n database.clearBranchSymbols(this.currentBranch);\n database.addSymbolsToBranchBatch(this.currentBranch, Array.from(allSymbolIds));\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\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(this.currentBranch);\n database.addChunksToBranchBatch(this.currentBranch, Array.from(currentChunkIds));\n database.clearBranchSymbols(this.currentBranch);\n database.addSymbolsToBranchBatch(this.currentBranch, Array.from(allSymbolIds));\n store.save();\n invertedIndex.save();\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\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\n const chunksNeedingEmbedding = pendingChunks.filter((c) => missingHashes.has(c.contentHash));\n const chunksWithExistingEmbedding = pendingChunks.filter((c) => !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 dynamicBatches = createDynamicBatches(chunksNeedingEmbedding);\n let rateLimitBackoffMs = 0;\n\n for (const batch of dynamicBatches) {\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 = batch.map((c) => c.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 items = batch.map((chunk, idx) => ({\n id: chunk.id,\n vector: result.embeddings[idx],\n metadata: chunk.metadata,\n }));\n\n store.addBatch(items);\n\n const embeddingBatchItems = batch.map((chunk, i) => ({\n contentHash: chunk.contentHash,\n embedding: float32ArrayToBuffer(result.embeddings[i]),\n chunkText: chunk.text,\n model: configuredProviderInfo.modelInfo.model,\n }));\n database.upsertEmbeddingsBatch(embeddingBatchItems);\n\n for (const chunk of batch) {\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n }\n\n stats.indexedChunks += batch.length;\n stats.tokensUsed += result.totalTokensUsed;\n\n this.logger.recordChunksEmbedded(batch.length);\n this.logger.recordEmbeddingApiCall(result.totalTokensUsed);\n this.logger.embedding(\"debug\", `Embedded batch`, {\n batchSize: batch.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 stats.failedChunks += batch.length;\n this.addFailedBatch(batch, getErrorMessage(error));\n this.logger.recordEmbeddingError();\n this.logger.embedding(\"error\", `Failed to embed batch after retries`, {\n batchSize: batch.length,\n error: getErrorMessage(error),\n });\n }\n });\n }\n\n await queue.onIdle();\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 database.clearBranch(this.currentBranch);\n database.addChunksToBranchBatch(this.currentBranch, Array.from(currentChunkIds));\n database.clearBranchSymbols(this.currentBranch);\n database.addSymbolsToBranchBatch(this.currentBranch, Array.from(allSymbolIds));\n\n store.save();\n invertedIndex.save();\n this.fileHashCache = currentFileHashes;\n this.saveFileHashCache();\n\n // Auto-GC after indexing: check if orphan count exceeds threshold\n if (this.config.indexing.autoGc && stats.removedChunks > 0) {\n await this.maybeRunOrphanGc();\n }\n\n stats.durationMs = Date.now() - startTime;\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 }\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\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.currentBranch !== \"default\") {\n branchChunkIds = new Set(database.getBranchChunkIds(this.currentBranch));\n }\n\n const prefilterStartTime = performance.now();\n const shouldPrefilterByBranch = branchChunkIds !== null && branchChunkIds.size > 0;\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 = (shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0)\n ? semanticResults\n : prefilteredSemantic;\n const keywordCandidates = (shouldPrefilterByBranch && keywordResults.length > 0 && prefilteredKeyword.length === 0)\n ? keywordResults\n : prefilteredKeyword;\n const prefilterMs = performance.now() - prefilterStartTime;\n\n if (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 (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 (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 });\n const fusionMs = performance.now() - fusionStartTime;\n\n const rescued = promoteIdentifierMatches(\n query,\n combined,\n semanticCandidates,\n keywordCandidates,\n database,\n branchChunkIds\n );\n\n const union = unionCandidates(semanticCandidates, keywordCandidates);\n\n const deterministicIdentifierLane = buildDeterministicIdentifierPass(\n query,\n union,\n maxResults\n );\n\n const identifierLane = buildIdentifierDefinitionLane(\n query,\n union,\n maxResults\n );\n\n const symbolLane = buildSymbolDefinitionLane(\n query,\n database,\n branchChunkIds,\n maxResults,\n union\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 sourceIntent = classifyQueryIntentRaw(query) === \"source\";\n const hasCodeHints = extractCodeTermHints(query).length > 0 || extractIdentifierHints(query).length > 0;\n\n const baseFiltered = tiered.filter((r) => {\n if (r.score < this.config.search.minScore) return false;\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 });\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 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: filtered.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 filtered.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 } = await this.ensureInitialized();\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 };\n }\n\n async clearIndex(): Promise<void> {\n const { store, invertedIndex, database } = await this.ensureInitialized();\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 branch catalog\n database.clearBranch(this.currentBranch);\n database.clearBranchSymbols(this.currentBranch);\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.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 let removedCount = 0;\n\n for (const [filePath, chunkKeys] of filePathsToChunkKeys) {\n if (!existsSync(filePath)) {\n for (const key of chunkKeys) {\n store.remove(key);\n invertedIndex.removeChunk(key);\n removedCount++;\n }\n database.deleteChunksByFile(filePath);\n database.deleteCallEdgesByFile(filePath);\n database.deleteSymbolsByFile(filePath);\n removedFilePaths.push(filePath);\n }\n }\n\n if (removedCount > 0) {\n store.save();\n invertedIndex.save();\n }\n\n const gcOrphanEmbeddings = database.gcOrphanEmbeddings();\n const gcOrphanChunks = database.gcOrphanChunks();\n const gcOrphanSymbols = database.gcOrphanSymbols();\n const gcOrphanCallEdges = database.gcOrphanCallEdges();\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 } = await this.ensureInitialized();\n\n const failedBatches = this.loadFailedBatches();\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 try {\n const result = await pRetry(\n async () => {\n const texts = batch.chunks.map((c) => c.text);\n return provider.embedBatch(texts);\n },\n {\n retries: this.config.indexing.retries,\n minTimeout: this.config.indexing.retryDelayMs,\n }\n );\n\n const items = batch.chunks.map((chunk, idx) => ({\n id: chunk.id,\n vector: result.embeddings[idx],\n metadata: chunk.metadata,\n }));\n\n store.addBatch(items);\n\n for (const chunk of batch.chunks) {\n invertedIndex.removeChunk(chunk.id);\n invertedIndex.addChunk(chunk.id, chunk.content);\n }\n\n this.logger.recordChunksEmbedded(batch.chunks.length);\n this.logger.recordEmbeddingApiCall(result.totalTokensUsed);\n\n succeeded += batch.chunks.length;\n } catch (error) {\n failed += batch.chunks.length;\n this.logger.recordEmbeddingError();\n stillFailing.push({\n ...batch,\n attemptCount: batch.attemptCount + 1,\n lastAttempt: new Date().toISOString(),\n error: String(error),\n });\n }\n }\n\n this.saveFailedBatches(stillFailing);\n\n if (succeeded > 0) {\n store.save();\n invertedIndex.save();\n }\n\n return { succeeded, failed, remaining: stillFailing.length };\n }\n\n getFailedBatchesCount(): number {\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.currentBranch !== \"default\") {\n branchChunkIds = new Set(database.getBranchChunkIds(this.currentBranch));\n }\n\n const prefilterStartTime = performance.now();\n const shouldPrefilterByBranch = branchChunkIds !== null && branchChunkIds.size > 0;\n const prefilteredSemantic = shouldPrefilterByBranch && branchChunkIds\n ? semanticResults.filter((r) => branchChunkIds.has(r.id))\n : semanticResults;\n const semanticCandidates = (shouldPrefilterByBranch && semanticResults.length > 0 && prefilteredSemantic.length === 0)\n ? semanticResults\n : prefilteredSemantic;\n const prefilterMs = performance.now() - prefilterStartTime;\n\n if (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 (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 return database.getCallersWithContext(targetName, this.currentBranch);\n }\n\n async getCallees(symbolId: string): Promise<CallEdgeData[]> {\n const { database } = await this.ensureInitialized();\n return database.getCallees(symbolId, this.currentBranch);\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 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 /**\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 this.#queue.enqueue(async () => {\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 }, options);\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 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'Failed to fetch', // 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// 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, availableProviders, 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}\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 availableProviders) {\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: ${availableProviders.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 },\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 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 async embedBatch(texts: string[]): Promise<EmbeddingBatchResult> {\n const results = await Promise.all(\n texts.map(async (text) => {\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 }),\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: Math.ceil(text.length / 4),\n };\n })\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 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 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 getModelInfo(): CustomModelInfo {\n return this.modelInfo;\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 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 (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 let regexPattern = pattern\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 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): AsyncGenerator<{ path: string; size: number }> {\n const entries = await fsPromises.readdir(dir, { withFileTypes: true });\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 (ignoreFilter.ignores(relativePath)) {\n if (entry.isFile()) {\n skipped.push({ path: relativePath, reason: \"gitignore\" });\n }\n continue;\n }\n\n if (entry.isDirectory()) {\n yield* walkDirectory(\n fullPath,\n projectRoot,\n includePatterns,\n excludePatterns,\n ignoreFilter,\n maxFileSize,\n skipped\n );\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 yield { path: fullPath, size: stat.size };\n }\n }\n }\n}\n\nexport async function collectFiles(\n projectRoot: string,\n includePatterns: string[],\n excludePatterns: string[],\n maxFileSize: number\n): Promise<CollectFilesResult> {\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 )) {\n files.push(file);\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 lines.push(\"=== Metrics ===\");\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 { 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 \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 } \n // Fallback to __dirname for CJS/bundled contexts\n else if (typeof __dirname !== 'undefined') {\n currentDir = __dirname;\n }\n // Last resort: use process.cwd() - shouldn't normally hit this\n else {\n currentDir = process.cwd();\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 isDevMode = currentDir.includes('/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 // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require(nativePath);\n}\n\nconst native = getNativeBinding();\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 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; // Truncate individual chunks beyond this\n\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nexport function createEmbeddingText(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 parts.push(\"\");\n \n let content = chunk.content;\n const headerLength = parts.join(\"\\n\").length;\n const maxContentChars = (MAX_SINGLE_CHUNK_TOKENS * CHARS_PER_TOKEN) - headerLength;\n \n if (content.length > maxContentChars) {\n content = content.slice(0, maxContentChars) + \"\\n... [truncated]\";\n }\n \n parts.push(content);\n\n return parts.join(\"\\n\");\n}\n\nexport function createDynamicBatches<T extends { text: string }>(chunks: T[]): T[][] {\n const batches: T[][] = [];\n let currentBatch: T[] = [];\n let currentTokens = 0;\n \n for (const chunk of chunks) {\n const chunkTokens = estimateTokens(chunk.text);\n \n if (currentBatch.length > 0 && currentTokens + chunkTokens > MAX_BATCH_TOKENS) {\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 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\n constructor(dbPath: string) {\n this.inner = new native.Database(dbPath);\n }\n\n embeddingExists(contentHash: string): boolean {\n return this.inner.embeddingExists(contentHash);\n }\n\n getEmbedding(contentHash: string): Buffer | null {\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.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 if (items.length === 0) return;\n this.inner.upsertEmbeddingsBatch(items);\n }\n\n getMissingEmbeddings(contentHashes: string[]): string[] {\n return this.inner.getMissingEmbeddings(contentHashes);\n }\n\n upsertChunk(chunk: ChunkData): void {\n this.inner.upsertChunk(chunk);\n }\n\n upsertChunksBatch(chunks: ChunkData[]): void {\n if (chunks.length === 0) return;\n this.inner.upsertChunksBatch(chunks);\n }\n\n getChunk(chunkId: string): ChunkData | null {\n return this.inner.getChunk(chunkId) ?? null;\n }\n\n getChunksByFile(filePath: string): ChunkData[] {\n return this.inner.getChunksByFile(filePath);\n }\n\n getChunksByName(name: string): ChunkData[] {\n return this.inner.getChunksByName(name);\n }\n\n getChunksByNameCi(name: string): ChunkData[] {\n return this.inner.getChunksByNameCi(name);\n }\n\n deleteChunksByFile(filePath: string): number {\n return this.inner.deleteChunksByFile(filePath);\n }\n\n addChunksToBranch(branch: string, chunkIds: string[]): void {\n this.inner.addChunksToBranch(branch, chunkIds);\n }\n\n addChunksToBranchBatch(branch: string, chunkIds: string[]): void {\n if (chunkIds.length === 0) return;\n this.inner.addChunksToBranchBatch(branch, chunkIds);\n }\n\n clearBranch(branch: string): number {\n return this.inner.clearBranch(branch);\n }\n\n getBranchChunkIds(branch: string): string[] {\n return this.inner.getBranchChunkIds(branch);\n }\n\n getBranchDelta(branch: string, baseBranch: string): BranchDelta {\n return this.inner.getBranchDelta(branch, baseBranch);\n }\n\n chunkExistsOnBranch(branch: string, chunkId: string): boolean {\n return this.inner.chunkExistsOnBranch(branch, chunkId);\n }\n\n getAllBranches(): string[] {\n return this.inner.getAllBranches();\n }\n\n getMetadata(key: string): string | null {\n return this.inner.getMetadata(key) ?? null;\n }\n\n setMetadata(key: string, value: string): void {\n this.inner.setMetadata(key, value);\n }\n\n deleteMetadata(key: string): boolean {\n return this.inner.deleteMetadata(key);\n }\n\n gcOrphanEmbeddings(): number {\n return this.inner.gcOrphanEmbeddings();\n }\n\n gcOrphanChunks(): number {\n return this.inner.gcOrphanChunks();\n }\n\n getStats(): DatabaseStats {\n return this.inner.getStats();\n }\n\n // ── Symbol methods ──────────────────────────────────────────────\n\n upsertSymbol(symbol: SymbolData): void {\n this.inner.upsertSymbol(symbol);\n }\n\n upsertSymbolsBatch(symbols: SymbolData[]): void {\n if (symbols.length === 0) return;\n this.inner.upsertSymbolsBatch(symbols);\n }\n\n getSymbolsByFile(filePath: string): SymbolData[] {\n return this.inner.getSymbolsByFile(filePath);\n }\n\n getSymbolByName(name: string, filePath: string): SymbolData | null {\n return this.inner.getSymbolByName(name, filePath) ?? null;\n }\n\n getSymbolsByName(name: string): SymbolData[] {\n return this.inner.getSymbolsByName(name);\n }\n\n getSymbolsByNameCi(name: string): SymbolData[] {\n return this.inner.getSymbolsByNameCi(name);\n }\n\n deleteSymbolsByFile(filePath: string): number {\n return this.inner.deleteSymbolsByFile(filePath);\n }\n\n // ── Call Edge methods ────────────────────────────────────────────\n\n upsertCallEdge(edge: CallEdgeData): void {\n this.inner.upsertCallEdge(edge);\n }\n\n upsertCallEdgesBatch(edges: CallEdgeData[]): void {\n if (edges.length === 0) return;\n this.inner.upsertCallEdgesBatch(edges);\n }\n\n getCallers(targetName: string, branch: string): CallEdgeData[] {\n return this.inner.getCallers(targetName, branch);\n }\n\n getCallersWithContext(targetName: string, branch: string): CallEdgeData[] {\n return this.inner.getCallersWithContext(targetName, branch);\n }\n\n getCallees(symbolId: string, branch: string): CallEdgeData[] {\n return this.inner.getCallees(symbolId, branch);\n }\n\n deleteCallEdgesByFile(filePath: string): number {\n return this.inner.deleteCallEdgesByFile(filePath);\n }\n\n resolveCallEdge(edgeId: string, toSymbolId: string): void {\n this.inner.resolveCallEdge(edgeId, toSymbolId);\n }\n\n // ── Branch Symbol methods ────────────────────────────────────────\n\n addSymbolsToBranch(branch: string, symbolIds: string[]): void {\n this.inner.addSymbolsToBranch(branch, symbolIds);\n }\n\n addSymbolsToBranchBatch(branch: string, symbolIds: string[]): void {\n if (symbolIds.length === 0) return;\n this.inner.addSymbolsToBranchBatch(branch, symbolIds);\n }\n\n getBranchSymbolIds(branch: string): string[] {\n return this.inner.getBranchSymbolIds(branch);\n }\n\n clearBranchSymbols(branch: string): number {\n return this.inner.clearBranchSymbols(branch);\n }\n\n // ── GC methods for symbols/edges ─────────────────────────────────\n\n gcOrphanSymbols(): number {\n return this.inner.gcOrphanSymbols();\n }\n\n gcOrphanCallEdges(): number {\n return this.inner.gcOrphanCallEdges();\n }\n}\n","import { existsSync, readFileSync, readdirSync, statSync } from \"fs\";\nimport * as path from \"path\";\nimport { execSync } from \"child_process\";\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 try {\n const result = execSync(\"git rev-parse HEAD\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n return result.trim();\n } catch {\n return null;\n }\n}\n\nexport function getBaseBranch(repoRoot: string): string {\n const gitDir = resolveGitDir(repoRoot);\n const candidates = [\"main\", \"master\", \"develop\", \"trunk\"];\n \n if (gitDir) {\n for (const candidate of candidates) {\n const refPath = path.join(gitDir, \"refs\", \"heads\", candidate);\n if (existsSync(refPath)) {\n return candidate;\n }\n \n const packedRefsPath = path.join(gitDir, \"packed-refs\");\n if (existsSync(packedRefsPath)) {\n try {\n const content = readFileSync(packedRefsPath, \"utf-8\");\n if (content.includes(`refs/heads/${candidate}`)) {\n return candidate;\n }\n } catch {\n // Ignore\n }\n }\n }\n }\n\n try {\n const result = execSync(\"git remote show origin\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n const match = result.match(/HEAD branch: (.+)/);\n if (match) {\n return match[1].trim();\n }\n } catch {\n // Ignore - remote might not exist\n }\n\n return getCurrentBranch(repoRoot) ?? \"main\";\n}\n\nexport function getAllBranches(repoRoot: string): string[] {\n const branches: string[] = [];\n const gitDir = resolveGitDir(repoRoot);\n \n if (!gitDir) {\n return branches;\n }\n \n const refsPath = path.join(gitDir, \"refs\", \"heads\");\n \n if (!existsSync(refsPath)) {\n return branches;\n }\n\n try {\n const result = execSync(\"git branch --list\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n \n for (const line of result.split(\"\\n\")) {\n const branch = line.replace(/^\\*?\\s+/, \"\").trim();\n if (branch) {\n branches.push(branch);\n }\n }\n } catch {\n try {\n const entries = readdirSync(refsPath);\n for (const entry of entries) {\n const stat = statSync(path.join(refsPath, entry));\n if (stat.isFile()) {\n branches.push(entry);\n }\n }\n } catch {\n // Ignore\n }\n }\n\n return branches;\n}\n\nexport function getChangedFiles(\n repoRoot: string,\n fromCommit: string,\n toCommit: string = \"HEAD\"\n): string[] {\n try {\n const result = execSync(`git diff --name-only ${fromCommit} ${toCommit}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n \n return result\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n } catch {\n return [];\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;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,IAAI,UAAU,QAAQ;AAAA,eAC3D,CAAC,QAAQ,QAAQ,GAAG,EAAE,GAAI,SAAQ,QAAQ,GAAG,EAAE,KAAK,QAAQ;AAAA,UAChE,SAAQ,QAAQ,GAAG,IAAI,CAAC,QAAQ,QAAQ,GAAG,GAAG,QAAQ;AAE3D,aAAO;AAAA,IACT;AASA,aAAS,WAAW,SAAS,KAAK;AAChC,UAAI,EAAE,QAAQ,iBAAiB,EAAG,SAAQ,UAAU,IAAI,OAAO;AAAA,UAC1D,QAAO,QAAQ,QAAQ,GAAG;AAAA,IACjC;AASA,aAASA,gBAAe;AACt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,KAAK,SAAS,MAAM;AACnD,QAAM,YAAY,IAAI,qBAAqB;AAE3C,QAAM,OAAO,QAAQ,SAAS;AAE9B,QAAM,WAAW,MAAY;AAC3B,WAAO,MAAM,EAAE,MAAM,MAAM;AAAA,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":["EventEmitter","path","Ignore","existsSync","readFileSync","path","os","existsSync","readFileSync","fsPromises","path","performance","resolve","EventEmitter","resolve","reject","resolve","existsSync","readFileSync","path","ignore","existsSync","readFileSync","path","os","platform","arch","existsSync","readFileSync","path","existsSync","readFileSync","existsSync","readFileSync","fsPromises","performance","resolve","main","formatted","existsSync","readFileSync"]}
|