codeorbit 0.9.4 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +392 -3166
- package/dist/cli.js.map +1 -1
- package/dist/index.js +10 -2
- package/dist/index.js.map +1 -1
- package/dist/server.js +10 -2
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/commander/lib/error.js","../node_modules/commander/lib/argument.js","../node_modules/commander/lib/help.js","../node_modules/commander/lib/option.js","../node_modules/commander/lib/suggestSimilar.js","../node_modules/commander/lib/command.js","../node_modules/commander/index.js","../src/adapters/cli/cli.ts","../node_modules/commander/esm.mjs","../src/infrastructure/SqliteGraphRepository.ts","../src/infrastructure/TreeSitterParser.ts","../src/infrastructure/FileSystemHelper.ts","../src/infrastructure/GitRunner.ts","../src/usecases/buildGraph.ts","../src/infrastructure/watch.ts","../src/adapters/mcp/server.ts","../src/adapters/mcp/tools.ts","../src/infrastructure/SqliteEmbeddingStore.ts","../src/infrastructure/LocalEmbeddingProvider.ts","../src/infrastructure/GoogleEmbeddingProvider.ts","../src/usecases/getImpactRadius.ts","../src/usecases/queryGraph.ts","../src/usecases/getReviewContext.ts","../src/usecases/semanticSearch.ts","../src/usecases/listStats.ts","../src/usecases/embedGraph.ts","../src/usecases/getDocsSection.ts","../src/usecases/findLargeFunctions.ts"],"sourcesContent":["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.length > 3 && this._name.slice(-3) === '...') {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n","const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(max, helper.subcommandTerm(command).length);\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(max, helper.argumentTerm(argument).length);\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n return `${option.description} (${extraInfo.join(', ')})`;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescripton = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescripton}`;\n }\n return extraDescripton;\n }\n return argument.description;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth || 80;\n const itemIndentWidth = 2;\n const itemSeparatorWidth = 2; // between term and description\n function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(\n fullText,\n helpWidth - itemIndentWidth,\n termWidth + itemSeparatorWidth,\n );\n }\n return term;\n }\n function formatList(textArray) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n }\n\n // Usage\n let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.wrap(commandDescription, helpWidth, 0),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(\n helper.argumentTerm(argument),\n helper.argumentDescription(argument),\n );\n });\n if (argumentList.length > 0) {\n output = output.concat(['Arguments:', formatList(argumentList), '']);\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (optionList.length > 0) {\n output = output.concat(['Options:', formatList(optionList), '']);\n }\n\n if (this.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (globalOptionList.length > 0) {\n output = output.concat([\n 'Global Options:',\n formatList(globalOptionList),\n '',\n ]);\n }\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((cmd) => {\n return formatItem(\n helper.subcommandTerm(cmd),\n helper.subcommandDescription(cmd),\n );\n });\n if (commandList.length > 0) {\n output = output.concat(['Commands:', formatList(commandList), '']);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Wrap the given string to width characters per line, with lines after the first indented.\n * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n *\n * @param {string} str\n * @param {number} width\n * @param {number} indent\n * @param {number} [minColumnWidth=40]\n * @return {string}\n *\n */\n\n wrap(str, width, indent, minColumnWidth = 40) {\n // Full \\s characters, minus the linefeeds.\n const indents =\n ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n if (str.match(manualIndent)) return str;\n // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n const columnWidth = width - indent;\n if (columnWidth < minColumnWidth) return str;\n\n const leadingStr = str.slice(0, indent);\n const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n const indentString = ' '.repeat(indent);\n const zeroWidthSpace = '\\u200B';\n const breaks = `\\\\s${zeroWidthSpace}`;\n // Match line end (so empty lines don't collapse),\n // or as much text as will fit in column, or excess text up to first break.\n const regex = new RegExp(\n `\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,\n 'g',\n );\n const lines = columnText.match(regex) || [];\n return (\n leadingStr +\n lines\n .map((line, i) => {\n if (line === '\\n') return ''; // preserve empty lines\n return (i > 0 ? indentString : '') + line.trimEnd();\n })\n .join('\\n')\n );\n }\n}\n\nexports.Help = Help;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag;\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // Use original very loose parsing to maintain backwards compatibility for now,\n // which allowed for example unintended `-sw, --short-word` [sic].\n const flagParts = flags.split(/[ |,]+/);\n if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))\n shortFlag = flagParts.shift();\n longFlag = flagParts.shift();\n // Add support for lone short flag without significantly changing parsing!\n if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n shortFlag = longFlag;\n longFlag = undefined;\n }\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n","const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = true;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n\n // see .configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n outputError: (str, write) => write(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n Object.assign(this._outputConfiguration, configuration);\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [fn] - custom argument processing function\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, fn, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof fn === 'function') {\n argument.default(defaultValue).argParser(fn);\n } else {\n argument.default(fn);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument && previousArgument.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n return this;\n }\n\n enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._concatValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch (err) {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise && promise.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent && this.parent.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} argv\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(argv) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n const args = argv.slice();\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n // parse options\n let activeVariadicOption = null;\n while (args.length) {\n const arg = args.shift();\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args);\n break;\n }\n\n if (activeVariadicOption && !maybeOption(arg)) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args.shift();\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (args.length > 0 && !maybeOption(args[0])) {\n value = args.shift();\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option, emit and put back remainder of arg for further processing\n this.emit(`option:${option.name()}`);\n args.unshift(`-${arg.slice(2)}`);\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n if (maybeOption(arg)) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg);\n if (args.length > 0) operands.push(...args);\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg);\n if (args.length > 0) dest.push(...args);\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n if (helper.helpWidth === undefined) {\n helper.helpWidth =\n contextOptions && contextOptions.error\n ? this._outputConfiguration.getErrHelpWidth()\n : this._outputConfiguration.getOutHelpWidth();\n }\n return helper.formatHelp(this, helper);\n }\n\n /**\n * @private\n */\n\n _getHelpContext(contextOptions) {\n contextOptions = contextOptions || {};\n const context = { error: !!contextOptions.error };\n let write;\n if (context.error) {\n write = (arg) => this._outputConfiguration.writeErr(arg);\n } else {\n write = (arg) => this._outputConfiguration.writeOut(arg);\n }\n context.write = contextOptions.write || write;\n context.command = this;\n return context;\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n const context = this._getHelpContext(contextOptions);\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', context));\n this.emit('beforeHelp', context);\n\n let helpInformation = this.helpInformation(context);\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n context.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', context);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', context),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n this._helpOption = this._helpOption ?? undefined; // preserve existing option\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n flags = flags ?? '-h, --help';\n description = description ?? 'display help for command';\n this._helpOption = this.createOption(flags, description);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = process.exitCode || 0;\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\nexports.Command = Command;\n","const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n","#!/usr/bin/env node\n/**\n * CLI entry point for codeorbit.\n *\n * Usage:\n * codeorbit install\n * codeorbit init\n * codeorbit build [--repo PATH]\n * codeorbit update [--base REF] [--repo PATH]\n * codeorbit watch [--repo PATH]\n * codeorbit status [--repo PATH]\n * codeorbit visualize [--repo PATH]\n * codeorbit serve [--repo PATH]\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { SqliteGraphRepository } from '../../infrastructure/SqliteGraphRepository.js'\nimport { TreeSitterParser } from '../../infrastructure/TreeSitterParser.js'\nimport {\n findProjectRoot,\n findRepoRoot,\n getDbPath,\n} from '../../infrastructure/FileSystemHelper.js'\nimport { fullBuild, incrementalUpdate } from '../../usecases/buildGraph.js'\nimport { watch } from '../../infrastructure/watch.js'\nimport { runMcpServer } from '../mcp/server.js'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction getVersion(): string {\n try {\n const req = createRequire(import.meta.url)\n const pkg = req('../package.json') as { version: string }\n return pkg.version\n } catch {\n return 'dev'\n }\n}\n\nfunction supportsColor(): boolean {\n if (process.env['NO_COLOR']) {\n return false\n }\n return Boolean(process.stdout.isTTY)\n}\n\nfunction printBanner(): void {\n const color = supportsColor()\n const c = color ? '\\x1b[36m' : '' // cyan — graph art\n const y = color ? '\\x1b[33m' : '' // yellow — center node\n const b = color ? '\\x1b[1m' : '' // bold\n const d = color ? '\\x1b[2m' : '' // dim\n const g = color ? '\\x1b[32m' : '' // green — commands\n const r = color ? '\\x1b[0m' : '' // reset\n\n const version = getVersion()\n console.log(`\n${c} ●──●──●${r}\n${c} │╲ │ ╱│${r} ${b}codeorbit${r} ${d}v${version}${r}\n${c} ●──${y}◆${c}──●${r}\n${c} │╱ │ ╲│${r} ${d}Structural knowledge graph for${r}\n${c} ●──●──●${r} ${d}smarter code reviews${r}\n\n ${b}Commands:${r}\n ${g}install${r} Set up Claude Code integration\n ${g}init${r} Alias for install\n ${g}build${r} Full graph build ${d}(parse all files)${r}\n ${g}update${r} Incremental update ${d}(changed files only)${r}\n ${g}watch${r} Auto-update on file changes\n ${g}status${r} Show graph statistics\n ${g}visualize${r} Generate interactive HTML graph\n ${g}serve${r} Start MCP server\n\n ${d}Run${r} ${b}codeorbit <command> --help${r} ${d}for details${r}\n`)\n}\n\n// ---------------------------------------------------------------------------\n// install / init\n// ---------------------------------------------------------------------------\n\nfunction handleInit(repoArg: string | undefined, dryRun: boolean): void {\n const repoRoot = repoArg\n ? path.resolve(repoArg)\n : (findRepoRoot() ?? process.cwd())\n\n const mcpPath = path.join(repoRoot, '.mcp.json')\n\n const newEntry = {\n command: 'npx',\n args: ['codeorbit', 'serve'],\n }\n\n let mcpConfig: Record<string, unknown> = {\n mcpServers: { codeorbit: newEntry },\n }\n\n // Merge into existing .mcp.json if present\n if (fs.existsSync(mcpPath)) {\n try {\n const existing = JSON.parse(fs.readFileSync(mcpPath, 'utf-8')) as Record<\n string,\n unknown\n >\n const servers = existing['mcpServers'] as\n | Record<string, unknown>\n | undefined\n if (servers && 'codeorbit' in servers) {\n console.log(`Already configured in ${mcpPath}`)\n return\n }\n if (!existing['mcpServers']) {\n existing['mcpServers'] = {}\n }\n ;(existing['mcpServers'] as Record<string, unknown>)['codeorbit'] =\n newEntry\n mcpConfig = existing\n } catch {\n console.log(`Warning: existing ${mcpPath} has invalid JSON, overwriting.`)\n }\n }\n\n if (dryRun) {\n console.log(`[dry-run] Would write to ${mcpPath}:`)\n console.log(JSON.stringify(mcpConfig, null, 2))\n console.log()\n console.log('[dry-run] No files were modified.')\n return\n }\n\n fs.writeFileSync(mcpPath, JSON.stringify(mcpConfig, null, 2) + '\\n')\n console.log(`Created ${mcpPath}`)\n console.log()\n console.log('Next steps:')\n console.log(' 1. codeorbit build # build the knowledge graph')\n console.log(' 2. Restart Claude Code # to pick up the new MCP server')\n}\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\nconst program = new Command()\n\nprogram\n .name('codeorbit')\n .description('Persistent incremental knowledge graph for code reviews')\n .version(getVersion(), '-v, --version')\n .action(() => {\n printBanner()\n })\n\n// install\nprogram\n .command('install')\n .description('Register MCP server with Claude Code (creates .mcp.json)')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .option('--dry-run', 'Show what would be done without writing files', false)\n .action((opts: { repo?: string; dryRun: boolean }) => {\n handleInit(opts.repo, opts.dryRun)\n })\n\n// init (alias for install)\nprogram\n .command('init')\n .description('Alias for install')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .option('--dry-run', 'Show what would be done without writing files', false)\n .action((opts: { repo?: string; dryRun: boolean }) => {\n handleInit(opts.repo, opts.dryRun)\n })\n\n// build\nprogram\n .command('build')\n .description('Full graph build (re-parse all files)')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n const parser = new TreeSitterParser()\n try {\n const result = fullBuild(repoRoot, repo, parser)\n console.log(\n `Full build: ${result.filesUpdated} files, ` +\n `${result.totalNodes} nodes, ${result.totalEdges} edges`,\n )\n if (result.errors.length > 0) {\n console.log(`Errors: ${result.errors.length}`)\n for (const e of result.errors) {\n console.error(` ${e}`)\n }\n }\n } finally {\n repo.close()\n }\n })\n\n// update\nprogram\n .command('update')\n .description('Incremental update (only changed files)')\n .option('--base <ref>', 'Git diff base', 'HEAD~1')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { base: string; repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findRepoRoot()\n if (!repoRoot) {\n console.error(\n \"Not in a git repository. 'update' requires git for diffing.\",\n )\n console.error(\"Use 'build' for a full parse, or run 'git init' first.\")\n process.exit(1)\n }\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n const parser = new TreeSitterParser()\n try {\n const result = incrementalUpdate(repoRoot, repo, parser, opts.base)\n console.log(\n `Incremental: ${result.filesUpdated} files updated, ` +\n `${result.totalNodes} nodes, ${result.totalEdges} edges`,\n )\n if (result.errors.length > 0) {\n console.log(`Errors: ${result.errors.length}`)\n for (const e of result.errors) {\n console.error(` ${e}`)\n }\n }\n } finally {\n repo.close()\n }\n })\n\n// watch\nprogram\n .command('watch')\n .description('Watch for changes and auto-update')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action(async (opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n const parser = new TreeSitterParser()\n await watch(repoRoot, repo, parser)\n repo.close()\n })\n\n// status\nprogram\n .command('status')\n .description('Show graph statistics')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n try {\n const stats = repo.getStats()\n console.log(`codeorbit v${getVersion()}`)\n console.log(`Repo: ${repoRoot}`)\n console.log(`DB: ${dbPath}`)\n console.log(`Nodes: ${stats.totalNodes}`)\n console.log(`Edges: ${stats.totalEdges}`)\n console.log(`Files: ${stats.filesCount}`)\n console.log(`Languages: ${stats.languages.join(', ')}`)\n console.log(`Last updated: ${stats.lastUpdated ?? 'never'}`)\n } finally {\n repo.close()\n }\n })\n\n// visualize\nprogram\n .command('visualize')\n .description('Generate interactive HTML graph visualization')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const htmlPath = path.join(repoRoot, '.codeorbit', 'graph.html')\n console.log('Visualization not yet implemented in the TypeScript port.')\n console.log(`Would write to: ${htmlPath}`)\n console.log(\n 'Visualization is not yet implemented. Coming in a future release.',\n )\n process.exit(1)\n })\n\n// serve\nprogram\n .command('serve')\n .description('Start MCP server (stdio transport)')\n .action(async () => {\n await runMcpServer()\n })\n\nprogram.parse()\n","import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n","/**\n * SQLite-backed knowledge graph storage — infrastructure implementation.\n *\n * Implements IGraphRepository. Pure CRUD + adjacency — no business logic.\n * BFS impact-radius computation was extracted to usecases/getImpactRadius.ts.\n *\n * Direct port of code_review_graph/graph.py.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport Database from 'better-sqlite3';\nimport type {\n NodeInfo,\n EdgeInfo,\n GraphNode,\n GraphEdge,\n GraphStats,\n NodeRow,\n EdgeRow,\n CountRow,\n KindCountRow,\n LanguageRow,\n FilePathRow,\n MetadataRow,\n EdgeKind,\n} from '../domain/types.js';\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js';\n\n// ---------------------------------------------------------------------------\n// Schema DDL — must match Python's _SCHEMA_SQL exactly (schema_version = 1)\n// ---------------------------------------------------------------------------\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS nodes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL UNIQUE,\n file_path TEXT NOT NULL,\n line_start INTEGER,\n line_end INTEGER,\n language TEXT,\n parent_name TEXT,\n params TEXT,\n return_type TEXT,\n modifiers TEXT,\n is_test INTEGER DEFAULT 0,\n file_hash TEXT,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n source_qualified TEXT NOT NULL,\n target_qualified TEXT NOT NULL,\n file_path TEXT NOT NULL,\n line INTEGER DEFAULT 0,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(file_path);\nCREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind);\nCREATE INDEX IF NOT EXISTS idx_nodes_qualified ON nodes(qualified_name);\nCREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);\nCREATE INDEX IF NOT EXISTS idx_edges_file ON edges(file_path);\n`;\n\n// ---------------------------------------------------------------------------\n// In-memory adjacency cache (replaces networkx.DiGraph)\n// ---------------------------------------------------------------------------\n\ninterface AdjacencyCache {\n out: Map<string, Set<string>>;\n in: Map<string, Set<string>>;\n}\n\n// ---------------------------------------------------------------------------\n// SqliteGraphRepository\n// ---------------------------------------------------------------------------\n\nexport class SqliteGraphRepository implements IGraphRepository {\n private db: Database.Database;\n private adjCache: AdjacencyCache | null = null;\n readonly dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n const dir = path.dirname(dbPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n this.db = new Database(dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000');\n\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore — safe to skip if another writer holds it\n }\n\n this._initSchema();\n }\n\n close(): void {\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore\n }\n this.db.close();\n for (const suffix of ['-wal', '-shm']) {\n const side = this.dbPath + suffix;\n try {\n if (fs.existsSync(side)) { fs.unlinkSync(side); }\n } catch {\n // locked by another process — leave it alone\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Write operations\n // ---------------------------------------------------------------------------\n\n upsertNode(node: NodeInfo, fileHash = ''): number {\n const now = Date.now() / 1000;\n const qualified = this._makeQualified(node);\n const extra = node.extra ? JSON.stringify(node.extra) : '{}';\n\n this.db.prepare(`\n INSERT INTO nodes\n (kind, name, qualified_name, file_path, line_start, line_end,\n language, parent_name, params, return_type, modifiers, is_test,\n file_hash, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(qualified_name) DO UPDATE SET\n kind=excluded.kind, name=excluded.name,\n file_path=excluded.file_path, line_start=excluded.line_start,\n line_end=excluded.line_end, language=excluded.language,\n parent_name=excluded.parent_name, params=excluded.params,\n return_type=excluded.return_type, modifiers=excluded.modifiers,\n is_test=excluded.is_test, file_hash=excluded.file_hash,\n extra=excluded.extra, updated_at=excluded.updated_at\n `).run(\n node.kind, node.name, qualified, node.filePath,\n node.lineStart, node.lineEnd, node.language ?? null,\n node.parentName ?? null, node.params ?? null, node.returnType ?? null,\n node.modifiers ?? null, node.isTest ? 1 : 0, fileHash,\n extra, now,\n );\n\n const row = this.db.prepare(\n 'SELECT id FROM nodes WHERE qualified_name = ?'\n ).get(qualified) as { id: number };\n return row.id;\n }\n\n upsertEdge(edge: EdgeInfo): number {\n const now = Date.now() / 1000;\n const extra = edge.extra ? JSON.stringify(edge.extra) : '{}';\n const line = edge.line ?? 0;\n\n const existing = this.db.prepare(`\n SELECT id FROM edges\n WHERE kind=? AND source_qualified=? AND target_qualified=?\n AND file_path=? AND line=?\n `).get(edge.kind, edge.source, edge.target, edge.filePath, line) as\n { id: number } | undefined;\n\n if (existing) {\n this.db.prepare(\n 'UPDATE edges SET line=?, extra=?, updated_at=? WHERE id=?'\n ).run(line, extra, now, existing.id);\n return existing.id;\n }\n\n const result = this.db.prepare(`\n INSERT INTO edges\n (kind, source_qualified, target_qualified, file_path, line, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(edge.kind, edge.source, edge.target, edge.filePath, line, extra, now);\n return Number(result.lastInsertRowid);\n }\n\n removeFileData(filePath: string): void {\n this.db.prepare('DELETE FROM nodes WHERE file_path = ?').run(filePath);\n this.db.prepare('DELETE FROM edges WHERE file_path = ?').run(filePath);\n this._invalidateCache();\n }\n\n storeFileNodesEdges(\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n fileHash = '',\n ): void {\n const txn = this.db.transaction(() => {\n this.removeFileData(filePath);\n for (const node of nodes) { this.upsertNode(node, fileHash); }\n for (const edge of edges) { this.upsertEdge(edge); }\n });\n txn();\n this._invalidateCache();\n }\n\n setMetadata(key: string, value: string): void {\n this.db.prepare(\n 'INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)'\n ).run(key, value);\n }\n\n getMetadata(key: string): string | undefined {\n const row = this.db.prepare(\n 'SELECT value FROM metadata WHERE key = ?'\n ).get(key) as MetadataRow | undefined;\n return row?.value;\n }\n\n // ---------------------------------------------------------------------------\n // Read operations\n // ---------------------------------------------------------------------------\n\n getNode(qualifiedName: string): GraphNode | undefined {\n const row = this.db.prepare(\n 'SELECT * FROM nodes WHERE qualified_name = ?'\n ).get(qualifiedName) as NodeRow | undefined;\n return row ? this._rowToNode(row) : undefined;\n }\n\n getNodesByFile(filePath: string): GraphNode[] {\n const rows = this.db.prepare(\n 'SELECT * FROM nodes WHERE file_path = ? ORDER BY line_start'\n ).all(filePath) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getEdgesBySource(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE source_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesByTarget(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n searchEdgesByTargetName(name: string, kind: EdgeKind = 'CALLS'): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ? AND kind = ?'\n ).all(name, kind) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getAllFiles(): string[] {\n const rows = this.db.prepare(\n \"SELECT DISTINCT file_path FROM nodes WHERE kind = 'File' ORDER BY file_path\"\n ).all() as FilePathRow[];\n return rows.map((r) => r.file_path);\n }\n\n searchNodes(query: string, limit = 20): GraphNode[] {\n const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n if (words.length === 0) { return []; }\n\n const conditions = words.map(\n () => '(LOWER(name) LIKE ? OR LOWER(qualified_name) LIKE ?)'\n );\n const params: Array<string | number> = [];\n for (const word of words) {\n params.push(`%${word}%`, `%${word}%`);\n }\n params.push(limit);\n\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getSubgraph(qualifiedNames: string[]): { nodes: GraphNode[]; edges: GraphEdge[] } {\n const nodes: GraphNode[] = [];\n for (const qn of qualifiedNames) {\n const n = this.getNode(qn);\n if (n) { nodes.push(n); }\n }\n const qnSet = new Set(qualifiedNames);\n const edges: GraphEdge[] = [];\n for (const qn of qualifiedNames) {\n for (const e of this.getEdgesBySource(qn)) {\n if (qnSet.has(e.targetQualified)) { edges.push(e); }\n }\n }\n return { nodes, edges };\n }\n\n getStats(): GraphStats {\n const totalNodes = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM nodes').get() as CountRow\n ).cnt;\n const totalEdges = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM edges').get() as CountRow\n ).cnt;\n\n const nodesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM nodes GROUP BY kind'\n ).all() as KindCountRow[]) {\n nodesByKind[r.kind] = r.cnt;\n }\n\n const edgesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM edges GROUP BY kind'\n ).all() as KindCountRow[]) {\n edgesByKind[r.kind] = r.cnt;\n }\n\n const languages = (this.db.prepare(\n \"SELECT DISTINCT language FROM nodes WHERE language IS NOT NULL AND language != ''\"\n ).all() as LanguageRow[]).map((r) => r.language);\n\n const filesCount = (this.db.prepare(\n \"SELECT COUNT(*) AS cnt FROM nodes WHERE kind = 'File'\"\n ).get() as CountRow).cnt;\n\n const lastUpdated = this.getMetadata('last_updated') ?? null;\n\n let embeddingsCount = 0;\n try {\n embeddingsCount = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM embeddings').get() as CountRow\n ).cnt;\n } catch {\n // embeddings table may not exist — that is fine\n }\n\n return {\n totalNodes, totalEdges, nodesByKind, edgesByKind,\n languages, filesCount, lastUpdated, embeddingsCount,\n };\n }\n\n getNodesBySize(\n minLines = 50,\n maxLines?: number,\n kind?: string,\n filePathPattern?: string,\n limit = 50,\n ): Array<GraphNode & { lineCount: number }> {\n const conditions = [\n 'line_start IS NOT NULL',\n 'line_end IS NOT NULL',\n '(line_end - line_start + 1) >= ?',\n ];\n const params: Array<string | number> = [minLines];\n\n if (maxLines !== undefined) {\n conditions.push('(line_end - line_start + 1) <= ?');\n params.push(maxLines);\n }\n if (kind) { conditions.push('kind = ?'); params.push(kind); }\n if (filePathPattern) {\n conditions.push('file_path LIKE ?');\n params.push(`%${filePathPattern}%`);\n }\n params.push(limit);\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} ORDER BY (line_end - line_start + 1) DESC LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => ({\n ...this._rowToNode(r),\n lineCount:\n r.line_start != null && r.line_end != null\n ? r.line_end - r.line_start + 1\n : 0,\n }));\n }\n\n getAllEdges(): GraphEdge[] {\n const rows = this.db.prepare('SELECT * FROM edges').all() as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesAmong(qualifiedNames: Set<string>): GraphEdge[] {\n if (qualifiedNames.size === 0) { return []; }\n const qns = [...qualifiedNames];\n const results: GraphEdge[] = [];\n const batchSize = 450;\n\n for (let i = 0; i < qns.length; i += batchSize) {\n const batch = qns.slice(i, i + batchSize);\n const placeholders = batch.map(() => '?').join(',');\n // nosec: placeholders are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM edges WHERE source_qualified IN (${placeholders})`\n ).all(...batch) as EdgeRow[];\n for (const r of rows) {\n const edge = this._rowToEdge(r);\n if (qualifiedNames.has(edge.targetQualified)) { results.push(edge); }\n }\n }\n return results;\n }\n\n // ---------------------------------------------------------------------------\n // Adjacency (BFS support for use cases)\n // ---------------------------------------------------------------------------\n\n getAdjacency(): { outgoing: Map<string, Set<string>>; incoming: Map<string, Set<string>> } {\n const cache = this._buildAdjacency();\n return { outgoing: cache.out, incoming: cache.in };\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private _initSchema(): void {\n this.db.exec(SCHEMA_SQL);\n this.setMetadata('schema_version', '1');\n }\n\n private _invalidateCache(): void {\n this.adjCache = null;\n }\n\n private _buildAdjacency(): AdjacencyCache {\n if (this.adjCache) { return this.adjCache; }\n const out = new Map<string, Set<string>>();\n const inMap = new Map<string, Set<string>>();\n\n const rows = this.db.prepare('SELECT source_qualified, target_qualified FROM edges').all() as\n Array<{ source_qualified: string; target_qualified: string }>;\n\n for (const r of rows) {\n if (!out.has(r.source_qualified)) { out.set(r.source_qualified, new Set()); }\n out.get(r.source_qualified)!.add(r.target_qualified);\n\n if (!inMap.has(r.target_qualified)) { inMap.set(r.target_qualified, new Set()); }\n inMap.get(r.target_qualified)!.add(r.source_qualified);\n }\n\n this.adjCache = { out, in: inMap };\n return this.adjCache;\n }\n\n private _makeQualified(node: NodeInfo): string {\n if (node.kind === 'File') { return node.filePath; }\n if (node.parentName) {\n return `${node.filePath}::${node.parentName}.${node.name}`;\n }\n return `${node.filePath}::${node.name}`;\n }\n\n private _rowToNode(row: NodeRow): GraphNode {\n return {\n id: row.id,\n kind: row.kind as GraphNode['kind'],\n name: row.name,\n qualifiedName: row.qualified_name,\n filePath: row.file_path,\n lineStart: row.line_start,\n lineEnd: row.line_end,\n language: row.language ?? null,\n parentName: row.parent_name ?? null,\n params: row.params ?? null,\n returnType: row.return_type ?? null,\n modifiers: row.modifiers ?? null,\n isTest: row.is_test === 1,\n fileHash: row.file_hash ?? null,\n };\n }\n\n private _rowToEdge(row: EdgeRow): GraphEdge {\n return {\n id: row.id,\n kind: row.kind as GraphEdge['kind'],\n sourceQualified: row.source_qualified,\n targetQualified: row.target_qualified,\n filePath: row.file_path,\n line: row.line ?? 0,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Utility exports (mirrors Python module-level helpers)\n// ---------------------------------------------------------------------------\n\nexport function sanitizeName(s: string, maxLen = 256): string {\n let cleaned = '';\n for (const ch of s) {\n const code = ch.codePointAt(0) ?? 0;\n if (ch === '\\t' || ch === '\\n' || code >= 0x20) { cleaned += ch; }\n }\n return cleaned.slice(0, maxLen);\n}\n\nexport function nodeToDict(n: GraphNode): Record<string, unknown> {\n return {\n id: n.id,\n kind: n.kind,\n name: sanitizeName(n.name),\n qualified_name: sanitizeName(n.qualifiedName),\n file_path: n.filePath,\n line_start: n.lineStart,\n line_end: n.lineEnd,\n language: n.language,\n parent_name: n.parentName ? sanitizeName(n.parentName) : n.parentName,\n is_test: n.isTest,\n };\n}\n\nexport function edgeToDict(e: GraphEdge): Record<string, unknown> {\n return {\n id: e.id,\n kind: e.kind,\n source: sanitizeName(e.sourceQualified),\n target: sanitizeName(e.targetQualified),\n file_path: e.filePath,\n line: e.line,\n };\n}\n\n// Backward-compat alias (used by tests + public index.ts)\nexport { SqliteGraphRepository as GraphStore };\n","/**\n * Tree-sitter based multi-language code parser.\n *\n * Extracts structural nodes (classes, functions, imports, types) and edges\n * (calls, inheritance, contains) from source files.\n *\n * Direct port of code_review_graph/parser.py.\n * Supports 14 languages: Python, JS/TS/TSX, Go, Rust, Java, C, C++, C#,\n * Ruby, Kotlin, Swift, PHP, Solidity, Vue SFC.\n */\n\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport Parser from 'tree-sitter';\n\nconst _require = createRequire(import.meta.url);\nimport type { NodeInfo, EdgeInfo } from '../domain/types.js';\nimport type { IParser } from '../domain/ports/IParser.js';\n\n// ---------------------------------------------------------------------------\n// Language loading — individual npm grammar packages\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Language = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype SyntaxNode = any;\n\nfunction loadLanguage(pkg: string): Language | null {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = _require(pkg);\n return mod.default ?? mod;\n } catch {\n return null;\n }\n}\n\n// Lazy-loaded grammar map. Languages are loaded on first use.\nconst _languageCache = new Map<string, Language | null>();\n\nfunction getLanguage(name: string): Language | null {\n if (_languageCache.has(name)) { return _languageCache.get(name) ?? null; }\n\n const pkgMap: Record<string, string> = {\n python: 'tree-sitter-python',\n javascript: 'tree-sitter-javascript',\n typescript: 'tree-sitter-typescript/bindings/node/typescript',\n tsx: 'tree-sitter-typescript/bindings/node/tsx',\n go: 'tree-sitter-go',\n rust: 'tree-sitter-rust',\n java: 'tree-sitter-java',\n c: 'tree-sitter-c',\n cpp: 'tree-sitter-cpp',\n csharp: 'tree-sitter-c-sharp',\n ruby: 'tree-sitter-ruby',\n kotlin: 'tree-sitter-kotlin',\n swift: 'tree-sitter-swift',\n php: 'tree-sitter-php/php',\n solidity: 'tree-sitter-solidity',\n vue: 'tree-sitter-vue',\n };\n\n const pkg = pkgMap[name];\n const lang = pkg ? loadLanguage(pkg) : null;\n _languageCache.set(name, lang);\n return lang;\n}\n\n// ---------------------------------------------------------------------------\n// Extension → language mapping\n// ---------------------------------------------------------------------------\n\nexport const EXTENSION_TO_LANGUAGE: Record<string, string> = {\n '.py': 'python',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.go': 'go',\n '.rs': 'rust',\n '.java': 'java',\n '.cs': 'csharp',\n '.rb': 'ruby',\n '.cpp': 'cpp',\n '.cc': 'cpp',\n '.cxx': 'cpp',\n '.c': 'c',\n '.h': 'c',\n '.hpp': 'cpp',\n '.kt': 'kotlin',\n '.swift': 'swift',\n '.php': 'php',\n '.sol': 'solidity',\n '.vue': 'vue',\n};\n\n// ---------------------------------------------------------------------------\n// AST node type sets per language\n// ---------------------------------------------------------------------------\n\nconst CLASS_TYPES: Record<string, string[]> = {\n python: ['class_definition'],\n javascript: ['class_declaration', 'class'],\n typescript: ['class_declaration', 'class'],\n tsx: ['class_declaration', 'class'],\n go: ['type_declaration'],\n rust: ['struct_item', 'enum_item', 'impl_item'],\n java: ['class_declaration', 'interface_declaration', 'enum_declaration'],\n c: ['struct_specifier', 'type_definition'],\n cpp: ['class_specifier', 'struct_specifier'],\n csharp: ['class_declaration', 'interface_declaration', 'enum_declaration', 'struct_declaration'],\n ruby: ['class', 'module'],\n kotlin: ['class_declaration', 'object_declaration'],\n swift: ['class_declaration', 'struct_declaration', 'protocol_declaration'],\n php: ['class_declaration', 'interface_declaration'],\n solidity: [\n 'contract_declaration', 'interface_declaration', 'library_declaration',\n 'struct_declaration', 'enum_declaration', 'error_declaration',\n 'user_defined_type_definition',\n ],\n};\n\nconst FUNCTION_TYPES: Record<string, string[]> = {\n python: ['function_definition'],\n javascript: ['function_declaration', 'method_definition', 'arrow_function'],\n typescript: ['function_declaration', 'method_definition', 'arrow_function'],\n tsx: ['function_declaration', 'method_definition', 'arrow_function'],\n go: ['function_declaration', 'method_declaration'],\n rust: ['function_item'],\n java: ['method_declaration', 'constructor_declaration'],\n c: ['function_definition'],\n cpp: ['function_definition'],\n csharp: ['method_declaration', 'constructor_declaration'],\n ruby: ['method', 'singleton_method'],\n kotlin: ['function_declaration'],\n swift: ['function_declaration'],\n php: ['function_definition', 'method_declaration'],\n solidity: [\n 'function_definition', 'constructor_definition', 'modifier_definition',\n 'event_definition', 'fallback_receive_definition',\n ],\n};\n\nconst IMPORT_TYPES: Record<string, string[]> = {\n python: ['import_statement', 'import_from_statement'],\n javascript: ['import_statement'],\n typescript: ['import_statement'],\n tsx: ['import_statement'],\n go: ['import_declaration'],\n rust: ['use_declaration'],\n java: ['import_declaration'],\n c: ['preproc_include'],\n cpp: ['preproc_include'],\n csharp: ['using_directive'],\n ruby: ['call'], // require / require_relative\n kotlin: ['import_header'],\n swift: ['import_declaration'],\n php: ['namespace_use_declaration'],\n solidity: ['import_directive'],\n};\n\nconst CALL_TYPES: Record<string, string[]> = {\n python: ['call'],\n javascript: ['call_expression', 'new_expression'],\n typescript: ['call_expression', 'new_expression'],\n tsx: ['call_expression', 'new_expression'],\n go: ['call_expression'],\n rust: ['call_expression', 'macro_invocation'],\n java: ['method_invocation', 'object_creation_expression'],\n c: ['call_expression'],\n cpp: ['call_expression'],\n csharp: ['invocation_expression', 'object_creation_expression'],\n ruby: ['call', 'method_call'],\n kotlin: ['call_expression'],\n swift: ['call_expression'],\n php: ['function_call_expression', 'member_call_expression'],\n solidity: ['call_expression'],\n};\n\n// ---------------------------------------------------------------------------\n// Test detection patterns\n// ---------------------------------------------------------------------------\n\nconst TEST_PATTERNS = [\n /^test_/,\n /^Test/,\n /_test$/,\n /\\.test\\./,\n /\\.spec\\./,\n /_spec$/,\n];\n\nconst TEST_FILE_PATTERNS = [\n /test_.*\\.py$/,\n /.*_test\\.py$/,\n /.*\\.test\\.[jt]sx?$/,\n /.*\\.spec\\.[jt]sx?$/,\n /.*_test\\.go$/,\n /tests?\\//,\n];\n\nfunction isTestFile(filePath: string): boolean {\n return TEST_FILE_PATTERNS.some((p) => p.test(filePath));\n}\n\n// Test-runner framework names that indicate a function IS a test even\n// if its name doesn't start with \"test\".\nconst TEST_RUNNER_NAMES = new Set([\n 'describe', 'it', 'test', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll',\n]);\n\nfunction isTestFunction(name: string, filePath: string): boolean {\n // Name-pattern match always wins\n if (TEST_PATTERNS.some((p) => p.test(name))) { return true; }\n // In a test file, only test-runner functions count (not every helper)\n if (isTestFile(filePath) && TEST_RUNNER_NAMES.has(name)) { return true; }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Public utility\n// ---------------------------------------------------------------------------\n\nexport function fileHash(filePath: string): string {\n const buf = fs.readFileSync(filePath);\n return crypto.createHash('sha256').update(buf).digest('hex');\n}\n\n// ---------------------------------------------------------------------------\n// CodeParser\n// ---------------------------------------------------------------------------\n\nconst MAX_AST_DEPTH = 180;\nconst MODULE_CACHE_MAX = 15_000;\n\nexport class CodeParser implements IParser {\n private parsers = new Map<string, Parser>();\n private moduleFileCache = new Map<string, string | null>();\n\n private getParser(language: string): Parser | null {\n if (this.parsers.has(language)) { return this.parsers.get(language) ?? null; }\n try {\n const lang = getLanguage(language);\n if (!lang) { return null; }\n const p = new Parser();\n p.setLanguage(lang);\n this.parsers.set(language, p);\n return p;\n } catch {\n return null;\n }\n }\n\n detectLanguage(filePath: string): string | null {\n const ext = path.extname(filePath).toLowerCase();\n return EXTENSION_TO_LANGUAGE[ext] ?? null;\n }\n\n parseFile(filePath: string): [NodeInfo[], EdgeInfo[]] {\n let source: Buffer;\n try {\n source = fs.readFileSync(filePath);\n } catch {\n return [[], []];\n }\n return this.parseBytes(filePath, source);\n }\n\n parseBytes(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const language = this.detectLanguage(filePath);\n if (!language) { return [[], []]; }\n\n if (language === 'vue') {\n return this._parseVue(filePath, source);\n }\n\n const parser = this.getParser(language);\n if (!parser) { return [[], []]; }\n\n const tree = parser.parse(source.toString('utf-8'));\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n const testFile = isTestFile(filePath);\n\n // File node\n const lineCount = source.toString('utf-8').split('\\n').length;\n nodes.push({\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language,\n isTest: testFile,\n });\n\n const [importMap, definedNames] = this._collectFileScope(\n tree.rootNode, language, source,\n );\n\n this._extractFromTree(\n tree.rootNode, source, language, filePath, nodes, edges,\n undefined, undefined, importMap, definedNames,\n );\n\n const resolvedEdges = this._resolveCallTargets(nodes, edges, filePath);\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of nodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of resolvedEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n resolvedEdges.push(...testedBy);\n }\n\n return [nodes, resolvedEdges];\n }\n\n private _parseVue(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const vueParser = this.getParser('vue');\n if (!vueParser) { return [[], []]; }\n\n const tree = vueParser.parse(source.toString('utf-8'));\n const testFile = isTestFile(filePath);\n const lineCount = source.toString('utf-8').split('\\n').length;\n\n const allNodes: NodeInfo[] = [{\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language: 'vue',\n isTest: testFile,\n }];\n const allEdges: EdgeInfo[] = [];\n\n for (const child of tree.rootNode.children) {\n if (child.type !== 'script_element') { continue; }\n\n let scriptLang = 'javascript';\n let startTag: SyntaxNode | null = null;\n let rawTextNode: SyntaxNode | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'start_tag') { startTag = sub; }\n else if (sub.type === 'raw_text') { rawTextNode = sub; }\n }\n\n if (startTag) {\n for (const attr of startTag.children) {\n if (attr.type === 'attribute') {\n let attrName: string | null = null;\n let attrValue: string | null = null;\n for (const a of attr.children) {\n if (a.type === 'attribute_name') { attrName = a.text; }\n else if (a.type === 'quoted_attribute_value') {\n for (const v of a.children) {\n if (v.type === 'attribute_value') { attrValue = v.text; }\n }\n }\n }\n if (attrName === 'lang' && (attrValue === 'ts' || attrValue === 'typescript')) {\n scriptLang = 'typescript';\n }\n }\n }\n }\n\n if (!rawTextNode) { continue; }\n\n const scriptSource = Buffer.from(rawTextNode.text, 'utf-8');\n const lineOffset: number = rawTextNode.startPosition.row;\n\n const scriptParser = this.getParser(scriptLang);\n if (!scriptParser) { continue; }\n\n const scriptTree = scriptParser.parse(scriptSource.toString('utf-8'));\n const [importMap, definedNames] = this._collectFileScope(\n scriptTree.rootNode, scriptLang, scriptSource,\n );\n\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n this._extractFromTree(\n scriptTree.rootNode, scriptSource, scriptLang, filePath,\n nodes, edges, undefined, undefined, importMap, definedNames,\n );\n\n // Adjust line numbers and language for position within .vue file\n for (const n of nodes) {\n n.lineStart += lineOffset;\n n.lineEnd += lineOffset;\n n.language = 'vue';\n }\n for (const e of edges) {\n e.line = (e.line ?? 0) + lineOffset;\n }\n\n allNodes.push(...nodes);\n allEdges.push(...edges);\n }\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of allNodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of allEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n allEdges.push(...testedBy);\n }\n\n return [allNodes, allEdges];\n }\n\n private _resolveCallTargets(\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n filePath: string,\n ): EdgeInfo[] {\n const symbols = new Map<string, string>();\n for (const node of nodes) {\n if (['Function', 'Class', 'Type', 'Test'].includes(node.kind)) {\n const bare = node.name;\n if (!symbols.has(bare)) {\n symbols.set(bare, this._qualify(bare, filePath, node.parentName ?? null));\n }\n }\n }\n\n return edges.map((edge) => {\n if (edge.kind === 'CALLS' && !edge.target.includes('::')) {\n const qualified = symbols.get(edge.target);\n if (qualified) {\n return { ...edge, target: qualified };\n }\n }\n return edge;\n });\n }\n\n private _extractFromTree(\n root: SyntaxNode,\n source: Buffer,\n language: string,\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n enclosingClass?: string | null,\n enclosingFunc?: string | null,\n importMap?: Map<string, string>,\n definedNames?: Set<string>,\n depth = 0,\n ): void {\n if (depth > MAX_AST_DEPTH) { return; }\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const callTypes = new Set(CALL_TYPES[language] ?? []);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // --- Classes ---\n if (classTypes.has(nodeType)) {\n const name = this._getName(child, language, 'class');\n if (name) {\n nodes.push({\n kind: 'Class',\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n });\n\n edges.push({\n kind: 'CONTAINS',\n source: filePath,\n target: this._qualify(name, filePath, enclosingClass ?? null),\n filePath,\n line: child.startPosition.row + 1,\n });\n\n const bases = this._getBases(child, language);\n for (const base of bases) {\n edges.push({\n kind: 'INHERITS',\n source: this._qualify(name, filePath, enclosingClass ?? null),\n target: base,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n name, null, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Functions ---\n if (funcTypes.has(nodeType)) {\n const name = this._getName(child, language, 'function');\n if (name) {\n const isTest = isTestFunction(name, filePath);\n const kind = isTest ? 'Test' : 'Function';\n const qualified = this._qualify(name, filePath, enclosingClass ?? null);\n const params = this._getParams(child, language);\n const retType = this._getReturnType(child, language);\n\n nodes.push({\n kind,\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n params,\n returnType: retType,\n isTest,\n });\n\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n\n // Solidity: modifier invocations → CALLS edges\n if (language === 'solidity') {\n for (const sub of child.children) {\n if (sub.type === 'modifier_invocation') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n edges.push({\n kind: 'CALLS',\n source: qualified,\n target: ident.text,\n filePath,\n line: sub.startPosition.row + 1,\n });\n break;\n }\n }\n }\n }\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, name, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Imports ---\n if (importTypes.has(nodeType)) {\n const imports = this._extractImport(child, language);\n for (const impTarget of imports) {\n edges.push({\n kind: 'IMPORTS_FROM',\n source: filePath,\n target: impTarget,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n\n // --- Calls ---\n if (callTypes.has(nodeType)) {\n const callName = this._getCallName(child, language);\n if (callName && enclosingFunc) {\n const caller = this._qualify(enclosingFunc, filePath, enclosingClass ?? null);\n const target = this._resolveCallTarget(\n callName, filePath, language,\n importMap ?? new Map(), definedNames ?? new Set(),\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n\n // --- Solidity-specific constructs ---\n if (language === 'solidity') {\n // emit statements → CALLS edges\n if (nodeType === 'emit_statement' && enclosingFunc) {\n for (const sub of child.children) {\n if (sub.type === 'expression') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n const caller = this._qualify(\n enclosingFunc, filePath, enclosingClass ?? null,\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target: ident.text,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n }\n }\n }\n\n // State variable declarations → Function nodes\n if (nodeType === 'state_variable_declaration' && enclosingClass) {\n let varName: string | null = null;\n let varVisibility: string | null = null;\n let varType: string | null = null;\n let varMutability: string | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'visibility') { varVisibility = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n else if (sub.type === 'constant' || sub.type === 'immutable') {\n varMutability = sub.type;\n }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass,\n returnType: varType,\n modifiers: varVisibility,\n extra: { solidity_kind: 'state_variable', mutability: varMutability },\n });\n edges.push({\n kind: 'CONTAINS',\n source: this._qualify(enclosingClass, filePath, null),\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Constant variable declarations\n if (nodeType === 'constant_variable_declaration') {\n let varName: string | null = null;\n let varType: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass ?? null);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n returnType: varType,\n extra: { solidity_kind: 'constant' },\n });\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Using directives → DEPENDS_ON edge\n if (nodeType === 'using_directive') {\n let libName: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'type_alias') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { libName = ident.text; break; }\n }\n }\n }\n if (libName) {\n const sourceName = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'DEPENDS_ON',\n source: sourceName,\n target: libName,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n }\n\n // Recurse for other node types\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, enclosingFunc, importMap, definedNames, depth + 1,\n );\n }\n }\n\n private _collectFileScope(\n root: SyntaxNode,\n language: string,\n source: Buffer,\n ): [Map<string, string>, Set<string>] {\n const importMap = new Map<string, string>();\n const definedNames = new Set<string>();\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const decoratorWrappers = new Set(['decorated_definition', 'decorator']);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // Unwrap decorator wrappers\n let target = child;\n if (decoratorWrappers.has(nodeType)) {\n for (const inner of child.children) {\n if (funcTypes.has(inner.type) || classTypes.has(inner.type)) {\n target = inner;\n break;\n }\n }\n }\n\n const targetType: string = target.type;\n\n if (funcTypes.has(targetType) || classTypes.has(targetType)) {\n const name = this._getName(\n target, language, classTypes.has(targetType) ? 'class' : 'function',\n );\n if (name) { definedNames.add(name); }\n }\n\n if (importTypes.has(nodeType)) {\n this._collectImportNames(child, language, source, importMap);\n }\n }\n\n return [importMap, definedNames];\n }\n\n private _collectImportNames(\n node: SyntaxNode,\n language: string,\n _source: Buffer,\n importMap: Map<string, string>,\n ): void {\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n let module: string | null = null;\n let seenImport = false;\n for (const child of node.children) {\n if (child.type === 'dotted_name' && !seenImport) {\n module = child.text;\n } else if (child.type === 'import') {\n seenImport = true;\n } else if (seenImport && module) {\n if (child.type === 'identifier' || child.type === 'dotted_name') {\n importMap.set(child.text, module);\n } else if (child.type === 'aliased_import') {\n const names = child.children\n .filter((c: SyntaxNode) =>\n c.type === 'identifier' || c.type === 'dotted_name'\n )\n .map((c: SyntaxNode) => c.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n } else if (language === 'javascript' || language === 'typescript' || language === 'tsx') {\n let module: string | null = null;\n for (const child of node.children) {\n if (child.type === 'string') {\n module = (child.text as string).replace(/^['\"]|['\"]$/g, '');\n }\n }\n if (module) {\n for (const child of node.children) {\n if (child.type === 'import_clause') {\n this._collectJsImportNames(child, module, importMap);\n }\n }\n }\n }\n }\n\n private _collectJsImportNames(\n clauseNode: SyntaxNode,\n module: string,\n importMap: Map<string, string>,\n ): void {\n for (const child of clauseNode.children) {\n if (child.type === 'identifier') {\n importMap.set(child.text, module);\n } else if (child.type === 'named_imports') {\n for (const spec of child.children) {\n if (spec.type === 'import_specifier') {\n const names = spec.children\n .filter((s: SyntaxNode) =>\n s.type === 'identifier' || s.type === 'property_identifier'\n )\n .map((s: SyntaxNode) => s.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n }\n\n private _resolveModuleToFile(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n const cacheKey = `${language}:${callerDir}:${module}`;\n if (this.moduleFileCache.has(cacheKey)) {\n return this.moduleFileCache.get(cacheKey) ?? null;\n }\n\n const resolved = this._doResolveModule(module, filePath, language);\n if (this.moduleFileCache.size >= MODULE_CACHE_MAX) {\n this.moduleFileCache.clear();\n }\n this.moduleFileCache.set(cacheKey, resolved);\n return resolved;\n }\n\n private _doResolveModule(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n\n if (language === 'python') {\n const relPath = module.replace(/\\./g, '/');\n const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];\n let current = callerDir;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n for (const candidate of candidates) {\n const target = path.join(current, candidate);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n const parent = path.dirname(current);\n if (parent === current) { break; }\n current = parent;\n }\n } else if (\n language === 'javascript' || language === 'typescript' ||\n language === 'tsx' || language === 'vue'\n ) {\n if (module.startsWith('.')) {\n const base = path.join(callerDir, module);\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '.vue'];\n if (fs.existsSync(base) && fs.statSync(base).isFile()) {\n return path.resolve(base);\n }\n for (const ext of extensions) {\n const target = base + ext;\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n // Try index file in directory\n if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {\n for (const ext of extensions) {\n const target = path.join(base, `index${ext}`);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n }\n }\n }\n\n return null;\n }\n\n private _resolveCallTarget(\n callName: string,\n filePath: string,\n language: string,\n importMap: Map<string, string>,\n definedNames: Set<string>,\n ): string {\n if (definedNames.has(callName)) {\n return this._qualify(callName, filePath, null);\n }\n const importedFrom = importMap.get(callName);\n if (importedFrom) {\n const resolved = this._resolveModuleToFile(importedFrom, filePath, language);\n if (resolved) { return this._qualify(callName, resolved, null); }\n }\n return callName;\n }\n\n private _qualify(name: string, filePath: string, enclosingClass: string | null): string {\n if (enclosingClass) { return `${filePath}::${enclosingClass}.${name}`; }\n return `${filePath}::${name}`;\n }\n\n private _getName(node: SyntaxNode, language: string, kind: string): string | null {\n // Solidity: constructor and receive/fallback have no identifier child\n if (language === 'solidity') {\n if (node.type === 'constructor_definition') { return 'constructor'; }\n if (node.type === 'fallback_receive_definition') {\n for (const child of node.children) {\n if (child.type === 'receive' || child.type === 'fallback') {\n return child.text;\n }\n }\n }\n }\n\n // C/C++: function names are inside function_declarator/pointer_declarator\n if ((language === 'c' || language === 'cpp') && kind === 'function') {\n for (const child of node.children) {\n if (child.type === 'function_declarator' || child.type === 'pointer_declarator') {\n const result = this._getName(child, language, kind);\n if (result) { return result; }\n }\n }\n }\n\n // Most languages: look for identifier child\n for (const child of node.children) {\n if ([\n 'identifier', 'name', 'type_identifier', 'property_identifier',\n 'simple_identifier', 'constant',\n ].includes(child.type)) {\n return child.text;\n }\n }\n\n // Go type declarations: look for type_spec\n if (language === 'go' && node.type === 'type_declaration') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n return this._getName(child, language, kind);\n }\n }\n }\n\n return null;\n }\n\n private _getParams(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if (['parameters', 'formal_parameters', 'parameter_list'].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'solidity') {\n const params = node.children\n .filter((c: SyntaxNode) => c.type === 'parameter')\n .map((c: SyntaxNode) => c.text as string);\n if (params.length > 0) { return `(${params.join(', ')})`; }\n }\n return null;\n }\n\n private _getReturnType(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if ([\n 'type', 'return_type', 'type_annotation', 'return_type_definition',\n ].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'python') {\n for (let i = 0; i < node.children.length - 1; i++) {\n if (node.children[i].type === '->') {\n return node.children[i + 1].text;\n }\n }\n }\n return null;\n }\n\n private _getBases(node: SyntaxNode, language: string): string[] {\n const bases: string[] = [];\n\n if (language === 'python') {\n for (const child of node.children) {\n if (child.type === 'argument_list') {\n for (const arg of child.children) {\n if (arg.type === 'identifier' || arg.type === 'attribute') {\n bases.push(arg.text);\n }\n }\n }\n }\n } else if (\n language === 'java' || language === 'csharp' || language === 'kotlin'\n ) {\n for (const child of node.children) {\n if ([\n 'superclass', 'super_interfaces', 'extends_type', 'implements_type',\n 'type_identifier', 'supertype', 'delegation_specifier',\n ].includes(child.type)) {\n bases.push(child.text);\n }\n }\n } else if (language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'base_class_clause') {\n for (const sub of child.children) {\n if (sub.type === 'type_identifier') { bases.push(sub.text); }\n }\n }\n }\n } else if (\n language === 'typescript' || language === 'javascript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'extends_clause' || child.type === 'implements_clause') {\n for (const sub of child.children) {\n if ([\n 'identifier', 'type_identifier', 'nested_identifier',\n ].includes(sub.type)) {\n bases.push(sub.text);\n }\n }\n }\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'inheritance_specifier') {\n for (const sub of child.children) {\n if (sub.type === 'user_defined_type') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { bases.push(ident.text); }\n }\n }\n }\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n for (const sub of child.children) {\n if (sub.type === 'struct_type' || sub.type === 'interface_type') {\n for (const fieldNode of sub.children) {\n if (fieldNode.type === 'field_declaration_list') {\n for (const f of fieldNode.children) {\n if (f.type === 'type_identifier') { bases.push(f.text); }\n }\n }\n }\n }\n }\n }\n }\n }\n\n return bases;\n }\n\n private _extractImport(node: SyntaxNode, language: string): string[] {\n const imports: string[] = [];\n const text: string = node.text.trim();\n\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n for (const child of node.children) {\n if (child.type === 'dotted_name') {\n imports.push(child.text);\n break;\n }\n }\n } else {\n for (const child of node.children) {\n if (child.type === 'dotted_name') { imports.push(child.text); }\n }\n }\n } else if (\n language === 'javascript' || language === 'typescript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'string') {\n imports.push((child.text as string).replace(/^['\"]|['\"]$/g, ''));\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'import_spec_list') {\n for (const spec of child.children) {\n if (spec.type === 'import_spec') {\n for (const s of spec.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (child.type === 'import_spec') {\n for (const s of child.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (language === 'rust') {\n imports.push(text.replace(/^use\\s+/, '').replace(/;$/, '').trim());\n } else if (language === 'c' || language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'system_lib_string' || child.type === 'string_literal') {\n imports.push((child.text as string).replace(/^[<\"\"]|[>\"\"]$/g, ''));\n }\n }\n } else if (language === 'java' || language === 'csharp') {\n const parts = text.split(/\\s+/);\n if (parts.length >= 2) {\n imports.push(parts[parts.length - 1]!.replace(/;$/, ''));\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'string') {\n const val = (child.text as string).replace(/^\"|\"$/g, '');\n if (val) { imports.push(val); }\n }\n }\n } else if (language === 'ruby') {\n if (text.includes('require')) {\n const match = /['\"]([^'\"]+)['\"]/u.exec(text);\n if (match) { imports.push(match[1]!); }\n }\n } else {\n imports.push(text);\n }\n\n return imports;\n }\n\n private _getCallName(node: SyntaxNode, language: string): string | null {\n if (!node.children || node.children.length === 0) { return null; }\n\n let first: SyntaxNode = node.children[0];\n\n // Solidity wraps call targets in 'expression' — unwrap\n if (\n language === 'solidity' &&\n first.type === 'expression' &&\n first.children.length > 0\n ) {\n first = first.children[0];\n }\n\n if (first.type === 'identifier') { return first.text; }\n\n const memberTypes = [\n 'attribute', 'member_expression', 'field_expression', 'selector_expression',\n ];\n if (memberTypes.includes(first.type)) {\n for (let i = first.children.length - 1; i >= 0; i--) {\n const child: SyntaxNode = first.children[i];\n if ([\n 'identifier', 'property_identifier', 'field_identifier', 'field_name',\n ].includes(child.type)) {\n return child.text;\n }\n }\n return first.text;\n }\n\n if (first.type === 'scoped_identifier' || first.type === 'qualified_name') {\n return first.text;\n }\n\n return null;\n }\n}\n\n// Canonical export alias matching the file name\nexport { CodeParser as TreeSitterParser }\n","/**\n * File-system infrastructure helpers.\n *\n * Extracted from incremental.ts: findRepoRoot, findProjectRoot, getDbPath,\n * loadIgnorePatterns, shouldIgnore, isBinary, walkDir, collectAllFiles.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport micromatch from 'micromatch'\nimport { CodeParser } from './TreeSitterParser.js'\nimport { getAllTrackedFiles } from './GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_IGNORE_PATTERNS = [\n '.codeorbit/**',\n 'node_modules/**',\n '.git/**',\n '__pycache__/**',\n '*.pyc',\n '.venv/**',\n 'venv/**',\n 'dist/**',\n 'build/**',\n '.next/**',\n 'target/**',\n '*.min.js',\n '*.min.css',\n '*.map',\n '*.lock',\n 'package-lock.json',\n 'yarn.lock',\n '*.db',\n '*.sqlite',\n '*.db-journal',\n '*.db-wal',\n]\n\nexport const PRUNE_DIRS = new Set([\n 'node_modules', '.git', '__pycache__', '.next', '.nuxt', '.svelte-kit',\n 'dist', 'build', '.venv', 'venv', 'env', 'target', '.mypy_cache',\n '.pytest_cache', 'coverage', '.tox', '.cache', '.tmp', 'tmp', 'temp',\n 'vendor', 'Pods', 'DerivedData', '.gradle', '.idea', '.vs',\n])\n\nexport const DEBOUNCE_MS = 300\n\n// ---------------------------------------------------------------------------\n// Repo / DB path discovery\n// ---------------------------------------------------------------------------\n\nexport function findRepoRoot(start?: string): string | undefined {\n let current = start ?? process.cwd()\n while (true) {\n if (fs.existsSync(path.join(current, '.git'))) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) { break }\n current = parent\n }\n return undefined\n}\n\nexport function findProjectRoot(start?: string): string {\n return findRepoRoot(start) ?? start ?? process.cwd()\n}\n\nexport function getDbPath(repoRoot: string): string {\n const crgDir = path.join(repoRoot, '.codeorbit')\n const newDb = path.join(crgDir, 'graph.db')\n\n if (!fs.existsSync(crgDir)) {\n fs.mkdirSync(crgDir, { recursive: true })\n }\n\n const innerGitignore = path.join(crgDir, '.gitignore')\n if (!fs.existsSync(innerGitignore)) {\n fs.writeFileSync(\n innerGitignore,\n '# Auto-generated by codeorbit — do not commit database files.\\n' +\n '# The graph.db contains absolute paths and code structure metadata.\\n' +\n '*\\n',\n )\n }\n\n const legacyDb = path.join(repoRoot, '.codeorbit.db')\n if (fs.existsSync(legacyDb) && !fs.existsSync(newDb)) {\n fs.renameSync(legacyDb, newDb)\n }\n for (const suffix of ['-wal', '-shm', '-journal']) {\n const side = legacyDb + suffix\n if (fs.existsSync(side)) {\n try { fs.unlinkSync(side) } catch { /* ignore */ }\n }\n }\n\n return newDb\n}\n\n// ---------------------------------------------------------------------------\n// Ignore patterns\n// ---------------------------------------------------------------------------\n\nexport function loadIgnorePatterns(repoRoot: string): string[] {\n const patterns = [...DEFAULT_IGNORE_PATTERNS]\n const ignoreFile = path.join(repoRoot, '.codeorbitignore')\n if (fs.existsSync(ignoreFile)) {\n for (const line of fs.readFileSync(ignoreFile, 'utf-8').split('\\n')) {\n const trimmed = line.trim()\n if (trimmed && !trimmed.startsWith('#')) {\n patterns.push(trimmed)\n }\n }\n }\n return patterns\n}\n\nexport function shouldIgnore(filePath: string, patterns: string[]): boolean {\n return micromatch.isMatch(filePath, patterns)\n}\n\nexport function isBinary(filePath: string): boolean {\n try {\n const chunk = Buffer.alloc(8192)\n const fd = fs.openSync(filePath, 'r')\n const bytesRead = fs.readSync(fd, chunk, 0, 8192, 0)\n fs.closeSync(fd)\n return chunk.slice(0, bytesRead).includes(0)\n } catch {\n return true\n }\n}\n\n// ---------------------------------------------------------------------------\n// File collection\n// ---------------------------------------------------------------------------\n\nfunction walkDir(dir: string, repoRoot: string): string[] {\n const files: string[] = []\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (PRUNE_DIRS.has(entry.name)) { continue }\n files.push(...walkDir(path.join(dir, entry.name), repoRoot))\n } else if (entry.isFile()) {\n const rel = path.relative(repoRoot, path.join(dir, entry.name))\n files.push(rel)\n }\n }\n return files\n}\n\nexport function collectAllFiles(repoRoot: string): string[] {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const parser = new CodeParser()\n const files: string[] = []\n\n const tracked = getAllTrackedFiles(repoRoot)\n const candidates = tracked.length > 0 ? tracked : walkDir(repoRoot, repoRoot)\n\n for (const relPath of candidates) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const fullPath = path.join(repoRoot, relPath)\n\n let stat: fs.Stats\n try {\n stat = fs.lstatSync(fullPath)\n } catch {\n continue\n }\n\n if (!stat.isFile() || stat.isSymbolicLink()) { continue }\n if (!parser.detectLanguage(fullPath)) { continue }\n if (isBinary(fullPath)) { continue }\n files.push(relPath)\n }\n\n return files\n}\n","/**\n * Git operations infrastructure.\n *\n * Extracted from incremental.ts: gitRun, getChangedFiles, getStagedAndUnstaged,\n * getAllTrackedFiles.\n */\n\nimport { spawnSync } from 'node:child_process'\n\nexport const GIT_TIMEOUT_MS = Number(process.env['CRG_GIT_TIMEOUT'] ?? 30) * 1000\n\nfunction gitRun(args: string[], cwd: string): string {\n const result = spawnSync('git', args, {\n cwd,\n encoding: 'utf-8',\n timeout: GIT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n if (result.error || result.status !== 0) {\n return ''\n }\n return result.stdout ?? ''\n}\n\nexport function getChangedFiles(repoRoot: string, base = 'HEAD~1'): string[] {\n let output = gitRun(['diff', '--name-only', base], repoRoot)\n if (!output.trim()) {\n output = gitRun(['diff', '--name-only', '--cached'], repoRoot)\n }\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n\nexport function getStagedAndUnstaged(repoRoot: string): string[] {\n const output = gitRun(['status', '--porcelain'], repoRoot)\n const files: string[] = []\n for (const line of output.split('\\n')) {\n if (line.length > 3) {\n let entry = line.slice(3).trim()\n if (entry.includes(' -> ')) {\n entry = entry.split(' -> ')[1]!\n }\n files.push(entry)\n }\n }\n return files\n}\n\nexport function getAllTrackedFiles(repoRoot: string): string[] {\n const output = gitRun(['ls-files'], repoRoot)\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n","/**\n * Use cases: full build and incremental update of the knowledge graph.\n *\n * Extracted from incremental.ts (fullBuild, incrementalUpdate, findDependents)\n * + tools.ts (buildOrUpdateGraph).\n *\n * Accepts IParser and IGraphRepository as parameters for testability.\n * Imports file-system and git utilities from infrastructure.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { BuildResult } from '../domain/types.js'\nimport type { IParser } from '../domain/ports/IParser.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport {\n collectAllFiles,\n loadIgnorePatterns,\n shouldIgnore,\n} from '../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles } from '../infrastructure/GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Full build\n// ---------------------------------------------------------------------------\n\nexport function fullBuild(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n): BuildResult {\n const files = collectAllFiles(repoRoot)\n\n // Purge stale data\n const existingFiles = new Set(repo.getAllFiles())\n const currentAbs = new Set(files.map((f) => path.join(repoRoot, f)))\n for (const stale of existingFiles) {\n if (!currentAbs.has(stale)) {\n repo.removeFileData(stale)\n }\n }\n\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (let i = 0; i < files.length; i++) {\n const relPath = files[i]!\n const fullPath = path.join(repoRoot, relPath)\n try {\n const source = fs.readFileSync(fullPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const [nodes, edges] = parser.parseBytes(fullPath, source)\n repo.storeFileNodesEdges(fullPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n if ((i + 1) % 50 === 0 || i + 1 === files.length) {\n process.stderr.write(`Progress: ${i + 1}/${files.length} files parsed\\n`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'full')\n\n return {\n buildType: 'full',\n filesUpdated: files.length,\n totalNodes,\n totalEdges,\n changedFiles: files,\n dependentFiles: [],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Incremental update\n// ---------------------------------------------------------------------------\n\nexport function incrementalUpdate(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n base = 'HEAD~1',\n changedFiles?: string[],\n): BuildResult {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const changed = changedFiles ?? getChangedFiles(repoRoot, base)\n\n if (changed.length === 0) {\n return {\n buildType: 'incremental',\n filesUpdated: 0,\n totalNodes: 0,\n totalEdges: 0,\n changedFiles: [],\n dependentFiles: [],\n errors: [],\n }\n }\n\n const dependentFiles = new Set<string>()\n for (const relPath of changed) {\n const fullPath = path.join(repoRoot, relPath)\n const deps = findDependents(repo, fullPath)\n for (const d of deps) {\n try {\n dependentFiles.add(path.relative(repoRoot, d))\n } catch {\n dependentFiles.add(d)\n }\n }\n }\n\n const allFiles = new Set([...changed, ...dependentFiles])\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (const relPath of allFiles) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const absPath = path.join(repoRoot, relPath)\n\n if (!fs.existsSync(absPath)) {\n repo.removeFileData(absPath)\n continue\n }\n if (!parser.detectLanguage(absPath)) { continue }\n\n try {\n const source = fs.readFileSync(absPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const existingNodes = repo.getNodesByFile(absPath)\n if (existingNodes.length > 0 && existingNodes[0]!.fileHash === fhash) {\n continue\n }\n const [nodes, edges] = parser.parseBytes(absPath, source)\n repo.storeFileNodesEdges(absPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'incremental')\n\n return {\n buildType: 'incremental',\n filesUpdated: allFiles.size,\n totalNodes,\n totalEdges,\n changedFiles: changed,\n dependentFiles: [...dependentFiles],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Private helper\n// ---------------------------------------------------------------------------\n\nfunction findDependents(repo: IGraphRepository, filePath: string): string[] {\n const dependents = new Set<string>()\n\n for (const e of repo.getEdgesByTarget(filePath)) {\n if (e.kind === 'IMPORTS_FROM') {\n dependents.add(e.filePath)\n }\n }\n\n for (const node of repo.getNodesByFile(filePath)) {\n for (const e of repo.getEdgesByTarget(node.qualifiedName)) {\n if (['CALLS', 'IMPORTS_FROM', 'INHERITS', 'IMPLEMENTS'].includes(e.kind)) {\n dependents.add(e.filePath)\n }\n }\n }\n\n dependents.delete(filePath)\n return [...dependents]\n}\n","/**\n * File watcher infrastructure (chokidar-based).\n *\n * Extracted from incremental.ts::watch.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IParser } from '../domain/ports/IParser.js'\nimport { DEBOUNCE_MS, loadIgnorePatterns, shouldIgnore, isBinary } from './FileSystemHelper.js'\n\nexport async function watch(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const chokidar = require('chokidar')\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n\n const pending = new Set<string>()\n let timer: ReturnType<typeof setTimeout> | null = null\n\n function shouldHandle(absPath: string): boolean {\n try {\n const stat = fs.lstatSync(absPath)\n if (stat.isSymbolicLink()) { return false }\n } catch {\n return false\n }\n const rel = path.relative(repoRoot, absPath)\n if (shouldIgnore(rel, ignorePatterns)) { return false }\n if (!parser.detectLanguage(absPath)) { return false }\n return true\n }\n\n function flushPending(): void {\n const paths = [...pending]\n pending.clear()\n timer = null\n for (const absPath of paths) { updateFile(absPath) }\n }\n\n function schedule(absPath: string): void {\n pending.add(absPath)\n if (timer !== null) { clearTimeout(timer) }\n timer = setTimeout(flushPending, DEBOUNCE_MS)\n }\n\n function updateFile(absPath: string): void {\n if (!fs.existsSync(absPath)) { return }\n try {\n const stat = fs.lstatSync(absPath)\n if (stat.isSymbolicLink() || !stat.isFile()) { return }\n } catch {\n return\n }\n if (isBinary(absPath)) { return }\n\n try {\n const source = fs.readFileSync(absPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const [nodes, edges] = parser.parseBytes(absPath, source)\n repo.storeFileNodesEdges(absPath, nodes, edges, fhash)\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n const rel = path.relative(repoRoot, absPath)\n process.stderr.write(`Updated: ${rel} (${nodes.length} nodes, ${edges.length} edges)\\n`)\n } catch (err) {\n process.stderr.write(`Error updating ${absPath}: ${String(err)}\\n`)\n }\n }\n\n const watcher = chokidar.watch(repoRoot, {\n ignoreInitial: true,\n ignored: ['**/node_modules/**', '**/.git/**', '**/.codeorbit/**'],\n persistent: true,\n })\n\n watcher\n .on('change', (p: string) => { if (shouldHandle(p)) { schedule(p) } })\n .on('add', (p: string) => { if (shouldHandle(p)) { schedule(p) } })\n .on('unlink', (p: string) => {\n const rel = path.relative(repoRoot, p)\n if (!shouldIgnore(rel, ignorePatterns)) { repo.removeFileData(p) }\n })\n\n process.stderr.write(`Watching ${repoRoot} for changes... (Ctrl+C to stop)\\n`)\n\n await new Promise<void>((_, reject) => {\n process.on('SIGINT', () => {\n watcher\n .close()\n .then(() => { process.stderr.write('Watch stopped.\\n'); process.exit(0) })\n .catch(reject)\n })\n })\n}\n","/**\n * MCP server entry point for codeorbit.\n *\n * Run as: codeorbit serve\n * Communicates via stdio (standard MCP transport).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport {\n buildOrUpdateGraph,\n embedGraph,\n findLargeFunctions,\n getDocsSection,\n getImpactRadius,\n getReviewContext,\n listGraphStats,\n queryGraph,\n semanticSearchNodes,\n} from './tools.js'\n\n// ---------------------------------------------------------------------------\n// Server setup\n// ---------------------------------------------------------------------------\n\nconst server = new McpServer(\n { name: 'codeorbit', version: '0.1.0' },\n {\n instructions:\n 'Persistent incremental knowledge graph for token-efficient, ' +\n 'context-aware code reviews. Parses your codebase with Tree-sitter, ' +\n 'builds a structural graph, and provides smart impact analysis.',\n },\n)\n\n// ---------------------------------------------------------------------------\n// Tool registrations\n// ---------------------------------------------------------------------------\n\nserver.tool(\n 'build_or_update_graph_tool',\n 'Build or incrementally update the code knowledge graph.\\n\\n' +\n 'Call this first to initialize the graph, or after making changes.\\n' +\n 'By default performs an incremental update (only changed files).\\n' +\n 'Set full_rebuild=True to re-parse every file.\\n\\n' +\n 'Args:\\n' +\n ' full_rebuild: If True, re-parse all files. Default: False (incremental).\\n' +\n ' repo_root: Repository root path. Auto-detected from current directory if omitted.\\n' +\n ' base: Git ref to diff against for incremental updates. Default: HEAD~1.',\n {\n full_rebuild: z.boolean().default(false),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n buildOrUpdateGraph({\n fullRebuild: args.full_rebuild,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_impact_radius_tool',\n 'Analyze the blast radius of changed files in the codebase.\\n\\n' +\n 'Shows which functions, classes, and files are impacted by changes.\\n' +\n 'Auto-detects changed files from git if not specified.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.\\n' +\n ' max_depth: Number of hops to traverse in the dependency graph. Default: 2.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for auto-detecting changes. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getImpactRadius({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'query_graph_tool',\n 'Run a predefined graph query to explore code relationships.\\n\\n' +\n 'Available patterns:\\n' +\n '- callers_of: Find functions that call the target\\n' +\n '- callees_of: Find functions called by the target\\n' +\n '- imports_of: Find what the target imports\\n' +\n '- importers_of: Find files that import the target\\n' +\n '- children_of: Find nodes contained in a file or class\\n' +\n '- tests_for: Find tests for the target\\n' +\n '- inheritors_of: Find classes inheriting from the target\\n' +\n '- file_summary: Get all nodes in a file\\n\\n' +\n 'Args:\\n' +\n ' pattern: Query pattern name (see above).\\n' +\n ' target: Node name, qualified name, or file path to query.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n pattern: z.string(),\n target: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n queryGraph({\n pattern: args.pattern,\n target: args.target,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_review_context_tool',\n 'Generate a focused, token-efficient review context for code changes.\\n\\n' +\n 'Combines impact analysis with source snippets and review guidance.\\n' +\n 'Use this for comprehensive code reviews.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: Files to review. Auto-detected from git diff if omitted.\\n' +\n ' max_depth: Impact radius depth. Default: 2.\\n' +\n ' include_source: Include source code snippets. Default: True.\\n' +\n ' max_lines_per_file: Max source lines per file. Default: 200.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for change detection. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n include_source: z.boolean().default(true),\n max_lines_per_file: z.number().int().default(200),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getReviewContext({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n includeSource: args.include_source,\n maxLinesPerFile: args.max_lines_per_file,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'semantic_search_nodes_tool',\n 'Search for code entities by name, keyword, or semantic similarity.\\n\\n' +\n 'Uses vector embeddings for semantic search when available (run embed_graph_tool\\n' +\n 'first, requires @huggingface/transformers). Falls back to keyword matching otherwise.\\n\\n' +\n 'Args:\\n' +\n ' query: Search string to match against node names.\\n' +\n ' kind: Optional filter: File, Class, Function, Type, or Test.\\n' +\n ' limit: Maximum results. Default: 20.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n query: z.string(),\n kind: z.string().nullable().default(null),\n limit: z.number().int().default(20),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n await semanticSearchNodes({\n query: args.query,\n kind: args.kind,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'embed_graph_tool',\n 'Compute vector embeddings for all graph nodes to enable semantic search.\\n\\n' +\n 'Requires: npm install @huggingface/transformers\\n' +\n 'Only computes embeddings for nodes that do not already have them.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(await embedGraph({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'list_graph_stats_tool',\n 'Get aggregate statistics about the code knowledge graph.\\n\\n' +\n 'Shows total nodes, edges, languages, files, and last update time.\\n' +\n 'Useful for checking if the graph is built and up to date.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(listGraphStats({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_docs_section_tool',\n 'Get a specific section from the LLM-optimized documentation reference.\\n\\n' +\n 'Returns only the requested section content for minimal token usage.\\n\\n' +\n 'Available sections: usage, review-delta, review-pr, commands, legal,\\n' +\n 'watch, embeddings, languages, troubleshooting.\\n\\n' +\n 'Args:\\n' +\n ' section_name: The section to retrieve (e.g. \"review-delta\", \"usage\").',\n {\n section_name: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getDocsSection({\n sectionName: args.section_name,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'find_large_functions_tool',\n 'Find functions, classes, or files exceeding a line-count threshold.\\n\\n' +\n 'Useful for decomposition audits, code quality checks, and enforcing\\n' +\n 'size limits during code review. Results are ordered by line count.\\n\\n' +\n 'Args:\\n' +\n ' min_lines: Minimum line count to flag. Default: 50.\\n' +\n ' kind: Optional filter: Function, Class, File, or Test.\\n' +\n ' file_path_pattern: Filter by file path substring (e.g. \"components/\").\\n' +\n ' limit: Maximum results. Default: 50.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n min_lines: z.number().int().default(50),\n kind: z.string().nullable().default(null),\n file_path_pattern: z.string().nullable().default(null),\n limit: z.number().int().default(50),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n findLargeFunctions({\n minLines: args.min_lines,\n kind: args.kind,\n filePathPattern: args.file_path_pattern,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\n// ---------------------------------------------------------------------------\n// Server entry point\n// ---------------------------------------------------------------------------\n\nexport async function runMcpServer(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n","/**\n * MCP tool adapter layer.\n *\n * Each function: validate args → create infrastructure → call use case → return result.\n * No business logic lives here — all logic is in src/usecases/.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { SqliteGraphRepository, nodeToDict, edgeToDict } from '../../infrastructure/SqliteGraphRepository.js'\nimport { TreeSitterParser } from '../../infrastructure/TreeSitterParser.js'\nimport { SqliteEmbeddingStore } from '../../infrastructure/SqliteEmbeddingStore.js'\nimport { findProjectRoot, getDbPath } from '../../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles, getStagedAndUnstaged } from '../../infrastructure/GitRunner.js'\nimport { fullBuild, incrementalUpdate } from '../../usecases/buildGraph.js'\nimport { computeImpactRadius } from '../../usecases/getImpactRadius.js'\nimport { queryGraph as queryGraphUseCase } from '../../usecases/queryGraph.js'\nimport { getReviewContext as getReviewContextUseCase } from '../../usecases/getReviewContext.js'\nimport { semanticSearchNodes as semanticSearchUseCase } from '../../usecases/semanticSearch.js'\nimport { listStats } from '../../usecases/listStats.js'\nimport { embedGraph as embedGraphUseCase } from '../../usecases/embedGraph.js'\nimport { getDocsSection as getDocsSectionUseCase } from '../../usecases/getDocsSection.js'\nimport { findLargeFunctions as findLargeFunctionsUseCase } from '../../usecases/findLargeFunctions.js'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction validateRepoRoot(repoRoot: string): string {\n const resolved = path.resolve(repoRoot)\n if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {\n throw new Error(`repo_root is not an existing directory: ${resolved}`)\n }\n if (\n !fs.existsSync(path.join(resolved, '.git')) &&\n !fs.existsSync(path.join(resolved, '.codeorbit'))\n ) {\n throw new Error(\n `repo_root does not look like a project root (no .git or .codeorbit): ${resolved}`,\n )\n }\n return resolved\n}\n\nfunction resolveRoot(repoRoot?: string | null): string {\n return repoRoot ? validateRepoRoot(repoRoot) : findProjectRoot()\n}\n\n// ---------------------------------------------------------------------------\n// Tool 1: buildOrUpdateGraph\n// ---------------------------------------------------------------------------\n\nexport function buildOrUpdateGraph(args: {\n fullRebuild?: boolean\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const { fullRebuild = false, repoRoot = null, base = 'HEAD~1' } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n const parser = new TreeSitterParser()\n try {\n if (fullRebuild) {\n const result = fullBuild(root, repo, parser)\n return {\n status: 'ok',\n build_type: 'full',\n summary:\n `Full build complete: parsed ${result.filesUpdated} files, ` +\n `created ${result.totalNodes} nodes and ${result.totalEdges} edges.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n errors: result.errors,\n }\n } else {\n const result = incrementalUpdate(root, repo, parser, base)\n if (result.filesUpdated === 0) {\n return {\n status: 'ok',\n build_type: 'incremental',\n summary: 'No changes detected. Graph is up to date.',\n files_updated: 0,\n total_nodes: 0,\n total_edges: 0,\n changed_files: [],\n dependent_files: [],\n errors: [],\n }\n }\n return {\n status: 'ok',\n build_type: 'incremental',\n summary:\n `Incremental update: ${result.filesUpdated} files re-parsed, ` +\n `${result.totalNodes} nodes and ${result.totalEdges} edges updated. ` +\n `Changed: ${JSON.stringify(result.changedFiles)}. ` +\n `Dependents also updated: ${JSON.stringify(result.dependentFiles)}.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n changed_files: result.changedFiles,\n dependent_files: result.dependentFiles,\n errors: result.errors,\n }\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 2: getImpactRadius\n// ---------------------------------------------------------------------------\n\nexport function getImpactRadius(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n maxResults?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n maxResults = 500,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changed files detected.',\n changed_nodes: [],\n impacted_nodes: [],\n impacted_files: [],\n truncated: false,\n total_impacted: 0,\n }\n }\n\n const absFiles = changed.map((f) => path.join(root, f))\n const result = computeImpactRadius(absFiles, repo, maxDepth, maxResults)\n\n const summaryParts = [\n `Blast radius for ${changed.length} changed file(s):`,\n ` - ${result.changedNodes.length} nodes directly changed`,\n ` - ${result.impactedNodes.length} nodes impacted (within ${maxDepth} hops)`,\n ` - ${result.impactedFiles.length} additional files affected`,\n ]\n if (result.truncated) {\n summaryParts.push(\n ` - Results truncated: showing ${result.impactedNodes.length} of ${result.totalImpacted} impacted nodes`,\n )\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n changed_files: changed,\n changed_nodes: result.changedNodes.map(nodeToDict),\n impacted_nodes: result.impactedNodes.map(nodeToDict),\n impacted_files: result.impactedFiles,\n edges: result.edges.map(edgeToDict),\n truncated: result.truncated,\n total_impacted: result.totalImpacted,\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 3: queryGraph\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { pattern, target, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return queryGraphUseCase({ pattern, target, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 4: getReviewContext\n// ---------------------------------------------------------------------------\n\nexport function getReviewContext(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changes detected. Nothing to review.',\n context: {},\n }\n }\n\n return getReviewContextUseCase({\n changedFiles: changed,\n repo,\n repoRoot: root,\n maxDepth,\n includeSource,\n maxLinesPerFile,\n })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 5: semanticSearchNodes\n// ---------------------------------------------------------------------------\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await semanticSearchUseCase({ query, kind, limit, repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 6: listGraphStats\n// ---------------------------------------------------------------------------\n\nexport function listGraphStats(args: {\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return listStats({ repo, embStore, repoRoot: root })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 7: embedGraph\n// ---------------------------------------------------------------------------\n\nexport async function embedGraph(args: {\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await embedGraphUseCase({ repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 8: getDocsSection\n// ---------------------------------------------------------------------------\n\nexport function getDocsSection(args: {\n sectionName: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { sectionName, repoRoot = null } = args\n const searchRoots: string[] = []\n\n if (repoRoot) {\n searchRoots.push(path.resolve(repoRoot))\n }\n\n try {\n const root = resolveRoot(repoRoot)\n if (!searchRoots.includes(root)) {\n searchRoots.push(root)\n }\n } catch {\n // ignore — repo root not required for docs lookup\n }\n\n return getDocsSectionUseCase({ sectionName, searchRoots })\n}\n\n// ---------------------------------------------------------------------------\n// Tool 9: findLargeFunctions\n// ---------------------------------------------------------------------------\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repoRoot?: string | null\n}): Record<string, unknown> {\n const {\n minLines = 50,\n kind = null,\n filePathPattern = null,\n limit = 50,\n repoRoot = null,\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return findLargeFunctionsUseCase({ minLines, kind, filePathPattern, limit, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n","/**\n * SQLite-backed embedding store.\n *\n * Extracted from embeddings.ts::EmbeddingStore + helper functions.\n * Implements IEmbeddingStore.\n */\n\nimport crypto from 'node:crypto'\nimport Database from 'better-sqlite3'\nimport type { GraphNode } from '../domain/types.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\nimport { LocalEmbeddingProvider } from './LocalEmbeddingProvider.js'\nimport { GoogleEmbeddingProvider } from './GoogleEmbeddingProvider.js'\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nconst EMBEDDINGS_SCHEMA = `\nCREATE TABLE IF NOT EXISTS embeddings (\n qualified_name TEXT PRIMARY KEY,\n vector BLOB NOT NULL,\n text_hash TEXT NOT NULL,\n provider TEXT NOT NULL DEFAULT 'unknown'\n);\n`\n\n// ---------------------------------------------------------------------------\n// Vector helpers\n// ---------------------------------------------------------------------------\n\nfunction encodeVector(vec: number[]): Buffer {\n const buf = Buffer.allocUnsafe(vec.length * 4)\n for (let i = 0; i < vec.length; i++) buf.writeFloatLE(vec[i]!, i * 4)\n return buf\n}\n\nfunction decodeVector(blob: Buffer): number[] {\n const n = blob.length / 4\n const result: number[] = new Array(n)\n for (let i = 0; i < n; i++) result[i] = blob.readFloatLE(i * 4)\n return result\n}\n\nfunction cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) return 0\n let dot = 0, normA = 0, normB = 0\n for (let i = 0; i < a.length; i++) {\n dot += a[i]! * b[i]!\n normA += a[i]! * a[i]!\n normB += b[i]! * b[i]!\n }\n if (normA === 0 || normB === 0) return 0\n return dot / (Math.sqrt(normA) * Math.sqrt(normB))\n}\n\nexport function nodeToText(node: GraphNode): string {\n const parts = [node.name]\n if (node.kind !== 'File') parts.push(node.kind.toLowerCase())\n if (node.parentName) parts.push(`in ${node.parentName}`)\n if (node.params) parts.push(node.params)\n if (node.returnType) parts.push(`returns ${node.returnType}`)\n if (node.language) parts.push(node.language)\n return parts.join(' ')\n}\n\n// ---------------------------------------------------------------------------\n// Provider factory\n// ---------------------------------------------------------------------------\n\nexport function getProvider(provider?: string | null): IEmbeddingProvider | null {\n if (provider === 'google') {\n const apiKey = process.env['GOOGLE_API_KEY']\n if (!apiKey) return null\n try { return new GoogleEmbeddingProvider(apiKey) } catch { return null }\n }\n return new LocalEmbeddingProvider()\n}\n\n// ---------------------------------------------------------------------------\n// SqliteEmbeddingStore\n// ---------------------------------------------------------------------------\n\nexport class SqliteEmbeddingStore implements IEmbeddingStore {\n private _db: Database.Database\n readonly available: boolean\n private _provider: IEmbeddingProvider | null\n\n constructor(dbPath: string, provider?: string | null) {\n this._db = new Database(dbPath)\n this._db.exec(EMBEDDINGS_SCHEMA)\n\n try {\n this._db.prepare('SELECT provider FROM embeddings LIMIT 1').get()\n } catch {\n this._db.exec(\n \"ALTER TABLE embeddings ADD COLUMN provider TEXT NOT NULL DEFAULT 'unknown'\",\n )\n }\n\n this._provider = getProvider(provider)\n this.available = this._provider !== null\n }\n\n count(): number {\n const row = this._db\n .prepare('SELECT COUNT(*) AS cnt FROM embeddings')\n .get() as { cnt: number }\n return row.cnt\n }\n\n async embedNodes(nodes: GraphNode[], batchSize = 64): Promise<number> {\n if (!this._provider) return 0\n const providerName = this._provider.name\n\n const toEmbed: Array<{ node: GraphNode; text: string; textHash: string }> = []\n for (const node of nodes) {\n if (node.kind === 'File') continue\n const text = nodeToText(node)\n const textHash = crypto.createHash('sha256').update(text).digest('hex')\n const existing = this._db\n .prepare('SELECT text_hash, provider FROM embeddings WHERE qualified_name = ?')\n .get(node.qualifiedName) as { text_hash: string; provider: string } | undefined\n if (existing && existing.text_hash === textHash && existing.provider === providerName) {\n continue\n }\n toEmbed.push({ node, text, textHash })\n }\n\n if (toEmbed.length === 0) return 0\n\n const insert = this._db.prepare(\n 'INSERT OR REPLACE INTO embeddings (qualified_name, vector, text_hash, provider) VALUES (?, ?, ?, ?)',\n )\n\n for (let i = 0; i < toEmbed.length; i += batchSize) {\n const batch = toEmbed.slice(i, i + batchSize)\n const vectors = await this._provider.embed(batch.map((b) => b.text))\n this._db.transaction(() => {\n for (let j = 0; j < batch.length; j++) {\n const { node, textHash } = batch[j]!\n insert.run(node.qualifiedName, encodeVector(vectors[j]!), textHash, providerName)\n }\n })()\n }\n\n return toEmbed.length\n }\n\n async search(\n query: string,\n limit = 20,\n ): Promise<Array<{ qualifiedName: string; score: number }>> {\n if (!this._provider) return []\n const providerName = this._provider.name\n const queryVec = await this._provider.embedQuery(query)\n\n const rows = this._db\n .prepare('SELECT qualified_name, vector FROM embeddings WHERE provider = ?')\n .all(providerName) as Array<{ qualified_name: string; vector: Buffer }>\n\n const scored = rows.map((row) => ({\n qualifiedName: row.qualified_name,\n score: cosineSimilarity(queryVec, decodeVector(row.vector)),\n }))\n\n scored.sort((a, b) => b.score - a.score)\n return scored.slice(0, limit)\n }\n\n removeNode(qualifiedName: string): void {\n this._db\n .prepare('DELETE FROM embeddings WHERE qualified_name = ?')\n .run(qualifiedName)\n }\n\n close(): void {\n this._db.close()\n }\n}\n\n// Backward-compat alias\nexport { SqliteEmbeddingStore as EmbeddingStore }\n","/**\n * Local HuggingFace embedding provider.\n *\n * Extracted from embeddings.ts::LocalEmbeddingProvider.\n */\n\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst NOMIC_MODEL = 'Xenova/nomic-embed-text-v1.5'\nconst MINILM_MODEL = 'Xenova/all-MiniLM-L6-v2'\n\nexport class LocalEmbeddingProvider implements IEmbeddingProvider {\n private _pipelinePromise: Promise<unknown> | null = null\n private readonly _model: string\n private readonly _dim: number\n\n constructor() {\n const hasToken = !!(process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN'])\n this._model = hasToken ? NOMIC_MODEL : MINILM_MODEL\n this._dim = hasToken ? 768 : 384\n }\n\n private _getPipeline(): Promise<unknown> {\n if (!this._pipelinePromise) {\n const model = this._model\n this._pipelinePromise = import('@huggingface/transformers').then((mod) => {\n const { pipeline, env } = mod as Record<string, unknown> & {\n env: Record<string, unknown>\n pipeline: (task: string, model: string) => Promise<unknown>\n }\n const hfToken = process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN']\n if (hfToken) env['token'] = hfToken\n return pipeline('feature-extraction', model)\n })\n }\n return this._pipelinePromise\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array; dims: number[] }>\n const inputs =\n this._model === NOMIC_MODEL ? texts.map((t) => `search_document: ${t}`) : texts\n const output = await pipe(inputs, { pooling: 'mean', normalize: true })\n const dim = this._dim\n return Array.from({ length: texts.length }, (_, i) =>\n Array.from(output.data.subarray(i * dim, (i + 1) * dim)),\n )\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array }>\n const input = this._model === NOMIC_MODEL ? `search_query: ${text}` : text\n const output = await pipe([input], { pooling: 'mean', normalize: true })\n return Array.from(output.data)\n }\n\n get dimension(): number { return this._dim }\n\n get name(): string { return `local:${this._model.split('/')[1]}` }\n}\n","/**\n * Google Gemini embedding provider.\n *\n * Extracted from embeddings.ts::GoogleEmbeddingProvider.\n */\n\nimport { createRequire } from 'node:module'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst _require = createRequire(import.meta.url)\n\nexport class GoogleEmbeddingProvider implements IEmbeddingProvider {\n private _model: {\n embedContent(req: unknown): Promise<{ embedding: { values: number[] } }>\n batchEmbedContents(req: unknown): Promise<{ embeddings: Array<{ values: number[] }> }>\n }\n private _dimension: number | null = null\n readonly modelName: string\n\n constructor(apiKey: string, model = 'gemini-embedding-001') {\n this.modelName = model\n const { GoogleGenerativeAI } = _require('@google/generative-ai') as {\n GoogleGenerativeAI: new (key: string) => {\n getGenerativeModel(opts: { model: string }): unknown\n }\n }\n const genAI = new GoogleGenerativeAI(apiKey)\n this._model = genAI.getGenerativeModel({ model }) as typeof this._model\n }\n\n private async _withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await fn()\n } catch (e) {\n const msg = String(e)\n const retryable = msg.includes('429') || msg.includes('500') || msg.includes('503')\n if (!retryable || attempt === maxRetries - 1) throw e\n await new Promise((r) => setTimeout(r, 2 ** attempt * 1000))\n }\n }\n throw new Error('unreachable')\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const batchSize = 100\n const results: number[][] = []\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize)\n const response = await this._withRetry(() =>\n this._model.batchEmbedContents({\n requests: batch.map((t) => ({\n content: { parts: [{ text: t }], role: 'user' },\n taskType: 'RETRIEVAL_DOCUMENT',\n })),\n }),\n )\n results.push(...response.embeddings.map((e) => e.values))\n }\n if (this._dimension === null && results.length > 0) {\n this._dimension = results[0]!.length\n }\n return results\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const response = await this._withRetry(() =>\n this._model.embedContent({\n content: { parts: [{ text }], role: 'user' },\n taskType: 'RETRIEVAL_QUERY',\n }),\n )\n const vec = response.embedding.values\n if (this._dimension === null) this._dimension = vec.length\n return vec\n }\n\n get dimension(): number { return this._dimension ?? 768 }\n\n get name(): string { return `google:${this.modelName}` }\n}\n","/**\n * Use case: compute impact radius via BFS.\n *\n * Extracted from GraphStore.getImpactRadius() so the BFS algorithm lives in\n * the application layer, independent of the SQLite infrastructure.\n */\n\nimport type { ImpactRadius } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\n\nexport function computeImpactRadius(\n changedFiles: string[],\n repo: IGraphRepository,\n maxDepth = 2,\n maxNodes = 500,\n): ImpactRadius {\n const adj = repo.getAdjacency()\n\n // Seed: all qualified names in changed files\n const seeds = new Set<string>()\n for (const f of changedFiles) {\n for (const node of repo.getNodesByFile(f)) {\n seeds.add(node.qualifiedName)\n }\n }\n\n const visited = new Set<string>()\n let frontier = new Set(seeds)\n const impacted = new Set<string>()\n let depth = 0\n\n while (frontier.size > 0 && depth < maxDepth) {\n const nextFrontier = new Set<string>()\n for (const qn of frontier) {\n visited.add(qn)\n const outNeighbors = adj.outgoing.get(qn)\n if (outNeighbors) {\n for (const nb of outNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n const inNeighbors = adj.incoming.get(qn)\n if (inNeighbors) {\n for (const nb of inNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n }\n if (visited.size + nextFrontier.size > maxNodes) { break }\n frontier = nextFrontier\n depth++\n }\n\n const changedNodes = []\n for (const qn of seeds) {\n const n = repo.getNode(qn)\n if (n) { changedNodes.push(n) }\n }\n\n let impactedNodes = []\n for (const qn of impacted) {\n if (seeds.has(qn)) { continue }\n const n = repo.getNode(qn)\n if (n) { impactedNodes.push(n) }\n }\n\n const totalImpacted = impactedNodes.length\n const truncated = totalImpacted > maxNodes\n if (truncated) { impactedNodes = impactedNodes.slice(0, maxNodes) }\n\n const impactedFiles = [...new Set(impactedNodes.map((n) => n.filePath))]\n\n const allQns = new Set([...seeds, ...impactedNodes.map((n) => n.qualifiedName)])\n const edges = allQns.size > 0 ? repo.getEdgesAmong(allQns) : []\n\n return { changedNodes, impactedNodes, impactedFiles, edges, truncated, totalImpacted }\n}\n","/**\n * Use case: predefined graph queries (callers_of, callees_of, etc.).\n *\n * Extracted from tools.ts::queryGraph.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const BUILTIN_CALL_NAMES = new Set([\n 'map', 'filter', 'reduce', 'reduceRight', 'forEach', 'find', 'findIndex',\n 'some', 'every', 'includes', 'indexOf', 'lastIndexOf', 'push', 'pop',\n 'shift', 'unshift', 'splice', 'slice', 'concat', 'join', 'flat', 'flatMap',\n 'sort', 'reverse', 'fill', 'keys', 'values', 'entries', 'from', 'isArray',\n 'of', 'at', 'trim', 'trimStart', 'trimEnd', 'split', 'replace', 'replaceAll',\n 'match', 'matchAll', 'search', 'substring', 'substr', 'toLowerCase',\n 'toUpperCase', 'startsWith', 'endsWith', 'padStart', 'padEnd', 'repeat',\n 'charAt', 'charCodeAt', 'assign', 'freeze', 'defineProperty',\n 'getOwnPropertyNames', 'hasOwnProperty', 'create', 'is', 'fromEntries',\n 'log', 'warn', 'error', 'info', 'debug', 'trace', 'dir', 'table', 'time',\n 'timeEnd', 'assert', 'clear', 'count', 'then', 'catch', 'finally',\n 'resolve', 'reject', 'all', 'allSettled', 'race', 'any', 'parse',\n 'stringify', 'floor', 'ceil', 'round', 'random', 'max', 'min', 'abs',\n 'pow', 'sqrt', 'addEventListener', 'removeEventListener', 'querySelector',\n 'querySelectorAll', 'getElementById', 'createElement', 'appendChild',\n 'removeChild', 'setAttribute', 'getAttribute', 'preventDefault',\n 'stopPropagation', 'setTimeout', 'clearTimeout', 'setInterval',\n 'clearInterval', 'toString', 'valueOf', 'toJSON', 'toISOString', 'getTime',\n 'getFullYear', 'now', 'isNaN', 'parseInt', 'parseFloat', 'toFixed',\n 'encodeURIComponent', 'decodeURIComponent', 'call', 'apply', 'bind',\n 'next', 'emit', 'on', 'off', 'once', 'pipe', 'write', 'read', 'end',\n 'close', 'destroy', 'send', 'status', 'json', 'redirect', 'set', 'get',\n 'delete', 'has', 'findUnique', 'findFirst', 'findMany', 'createMany',\n 'update', 'updateMany', 'deleteMany', 'upsert', 'aggregate', 'groupBy',\n 'transaction', 'describe', 'it', 'test', 'expect', 'beforeEach',\n 'afterEach', 'beforeAll', 'afterAll', 'mock', 'spyOn', 'require', 'fetch',\n])\n\nexport const QUERY_PATTERNS: Record<string, string> = {\n callers_of: 'Find all functions that call a given function',\n callees_of: 'Find all functions called by a given function',\n imports_of: 'Find all imports of a given file or module',\n importers_of: 'Find all files that import a given file or module',\n children_of: 'Find all nodes contained in a file or class',\n tests_for: 'Find all tests for a given function or class',\n inheritors_of: 'Find all classes that inherit from a given class',\n file_summary: 'Get a summary of all nodes in a file',\n}\n\n// ---------------------------------------------------------------------------\n// Use case\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { pattern, target, repo, repoRoot } = args\n\n if (!QUERY_PATTERNS[pattern]) {\n return {\n status: 'error',\n error: `Unknown pattern '${pattern}'. Available: ${Object.keys(QUERY_PATTERNS).join(', ')}`,\n }\n }\n\n const results: Array<Record<string, unknown>> = []\n const edgesOut: Array<Record<string, unknown>> = []\n\n if (\n pattern === 'callers_of' &&\n BUILTIN_CALL_NAMES.has(target) &&\n !target.includes('::')\n ) {\n return {\n status: 'ok',\n pattern,\n target,\n description: QUERY_PATTERNS[pattern],\n summary: `'${target}' is a common builtin — callers_of skipped to avoid noise.`,\n results: [],\n edges: [],\n }\n }\n\n let node = repo.getNode(target)\n let resolvedTarget = target\n\n if (!node) {\n const absTarget = path.join(repoRoot, target)\n node = repo.getNode(absTarget)\n if (node) { resolvedTarget = absTarget }\n }\n if (!node) {\n const candidates = repo.searchNodes(target, 5)\n if (candidates.length === 1) {\n node = candidates[0]!\n resolvedTarget = node.qualifiedName\n } else if (candidates.length > 1) {\n return {\n status: 'ambiguous',\n summary: `Multiple matches for '${target}'. Please use a qualified name.`,\n candidates: candidates.map(nodeToDict),\n }\n }\n }\n\n if (!node && pattern !== 'file_summary') {\n return { status: 'not_found', summary: `No node found matching '${target}'.` }\n }\n\n const qn = node?.qualifiedName ?? resolvedTarget\n\n if (pattern === 'callers_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'CALLS') {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n if (results.length === 0 && node) {\n for (const e of repo.searchEdgesByTargetName(node.name)) {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'callees_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CALLS') {\n const callee = repo.getNode(e.targetQualified)\n if (callee) { results.push(nodeToDict(callee)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'imports_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ import_target: e.targetQualified })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'importers_of') {\n const absTarget = node ? node.filePath : path.join(repoRoot, target)\n for (const e of repo.getEdgesByTarget(absTarget)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ importer: e.sourceQualified, file: e.filePath })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'children_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CONTAINS') {\n const child = repo.getNode(e.targetQualified)\n if (child) { results.push(nodeToDict(child)) }\n }\n }\n } else if (pattern === 'tests_for') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'TESTED_BY') {\n const testNode = repo.getNode(e.sourceQualified)\n if (testNode) { results.push(nodeToDict(testNode)) }\n }\n }\n const name = node?.name ?? target\n const seenQns = new Set(results.map((r) => r['qualified_name']))\n for (const t of [\n ...repo.searchNodes(`test_${name}`, 10),\n ...repo.searchNodes(`Test${name}`, 10),\n ]) {\n if (!seenQns.has(t.qualifiedName) && t.isTest) {\n results.push(nodeToDict(t))\n }\n }\n } else if (pattern === 'inheritors_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS') {\n const child = repo.getNode(e.sourceQualified)\n if (child) { results.push(nodeToDict(child)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'file_summary') {\n const absPath = path.join(repoRoot, target)\n for (const n of repo.getNodesByFile(absPath)) {\n results.push(nodeToDict(n))\n }\n }\n\n return {\n status: 'ok',\n pattern,\n target: resolvedTarget,\n description: QUERY_PATTERNS[pattern],\n summary: `Found ${results.length} result(s) for ${pattern}('${resolvedTarget}')`,\n results,\n edges: edgesOut,\n }\n}\n","/**\n * Use case: generate focused review context for changed files.\n *\n * Extracted from tools.ts::getReviewContext + extractRelevantLines + generateReviewGuidance.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { ImpactRadius, GraphNode } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\nimport { computeImpactRadius } from './getImpactRadius.js'\n\nexport function getReviewContext(args: {\n changedFiles: string[]\n repo: IGraphRepository\n repoRoot: string\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n}): Record<string, unknown> {\n const {\n changedFiles,\n repo,\n repoRoot,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n } = args\n\n if (changedFiles.length === 0) {\n return { status: 'ok', summary: 'No changes detected. Nothing to review.', context: {} }\n }\n\n const absFiles = changedFiles.map((f) => path.join(repoRoot, f))\n const impact = computeImpactRadius(absFiles, repo, maxDepth)\n\n const context: Record<string, unknown> = {\n changed_files: changedFiles,\n impacted_files: impact.impactedFiles,\n graph: {\n changed_nodes: impact.changedNodes.map(nodeToDict),\n impacted_nodes: impact.impactedNodes.map(nodeToDict),\n edges: impact.edges.map(edgeToDict),\n },\n }\n\n if (includeSource) {\n const snippets: Record<string, string> = {}\n for (const relPath of changedFiles) {\n const fullPath = path.join(repoRoot, relPath)\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {\n try {\n const content = fs.readFileSync(fullPath, 'utf-8')\n const lines = content.split('\\n')\n if (lines.length > maxLinesPerFile) {\n snippets[relPath] = extractRelevantLines(lines, impact.changedNodes, fullPath)\n } else {\n snippets[relPath] = lines.map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n } catch {\n snippets[relPath] = '(could not read file)'\n }\n }\n }\n context['source_snippets'] = snippets\n }\n\n const guidance = generateReviewGuidance(impact, changedFiles)\n context['review_guidance'] = guidance\n\n const summaryParts = [\n `Review context for ${changedFiles.length} changed file(s):`,\n ` - ${impact.changedNodes.length} directly changed nodes`,\n ` - ${impact.impactedNodes.length} impacted nodes in ${impact.impactedFiles.length} files`,\n '',\n 'Review guidance:',\n guidance,\n ]\n\n return { status: 'ok', summary: summaryParts.join('\\n'), context }\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\nfunction extractRelevantLines(\n lines: string[],\n nodes: GraphNode[],\n filePath: string,\n): string {\n const ranges: Array<[number, number]> = []\n for (const n of nodes) {\n if (n.filePath === filePath) {\n const start = Math.max(0, (n.lineStart ?? 1) - 3)\n const end = Math.min(lines.length, (n.lineEnd ?? lines.length) + 2)\n ranges.push([start, end])\n }\n }\n\n if (ranges.length === 0) {\n return lines.slice(0, 50).map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n\n ranges.sort((a, b) => a[0] - b[0])\n const merged: Array<[number, number]> = [ranges[0]!]\n for (const [start, end] of ranges.slice(1)) {\n const last = merged[merged.length - 1]!\n if (start <= last[1] + 1) {\n merged[merged.length - 1] = [last[0], Math.max(last[1], end)]\n } else {\n merged.push([start, end])\n }\n }\n\n const parts: string[] = []\n for (const [start, end] of merged) {\n if (parts.length > 0) { parts.push('...') }\n for (let i = start; i < end; i++) {\n parts.push(`${i + 1}: ${lines[i] ?? ''}`)\n }\n }\n return parts.join('\\n')\n}\n\nfunction generateReviewGuidance(impact: ImpactRadius, _changedFiles: string[]): string {\n const guidanceParts: string[] = []\n\n const changedFuncs = impact.changedNodes.filter((n) => n.kind === 'Function')\n const testedFuncQns = new Set(\n impact.edges\n .filter((e) => e.kind === 'TESTED_BY')\n .map((e) => e.sourceQualified),\n )\n const untested = changedFuncs.filter(\n (f) => !testedFuncQns.has(f.qualifiedName) && !f.isTest,\n )\n if (untested.length > 0) {\n guidanceParts.push(\n `- ${untested.length} changed function(s) lack test coverage: ` +\n untested.slice(0, 5).map((n) => n.name).join(', '),\n )\n }\n\n if (impact.impactedNodes.length > 20) {\n guidanceParts.push(\n `- Wide blast radius: ${impact.impactedNodes.length} nodes impacted. ` +\n 'Review callers and dependents carefully.',\n )\n }\n\n const inheritanceEdges = impact.edges.filter(\n (e) => e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS',\n )\n if (inheritanceEdges.length > 0) {\n guidanceParts.push(\n `- ${inheritanceEdges.length} inheritance/implementation relationship(s) affected. ` +\n 'Check for Liskov substitution violations.',\n )\n }\n\n if (impact.impactedFiles.length > 3) {\n guidanceParts.push(\n `- Changes impact ${impact.impactedFiles.length} other files. ` +\n 'Consider splitting into smaller PRs.',\n )\n }\n\n if (guidanceParts.length === 0) {\n guidanceParts.push('- Changes appear well-contained with minimal blast radius.')\n }\n\n return guidanceParts.join('\\n')\n}\n","/**\n * Use case: semantic or keyword search across graph nodes.\n *\n * Extracted from tools.ts::semanticSearchNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repo, embStore } = args\n let searchMode = 'keyword'\n\n try {\n if (embStore.available && embStore.count() > 0) {\n searchMode = 'semantic'\n let raw = await semanticSearch(query, repo, embStore, limit * 2)\n if (kind) { raw = raw.filter((r) => r['kind'] === kind) }\n raw = raw.slice(0, limit)\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${raw.length} node(s) matching '${query}' via semantic search` +\n (kind ? ` (kind=${kind})` : ''),\n results: raw,\n }\n }\n } catch {\n searchMode = 'keyword'\n }\n\n let results = repo.searchNodes(query, limit * 2)\n if (kind) { results = results.filter((r) => r.kind === kind) }\n\n const qLower = query.toLowerCase()\n results.sort((a, b) => {\n const aLower = a.name.toLowerCase()\n const bLower = b.name.toLowerCase()\n const aScore = aLower === qLower ? 0 : aLower.startsWith(qLower) ? 1 : 2\n const bScore = bLower === qLower ? 0 : bLower.startsWith(qLower) ? 1 : 2\n return aScore - bScore\n })\n results = results.slice(0, limit)\n\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${results.length} node(s) matching '${query}'` +\n (kind ? ` (kind=${kind})` : ''),\n results: results.map(nodeToDict),\n }\n}\n\nasync function semanticSearch(\n query: string,\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n limit = 20,\n): Promise<Array<Record<string, unknown>>> {\n if (embStore.available && embStore.count() > 0) {\n const results = await embStore.search(query, limit)\n const output: Array<Record<string, unknown>> = []\n for (const { qualifiedName, score } of results) {\n const node = repo.getNode(qualifiedName)\n if (node) {\n const d = nodeToDict(node)\n d['similarity_score'] = Math.round(score * 10000) / 10000\n output.push(d)\n }\n }\n return output\n }\n return repo.searchNodes(query, limit).map((n) => nodeToDict(n))\n}\n","/**\n * Use case: list aggregate graph statistics.\n *\n * Extracted from tools.ts::listGraphStats.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport function listStats(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n repoRoot: string\n}): Record<string, unknown> {\n const { repo, embStore, repoRoot } = args\n const stats = repo.getStats()\n const rootName = path.basename(repoRoot)\n\n const summaryParts = [\n `Graph statistics for ${rootName}:`,\n ` Files: ${stats.filesCount}`,\n ` Total nodes: ${stats.totalNodes}`,\n ` Total edges: ${stats.totalEdges}`,\n ` Languages: ${stats.languages.length > 0 ? stats.languages.join(', ') : 'none'}`,\n ` Last updated: ${stats.lastUpdated ?? 'never'}`,\n '',\n 'Nodes by kind:',\n ...Object.entries(stats.nodesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n '',\n 'Edges by kind:',\n ...Object.entries(stats.edgesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n ]\n\n let embCount = 0\n try {\n embCount = embStore.count()\n summaryParts.push('', `Embeddings: ${embCount} nodes embedded`)\n if (!embStore.available) {\n summaryParts.push(' (install @huggingface/transformers for semantic search)')\n }\n } catch {\n // embeddings unavailable\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_nodes: stats.totalNodes,\n total_edges: stats.totalEdges,\n nodes_by_kind: stats.nodesByKind,\n edges_by_kind: stats.edgesByKind,\n languages: stats.languages,\n files_count: stats.filesCount,\n last_updated: stats.lastUpdated,\n embeddings_count: embCount,\n }\n}\n","/**\n * Use case: embed all graph nodes for semantic search.\n *\n * Extracted from tools.ts::embedGraph + embeddings.ts::embedAllNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport async function embedAllNodes(\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n): Promise<number> {\n if (!embStore.available) return 0\n const allNodes = []\n for (const f of repo.getAllFiles()) {\n allNodes.push(...repo.getNodesByFile(f))\n }\n return embStore.embedNodes(allNodes)\n}\n\nexport async function embedGraph(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { repo, embStore } = args\n\n if (!embStore.available) {\n return {\n status: 'error',\n error:\n '@huggingface/transformers is not installed. ' +\n 'Install with: npm install codeorbit (with optional deps)',\n }\n }\n\n const newlyEmbedded = await embedAllNodes(repo, embStore)\n const total = embStore.count()\n return {\n status: 'ok',\n summary:\n `Embedded ${newlyEmbedded} new node(s). Total embeddings: ${total}. ` +\n 'Semantic search is now active.',\n newly_embedded: newlyEmbedded,\n total_embeddings: total,\n }\n}\n","/**\n * Use case: retrieve a named section from the LLM-optimized docs reference.\n *\n * Extracted from tools.ts::getDocsSection.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nconst AVAILABLE_SECTIONS = [\n 'usage',\n 'review-delta',\n 'review-pr',\n 'commands',\n 'legal',\n 'watch',\n 'embeddings',\n 'languages',\n 'troubleshooting',\n]\n\nexport function getDocsSection(args: {\n sectionName: string\n searchRoots: string[]\n}): Record<string, unknown> {\n const { sectionName, searchRoots } = args\n\n for (const searchRoot of searchRoots) {\n const candidate = path.join(searchRoot, 'docs', 'LLM-OPTIMIZED-REFERENCE.md')\n if (fs.existsSync(candidate)) {\n const content = fs.readFileSync(candidate, 'utf-8')\n const escapedName = sectionName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const match = new RegExp(\n `<section name=\"${escapedName}\">(.*?)</section>`,\n 'si',\n ).exec(content)\n if (match) {\n return { status: 'ok', section: sectionName, content: match[1]!.trim() }\n }\n }\n }\n\n return {\n status: 'not_found',\n error: `Section '${sectionName}' not found. Available: ${AVAILABLE_SECTIONS.join(', ')}`,\n }\n}\n","/**\n * Use case: find functions/classes exceeding a line-count threshold.\n *\n * Extracted from tools.ts::findLargeFunctions.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { minLines = 50, kind = null, filePathPattern = null, limit = 50, repo, repoRoot } = args\n\n const nodes = repo.getNodesBySize(\n minLines,\n undefined,\n kind ?? undefined,\n filePathPattern ?? undefined,\n limit,\n )\n\n const results = nodes.map((n) => {\n const d = nodeToDict(n) as Record<string, unknown>\n d['line_count'] =\n n.lineStart != null && n.lineEnd != null ? n.lineEnd - n.lineStart + 1 : 0\n try {\n d['relative_path'] = path.relative(repoRoot, n.filePath)\n } catch {\n d['relative_path'] = n.filePath\n }\n return d\n })\n\n const summaryParts = [\n `Found ${results.length} node(s) with >= ${minLines} lines` +\n (kind ? ` (kind=${kind})` : '') +\n (filePathPattern ? ` matching '${filePathPattern}'` : '') +\n ':',\n ]\n for (const r of results.slice(0, 10)) {\n summaryParts.push(\n ` ${String(r['line_count']).padStart(4)} lines | ${String(r['kind']).padStart(8)} | ` +\n `${r['name']} (${r['relative_path']}:${r['line_start']})`,\n )\n }\n if (results.length > 10) {\n summaryParts.push(` ... and ${results.length - 10} more`)\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_found: results.length,\n min_lines: minLines,\n results,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAGA,QAAMA,kBAAN,cAA6B,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","InvalidArgumentError","Option","str","path","fs","process","Argument","CommanderError","Help","Option","Command","option","Argument","Command","CommanderError","InvalidArgumentError","Help","Option","fs","path","createRequire","commander","fs","path","path","fs","fs","path","fs","path","crypto","fs","path","path","fs","crypto","crypto","fs","path","fs","path","crypto","fs","path","crypto","Database","createRequire","_require","Database","crypto","path","path","fs","path","path","fs","path","fs","path","path","path","path","fs","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions","createRequire","path","fs","program"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters/cli/cli.ts","../src/infrastructure/SqliteGraphRepository.ts","../src/infrastructure/TreeSitterParser.ts","../src/infrastructure/FileSystemHelper.ts","../src/infrastructure/GitRunner.ts","../src/usecases/buildGraph.ts","../src/infrastructure/watch.ts","../src/adapters/mcp/server.ts","../src/adapters/mcp/tools.ts","../src/infrastructure/SqliteEmbeddingStore.ts","../src/infrastructure/LocalEmbeddingProvider.ts","../src/infrastructure/GoogleEmbeddingProvider.ts","../src/usecases/getImpactRadius.ts","../src/usecases/queryGraph.ts","../src/usecases/getReviewContext.ts","../src/usecases/semanticSearch.ts","../src/usecases/listStats.ts","../src/usecases/embedGraph.ts","../src/usecases/getDocsSection.ts","../src/usecases/findLargeFunctions.ts","../src/adapters/cli/ipcWorker.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * CLI entry point for codeorbit.\n *\n * Usage:\n * codeorbit install\n * codeorbit init\n * codeorbit build [--repo PATH]\n * codeorbit update [--base REF] [--repo PATH]\n * codeorbit watch [--repo PATH]\n * codeorbit status [--repo PATH]\n * codeorbit visualize [--repo PATH]\n * codeorbit serve [--repo PATH]\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { SqliteGraphRepository } from '../../infrastructure/SqliteGraphRepository.js'\nimport { TreeSitterParser } from '../../infrastructure/TreeSitterParser.js'\nimport {\n findProjectRoot,\n findRepoRoot,\n getDbPath,\n} from '../../infrastructure/FileSystemHelper.js'\nimport { fullBuild, incrementalUpdate } from '../../usecases/buildGraph.js'\nimport { watch } from '../../infrastructure/watch.js'\nimport { runMcpServer } from '../mcp/server.js'\nimport { runIpcWorker } from './ipcWorker.js'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction getVersion(): string {\n try {\n const req = createRequire(import.meta.url)\n const pkg = req('../package.json') as { version: string }\n return pkg.version\n } catch {\n return 'dev'\n }\n}\n\nfunction supportsColor(): boolean {\n if (process.env['NO_COLOR']) {\n return false\n }\n return Boolean(process.stdout.isTTY)\n}\n\nfunction printBanner(): void {\n const color = supportsColor()\n const c = color ? '\\x1b[36m' : '' // cyan — graph art\n const y = color ? '\\x1b[33m' : '' // yellow — center node\n const b = color ? '\\x1b[1m' : '' // bold\n const d = color ? '\\x1b[2m' : '' // dim\n const g = color ? '\\x1b[32m' : '' // green — commands\n const r = color ? '\\x1b[0m' : '' // reset\n\n const version = getVersion()\n console.log(`\n${c} ●──●──●${r}\n${c} │╲ │ ╱│${r} ${b}codeorbit${r} ${d}v${version}${r}\n${c} ●──${y}◆${c}──●${r}\n${c} │╱ │ ╲│${r} ${d}Structural knowledge graph for${r}\n${c} ●──●──●${r} ${d}smarter code reviews${r}\n\n ${b}Commands:${r}\n ${g}install${r} Set up Claude Code integration\n ${g}init${r} Alias for install\n ${g}build${r} Full graph build ${d}(parse all files)${r}\n ${g}update${r} Incremental update ${d}(changed files only)${r}\n ${g}watch${r} Auto-update on file changes\n ${g}status${r} Show graph statistics\n ${g}visualize${r} Generate interactive HTML graph\n ${g}serve${r} Start MCP server\n\n ${d}Run${r} ${b}codeorbit <command> --help${r} ${d}for details${r}\n`)\n}\n\n// ---------------------------------------------------------------------------\n// install / init\n// ---------------------------------------------------------------------------\n\nfunction handleInit(repoArg: string | undefined, dryRun: boolean): void {\n const repoRoot = repoArg\n ? path.resolve(repoArg)\n : (findRepoRoot() ?? process.cwd())\n\n const mcpPath = path.join(repoRoot, '.mcp.json')\n\n const newEntry = {\n command: 'npx',\n args: ['codeorbit', 'serve'],\n }\n\n let mcpConfig: Record<string, unknown> = {\n mcpServers: { codeorbit: newEntry },\n }\n\n // Merge into existing .mcp.json if present\n if (fs.existsSync(mcpPath)) {\n try {\n const existing = JSON.parse(fs.readFileSync(mcpPath, 'utf-8')) as Record<\n string,\n unknown\n >\n const servers = existing['mcpServers'] as\n | Record<string, unknown>\n | undefined\n if (servers && 'codeorbit' in servers) {\n console.log(`Already configured in ${mcpPath}`)\n return\n }\n if (!existing['mcpServers']) {\n existing['mcpServers'] = {}\n }\n ;(existing['mcpServers'] as Record<string, unknown>)['codeorbit'] =\n newEntry\n mcpConfig = existing\n } catch {\n console.log(`Warning: existing ${mcpPath} has invalid JSON, overwriting.`)\n }\n }\n\n if (dryRun) {\n console.log(`[dry-run] Would write to ${mcpPath}:`)\n console.log(JSON.stringify(mcpConfig, null, 2))\n console.log()\n console.log('[dry-run] No files were modified.')\n return\n }\n\n fs.writeFileSync(mcpPath, JSON.stringify(mcpConfig, null, 2) + '\\n')\n console.log(`Created ${mcpPath}`)\n console.log()\n console.log('Next steps:')\n console.log(' 1. codeorbit build # build the knowledge graph')\n console.log(' 2. Restart Claude Code # to pick up the new MCP server')\n}\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\nconst program = new Command()\n\nprogram\n .name('codeorbit')\n .description('Persistent incremental knowledge graph for code reviews')\n .version(getVersion(), '-v, --version')\n .action(() => {\n printBanner()\n })\n\n// install\nprogram\n .command('install')\n .description('Register MCP server with Claude Code (creates .mcp.json)')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .option('--dry-run', 'Show what would be done without writing files', false)\n .action((opts: { repo?: string; dryRun: boolean }) => {\n handleInit(opts.repo, opts.dryRun)\n })\n\n// init (alias for install)\nprogram\n .command('init')\n .description('Alias for install')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .option('--dry-run', 'Show what would be done without writing files', false)\n .action((opts: { repo?: string; dryRun: boolean }) => {\n handleInit(opts.repo, opts.dryRun)\n })\n\n// build\nprogram\n .command('build')\n .description('Full graph build (re-parse all files)')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n const parser = new TreeSitterParser()\n try {\n const result = fullBuild(repoRoot, repo, parser)\n console.log(\n `Full build: ${result.filesUpdated} files, ` +\n `${result.totalNodes} nodes, ${result.totalEdges} edges`,\n )\n if (result.errors.length > 0) {\n console.log(`Errors: ${result.errors.length}`)\n for (const e of result.errors) {\n console.error(` ${e}`)\n }\n }\n } finally {\n repo.close()\n }\n })\n\n// update\nprogram\n .command('update')\n .description('Incremental update (only changed files)')\n .option('--base <ref>', 'Git diff base', 'HEAD~1')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { base: string; repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findRepoRoot()\n if (!repoRoot) {\n console.error(\n \"Not in a git repository. 'update' requires git for diffing.\",\n )\n console.error(\"Use 'build' for a full parse, or run 'git init' first.\")\n process.exit(1)\n }\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n const parser = new TreeSitterParser()\n try {\n const result = incrementalUpdate(repoRoot, repo, parser, opts.base)\n console.log(\n `Incremental: ${result.filesUpdated} files updated, ` +\n `${result.totalNodes} nodes, ${result.totalEdges} edges`,\n )\n if (result.errors.length > 0) {\n console.log(`Errors: ${result.errors.length}`)\n for (const e of result.errors) {\n console.error(` ${e}`)\n }\n }\n } finally {\n repo.close()\n }\n })\n\n// watch\nprogram\n .command('watch')\n .description('Watch for changes and auto-update')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action(async (opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n const parser = new TreeSitterParser()\n await watch(repoRoot, repo, parser)\n repo.close()\n })\n\n// status\nprogram\n .command('status')\n .description('Show graph statistics')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const dbPath = getDbPath(repoRoot)\n const repo = new SqliteGraphRepository(dbPath)\n try {\n const stats = repo.getStats()\n console.log(`codeorbit v${getVersion()}`)\n console.log(`Repo: ${repoRoot}`)\n console.log(`DB: ${dbPath}`)\n console.log(`Nodes: ${stats.totalNodes}`)\n console.log(`Edges: ${stats.totalEdges}`)\n console.log(`Files: ${stats.filesCount}`)\n console.log(`Languages: ${stats.languages.join(', ')}`)\n console.log(`Last updated: ${stats.lastUpdated ?? 'never'}`)\n } finally {\n repo.close()\n }\n })\n\n// visualize\nprogram\n .command('visualize')\n .description('Generate interactive HTML graph visualization')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action((opts: { repo?: string }) => {\n const repoRoot = opts.repo ? path.resolve(opts.repo) : findProjectRoot()\n const htmlPath = path.join(repoRoot, '.codeorbit', 'graph.html')\n console.log('Visualization not yet implemented in the TypeScript port.')\n console.log(`Would write to: ${htmlPath}`)\n console.log(\n 'Visualization is not yet implemented. Coming in a future release.',\n )\n process.exit(1)\n })\n\n// serve\nprogram\n .command('serve')\n .description('Start MCP server (stdio transport)')\n .action(async () => {\n await runMcpServer()\n })\n\n// ipc\nprogram\n .command('ipc')\n .description('Start persistent IPC worker for the VS Code extension (internal)')\n .option('--repo <path>', 'Repository root (auto-detected)')\n .action(async () => {\n await runIpcWorker()\n })\n\nprogram.parse()\n","/**\n * SQLite-backed knowledge graph storage — infrastructure implementation.\n *\n * Implements IGraphRepository. Pure CRUD + adjacency — no business logic.\n * BFS impact-radius computation was extracted to usecases/getImpactRadius.ts.\n *\n * Direct port of code_review_graph/graph.py.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport Database from 'better-sqlite3';\nimport type {\n NodeInfo,\n EdgeInfo,\n GraphNode,\n GraphEdge,\n GraphStats,\n NodeRow,\n EdgeRow,\n CountRow,\n KindCountRow,\n LanguageRow,\n FilePathRow,\n MetadataRow,\n EdgeKind,\n} from '../domain/types.js';\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js';\n\n// ---------------------------------------------------------------------------\n// Schema DDL — must match Python's _SCHEMA_SQL exactly (schema_version = 1)\n// ---------------------------------------------------------------------------\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS nodes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL UNIQUE,\n file_path TEXT NOT NULL,\n line_start INTEGER,\n line_end INTEGER,\n language TEXT,\n parent_name TEXT,\n params TEXT,\n return_type TEXT,\n modifiers TEXT,\n is_test INTEGER DEFAULT 0,\n file_hash TEXT,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n source_qualified TEXT NOT NULL,\n target_qualified TEXT NOT NULL,\n file_path TEXT NOT NULL,\n line INTEGER DEFAULT 0,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(file_path);\nCREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind);\nCREATE INDEX IF NOT EXISTS idx_nodes_qualified ON nodes(qualified_name);\nCREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);\nCREATE INDEX IF NOT EXISTS idx_edges_file ON edges(file_path);\n`;\n\n// ---------------------------------------------------------------------------\n// In-memory adjacency cache (replaces networkx.DiGraph)\n// ---------------------------------------------------------------------------\n\ninterface AdjacencyCache {\n out: Map<string, Set<string>>;\n in: Map<string, Set<string>>;\n}\n\n// ---------------------------------------------------------------------------\n// SqliteGraphRepository\n// ---------------------------------------------------------------------------\n\nexport class SqliteGraphRepository implements IGraphRepository {\n private db: Database.Database;\n private adjCache: AdjacencyCache | null = null;\n readonly dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n const dir = path.dirname(dbPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n this.db = new Database(dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000');\n\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore — safe to skip if another writer holds it\n }\n\n this._initSchema();\n }\n\n close(): void {\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore\n }\n this.db.close();\n for (const suffix of ['-wal', '-shm']) {\n const side = this.dbPath + suffix;\n try {\n if (fs.existsSync(side)) { fs.unlinkSync(side); }\n } catch {\n // locked by another process — leave it alone\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Write operations\n // ---------------------------------------------------------------------------\n\n upsertNode(node: NodeInfo, fileHash = ''): number {\n const now = Date.now() / 1000;\n const qualified = this._makeQualified(node);\n const extra = node.extra ? JSON.stringify(node.extra) : '{}';\n\n this.db.prepare(`\n INSERT INTO nodes\n (kind, name, qualified_name, file_path, line_start, line_end,\n language, parent_name, params, return_type, modifiers, is_test,\n file_hash, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(qualified_name) DO UPDATE SET\n kind=excluded.kind, name=excluded.name,\n file_path=excluded.file_path, line_start=excluded.line_start,\n line_end=excluded.line_end, language=excluded.language,\n parent_name=excluded.parent_name, params=excluded.params,\n return_type=excluded.return_type, modifiers=excluded.modifiers,\n is_test=excluded.is_test, file_hash=excluded.file_hash,\n extra=excluded.extra, updated_at=excluded.updated_at\n `).run(\n node.kind, node.name, qualified, node.filePath,\n node.lineStart, node.lineEnd, node.language ?? null,\n node.parentName ?? null, node.params ?? null, node.returnType ?? null,\n node.modifiers ?? null, node.isTest ? 1 : 0, fileHash,\n extra, now,\n );\n\n const row = this.db.prepare(\n 'SELECT id FROM nodes WHERE qualified_name = ?'\n ).get(qualified) as { id: number };\n return row.id;\n }\n\n upsertEdge(edge: EdgeInfo): number {\n const now = Date.now() / 1000;\n const extra = edge.extra ? JSON.stringify(edge.extra) : '{}';\n const line = edge.line ?? 0;\n\n const existing = this.db.prepare(`\n SELECT id FROM edges\n WHERE kind=? AND source_qualified=? AND target_qualified=?\n AND file_path=? AND line=?\n `).get(edge.kind, edge.source, edge.target, edge.filePath, line) as\n { id: number } | undefined;\n\n if (existing) {\n this.db.prepare(\n 'UPDATE edges SET line=?, extra=?, updated_at=? WHERE id=?'\n ).run(line, extra, now, existing.id);\n return existing.id;\n }\n\n const result = this.db.prepare(`\n INSERT INTO edges\n (kind, source_qualified, target_qualified, file_path, line, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(edge.kind, edge.source, edge.target, edge.filePath, line, extra, now);\n return Number(result.lastInsertRowid);\n }\n\n removeFileData(filePath: string): void {\n this.db.prepare('DELETE FROM nodes WHERE file_path = ?').run(filePath);\n this.db.prepare('DELETE FROM edges WHERE file_path = ?').run(filePath);\n this._invalidateCache();\n }\n\n storeFileNodesEdges(\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n fileHash = '',\n ): void {\n const txn = this.db.transaction(() => {\n this.removeFileData(filePath);\n for (const node of nodes) { this.upsertNode(node, fileHash); }\n for (const edge of edges) { this.upsertEdge(edge); }\n });\n txn();\n this._invalidateCache();\n }\n\n setMetadata(key: string, value: string): void {\n this.db.prepare(\n 'INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)'\n ).run(key, value);\n }\n\n getMetadata(key: string): string | undefined {\n const row = this.db.prepare(\n 'SELECT value FROM metadata WHERE key = ?'\n ).get(key) as MetadataRow | undefined;\n return row?.value;\n }\n\n // ---------------------------------------------------------------------------\n // Read operations\n // ---------------------------------------------------------------------------\n\n getNode(qualifiedName: string): GraphNode | undefined {\n const row = this.db.prepare(\n 'SELECT * FROM nodes WHERE qualified_name = ?'\n ).get(qualifiedName) as NodeRow | undefined;\n return row ? this._rowToNode(row) : undefined;\n }\n\n getNodesByFile(filePath: string): GraphNode[] {\n const rows = this.db.prepare(\n 'SELECT * FROM nodes WHERE file_path = ? ORDER BY line_start'\n ).all(filePath) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getEdgesBySource(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE source_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesByTarget(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n searchEdgesByTargetName(name: string, kind: EdgeKind = 'CALLS'): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ? AND kind = ?'\n ).all(name, kind) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getAllFiles(): string[] {\n const rows = this.db.prepare(\n \"SELECT DISTINCT file_path FROM nodes WHERE kind = 'File' ORDER BY file_path\"\n ).all() as FilePathRow[];\n return rows.map((r) => r.file_path);\n }\n\n searchNodes(query: string, limit = 20): GraphNode[] {\n const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n if (words.length === 0) { return []; }\n\n const conditions = words.map(\n () => '(LOWER(name) LIKE ? OR LOWER(qualified_name) LIKE ?)'\n );\n const params: Array<string | number> = [];\n for (const word of words) {\n params.push(`%${word}%`, `%${word}%`);\n }\n params.push(limit);\n\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getSubgraph(qualifiedNames: string[]): { nodes: GraphNode[]; edges: GraphEdge[] } {\n const nodes: GraphNode[] = [];\n for (const qn of qualifiedNames) {\n const n = this.getNode(qn);\n if (n) { nodes.push(n); }\n }\n const qnSet = new Set(qualifiedNames);\n const edges: GraphEdge[] = [];\n for (const qn of qualifiedNames) {\n for (const e of this.getEdgesBySource(qn)) {\n if (qnSet.has(e.targetQualified)) { edges.push(e); }\n }\n }\n return { nodes, edges };\n }\n\n getStats(): GraphStats {\n const totalNodes = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM nodes').get() as CountRow\n ).cnt;\n const totalEdges = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM edges').get() as CountRow\n ).cnt;\n\n const nodesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM nodes GROUP BY kind'\n ).all() as KindCountRow[]) {\n nodesByKind[r.kind] = r.cnt;\n }\n\n const edgesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM edges GROUP BY kind'\n ).all() as KindCountRow[]) {\n edgesByKind[r.kind] = r.cnt;\n }\n\n const languages = (this.db.prepare(\n \"SELECT DISTINCT language FROM nodes WHERE language IS NOT NULL AND language != ''\"\n ).all() as LanguageRow[]).map((r) => r.language);\n\n const filesCount = (this.db.prepare(\n \"SELECT COUNT(*) AS cnt FROM nodes WHERE kind = 'File'\"\n ).get() as CountRow).cnt;\n\n const lastUpdated = this.getMetadata('last_updated') ?? null;\n\n let embeddingsCount = 0;\n try {\n embeddingsCount = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM embeddings').get() as CountRow\n ).cnt;\n } catch {\n // embeddings table may not exist — that is fine\n }\n\n return {\n totalNodes, totalEdges, nodesByKind, edgesByKind,\n languages, filesCount, lastUpdated, embeddingsCount,\n };\n }\n\n getNodesBySize(\n minLines = 50,\n maxLines?: number,\n kind?: string,\n filePathPattern?: string,\n limit = 50,\n ): Array<GraphNode & { lineCount: number }> {\n const conditions = [\n 'line_start IS NOT NULL',\n 'line_end IS NOT NULL',\n '(line_end - line_start + 1) >= ?',\n ];\n const params: Array<string | number> = [minLines];\n\n if (maxLines !== undefined) {\n conditions.push('(line_end - line_start + 1) <= ?');\n params.push(maxLines);\n }\n if (kind) { conditions.push('kind = ?'); params.push(kind); }\n if (filePathPattern) {\n conditions.push('file_path LIKE ?');\n params.push(`%${filePathPattern}%`);\n }\n params.push(limit);\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} ORDER BY (line_end - line_start + 1) DESC LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => ({\n ...this._rowToNode(r),\n lineCount:\n r.line_start != null && r.line_end != null\n ? r.line_end - r.line_start + 1\n : 0,\n }));\n }\n\n getAllEdges(): GraphEdge[] {\n const rows = this.db.prepare('SELECT * FROM edges').all() as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesAmong(qualifiedNames: Set<string>): GraphEdge[] {\n if (qualifiedNames.size === 0) { return []; }\n const qns = [...qualifiedNames];\n const results: GraphEdge[] = [];\n const batchSize = 450;\n\n for (let i = 0; i < qns.length; i += batchSize) {\n const batch = qns.slice(i, i + batchSize);\n const placeholders = batch.map(() => '?').join(',');\n // nosec: placeholders are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM edges WHERE source_qualified IN (${placeholders})`\n ).all(...batch) as EdgeRow[];\n for (const r of rows) {\n const edge = this._rowToEdge(r);\n if (qualifiedNames.has(edge.targetQualified)) { results.push(edge); }\n }\n }\n return results;\n }\n\n // ---------------------------------------------------------------------------\n // Adjacency (BFS support for use cases)\n // ---------------------------------------------------------------------------\n\n getAdjacency(): { outgoing: Map<string, Set<string>>; incoming: Map<string, Set<string>> } {\n const cache = this._buildAdjacency();\n return { outgoing: cache.out, incoming: cache.in };\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private _initSchema(): void {\n this.db.exec(SCHEMA_SQL);\n this.setMetadata('schema_version', '1');\n }\n\n private _invalidateCache(): void {\n this.adjCache = null;\n }\n\n private _buildAdjacency(): AdjacencyCache {\n if (this.adjCache) { return this.adjCache; }\n const out = new Map<string, Set<string>>();\n const inMap = new Map<string, Set<string>>();\n\n const rows = this.db.prepare('SELECT source_qualified, target_qualified FROM edges').all() as\n Array<{ source_qualified: string; target_qualified: string }>;\n\n for (const r of rows) {\n if (!out.has(r.source_qualified)) { out.set(r.source_qualified, new Set()); }\n out.get(r.source_qualified)!.add(r.target_qualified);\n\n if (!inMap.has(r.target_qualified)) { inMap.set(r.target_qualified, new Set()); }\n inMap.get(r.target_qualified)!.add(r.source_qualified);\n }\n\n this.adjCache = { out, in: inMap };\n return this.adjCache;\n }\n\n private _makeQualified(node: NodeInfo): string {\n if (node.kind === 'File') { return node.filePath; }\n if (node.parentName) {\n return `${node.filePath}::${node.parentName}.${node.name}`;\n }\n return `${node.filePath}::${node.name}`;\n }\n\n private _rowToNode(row: NodeRow): GraphNode {\n return {\n id: row.id,\n kind: row.kind as GraphNode['kind'],\n name: row.name,\n qualifiedName: row.qualified_name,\n filePath: row.file_path,\n lineStart: row.line_start,\n lineEnd: row.line_end,\n language: row.language ?? null,\n parentName: row.parent_name ?? null,\n params: row.params ?? null,\n returnType: row.return_type ?? null,\n modifiers: row.modifiers ?? null,\n isTest: row.is_test === 1,\n fileHash: row.file_hash ?? null,\n };\n }\n\n private _rowToEdge(row: EdgeRow): GraphEdge {\n return {\n id: row.id,\n kind: row.kind as GraphEdge['kind'],\n sourceQualified: row.source_qualified,\n targetQualified: row.target_qualified,\n filePath: row.file_path,\n line: row.line ?? 0,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Utility exports (mirrors Python module-level helpers)\n// ---------------------------------------------------------------------------\n\nexport function sanitizeName(s: string, maxLen = 256): string {\n let cleaned = '';\n for (const ch of s) {\n const code = ch.codePointAt(0) ?? 0;\n if (ch === '\\t' || ch === '\\n' || code >= 0x20) { cleaned += ch; }\n }\n return cleaned.slice(0, maxLen);\n}\n\nexport function nodeToDict(n: GraphNode): Record<string, unknown> {\n return {\n id: n.id,\n kind: n.kind,\n name: sanitizeName(n.name),\n qualified_name: sanitizeName(n.qualifiedName),\n file_path: n.filePath,\n line_start: n.lineStart,\n line_end: n.lineEnd,\n language: n.language,\n parent_name: n.parentName ? sanitizeName(n.parentName) : n.parentName,\n is_test: n.isTest,\n };\n}\n\nexport function edgeToDict(e: GraphEdge): Record<string, unknown> {\n return {\n id: e.id,\n kind: e.kind,\n source: sanitizeName(e.sourceQualified),\n target: sanitizeName(e.targetQualified),\n file_path: e.filePath,\n line: e.line,\n };\n}\n\n// Backward-compat alias (used by tests + public index.ts)\nexport { SqliteGraphRepository as GraphStore };\n","/**\n * Tree-sitter based multi-language code parser.\n *\n * Extracts structural nodes (classes, functions, imports, types) and edges\n * (calls, inheritance, contains) from source files.\n *\n * Direct port of code_review_graph/parser.py.\n * Supports 14 languages: Python, JS/TS/TSX, Go, Rust, Java, C, C++, C#,\n * Ruby, Kotlin, Swift, PHP, Solidity, Vue SFC.\n */\n\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nconst _require = createRequire(import.meta.url);\n\n// Lazy-load tree-sitter so the require() doesn't execute at bundle load time.\n// This prevents VS Code from crashing the extension host when the native\n// tree-sitter binary was compiled for a different Node.js ABI than Electron uses.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _ParserClass: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getParserClass(): any {\n if (!_ParserClass) { _ParserClass = _require('tree-sitter'); }\n return _ParserClass;\n}\nimport type { NodeInfo, EdgeInfo } from '../domain/types.js';\nimport type { IParser } from '../domain/ports/IParser.js';\n\n// ---------------------------------------------------------------------------\n// Language loading — individual npm grammar packages\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Language = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype SyntaxNode = any;\n\nfunction loadLanguage(pkg: string): Language | null {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = _require(pkg);\n return mod.default ?? mod;\n } catch {\n return null;\n }\n}\n\n// Lazy-loaded grammar map. Languages are loaded on first use.\nconst _languageCache = new Map<string, Language | null>();\n\nfunction getLanguage(name: string): Language | null {\n if (_languageCache.has(name)) { return _languageCache.get(name) ?? null; }\n\n const pkgMap: Record<string, string> = {\n python: 'tree-sitter-python',\n javascript: 'tree-sitter-javascript',\n typescript: 'tree-sitter-typescript/bindings/node/typescript',\n tsx: 'tree-sitter-typescript/bindings/node/tsx',\n go: 'tree-sitter-go',\n rust: 'tree-sitter-rust',\n java: 'tree-sitter-java',\n c: 'tree-sitter-c',\n cpp: 'tree-sitter-cpp',\n csharp: 'tree-sitter-c-sharp',\n ruby: 'tree-sitter-ruby',\n kotlin: 'tree-sitter-kotlin',\n swift: 'tree-sitter-swift',\n php: 'tree-sitter-php/php',\n solidity: 'tree-sitter-solidity',\n vue: 'tree-sitter-vue',\n };\n\n const pkg = pkgMap[name];\n const lang = pkg ? loadLanguage(pkg) : null;\n _languageCache.set(name, lang);\n return lang;\n}\n\n// ---------------------------------------------------------------------------\n// Extension → language mapping\n// ---------------------------------------------------------------------------\n\nexport const EXTENSION_TO_LANGUAGE: Record<string, string> = {\n '.py': 'python',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.go': 'go',\n '.rs': 'rust',\n '.java': 'java',\n '.cs': 'csharp',\n '.rb': 'ruby',\n '.cpp': 'cpp',\n '.cc': 'cpp',\n '.cxx': 'cpp',\n '.c': 'c',\n '.h': 'c',\n '.hpp': 'cpp',\n '.kt': 'kotlin',\n '.swift': 'swift',\n '.php': 'php',\n '.sol': 'solidity',\n '.vue': 'vue',\n};\n\n// ---------------------------------------------------------------------------\n// AST node type sets per language\n// ---------------------------------------------------------------------------\n\nconst CLASS_TYPES: Record<string, string[]> = {\n python: ['class_definition'],\n javascript: ['class_declaration', 'class'],\n typescript: ['class_declaration', 'class'],\n tsx: ['class_declaration', 'class'],\n go: ['type_declaration'],\n rust: ['struct_item', 'enum_item', 'impl_item'],\n java: ['class_declaration', 'interface_declaration', 'enum_declaration'],\n c: ['struct_specifier', 'type_definition'],\n cpp: ['class_specifier', 'struct_specifier'],\n csharp: ['class_declaration', 'interface_declaration', 'enum_declaration', 'struct_declaration'],\n ruby: ['class', 'module'],\n kotlin: ['class_declaration', 'object_declaration'],\n swift: ['class_declaration', 'struct_declaration', 'protocol_declaration'],\n php: ['class_declaration', 'interface_declaration'],\n solidity: [\n 'contract_declaration', 'interface_declaration', 'library_declaration',\n 'struct_declaration', 'enum_declaration', 'error_declaration',\n 'user_defined_type_definition',\n ],\n};\n\nconst FUNCTION_TYPES: Record<string, string[]> = {\n python: ['function_definition'],\n javascript: ['function_declaration', 'method_definition', 'arrow_function'],\n typescript: ['function_declaration', 'method_definition', 'arrow_function'],\n tsx: ['function_declaration', 'method_definition', 'arrow_function'],\n go: ['function_declaration', 'method_declaration'],\n rust: ['function_item'],\n java: ['method_declaration', 'constructor_declaration'],\n c: ['function_definition'],\n cpp: ['function_definition'],\n csharp: ['method_declaration', 'constructor_declaration'],\n ruby: ['method', 'singleton_method'],\n kotlin: ['function_declaration'],\n swift: ['function_declaration'],\n php: ['function_definition', 'method_declaration'],\n solidity: [\n 'function_definition', 'constructor_definition', 'modifier_definition',\n 'event_definition', 'fallback_receive_definition',\n ],\n};\n\nconst IMPORT_TYPES: Record<string, string[]> = {\n python: ['import_statement', 'import_from_statement'],\n javascript: ['import_statement'],\n typescript: ['import_statement'],\n tsx: ['import_statement'],\n go: ['import_declaration'],\n rust: ['use_declaration'],\n java: ['import_declaration'],\n c: ['preproc_include'],\n cpp: ['preproc_include'],\n csharp: ['using_directive'],\n ruby: ['call'], // require / require_relative\n kotlin: ['import_header'],\n swift: ['import_declaration'],\n php: ['namespace_use_declaration'],\n solidity: ['import_directive'],\n};\n\nconst CALL_TYPES: Record<string, string[]> = {\n python: ['call'],\n javascript: ['call_expression', 'new_expression'],\n typescript: ['call_expression', 'new_expression'],\n tsx: ['call_expression', 'new_expression'],\n go: ['call_expression'],\n rust: ['call_expression', 'macro_invocation'],\n java: ['method_invocation', 'object_creation_expression'],\n c: ['call_expression'],\n cpp: ['call_expression'],\n csharp: ['invocation_expression', 'object_creation_expression'],\n ruby: ['call', 'method_call'],\n kotlin: ['call_expression'],\n swift: ['call_expression'],\n php: ['function_call_expression', 'member_call_expression'],\n solidity: ['call_expression'],\n};\n\n// ---------------------------------------------------------------------------\n// Test detection patterns\n// ---------------------------------------------------------------------------\n\nconst TEST_PATTERNS = [\n /^test_/,\n /^Test/,\n /_test$/,\n /\\.test\\./,\n /\\.spec\\./,\n /_spec$/,\n];\n\nconst TEST_FILE_PATTERNS = [\n /test_.*\\.py$/,\n /.*_test\\.py$/,\n /.*\\.test\\.[jt]sx?$/,\n /.*\\.spec\\.[jt]sx?$/,\n /.*_test\\.go$/,\n /tests?\\//,\n];\n\nfunction isTestFile(filePath: string): boolean {\n return TEST_FILE_PATTERNS.some((p) => p.test(filePath));\n}\n\n// Test-runner framework names that indicate a function IS a test even\n// if its name doesn't start with \"test\".\nconst TEST_RUNNER_NAMES = new Set([\n 'describe', 'it', 'test', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll',\n]);\n\nfunction isTestFunction(name: string, filePath: string): boolean {\n // Name-pattern match always wins\n if (TEST_PATTERNS.some((p) => p.test(name))) { return true; }\n // In a test file, only test-runner functions count (not every helper)\n if (isTestFile(filePath) && TEST_RUNNER_NAMES.has(name)) { return true; }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Public utility\n// ---------------------------------------------------------------------------\n\nexport function fileHash(filePath: string): string {\n const buf = fs.readFileSync(filePath);\n return crypto.createHash('sha256').update(buf).digest('hex');\n}\n\n// ---------------------------------------------------------------------------\n// CodeParser\n// ---------------------------------------------------------------------------\n\nconst MAX_AST_DEPTH = 180;\nconst MODULE_CACHE_MAX = 15_000;\n\nexport class CodeParser implements IParser {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private parsers = new Map<string, any>();\n private moduleFileCache = new Map<string, string | null>();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private getParser(language: string): any {\n if (this.parsers.has(language)) { return this.parsers.get(language) ?? null; }\n try {\n const lang = getLanguage(language);\n if (!lang) { return null; }\n const p = new (getParserClass())();\n p.setLanguage(lang);\n this.parsers.set(language, p);\n return p;\n } catch {\n return null;\n }\n }\n\n detectLanguage(filePath: string): string | null {\n const ext = path.extname(filePath).toLowerCase();\n return EXTENSION_TO_LANGUAGE[ext] ?? null;\n }\n\n parseFile(filePath: string): [NodeInfo[], EdgeInfo[]] {\n let source: Buffer;\n try {\n source = fs.readFileSync(filePath);\n } catch {\n return [[], []];\n }\n return this.parseBytes(filePath, source);\n }\n\n parseBytes(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const language = this.detectLanguage(filePath);\n if (!language) { return [[], []]; }\n\n if (language === 'vue') {\n return this._parseVue(filePath, source);\n }\n\n const parser = this.getParser(language);\n if (!parser) { return [[], []]; }\n\n const tree = parser.parse(source.toString('utf-8'));\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n const testFile = isTestFile(filePath);\n\n // File node\n const lineCount = source.toString('utf-8').split('\\n').length;\n nodes.push({\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language,\n isTest: testFile,\n });\n\n const [importMap, definedNames] = this._collectFileScope(\n tree.rootNode, language, source,\n );\n\n this._extractFromTree(\n tree.rootNode, source, language, filePath, nodes, edges,\n undefined, undefined, importMap, definedNames,\n );\n\n const resolvedEdges = this._resolveCallTargets(nodes, edges, filePath);\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of nodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of resolvedEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n resolvedEdges.push(...testedBy);\n }\n\n return [nodes, resolvedEdges];\n }\n\n private _parseVue(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const vueParser = this.getParser('vue');\n if (!vueParser) { return [[], []]; }\n\n const tree = vueParser.parse(source.toString('utf-8'));\n const testFile = isTestFile(filePath);\n const lineCount = source.toString('utf-8').split('\\n').length;\n\n const allNodes: NodeInfo[] = [{\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language: 'vue',\n isTest: testFile,\n }];\n const allEdges: EdgeInfo[] = [];\n\n for (const child of tree.rootNode.children) {\n if (child.type !== 'script_element') { continue; }\n\n let scriptLang = 'javascript';\n let startTag: SyntaxNode | null = null;\n let rawTextNode: SyntaxNode | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'start_tag') { startTag = sub; }\n else if (sub.type === 'raw_text') { rawTextNode = sub; }\n }\n\n if (startTag) {\n for (const attr of startTag.children) {\n if (attr.type === 'attribute') {\n let attrName: string | null = null;\n let attrValue: string | null = null;\n for (const a of attr.children) {\n if (a.type === 'attribute_name') { attrName = a.text; }\n else if (a.type === 'quoted_attribute_value') {\n for (const v of a.children) {\n if (v.type === 'attribute_value') { attrValue = v.text; }\n }\n }\n }\n if (attrName === 'lang' && (attrValue === 'ts' || attrValue === 'typescript')) {\n scriptLang = 'typescript';\n }\n }\n }\n }\n\n if (!rawTextNode) { continue; }\n\n const scriptSource = Buffer.from(rawTextNode.text, 'utf-8');\n const lineOffset: number = rawTextNode.startPosition.row;\n\n const scriptParser = this.getParser(scriptLang);\n if (!scriptParser) { continue; }\n\n const scriptTree = scriptParser.parse(scriptSource.toString('utf-8'));\n const [importMap, definedNames] = this._collectFileScope(\n scriptTree.rootNode, scriptLang, scriptSource,\n );\n\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n this._extractFromTree(\n scriptTree.rootNode, scriptSource, scriptLang, filePath,\n nodes, edges, undefined, undefined, importMap, definedNames,\n );\n\n // Adjust line numbers and language for position within .vue file\n for (const n of nodes) {\n n.lineStart += lineOffset;\n n.lineEnd += lineOffset;\n n.language = 'vue';\n }\n for (const e of edges) {\n e.line = (e.line ?? 0) + lineOffset;\n }\n\n allNodes.push(...nodes);\n allEdges.push(...edges);\n }\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of allNodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of allEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n allEdges.push(...testedBy);\n }\n\n return [allNodes, allEdges];\n }\n\n private _resolveCallTargets(\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n filePath: string,\n ): EdgeInfo[] {\n const symbols = new Map<string, string>();\n for (const node of nodes) {\n if (['Function', 'Class', 'Type', 'Test'].includes(node.kind)) {\n const bare = node.name;\n if (!symbols.has(bare)) {\n symbols.set(bare, this._qualify(bare, filePath, node.parentName ?? null));\n }\n }\n }\n\n return edges.map((edge) => {\n if (edge.kind === 'CALLS' && !edge.target.includes('::')) {\n const qualified = symbols.get(edge.target);\n if (qualified) {\n return { ...edge, target: qualified };\n }\n }\n return edge;\n });\n }\n\n private _extractFromTree(\n root: SyntaxNode,\n source: Buffer,\n language: string,\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n enclosingClass?: string | null,\n enclosingFunc?: string | null,\n importMap?: Map<string, string>,\n definedNames?: Set<string>,\n depth = 0,\n ): void {\n if (depth > MAX_AST_DEPTH) { return; }\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const callTypes = new Set(CALL_TYPES[language] ?? []);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // --- Classes ---\n if (classTypes.has(nodeType)) {\n const name = this._getName(child, language, 'class');\n if (name) {\n nodes.push({\n kind: 'Class',\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n });\n\n edges.push({\n kind: 'CONTAINS',\n source: filePath,\n target: this._qualify(name, filePath, enclosingClass ?? null),\n filePath,\n line: child.startPosition.row + 1,\n });\n\n const bases = this._getBases(child, language);\n for (const base of bases) {\n edges.push({\n kind: 'INHERITS',\n source: this._qualify(name, filePath, enclosingClass ?? null),\n target: base,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n name, null, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Functions ---\n if (funcTypes.has(nodeType)) {\n const name = this._getName(child, language, 'function');\n if (name) {\n const isTest = isTestFunction(name, filePath);\n const kind = isTest ? 'Test' : 'Function';\n const qualified = this._qualify(name, filePath, enclosingClass ?? null);\n const params = this._getParams(child, language);\n const retType = this._getReturnType(child, language);\n\n nodes.push({\n kind,\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n params,\n returnType: retType,\n isTest,\n });\n\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n\n // Solidity: modifier invocations → CALLS edges\n if (language === 'solidity') {\n for (const sub of child.children) {\n if (sub.type === 'modifier_invocation') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n edges.push({\n kind: 'CALLS',\n source: qualified,\n target: ident.text,\n filePath,\n line: sub.startPosition.row + 1,\n });\n break;\n }\n }\n }\n }\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, name, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Imports ---\n if (importTypes.has(nodeType)) {\n const imports = this._extractImport(child, language);\n for (const impTarget of imports) {\n edges.push({\n kind: 'IMPORTS_FROM',\n source: filePath,\n target: impTarget,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n\n // --- Calls ---\n if (callTypes.has(nodeType)) {\n const callName = this._getCallName(child, language);\n if (callName && enclosingFunc) {\n const caller = this._qualify(enclosingFunc, filePath, enclosingClass ?? null);\n const target = this._resolveCallTarget(\n callName, filePath, language,\n importMap ?? new Map(), definedNames ?? new Set(),\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n\n // --- Solidity-specific constructs ---\n if (language === 'solidity') {\n // emit statements → CALLS edges\n if (nodeType === 'emit_statement' && enclosingFunc) {\n for (const sub of child.children) {\n if (sub.type === 'expression') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n const caller = this._qualify(\n enclosingFunc, filePath, enclosingClass ?? null,\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target: ident.text,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n }\n }\n }\n\n // State variable declarations → Function nodes\n if (nodeType === 'state_variable_declaration' && enclosingClass) {\n let varName: string | null = null;\n let varVisibility: string | null = null;\n let varType: string | null = null;\n let varMutability: string | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'visibility') { varVisibility = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n else if (sub.type === 'constant' || sub.type === 'immutable') {\n varMutability = sub.type;\n }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass,\n returnType: varType,\n modifiers: varVisibility,\n extra: { solidity_kind: 'state_variable', mutability: varMutability },\n });\n edges.push({\n kind: 'CONTAINS',\n source: this._qualify(enclosingClass, filePath, null),\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Constant variable declarations\n if (nodeType === 'constant_variable_declaration') {\n let varName: string | null = null;\n let varType: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass ?? null);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n returnType: varType,\n extra: { solidity_kind: 'constant' },\n });\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Using directives → DEPENDS_ON edge\n if (nodeType === 'using_directive') {\n let libName: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'type_alias') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { libName = ident.text; break; }\n }\n }\n }\n if (libName) {\n const sourceName = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'DEPENDS_ON',\n source: sourceName,\n target: libName,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n }\n\n // Recurse for other node types\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, enclosingFunc, importMap, definedNames, depth + 1,\n );\n }\n }\n\n private _collectFileScope(\n root: SyntaxNode,\n language: string,\n source: Buffer,\n ): [Map<string, string>, Set<string>] {\n const importMap = new Map<string, string>();\n const definedNames = new Set<string>();\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const decoratorWrappers = new Set(['decorated_definition', 'decorator']);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // Unwrap decorator wrappers\n let target = child;\n if (decoratorWrappers.has(nodeType)) {\n for (const inner of child.children) {\n if (funcTypes.has(inner.type) || classTypes.has(inner.type)) {\n target = inner;\n break;\n }\n }\n }\n\n const targetType: string = target.type;\n\n if (funcTypes.has(targetType) || classTypes.has(targetType)) {\n const name = this._getName(\n target, language, classTypes.has(targetType) ? 'class' : 'function',\n );\n if (name) { definedNames.add(name); }\n }\n\n if (importTypes.has(nodeType)) {\n this._collectImportNames(child, language, source, importMap);\n }\n }\n\n return [importMap, definedNames];\n }\n\n private _collectImportNames(\n node: SyntaxNode,\n language: string,\n _source: Buffer,\n importMap: Map<string, string>,\n ): void {\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n let module: string | null = null;\n let seenImport = false;\n for (const child of node.children) {\n if (child.type === 'dotted_name' && !seenImport) {\n module = child.text;\n } else if (child.type === 'import') {\n seenImport = true;\n } else if (seenImport && module) {\n if (child.type === 'identifier' || child.type === 'dotted_name') {\n importMap.set(child.text, module);\n } else if (child.type === 'aliased_import') {\n const names = child.children\n .filter((c: SyntaxNode) =>\n c.type === 'identifier' || c.type === 'dotted_name'\n )\n .map((c: SyntaxNode) => c.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n } else if (language === 'javascript' || language === 'typescript' || language === 'tsx') {\n let module: string | null = null;\n for (const child of node.children) {\n if (child.type === 'string') {\n module = (child.text as string).replace(/^['\"]|['\"]$/g, '');\n }\n }\n if (module) {\n for (const child of node.children) {\n if (child.type === 'import_clause') {\n this._collectJsImportNames(child, module, importMap);\n }\n }\n }\n }\n }\n\n private _collectJsImportNames(\n clauseNode: SyntaxNode,\n module: string,\n importMap: Map<string, string>,\n ): void {\n for (const child of clauseNode.children) {\n if (child.type === 'identifier') {\n importMap.set(child.text, module);\n } else if (child.type === 'named_imports') {\n for (const spec of child.children) {\n if (spec.type === 'import_specifier') {\n const names = spec.children\n .filter((s: SyntaxNode) =>\n s.type === 'identifier' || s.type === 'property_identifier'\n )\n .map((s: SyntaxNode) => s.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n }\n\n private _resolveModuleToFile(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n const cacheKey = `${language}:${callerDir}:${module}`;\n if (this.moduleFileCache.has(cacheKey)) {\n return this.moduleFileCache.get(cacheKey) ?? null;\n }\n\n const resolved = this._doResolveModule(module, filePath, language);\n if (this.moduleFileCache.size >= MODULE_CACHE_MAX) {\n this.moduleFileCache.clear();\n }\n this.moduleFileCache.set(cacheKey, resolved);\n return resolved;\n }\n\n private _doResolveModule(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n\n if (language === 'python') {\n const relPath = module.replace(/\\./g, '/');\n const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];\n let current = callerDir;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n for (const candidate of candidates) {\n const target = path.join(current, candidate);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n const parent = path.dirname(current);\n if (parent === current) { break; }\n current = parent;\n }\n } else if (\n language === 'javascript' || language === 'typescript' ||\n language === 'tsx' || language === 'vue'\n ) {\n if (module.startsWith('.')) {\n const base = path.join(callerDir, module);\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '.vue'];\n if (fs.existsSync(base) && fs.statSync(base).isFile()) {\n return path.resolve(base);\n }\n for (const ext of extensions) {\n const target = base + ext;\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n // Try index file in directory\n if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {\n for (const ext of extensions) {\n const target = path.join(base, `index${ext}`);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n }\n }\n }\n\n return null;\n }\n\n private _resolveCallTarget(\n callName: string,\n filePath: string,\n language: string,\n importMap: Map<string, string>,\n definedNames: Set<string>,\n ): string {\n if (definedNames.has(callName)) {\n return this._qualify(callName, filePath, null);\n }\n const importedFrom = importMap.get(callName);\n if (importedFrom) {\n const resolved = this._resolveModuleToFile(importedFrom, filePath, language);\n if (resolved) { return this._qualify(callName, resolved, null); }\n }\n return callName;\n }\n\n private _qualify(name: string, filePath: string, enclosingClass: string | null): string {\n if (enclosingClass) { return `${filePath}::${enclosingClass}.${name}`; }\n return `${filePath}::${name}`;\n }\n\n private _getName(node: SyntaxNode, language: string, kind: string): string | null {\n // Solidity: constructor and receive/fallback have no identifier child\n if (language === 'solidity') {\n if (node.type === 'constructor_definition') { return 'constructor'; }\n if (node.type === 'fallback_receive_definition') {\n for (const child of node.children) {\n if (child.type === 'receive' || child.type === 'fallback') {\n return child.text;\n }\n }\n }\n }\n\n // C/C++: function names are inside function_declarator/pointer_declarator\n if ((language === 'c' || language === 'cpp') && kind === 'function') {\n for (const child of node.children) {\n if (child.type === 'function_declarator' || child.type === 'pointer_declarator') {\n const result = this._getName(child, language, kind);\n if (result) { return result; }\n }\n }\n }\n\n // Most languages: look for identifier child\n for (const child of node.children) {\n if ([\n 'identifier', 'name', 'type_identifier', 'property_identifier',\n 'simple_identifier', 'constant',\n ].includes(child.type)) {\n return child.text;\n }\n }\n\n // Go type declarations: look for type_spec\n if (language === 'go' && node.type === 'type_declaration') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n return this._getName(child, language, kind);\n }\n }\n }\n\n return null;\n }\n\n private _getParams(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if (['parameters', 'formal_parameters', 'parameter_list'].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'solidity') {\n const params = node.children\n .filter((c: SyntaxNode) => c.type === 'parameter')\n .map((c: SyntaxNode) => c.text as string);\n if (params.length > 0) { return `(${params.join(', ')})`; }\n }\n return null;\n }\n\n private _getReturnType(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if ([\n 'type', 'return_type', 'type_annotation', 'return_type_definition',\n ].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'python') {\n for (let i = 0; i < node.children.length - 1; i++) {\n if (node.children[i].type === '->') {\n return node.children[i + 1].text;\n }\n }\n }\n return null;\n }\n\n private _getBases(node: SyntaxNode, language: string): string[] {\n const bases: string[] = [];\n\n if (language === 'python') {\n for (const child of node.children) {\n if (child.type === 'argument_list') {\n for (const arg of child.children) {\n if (arg.type === 'identifier' || arg.type === 'attribute') {\n bases.push(arg.text);\n }\n }\n }\n }\n } else if (\n language === 'java' || language === 'csharp' || language === 'kotlin'\n ) {\n for (const child of node.children) {\n if ([\n 'superclass', 'super_interfaces', 'extends_type', 'implements_type',\n 'type_identifier', 'supertype', 'delegation_specifier',\n ].includes(child.type)) {\n bases.push(child.text);\n }\n }\n } else if (language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'base_class_clause') {\n for (const sub of child.children) {\n if (sub.type === 'type_identifier') { bases.push(sub.text); }\n }\n }\n }\n } else if (\n language === 'typescript' || language === 'javascript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'extends_clause' || child.type === 'implements_clause') {\n for (const sub of child.children) {\n if ([\n 'identifier', 'type_identifier', 'nested_identifier',\n ].includes(sub.type)) {\n bases.push(sub.text);\n }\n }\n }\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'inheritance_specifier') {\n for (const sub of child.children) {\n if (sub.type === 'user_defined_type') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { bases.push(ident.text); }\n }\n }\n }\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n for (const sub of child.children) {\n if (sub.type === 'struct_type' || sub.type === 'interface_type') {\n for (const fieldNode of sub.children) {\n if (fieldNode.type === 'field_declaration_list') {\n for (const f of fieldNode.children) {\n if (f.type === 'type_identifier') { bases.push(f.text); }\n }\n }\n }\n }\n }\n }\n }\n }\n\n return bases;\n }\n\n private _extractImport(node: SyntaxNode, language: string): string[] {\n const imports: string[] = [];\n const text: string = node.text.trim();\n\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n for (const child of node.children) {\n if (child.type === 'dotted_name') {\n imports.push(child.text);\n break;\n }\n }\n } else {\n for (const child of node.children) {\n if (child.type === 'dotted_name') { imports.push(child.text); }\n }\n }\n } else if (\n language === 'javascript' || language === 'typescript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'string') {\n imports.push((child.text as string).replace(/^['\"]|['\"]$/g, ''));\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'import_spec_list') {\n for (const spec of child.children) {\n if (spec.type === 'import_spec') {\n for (const s of spec.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (child.type === 'import_spec') {\n for (const s of child.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (language === 'rust') {\n imports.push(text.replace(/^use\\s+/, '').replace(/;$/, '').trim());\n } else if (language === 'c' || language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'system_lib_string' || child.type === 'string_literal') {\n imports.push((child.text as string).replace(/^[<\"\"]|[>\"\"]$/g, ''));\n }\n }\n } else if (language === 'java' || language === 'csharp') {\n const parts = text.split(/\\s+/);\n if (parts.length >= 2) {\n imports.push(parts[parts.length - 1]!.replace(/;$/, ''));\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'string') {\n const val = (child.text as string).replace(/^\"|\"$/g, '');\n if (val) { imports.push(val); }\n }\n }\n } else if (language === 'ruby') {\n if (text.includes('require')) {\n const match = /['\"]([^'\"]+)['\"]/u.exec(text);\n if (match) { imports.push(match[1]!); }\n }\n } else {\n imports.push(text);\n }\n\n return imports;\n }\n\n private _getCallName(node: SyntaxNode, language: string): string | null {\n if (!node.children || node.children.length === 0) { return null; }\n\n let first: SyntaxNode = node.children[0];\n\n // Solidity wraps call targets in 'expression' — unwrap\n if (\n language === 'solidity' &&\n first.type === 'expression' &&\n first.children.length > 0\n ) {\n first = first.children[0];\n }\n\n if (first.type === 'identifier') { return first.text; }\n\n const memberTypes = [\n 'attribute', 'member_expression', 'field_expression', 'selector_expression',\n ];\n if (memberTypes.includes(first.type)) {\n for (let i = first.children.length - 1; i >= 0; i--) {\n const child: SyntaxNode = first.children[i];\n if ([\n 'identifier', 'property_identifier', 'field_identifier', 'field_name',\n ].includes(child.type)) {\n return child.text;\n }\n }\n return first.text;\n }\n\n if (first.type === 'scoped_identifier' || first.type === 'qualified_name') {\n return first.text;\n }\n\n return null;\n }\n}\n\n// Canonical export alias matching the file name\nexport { CodeParser as TreeSitterParser }\n","/**\n * File-system infrastructure helpers.\n *\n * Extracted from incremental.ts: findRepoRoot, findProjectRoot, getDbPath,\n * loadIgnorePatterns, shouldIgnore, isBinary, walkDir, collectAllFiles.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport micromatch from 'micromatch'\nimport { CodeParser } from './TreeSitterParser.js'\nimport { getAllTrackedFiles } from './GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_IGNORE_PATTERNS = [\n '.codeorbit/**',\n 'node_modules/**',\n '.git/**',\n '__pycache__/**',\n '*.pyc',\n '.venv/**',\n 'venv/**',\n 'dist/**',\n 'build/**',\n '.next/**',\n 'target/**',\n '*.min.js',\n '*.min.css',\n '*.map',\n '*.lock',\n 'package-lock.json',\n 'yarn.lock',\n '*.db',\n '*.sqlite',\n '*.db-journal',\n '*.db-wal',\n]\n\nexport const PRUNE_DIRS = new Set([\n 'node_modules', '.git', '__pycache__', '.next', '.nuxt', '.svelte-kit',\n 'dist', 'build', '.venv', 'venv', 'env', 'target', '.mypy_cache',\n '.pytest_cache', 'coverage', '.tox', '.cache', '.tmp', 'tmp', 'temp',\n 'vendor', 'Pods', 'DerivedData', '.gradle', '.idea', '.vs',\n])\n\nexport const DEBOUNCE_MS = 300\n\n// ---------------------------------------------------------------------------\n// Repo / DB path discovery\n// ---------------------------------------------------------------------------\n\nexport function findRepoRoot(start?: string): string | undefined {\n let current = start ?? process.cwd()\n while (true) {\n if (fs.existsSync(path.join(current, '.git'))) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) { break }\n current = parent\n }\n return undefined\n}\n\nexport function findProjectRoot(start?: string): string {\n return findRepoRoot(start) ?? start ?? process.cwd()\n}\n\nexport function getDbPath(repoRoot: string): string {\n const crgDir = path.join(repoRoot, '.codeorbit')\n const newDb = path.join(crgDir, 'graph.db')\n\n if (!fs.existsSync(crgDir)) {\n fs.mkdirSync(crgDir, { recursive: true })\n }\n\n const innerGitignore = path.join(crgDir, '.gitignore')\n if (!fs.existsSync(innerGitignore)) {\n fs.writeFileSync(\n innerGitignore,\n '# Auto-generated by codeorbit — do not commit database files.\\n' +\n '# The graph.db contains absolute paths and code structure metadata.\\n' +\n '*\\n',\n )\n }\n\n const legacyDb = path.join(repoRoot, '.codeorbit.db')\n if (fs.existsSync(legacyDb) && !fs.existsSync(newDb)) {\n fs.renameSync(legacyDb, newDb)\n }\n for (const suffix of ['-wal', '-shm', '-journal']) {\n const side = legacyDb + suffix\n if (fs.existsSync(side)) {\n try { fs.unlinkSync(side) } catch { /* ignore */ }\n }\n }\n\n return newDb\n}\n\n// ---------------------------------------------------------------------------\n// Ignore patterns\n// ---------------------------------------------------------------------------\n\nexport function loadIgnorePatterns(repoRoot: string): string[] {\n const patterns = [...DEFAULT_IGNORE_PATTERNS]\n const ignoreFile = path.join(repoRoot, '.codeorbitignore')\n if (fs.existsSync(ignoreFile)) {\n for (const line of fs.readFileSync(ignoreFile, 'utf-8').split('\\n')) {\n const trimmed = line.trim()\n if (trimmed && !trimmed.startsWith('#')) {\n patterns.push(trimmed)\n }\n }\n }\n return patterns\n}\n\nexport function shouldIgnore(filePath: string, patterns: string[]): boolean {\n return micromatch.isMatch(filePath, patterns)\n}\n\nexport function isBinary(filePath: string): boolean {\n try {\n const chunk = Buffer.alloc(8192)\n const fd = fs.openSync(filePath, 'r')\n const bytesRead = fs.readSync(fd, chunk, 0, 8192, 0)\n fs.closeSync(fd)\n return chunk.slice(0, bytesRead).includes(0)\n } catch {\n return true\n }\n}\n\n// ---------------------------------------------------------------------------\n// File collection\n// ---------------------------------------------------------------------------\n\nfunction walkDir(dir: string, repoRoot: string): string[] {\n const files: string[] = []\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (PRUNE_DIRS.has(entry.name)) { continue }\n files.push(...walkDir(path.join(dir, entry.name), repoRoot))\n } else if (entry.isFile()) {\n const rel = path.relative(repoRoot, path.join(dir, entry.name))\n files.push(rel)\n }\n }\n return files\n}\n\nexport function collectAllFiles(repoRoot: string): string[] {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const parser = new CodeParser()\n const files: string[] = []\n\n const tracked = getAllTrackedFiles(repoRoot)\n const candidates = tracked.length > 0 ? tracked : walkDir(repoRoot, repoRoot)\n\n for (const relPath of candidates) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const fullPath = path.join(repoRoot, relPath)\n\n let stat: fs.Stats\n try {\n stat = fs.lstatSync(fullPath)\n } catch {\n continue\n }\n\n if (!stat.isFile() || stat.isSymbolicLink()) { continue }\n if (!parser.detectLanguage(fullPath)) { continue }\n if (isBinary(fullPath)) { continue }\n files.push(relPath)\n }\n\n return files\n}\n","/**\n * Git operations infrastructure.\n *\n * Extracted from incremental.ts: gitRun, getChangedFiles, getStagedAndUnstaged,\n * getAllTrackedFiles.\n */\n\nimport { spawnSync } from 'node:child_process'\n\nexport const GIT_TIMEOUT_MS = Number(process.env['CRG_GIT_TIMEOUT'] ?? 30) * 1000\n\nfunction gitRun(args: string[], cwd: string): string {\n const result = spawnSync('git', args, {\n cwd,\n encoding: 'utf-8',\n timeout: GIT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n if (result.error || result.status !== 0) {\n return ''\n }\n return result.stdout ?? ''\n}\n\nexport function getChangedFiles(repoRoot: string, base = 'HEAD~1'): string[] {\n let output = gitRun(['diff', '--name-only', base], repoRoot)\n if (!output.trim()) {\n output = gitRun(['diff', '--name-only', '--cached'], repoRoot)\n }\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n\nexport function getStagedAndUnstaged(repoRoot: string): string[] {\n const output = gitRun(['status', '--porcelain'], repoRoot)\n const files: string[] = []\n for (const line of output.split('\\n')) {\n if (line.length > 3) {\n let entry = line.slice(3).trim()\n if (entry.includes(' -> ')) {\n entry = entry.split(' -> ')[1]!\n }\n files.push(entry)\n }\n }\n return files\n}\n\nexport function getAllTrackedFiles(repoRoot: string): string[] {\n const output = gitRun(['ls-files'], repoRoot)\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n","/**\n * Use cases: full build and incremental update of the knowledge graph.\n *\n * Extracted from incremental.ts (fullBuild, incrementalUpdate, findDependents)\n * + tools.ts (buildOrUpdateGraph).\n *\n * Accepts IParser and IGraphRepository as parameters for testability.\n * Imports file-system and git utilities from infrastructure.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { BuildResult } from '../domain/types.js'\nimport type { IParser } from '../domain/ports/IParser.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport {\n collectAllFiles,\n loadIgnorePatterns,\n shouldIgnore,\n} from '../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles } from '../infrastructure/GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Full build\n// ---------------------------------------------------------------------------\n\nexport function fullBuild(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n): BuildResult {\n const files = collectAllFiles(repoRoot)\n\n // Purge stale data\n const existingFiles = new Set(repo.getAllFiles())\n const currentAbs = new Set(files.map((f) => path.join(repoRoot, f)))\n for (const stale of existingFiles) {\n if (!currentAbs.has(stale)) {\n repo.removeFileData(stale)\n }\n }\n\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (let i = 0; i < files.length; i++) {\n const relPath = files[i]!\n const fullPath = path.join(repoRoot, relPath)\n try {\n const source = fs.readFileSync(fullPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const [nodes, edges] = parser.parseBytes(fullPath, source)\n repo.storeFileNodesEdges(fullPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n if ((i + 1) % 50 === 0 || i + 1 === files.length) {\n process.stderr.write(`Progress: ${i + 1}/${files.length} files parsed\\n`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'full')\n\n return {\n buildType: 'full',\n filesUpdated: files.length,\n totalNodes,\n totalEdges,\n changedFiles: files,\n dependentFiles: [],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Incremental update\n// ---------------------------------------------------------------------------\n\nexport function incrementalUpdate(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n base = 'HEAD~1',\n changedFiles?: string[],\n): BuildResult {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const changed = changedFiles ?? getChangedFiles(repoRoot, base)\n\n if (changed.length === 0) {\n return {\n buildType: 'incremental',\n filesUpdated: 0,\n totalNodes: 0,\n totalEdges: 0,\n changedFiles: [],\n dependentFiles: [],\n errors: [],\n }\n }\n\n const dependentFiles = new Set<string>()\n for (const relPath of changed) {\n const fullPath = path.join(repoRoot, relPath)\n const deps = findDependents(repo, fullPath)\n for (const d of deps) {\n try {\n dependentFiles.add(path.relative(repoRoot, d))\n } catch {\n dependentFiles.add(d)\n }\n }\n }\n\n const allFiles = new Set([...changed, ...dependentFiles])\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (const relPath of allFiles) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const absPath = path.join(repoRoot, relPath)\n\n if (!fs.existsSync(absPath)) {\n repo.removeFileData(absPath)\n continue\n }\n if (!parser.detectLanguage(absPath)) { continue }\n\n try {\n const source = fs.readFileSync(absPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const existingNodes = repo.getNodesByFile(absPath)\n if (existingNodes.length > 0 && existingNodes[0]!.fileHash === fhash) {\n continue\n }\n const [nodes, edges] = parser.parseBytes(absPath, source)\n repo.storeFileNodesEdges(absPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'incremental')\n\n return {\n buildType: 'incremental',\n filesUpdated: allFiles.size,\n totalNodes,\n totalEdges,\n changedFiles: changed,\n dependentFiles: [...dependentFiles],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Private helper\n// ---------------------------------------------------------------------------\n\nfunction findDependents(repo: IGraphRepository, filePath: string): string[] {\n const dependents = new Set<string>()\n\n for (const e of repo.getEdgesByTarget(filePath)) {\n if (e.kind === 'IMPORTS_FROM') {\n dependents.add(e.filePath)\n }\n }\n\n for (const node of repo.getNodesByFile(filePath)) {\n for (const e of repo.getEdgesByTarget(node.qualifiedName)) {\n if (['CALLS', 'IMPORTS_FROM', 'INHERITS', 'IMPLEMENTS'].includes(e.kind)) {\n dependents.add(e.filePath)\n }\n }\n }\n\n dependents.delete(filePath)\n return [...dependents]\n}\n","/**\n * File watcher infrastructure (chokidar-based).\n *\n * Extracted from incremental.ts::watch.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IParser } from '../domain/ports/IParser.js'\nimport { DEBOUNCE_MS, loadIgnorePatterns, shouldIgnore, isBinary } from './FileSystemHelper.js'\n\nexport async function watch(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const chokidar = require('chokidar')\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n\n const pending = new Set<string>()\n let timer: ReturnType<typeof setTimeout> | null = null\n\n function shouldHandle(absPath: string): boolean {\n try {\n const stat = fs.lstatSync(absPath)\n if (stat.isSymbolicLink()) { return false }\n } catch {\n return false\n }\n const rel = path.relative(repoRoot, absPath)\n if (shouldIgnore(rel, ignorePatterns)) { return false }\n if (!parser.detectLanguage(absPath)) { return false }\n return true\n }\n\n function flushPending(): void {\n const paths = [...pending]\n pending.clear()\n timer = null\n for (const absPath of paths) { updateFile(absPath) }\n }\n\n function schedule(absPath: string): void {\n pending.add(absPath)\n if (timer !== null) { clearTimeout(timer) }\n timer = setTimeout(flushPending, DEBOUNCE_MS)\n }\n\n function updateFile(absPath: string): void {\n if (!fs.existsSync(absPath)) { return }\n try {\n const stat = fs.lstatSync(absPath)\n if (stat.isSymbolicLink() || !stat.isFile()) { return }\n } catch {\n return\n }\n if (isBinary(absPath)) { return }\n\n try {\n const source = fs.readFileSync(absPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const [nodes, edges] = parser.parseBytes(absPath, source)\n repo.storeFileNodesEdges(absPath, nodes, edges, fhash)\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n const rel = path.relative(repoRoot, absPath)\n process.stderr.write(`Updated: ${rel} (${nodes.length} nodes, ${edges.length} edges)\\n`)\n } catch (err) {\n process.stderr.write(`Error updating ${absPath}: ${String(err)}\\n`)\n }\n }\n\n const watcher = chokidar.watch(repoRoot, {\n ignoreInitial: true,\n ignored: ['**/node_modules/**', '**/.git/**', '**/.codeorbit/**'],\n persistent: true,\n })\n\n watcher\n .on('change', (p: string) => { if (shouldHandle(p)) { schedule(p) } })\n .on('add', (p: string) => { if (shouldHandle(p)) { schedule(p) } })\n .on('unlink', (p: string) => {\n const rel = path.relative(repoRoot, p)\n if (!shouldIgnore(rel, ignorePatterns)) { repo.removeFileData(p) }\n })\n\n process.stderr.write(`Watching ${repoRoot} for changes... (Ctrl+C to stop)\\n`)\n\n await new Promise<void>((_, reject) => {\n process.on('SIGINT', () => {\n watcher\n .close()\n .then(() => { process.stderr.write('Watch stopped.\\n'); process.exit(0) })\n .catch(reject)\n })\n })\n}\n","/**\n * MCP server entry point for codeorbit.\n *\n * Run as: codeorbit serve\n * Communicates via stdio (standard MCP transport).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport {\n buildOrUpdateGraph,\n embedGraph,\n findLargeFunctions,\n getDocsSection,\n getImpactRadius,\n getReviewContext,\n listGraphStats,\n queryGraph,\n semanticSearchNodes,\n} from './tools.js'\n\n// ---------------------------------------------------------------------------\n// Server setup\n// ---------------------------------------------------------------------------\n\nconst server = new McpServer(\n { name: 'codeorbit', version: '0.1.0' },\n {\n instructions:\n 'Persistent incremental knowledge graph for token-efficient, ' +\n 'context-aware code reviews. Parses your codebase with Tree-sitter, ' +\n 'builds a structural graph, and provides smart impact analysis.',\n },\n)\n\n// ---------------------------------------------------------------------------\n// Tool registrations\n// ---------------------------------------------------------------------------\n\nserver.tool(\n 'build_or_update_graph_tool',\n 'Build or incrementally update the code knowledge graph.\\n\\n' +\n 'Call this first to initialize the graph, or after making changes.\\n' +\n 'By default performs an incremental update (only changed files).\\n' +\n 'Set full_rebuild=True to re-parse every file.\\n\\n' +\n 'Args:\\n' +\n ' full_rebuild: If True, re-parse all files. Default: False (incremental).\\n' +\n ' repo_root: Repository root path. Auto-detected from current directory if omitted.\\n' +\n ' base: Git ref to diff against for incremental updates. Default: HEAD~1.',\n {\n full_rebuild: z.boolean().default(false),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n buildOrUpdateGraph({\n fullRebuild: args.full_rebuild,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_impact_radius_tool',\n 'Analyze the blast radius of changed files in the codebase.\\n\\n' +\n 'Shows which functions, classes, and files are impacted by changes.\\n' +\n 'Auto-detects changed files from git if not specified.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.\\n' +\n ' max_depth: Number of hops to traverse in the dependency graph. Default: 2.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for auto-detecting changes. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getImpactRadius({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'query_graph_tool',\n 'Run a predefined graph query to explore code relationships.\\n\\n' +\n 'Available patterns:\\n' +\n '- callers_of: Find functions that call the target\\n' +\n '- callees_of: Find functions called by the target\\n' +\n '- imports_of: Find what the target imports\\n' +\n '- importers_of: Find files that import the target\\n' +\n '- children_of: Find nodes contained in a file or class\\n' +\n '- tests_for: Find tests for the target\\n' +\n '- inheritors_of: Find classes inheriting from the target\\n' +\n '- file_summary: Get all nodes in a file\\n\\n' +\n 'Args:\\n' +\n ' pattern: Query pattern name (see above).\\n' +\n ' target: Node name, qualified name, or file path to query.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n pattern: z.string(),\n target: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n queryGraph({\n pattern: args.pattern,\n target: args.target,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_review_context_tool',\n 'Generate a focused, token-efficient review context for code changes.\\n\\n' +\n 'Combines impact analysis with source snippets and review guidance.\\n' +\n 'Use this for comprehensive code reviews.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: Files to review. Auto-detected from git diff if omitted.\\n' +\n ' max_depth: Impact radius depth. Default: 2.\\n' +\n ' include_source: Include source code snippets. Default: True.\\n' +\n ' max_lines_per_file: Max source lines per file. Default: 200.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for change detection. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n include_source: z.boolean().default(true),\n max_lines_per_file: z.number().int().default(200),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getReviewContext({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n includeSource: args.include_source,\n maxLinesPerFile: args.max_lines_per_file,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'semantic_search_nodes_tool',\n 'Search for code entities by name, keyword, or semantic similarity.\\n\\n' +\n 'Uses vector embeddings for semantic search when available (run embed_graph_tool\\n' +\n 'first, requires @huggingface/transformers). Falls back to keyword matching otherwise.\\n\\n' +\n 'Args:\\n' +\n ' query: Search string to match against node names.\\n' +\n ' kind: Optional filter: File, Class, Function, Type, or Test.\\n' +\n ' limit: Maximum results. Default: 20.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n query: z.string(),\n kind: z.string().nullable().default(null),\n limit: z.number().int().default(20),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n await semanticSearchNodes({\n query: args.query,\n kind: args.kind,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'embed_graph_tool',\n 'Compute vector embeddings for all graph nodes to enable semantic search.\\n\\n' +\n 'Requires: npm install @huggingface/transformers\\n' +\n 'Only computes embeddings for nodes that do not already have them.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(await embedGraph({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'list_graph_stats_tool',\n 'Get aggregate statistics about the code knowledge graph.\\n\\n' +\n 'Shows total nodes, edges, languages, files, and last update time.\\n' +\n 'Useful for checking if the graph is built and up to date.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(listGraphStats({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_docs_section_tool',\n 'Get a specific section from the LLM-optimized documentation reference.\\n\\n' +\n 'Returns only the requested section content for minimal token usage.\\n\\n' +\n 'Available sections: usage, review-delta, review-pr, commands, legal,\\n' +\n 'watch, embeddings, languages, troubleshooting.\\n\\n' +\n 'Args:\\n' +\n ' section_name: The section to retrieve (e.g. \"review-delta\", \"usage\").',\n {\n section_name: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getDocsSection({\n sectionName: args.section_name,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'find_large_functions_tool',\n 'Find functions, classes, or files exceeding a line-count threshold.\\n\\n' +\n 'Useful for decomposition audits, code quality checks, and enforcing\\n' +\n 'size limits during code review. Results are ordered by line count.\\n\\n' +\n 'Args:\\n' +\n ' min_lines: Minimum line count to flag. Default: 50.\\n' +\n ' kind: Optional filter: Function, Class, File, or Test.\\n' +\n ' file_path_pattern: Filter by file path substring (e.g. \"components/\").\\n' +\n ' limit: Maximum results. Default: 50.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n min_lines: z.number().int().default(50),\n kind: z.string().nullable().default(null),\n file_path_pattern: z.string().nullable().default(null),\n limit: z.number().int().default(50),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n findLargeFunctions({\n minLines: args.min_lines,\n kind: args.kind,\n filePathPattern: args.file_path_pattern,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\n// ---------------------------------------------------------------------------\n// Server entry point\n// ---------------------------------------------------------------------------\n\nexport async function runMcpServer(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n","/**\n * MCP tool adapter layer.\n *\n * Each function: validate args → create infrastructure → call use case → return result.\n * No business logic lives here — all logic is in src/usecases/.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { SqliteGraphRepository, nodeToDict, edgeToDict } from '../../infrastructure/SqliteGraphRepository.js'\nimport { TreeSitterParser } from '../../infrastructure/TreeSitterParser.js'\nimport { SqliteEmbeddingStore } from '../../infrastructure/SqliteEmbeddingStore.js'\nimport { findProjectRoot, getDbPath } from '../../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles, getStagedAndUnstaged } from '../../infrastructure/GitRunner.js'\nimport { fullBuild, incrementalUpdate } from '../../usecases/buildGraph.js'\nimport { computeImpactRadius } from '../../usecases/getImpactRadius.js'\nimport { queryGraph as queryGraphUseCase } from '../../usecases/queryGraph.js'\nimport { getReviewContext as getReviewContextUseCase } from '../../usecases/getReviewContext.js'\nimport { semanticSearchNodes as semanticSearchUseCase } from '../../usecases/semanticSearch.js'\nimport { listStats } from '../../usecases/listStats.js'\nimport { embedGraph as embedGraphUseCase } from '../../usecases/embedGraph.js'\nimport { getDocsSection as getDocsSectionUseCase } from '../../usecases/getDocsSection.js'\nimport { findLargeFunctions as findLargeFunctionsUseCase } from '../../usecases/findLargeFunctions.js'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction validateRepoRoot(repoRoot: string): string {\n const resolved = path.resolve(repoRoot)\n if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {\n throw new Error(`repo_root is not an existing directory: ${resolved}`)\n }\n if (\n !fs.existsSync(path.join(resolved, '.git')) &&\n !fs.existsSync(path.join(resolved, '.codeorbit'))\n ) {\n throw new Error(\n `repo_root does not look like a project root (no .git or .codeorbit): ${resolved}`,\n )\n }\n return resolved\n}\n\nfunction resolveRoot(repoRoot?: string | null): string {\n return repoRoot ? validateRepoRoot(repoRoot) : findProjectRoot()\n}\n\n// ---------------------------------------------------------------------------\n// Tool 1: buildOrUpdateGraph\n// ---------------------------------------------------------------------------\n\nexport function buildOrUpdateGraph(args: {\n fullRebuild?: boolean\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const { fullRebuild = false, repoRoot = null, base = 'HEAD~1' } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n const parser = new TreeSitterParser()\n try {\n if (fullRebuild) {\n const result = fullBuild(root, repo, parser)\n return {\n status: 'ok',\n build_type: 'full',\n summary:\n `Full build complete: parsed ${result.filesUpdated} files, ` +\n `created ${result.totalNodes} nodes and ${result.totalEdges} edges.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n errors: result.errors,\n }\n } else {\n const result = incrementalUpdate(root, repo, parser, base)\n if (result.filesUpdated === 0) {\n return {\n status: 'ok',\n build_type: 'incremental',\n summary: 'No changes detected. Graph is up to date.',\n files_updated: 0,\n total_nodes: 0,\n total_edges: 0,\n changed_files: [],\n dependent_files: [],\n errors: [],\n }\n }\n return {\n status: 'ok',\n build_type: 'incremental',\n summary:\n `Incremental update: ${result.filesUpdated} files re-parsed, ` +\n `${result.totalNodes} nodes and ${result.totalEdges} edges updated. ` +\n `Changed: ${JSON.stringify(result.changedFiles)}. ` +\n `Dependents also updated: ${JSON.stringify(result.dependentFiles)}.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n changed_files: result.changedFiles,\n dependent_files: result.dependentFiles,\n errors: result.errors,\n }\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 2: getImpactRadius\n// ---------------------------------------------------------------------------\n\nexport function getImpactRadius(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n maxResults?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n maxResults = 500,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changed files detected.',\n changed_nodes: [],\n impacted_nodes: [],\n impacted_files: [],\n truncated: false,\n total_impacted: 0,\n }\n }\n\n const absFiles = changed.map((f) => path.join(root, f))\n const result = computeImpactRadius(absFiles, repo, maxDepth, maxResults)\n\n const summaryParts = [\n `Blast radius for ${changed.length} changed file(s):`,\n ` - ${result.changedNodes.length} nodes directly changed`,\n ` - ${result.impactedNodes.length} nodes impacted (within ${maxDepth} hops)`,\n ` - ${result.impactedFiles.length} additional files affected`,\n ]\n if (result.truncated) {\n summaryParts.push(\n ` - Results truncated: showing ${result.impactedNodes.length} of ${result.totalImpacted} impacted nodes`,\n )\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n changed_files: changed,\n changed_nodes: result.changedNodes.map(nodeToDict),\n impacted_nodes: result.impactedNodes.map(nodeToDict),\n impacted_files: result.impactedFiles,\n edges: result.edges.map(edgeToDict),\n truncated: result.truncated,\n total_impacted: result.totalImpacted,\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 3: queryGraph\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { pattern, target, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return queryGraphUseCase({ pattern, target, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 4: getReviewContext\n// ---------------------------------------------------------------------------\n\nexport function getReviewContext(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changes detected. Nothing to review.',\n context: {},\n }\n }\n\n return getReviewContextUseCase({\n changedFiles: changed,\n repo,\n repoRoot: root,\n maxDepth,\n includeSource,\n maxLinesPerFile,\n })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 5: semanticSearchNodes\n// ---------------------------------------------------------------------------\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await semanticSearchUseCase({ query, kind, limit, repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 6: listGraphStats\n// ---------------------------------------------------------------------------\n\nexport function listGraphStats(args: {\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return listStats({ repo, embStore, repoRoot: root })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 7: embedGraph\n// ---------------------------------------------------------------------------\n\nexport async function embedGraph(args: {\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await embedGraphUseCase({ repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 8: getDocsSection\n// ---------------------------------------------------------------------------\n\nexport function getDocsSection(args: {\n sectionName: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { sectionName, repoRoot = null } = args\n const searchRoots: string[] = []\n\n if (repoRoot) {\n searchRoots.push(path.resolve(repoRoot))\n }\n\n try {\n const root = resolveRoot(repoRoot)\n if (!searchRoots.includes(root)) {\n searchRoots.push(root)\n }\n } catch {\n // ignore — repo root not required for docs lookup\n }\n\n return getDocsSectionUseCase({ sectionName, searchRoots })\n}\n\n// ---------------------------------------------------------------------------\n// Tool 9: findLargeFunctions\n// ---------------------------------------------------------------------------\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repoRoot?: string | null\n}): Record<string, unknown> {\n const {\n minLines = 50,\n kind = null,\n filePathPattern = null,\n limit = 50,\n repoRoot = null,\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return findLargeFunctionsUseCase({ minLines, kind, filePathPattern, limit, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n","/**\n * SQLite-backed embedding store.\n *\n * Extracted from embeddings.ts::EmbeddingStore + helper functions.\n * Implements IEmbeddingStore.\n */\n\nimport crypto from 'node:crypto'\nimport Database from 'better-sqlite3'\nimport type { GraphNode } from '../domain/types.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\nimport { LocalEmbeddingProvider } from './LocalEmbeddingProvider.js'\nimport { GoogleEmbeddingProvider } from './GoogleEmbeddingProvider.js'\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nconst EMBEDDINGS_SCHEMA = `\nCREATE TABLE IF NOT EXISTS embeddings (\n qualified_name TEXT PRIMARY KEY,\n vector BLOB NOT NULL,\n text_hash TEXT NOT NULL,\n provider TEXT NOT NULL DEFAULT 'unknown'\n);\n`\n\n// ---------------------------------------------------------------------------\n// Vector helpers\n// ---------------------------------------------------------------------------\n\nfunction encodeVector(vec: number[]): Buffer {\n const buf = Buffer.allocUnsafe(vec.length * 4)\n for (let i = 0; i < vec.length; i++) buf.writeFloatLE(vec[i]!, i * 4)\n return buf\n}\n\nfunction decodeVector(blob: Buffer): number[] {\n const n = blob.length / 4\n const result: number[] = new Array(n)\n for (let i = 0; i < n; i++) result[i] = blob.readFloatLE(i * 4)\n return result\n}\n\nfunction cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) return 0\n let dot = 0, normA = 0, normB = 0\n for (let i = 0; i < a.length; i++) {\n dot += a[i]! * b[i]!\n normA += a[i]! * a[i]!\n normB += b[i]! * b[i]!\n }\n if (normA === 0 || normB === 0) return 0\n return dot / (Math.sqrt(normA) * Math.sqrt(normB))\n}\n\nexport function nodeToText(node: GraphNode): string {\n const parts = [node.name]\n if (node.kind !== 'File') parts.push(node.kind.toLowerCase())\n if (node.parentName) parts.push(`in ${node.parentName}`)\n if (node.params) parts.push(node.params)\n if (node.returnType) parts.push(`returns ${node.returnType}`)\n if (node.language) parts.push(node.language)\n return parts.join(' ')\n}\n\n// ---------------------------------------------------------------------------\n// Provider factory\n// ---------------------------------------------------------------------------\n\nexport function getProvider(provider?: string | null): IEmbeddingProvider | null {\n if (provider === 'google') {\n const apiKey = process.env['GOOGLE_API_KEY']\n if (!apiKey) return null\n try { return new GoogleEmbeddingProvider(apiKey) } catch { return null }\n }\n return new LocalEmbeddingProvider()\n}\n\n// ---------------------------------------------------------------------------\n// SqliteEmbeddingStore\n// ---------------------------------------------------------------------------\n\nexport class SqliteEmbeddingStore implements IEmbeddingStore {\n private _db: Database.Database\n readonly available: boolean\n private _provider: IEmbeddingProvider | null\n\n constructor(dbPath: string, provider?: string | null) {\n this._db = new Database(dbPath)\n this._db.exec(EMBEDDINGS_SCHEMA)\n\n try {\n this._db.prepare('SELECT provider FROM embeddings LIMIT 1').get()\n } catch {\n this._db.exec(\n \"ALTER TABLE embeddings ADD COLUMN provider TEXT NOT NULL DEFAULT 'unknown'\",\n )\n }\n\n this._provider = getProvider(provider)\n this.available = this._provider !== null\n }\n\n count(): number {\n const row = this._db\n .prepare('SELECT COUNT(*) AS cnt FROM embeddings')\n .get() as { cnt: number }\n return row.cnt\n }\n\n async embedNodes(nodes: GraphNode[], batchSize = 64): Promise<number> {\n if (!this._provider) return 0\n const providerName = this._provider.name\n\n const toEmbed: Array<{ node: GraphNode; text: string; textHash: string }> = []\n for (const node of nodes) {\n if (node.kind === 'File') continue\n const text = nodeToText(node)\n const textHash = crypto.createHash('sha256').update(text).digest('hex')\n const existing = this._db\n .prepare('SELECT text_hash, provider FROM embeddings WHERE qualified_name = ?')\n .get(node.qualifiedName) as { text_hash: string; provider: string } | undefined\n if (existing && existing.text_hash === textHash && existing.provider === providerName) {\n continue\n }\n toEmbed.push({ node, text, textHash })\n }\n\n if (toEmbed.length === 0) return 0\n\n const insert = this._db.prepare(\n 'INSERT OR REPLACE INTO embeddings (qualified_name, vector, text_hash, provider) VALUES (?, ?, ?, ?)',\n )\n\n for (let i = 0; i < toEmbed.length; i += batchSize) {\n const batch = toEmbed.slice(i, i + batchSize)\n const vectors = await this._provider.embed(batch.map((b) => b.text))\n this._db.transaction(() => {\n for (let j = 0; j < batch.length; j++) {\n const { node, textHash } = batch[j]!\n insert.run(node.qualifiedName, encodeVector(vectors[j]!), textHash, providerName)\n }\n })()\n }\n\n return toEmbed.length\n }\n\n async search(\n query: string,\n limit = 20,\n ): Promise<Array<{ qualifiedName: string; score: number }>> {\n if (!this._provider) return []\n const providerName = this._provider.name\n const queryVec = await this._provider.embedQuery(query)\n\n const rows = this._db\n .prepare('SELECT qualified_name, vector FROM embeddings WHERE provider = ?')\n .all(providerName) as Array<{ qualified_name: string; vector: Buffer }>\n\n const scored = rows.map((row) => ({\n qualifiedName: row.qualified_name,\n score: cosineSimilarity(queryVec, decodeVector(row.vector)),\n }))\n\n scored.sort((a, b) => b.score - a.score)\n return scored.slice(0, limit)\n }\n\n removeNode(qualifiedName: string): void {\n this._db\n .prepare('DELETE FROM embeddings WHERE qualified_name = ?')\n .run(qualifiedName)\n }\n\n close(): void {\n this._db.close()\n }\n}\n\n// Backward-compat alias\nexport { SqliteEmbeddingStore as EmbeddingStore }\n","/**\n * Local HuggingFace embedding provider.\n *\n * Extracted from embeddings.ts::LocalEmbeddingProvider.\n */\n\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst NOMIC_MODEL = 'Xenova/nomic-embed-text-v1.5'\nconst MINILM_MODEL = 'Xenova/all-MiniLM-L6-v2'\n\nexport class LocalEmbeddingProvider implements IEmbeddingProvider {\n private _pipelinePromise: Promise<unknown> | null = null\n private readonly _model: string\n private readonly _dim: number\n\n constructor() {\n const hasToken = !!(process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN'])\n this._model = hasToken ? NOMIC_MODEL : MINILM_MODEL\n this._dim = hasToken ? 768 : 384\n }\n\n private _getPipeline(): Promise<unknown> {\n if (!this._pipelinePromise) {\n const model = this._model\n this._pipelinePromise = import('@huggingface/transformers').then((mod) => {\n const { pipeline, env } = mod as Record<string, unknown> & {\n env: Record<string, unknown>\n pipeline: (task: string, model: string) => Promise<unknown>\n }\n const hfToken = process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN']\n if (hfToken) env['token'] = hfToken\n return pipeline('feature-extraction', model)\n })\n }\n return this._pipelinePromise\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array; dims: number[] }>\n const inputs =\n this._model === NOMIC_MODEL ? texts.map((t) => `search_document: ${t}`) : texts\n const output = await pipe(inputs, { pooling: 'mean', normalize: true })\n const dim = this._dim\n return Array.from({ length: texts.length }, (_, i) =>\n Array.from(output.data.subarray(i * dim, (i + 1) * dim)),\n )\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array }>\n const input = this._model === NOMIC_MODEL ? `search_query: ${text}` : text\n const output = await pipe([input], { pooling: 'mean', normalize: true })\n return Array.from(output.data)\n }\n\n get dimension(): number { return this._dim }\n\n get name(): string { return `local:${this._model.split('/')[1]}` }\n}\n","/**\n * Google Gemini embedding provider.\n *\n * Extracted from embeddings.ts::GoogleEmbeddingProvider.\n */\n\nimport { createRequire } from 'node:module'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst _require = createRequire(import.meta.url)\n\nexport class GoogleEmbeddingProvider implements IEmbeddingProvider {\n private _model: {\n embedContent(req: unknown): Promise<{ embedding: { values: number[] } }>\n batchEmbedContents(req: unknown): Promise<{ embeddings: Array<{ values: number[] }> }>\n }\n private _dimension: number | null = null\n readonly modelName: string\n\n constructor(apiKey: string, model = 'gemini-embedding-001') {\n this.modelName = model\n const { GoogleGenerativeAI } = _require('@google/generative-ai') as {\n GoogleGenerativeAI: new (key: string) => {\n getGenerativeModel(opts: { model: string }): unknown\n }\n }\n const genAI = new GoogleGenerativeAI(apiKey)\n this._model = genAI.getGenerativeModel({ model }) as typeof this._model\n }\n\n private async _withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await fn()\n } catch (e) {\n const msg = String(e)\n const retryable = msg.includes('429') || msg.includes('500') || msg.includes('503')\n if (!retryable || attempt === maxRetries - 1) throw e\n await new Promise((r) => setTimeout(r, 2 ** attempt * 1000))\n }\n }\n throw new Error('unreachable')\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const batchSize = 100\n const results: number[][] = []\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize)\n const response = await this._withRetry(() =>\n this._model.batchEmbedContents({\n requests: batch.map((t) => ({\n content: { parts: [{ text: t }], role: 'user' },\n taskType: 'RETRIEVAL_DOCUMENT',\n })),\n }),\n )\n results.push(...response.embeddings.map((e) => e.values))\n }\n if (this._dimension === null && results.length > 0) {\n this._dimension = results[0]!.length\n }\n return results\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const response = await this._withRetry(() =>\n this._model.embedContent({\n content: { parts: [{ text }], role: 'user' },\n taskType: 'RETRIEVAL_QUERY',\n }),\n )\n const vec = response.embedding.values\n if (this._dimension === null) this._dimension = vec.length\n return vec\n }\n\n get dimension(): number { return this._dimension ?? 768 }\n\n get name(): string { return `google:${this.modelName}` }\n}\n","/**\n * Use case: compute impact radius via BFS.\n *\n * Extracted from GraphStore.getImpactRadius() so the BFS algorithm lives in\n * the application layer, independent of the SQLite infrastructure.\n */\n\nimport type { ImpactRadius } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\n\nexport function computeImpactRadius(\n changedFiles: string[],\n repo: IGraphRepository,\n maxDepth = 2,\n maxNodes = 500,\n): ImpactRadius {\n const adj = repo.getAdjacency()\n\n // Seed: all qualified names in changed files\n const seeds = new Set<string>()\n for (const f of changedFiles) {\n for (const node of repo.getNodesByFile(f)) {\n seeds.add(node.qualifiedName)\n }\n }\n\n const visited = new Set<string>()\n let frontier = new Set(seeds)\n const impacted = new Set<string>()\n let depth = 0\n\n while (frontier.size > 0 && depth < maxDepth) {\n const nextFrontier = new Set<string>()\n for (const qn of frontier) {\n visited.add(qn)\n const outNeighbors = adj.outgoing.get(qn)\n if (outNeighbors) {\n for (const nb of outNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n const inNeighbors = adj.incoming.get(qn)\n if (inNeighbors) {\n for (const nb of inNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n }\n if (visited.size + nextFrontier.size > maxNodes) { break }\n frontier = nextFrontier\n depth++\n }\n\n const changedNodes = []\n for (const qn of seeds) {\n const n = repo.getNode(qn)\n if (n) { changedNodes.push(n) }\n }\n\n let impactedNodes = []\n for (const qn of impacted) {\n if (seeds.has(qn)) { continue }\n const n = repo.getNode(qn)\n if (n) { impactedNodes.push(n) }\n }\n\n const totalImpacted = impactedNodes.length\n const truncated = totalImpacted > maxNodes\n if (truncated) { impactedNodes = impactedNodes.slice(0, maxNodes) }\n\n const impactedFiles = [...new Set(impactedNodes.map((n) => n.filePath))]\n\n const allQns = new Set([...seeds, ...impactedNodes.map((n) => n.qualifiedName)])\n const edges = allQns.size > 0 ? repo.getEdgesAmong(allQns) : []\n\n return { changedNodes, impactedNodes, impactedFiles, edges, truncated, totalImpacted }\n}\n","/**\n * Use case: predefined graph queries (callers_of, callees_of, etc.).\n *\n * Extracted from tools.ts::queryGraph.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const BUILTIN_CALL_NAMES = new Set([\n 'map', 'filter', 'reduce', 'reduceRight', 'forEach', 'find', 'findIndex',\n 'some', 'every', 'includes', 'indexOf', 'lastIndexOf', 'push', 'pop',\n 'shift', 'unshift', 'splice', 'slice', 'concat', 'join', 'flat', 'flatMap',\n 'sort', 'reverse', 'fill', 'keys', 'values', 'entries', 'from', 'isArray',\n 'of', 'at', 'trim', 'trimStart', 'trimEnd', 'split', 'replace', 'replaceAll',\n 'match', 'matchAll', 'search', 'substring', 'substr', 'toLowerCase',\n 'toUpperCase', 'startsWith', 'endsWith', 'padStart', 'padEnd', 'repeat',\n 'charAt', 'charCodeAt', 'assign', 'freeze', 'defineProperty',\n 'getOwnPropertyNames', 'hasOwnProperty', 'create', 'is', 'fromEntries',\n 'log', 'warn', 'error', 'info', 'debug', 'trace', 'dir', 'table', 'time',\n 'timeEnd', 'assert', 'clear', 'count', 'then', 'catch', 'finally',\n 'resolve', 'reject', 'all', 'allSettled', 'race', 'any', 'parse',\n 'stringify', 'floor', 'ceil', 'round', 'random', 'max', 'min', 'abs',\n 'pow', 'sqrt', 'addEventListener', 'removeEventListener', 'querySelector',\n 'querySelectorAll', 'getElementById', 'createElement', 'appendChild',\n 'removeChild', 'setAttribute', 'getAttribute', 'preventDefault',\n 'stopPropagation', 'setTimeout', 'clearTimeout', 'setInterval',\n 'clearInterval', 'toString', 'valueOf', 'toJSON', 'toISOString', 'getTime',\n 'getFullYear', 'now', 'isNaN', 'parseInt', 'parseFloat', 'toFixed',\n 'encodeURIComponent', 'decodeURIComponent', 'call', 'apply', 'bind',\n 'next', 'emit', 'on', 'off', 'once', 'pipe', 'write', 'read', 'end',\n 'close', 'destroy', 'send', 'status', 'json', 'redirect', 'set', 'get',\n 'delete', 'has', 'findUnique', 'findFirst', 'findMany', 'createMany',\n 'update', 'updateMany', 'deleteMany', 'upsert', 'aggregate', 'groupBy',\n 'transaction', 'describe', 'it', 'test', 'expect', 'beforeEach',\n 'afterEach', 'beforeAll', 'afterAll', 'mock', 'spyOn', 'require', 'fetch',\n])\n\nexport const QUERY_PATTERNS: Record<string, string> = {\n callers_of: 'Find all functions that call a given function',\n callees_of: 'Find all functions called by a given function',\n imports_of: 'Find all imports of a given file or module',\n importers_of: 'Find all files that import a given file or module',\n children_of: 'Find all nodes contained in a file or class',\n tests_for: 'Find all tests for a given function or class',\n inheritors_of: 'Find all classes that inherit from a given class',\n file_summary: 'Get a summary of all nodes in a file',\n}\n\n// ---------------------------------------------------------------------------\n// Use case\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { pattern, target, repo, repoRoot } = args\n\n if (!QUERY_PATTERNS[pattern]) {\n return {\n status: 'error',\n error: `Unknown pattern '${pattern}'. Available: ${Object.keys(QUERY_PATTERNS).join(', ')}`,\n }\n }\n\n const results: Array<Record<string, unknown>> = []\n const edgesOut: Array<Record<string, unknown>> = []\n\n if (\n pattern === 'callers_of' &&\n BUILTIN_CALL_NAMES.has(target) &&\n !target.includes('::')\n ) {\n return {\n status: 'ok',\n pattern,\n target,\n description: QUERY_PATTERNS[pattern],\n summary: `'${target}' is a common builtin — callers_of skipped to avoid noise.`,\n results: [],\n edges: [],\n }\n }\n\n let node = repo.getNode(target)\n let resolvedTarget = target\n\n if (!node) {\n const absTarget = path.join(repoRoot, target)\n node = repo.getNode(absTarget)\n if (node) { resolvedTarget = absTarget }\n }\n if (!node) {\n const candidates = repo.searchNodes(target, 5)\n if (candidates.length === 1) {\n node = candidates[0]!\n resolvedTarget = node.qualifiedName\n } else if (candidates.length > 1) {\n return {\n status: 'ambiguous',\n summary: `Multiple matches for '${target}'. Please use a qualified name.`,\n candidates: candidates.map(nodeToDict),\n }\n }\n }\n\n if (!node && pattern !== 'file_summary') {\n return { status: 'not_found', summary: `No node found matching '${target}'.` }\n }\n\n const qn = node?.qualifiedName ?? resolvedTarget\n\n if (pattern === 'callers_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'CALLS') {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n if (results.length === 0 && node) {\n for (const e of repo.searchEdgesByTargetName(node.name)) {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'callees_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CALLS') {\n const callee = repo.getNode(e.targetQualified)\n if (callee) { results.push(nodeToDict(callee)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'imports_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ import_target: e.targetQualified })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'importers_of') {\n const absTarget = node ? node.filePath : path.join(repoRoot, target)\n for (const e of repo.getEdgesByTarget(absTarget)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ importer: e.sourceQualified, file: e.filePath })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'children_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CONTAINS') {\n const child = repo.getNode(e.targetQualified)\n if (child) { results.push(nodeToDict(child)) }\n }\n }\n } else if (pattern === 'tests_for') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'TESTED_BY') {\n const testNode = repo.getNode(e.sourceQualified)\n if (testNode) { results.push(nodeToDict(testNode)) }\n }\n }\n const name = node?.name ?? target\n const seenQns = new Set(results.map((r) => r['qualified_name']))\n for (const t of [\n ...repo.searchNodes(`test_${name}`, 10),\n ...repo.searchNodes(`Test${name}`, 10),\n ]) {\n if (!seenQns.has(t.qualifiedName) && t.isTest) {\n results.push(nodeToDict(t))\n }\n }\n } else if (pattern === 'inheritors_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS') {\n const child = repo.getNode(e.sourceQualified)\n if (child) { results.push(nodeToDict(child)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'file_summary') {\n const absPath = path.join(repoRoot, target)\n for (const n of repo.getNodesByFile(absPath)) {\n results.push(nodeToDict(n))\n }\n }\n\n return {\n status: 'ok',\n pattern,\n target: resolvedTarget,\n description: QUERY_PATTERNS[pattern],\n summary: `Found ${results.length} result(s) for ${pattern}('${resolvedTarget}')`,\n results,\n edges: edgesOut,\n }\n}\n","/**\n * Use case: generate focused review context for changed files.\n *\n * Extracted from tools.ts::getReviewContext + extractRelevantLines + generateReviewGuidance.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { ImpactRadius, GraphNode } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\nimport { computeImpactRadius } from './getImpactRadius.js'\n\nexport function getReviewContext(args: {\n changedFiles: string[]\n repo: IGraphRepository\n repoRoot: string\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n}): Record<string, unknown> {\n const {\n changedFiles,\n repo,\n repoRoot,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n } = args\n\n if (changedFiles.length === 0) {\n return { status: 'ok', summary: 'No changes detected. Nothing to review.', context: {} }\n }\n\n const absFiles = changedFiles.map((f) => path.join(repoRoot, f))\n const impact = computeImpactRadius(absFiles, repo, maxDepth)\n\n const context: Record<string, unknown> = {\n changed_files: changedFiles,\n impacted_files: impact.impactedFiles,\n graph: {\n changed_nodes: impact.changedNodes.map(nodeToDict),\n impacted_nodes: impact.impactedNodes.map(nodeToDict),\n edges: impact.edges.map(edgeToDict),\n },\n }\n\n if (includeSource) {\n const snippets: Record<string, string> = {}\n for (const relPath of changedFiles) {\n const fullPath = path.join(repoRoot, relPath)\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {\n try {\n const content = fs.readFileSync(fullPath, 'utf-8')\n const lines = content.split('\\n')\n if (lines.length > maxLinesPerFile) {\n snippets[relPath] = extractRelevantLines(lines, impact.changedNodes, fullPath)\n } else {\n snippets[relPath] = lines.map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n } catch {\n snippets[relPath] = '(could not read file)'\n }\n }\n }\n context['source_snippets'] = snippets\n }\n\n const guidance = generateReviewGuidance(impact, changedFiles)\n context['review_guidance'] = guidance\n\n const summaryParts = [\n `Review context for ${changedFiles.length} changed file(s):`,\n ` - ${impact.changedNodes.length} directly changed nodes`,\n ` - ${impact.impactedNodes.length} impacted nodes in ${impact.impactedFiles.length} files`,\n '',\n 'Review guidance:',\n guidance,\n ]\n\n return { status: 'ok', summary: summaryParts.join('\\n'), context }\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\nfunction extractRelevantLines(\n lines: string[],\n nodes: GraphNode[],\n filePath: string,\n): string {\n const ranges: Array<[number, number]> = []\n for (const n of nodes) {\n if (n.filePath === filePath) {\n const start = Math.max(0, (n.lineStart ?? 1) - 3)\n const end = Math.min(lines.length, (n.lineEnd ?? lines.length) + 2)\n ranges.push([start, end])\n }\n }\n\n if (ranges.length === 0) {\n return lines.slice(0, 50).map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n\n ranges.sort((a, b) => a[0] - b[0])\n const merged: Array<[number, number]> = [ranges[0]!]\n for (const [start, end] of ranges.slice(1)) {\n const last = merged[merged.length - 1]!\n if (start <= last[1] + 1) {\n merged[merged.length - 1] = [last[0], Math.max(last[1], end)]\n } else {\n merged.push([start, end])\n }\n }\n\n const parts: string[] = []\n for (const [start, end] of merged) {\n if (parts.length > 0) { parts.push('...') }\n for (let i = start; i < end; i++) {\n parts.push(`${i + 1}: ${lines[i] ?? ''}`)\n }\n }\n return parts.join('\\n')\n}\n\nfunction generateReviewGuidance(impact: ImpactRadius, _changedFiles: string[]): string {\n const guidanceParts: string[] = []\n\n const changedFuncs = impact.changedNodes.filter((n) => n.kind === 'Function')\n const testedFuncQns = new Set(\n impact.edges\n .filter((e) => e.kind === 'TESTED_BY')\n .map((e) => e.sourceQualified),\n )\n const untested = changedFuncs.filter(\n (f) => !testedFuncQns.has(f.qualifiedName) && !f.isTest,\n )\n if (untested.length > 0) {\n guidanceParts.push(\n `- ${untested.length} changed function(s) lack test coverage: ` +\n untested.slice(0, 5).map((n) => n.name).join(', '),\n )\n }\n\n if (impact.impactedNodes.length > 20) {\n guidanceParts.push(\n `- Wide blast radius: ${impact.impactedNodes.length} nodes impacted. ` +\n 'Review callers and dependents carefully.',\n )\n }\n\n const inheritanceEdges = impact.edges.filter(\n (e) => e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS',\n )\n if (inheritanceEdges.length > 0) {\n guidanceParts.push(\n `- ${inheritanceEdges.length} inheritance/implementation relationship(s) affected. ` +\n 'Check for Liskov substitution violations.',\n )\n }\n\n if (impact.impactedFiles.length > 3) {\n guidanceParts.push(\n `- Changes impact ${impact.impactedFiles.length} other files. ` +\n 'Consider splitting into smaller PRs.',\n )\n }\n\n if (guidanceParts.length === 0) {\n guidanceParts.push('- Changes appear well-contained with minimal blast radius.')\n }\n\n return guidanceParts.join('\\n')\n}\n","/**\n * Use case: semantic or keyword search across graph nodes.\n *\n * Extracted from tools.ts::semanticSearchNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repo, embStore } = args\n let searchMode = 'keyword'\n\n try {\n if (embStore.available && embStore.count() > 0) {\n searchMode = 'semantic'\n let raw = await semanticSearch(query, repo, embStore, limit * 2)\n if (kind) { raw = raw.filter((r) => r['kind'] === kind) }\n raw = raw.slice(0, limit)\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${raw.length} node(s) matching '${query}' via semantic search` +\n (kind ? ` (kind=${kind})` : ''),\n results: raw,\n }\n }\n } catch {\n searchMode = 'keyword'\n }\n\n let results = repo.searchNodes(query, limit * 2)\n if (kind) { results = results.filter((r) => r.kind === kind) }\n\n const qLower = query.toLowerCase()\n results.sort((a, b) => {\n const aLower = a.name.toLowerCase()\n const bLower = b.name.toLowerCase()\n const aScore = aLower === qLower ? 0 : aLower.startsWith(qLower) ? 1 : 2\n const bScore = bLower === qLower ? 0 : bLower.startsWith(qLower) ? 1 : 2\n return aScore - bScore\n })\n results = results.slice(0, limit)\n\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${results.length} node(s) matching '${query}'` +\n (kind ? ` (kind=${kind})` : ''),\n results: results.map(nodeToDict),\n }\n}\n\nasync function semanticSearch(\n query: string,\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n limit = 20,\n): Promise<Array<Record<string, unknown>>> {\n if (embStore.available && embStore.count() > 0) {\n const results = await embStore.search(query, limit)\n const output: Array<Record<string, unknown>> = []\n for (const { qualifiedName, score } of results) {\n const node = repo.getNode(qualifiedName)\n if (node) {\n const d = nodeToDict(node)\n d['similarity_score'] = Math.round(score * 10000) / 10000\n output.push(d)\n }\n }\n return output\n }\n return repo.searchNodes(query, limit).map((n) => nodeToDict(n))\n}\n","/**\n * Use case: list aggregate graph statistics.\n *\n * Extracted from tools.ts::listGraphStats.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport function listStats(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n repoRoot: string\n}): Record<string, unknown> {\n const { repo, embStore, repoRoot } = args\n const stats = repo.getStats()\n const rootName = path.basename(repoRoot)\n\n const summaryParts = [\n `Graph statistics for ${rootName}:`,\n ` Files: ${stats.filesCount}`,\n ` Total nodes: ${stats.totalNodes}`,\n ` Total edges: ${stats.totalEdges}`,\n ` Languages: ${stats.languages.length > 0 ? stats.languages.join(', ') : 'none'}`,\n ` Last updated: ${stats.lastUpdated ?? 'never'}`,\n '',\n 'Nodes by kind:',\n ...Object.entries(stats.nodesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n '',\n 'Edges by kind:',\n ...Object.entries(stats.edgesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n ]\n\n let embCount = 0\n try {\n embCount = embStore.count()\n summaryParts.push('', `Embeddings: ${embCount} nodes embedded`)\n if (!embStore.available) {\n summaryParts.push(' (install @huggingface/transformers for semantic search)')\n }\n } catch {\n // embeddings unavailable\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_nodes: stats.totalNodes,\n total_edges: stats.totalEdges,\n nodes_by_kind: stats.nodesByKind,\n edges_by_kind: stats.edgesByKind,\n languages: stats.languages,\n files_count: stats.filesCount,\n last_updated: stats.lastUpdated,\n embeddings_count: embCount,\n }\n}\n","/**\n * Use case: embed all graph nodes for semantic search.\n *\n * Extracted from tools.ts::embedGraph + embeddings.ts::embedAllNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport async function embedAllNodes(\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n): Promise<number> {\n if (!embStore.available) return 0\n const allNodes = []\n for (const f of repo.getAllFiles()) {\n allNodes.push(...repo.getNodesByFile(f))\n }\n return embStore.embedNodes(allNodes)\n}\n\nexport async function embedGraph(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { repo, embStore } = args\n\n if (!embStore.available) {\n return {\n status: 'error',\n error:\n '@huggingface/transformers is not installed. ' +\n 'Install with: npm install codeorbit (with optional deps)',\n }\n }\n\n const newlyEmbedded = await embedAllNodes(repo, embStore)\n const total = embStore.count()\n return {\n status: 'ok',\n summary:\n `Embedded ${newlyEmbedded} new node(s). Total embeddings: ${total}. ` +\n 'Semantic search is now active.',\n newly_embedded: newlyEmbedded,\n total_embeddings: total,\n }\n}\n","/**\n * Use case: retrieve a named section from the LLM-optimized docs reference.\n *\n * Extracted from tools.ts::getDocsSection.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nconst AVAILABLE_SECTIONS = [\n 'usage',\n 'review-delta',\n 'review-pr',\n 'commands',\n 'legal',\n 'watch',\n 'embeddings',\n 'languages',\n 'troubleshooting',\n]\n\nexport function getDocsSection(args: {\n sectionName: string\n searchRoots: string[]\n}): Record<string, unknown> {\n const { sectionName, searchRoots } = args\n\n for (const searchRoot of searchRoots) {\n const candidate = path.join(searchRoot, 'docs', 'LLM-OPTIMIZED-REFERENCE.md')\n if (fs.existsSync(candidate)) {\n const content = fs.readFileSync(candidate, 'utf-8')\n const escapedName = sectionName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const match = new RegExp(\n `<section name=\"${escapedName}\">(.*?)</section>`,\n 'si',\n ).exec(content)\n if (match) {\n return { status: 'ok', section: sectionName, content: match[1]!.trim() }\n }\n }\n }\n\n return {\n status: 'not_found',\n error: `Section '${sectionName}' not found. Available: ${AVAILABLE_SECTIONS.join(', ')}`,\n }\n}\n","/**\n * Use case: find functions/classes exceeding a line-count threshold.\n *\n * Extracted from tools.ts::findLargeFunctions.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { minLines = 50, kind = null, filePathPattern = null, limit = 50, repo, repoRoot } = args\n\n const nodes = repo.getNodesBySize(\n minLines,\n undefined,\n kind ?? undefined,\n filePathPattern ?? undefined,\n limit,\n )\n\n const results = nodes.map((n) => {\n const d = nodeToDict(n) as Record<string, unknown>\n d['line_count'] =\n n.lineStart != null && n.lineEnd != null ? n.lineEnd - n.lineStart + 1 : 0\n try {\n d['relative_path'] = path.relative(repoRoot, n.filePath)\n } catch {\n d['relative_path'] = n.filePath\n }\n return d\n })\n\n const summaryParts = [\n `Found ${results.length} node(s) with >= ${minLines} lines` +\n (kind ? ` (kind=${kind})` : '') +\n (filePathPattern ? ` matching '${filePathPattern}'` : '') +\n ':',\n ]\n for (const r of results.slice(0, 10)) {\n summaryParts.push(\n ` ${String(r['line_count']).padStart(4)} lines | ${String(r['kind']).padStart(8)} | ` +\n `${r['name']} (${r['relative_path']}:${r['line_start']})`,\n )\n }\n if (results.length > 10) {\n summaryParts.push(` ... and ${results.length - 10} more`)\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_found: results.length,\n min_lines: minLines,\n results,\n }\n}\n","#!/usr/bin/env node\n/**\n * IPC worker for the VS Code extension.\n *\n * Spawned as a child process by IpcClient (system Node.js, not Electron).\n * Reads newline-delimited JSON requests from stdin, writes JSON responses to stdout.\n *\n * Protocol:\n * Request: { id: number, method: string, params: Record<string, unknown> }\n * Response: { id: number, result: unknown } | { id: number, error: string }\n */\n\nimport * as path from 'node:path'\nimport * as readline from 'node:readline'\nimport { SqliteGraphRepository } from '../../infrastructure/SqliteGraphRepository.js'\nimport { TreeSitterParser } from '../../infrastructure/TreeSitterParser.js'\nimport { SqliteEmbeddingStore } from '../../infrastructure/SqliteEmbeddingStore.js'\nimport { getDbPath } from '../../infrastructure/FileSystemHelper.js'\nimport { fullBuild, incrementalUpdate } from '../../usecases/buildGraph.js'\nimport { embedGraph as embedGraphUseCase } from '../../usecases/embedGraph.js'\n\n// ---------------------------------------------------------------------------\n// Types mirroring sqlite.ts (kept local so the worker is self-contained)\n// ---------------------------------------------------------------------------\n\ntype NodeKind = 'File' | 'Class' | 'Function' | 'Type' | 'Test'\ntype EdgeKind = 'CALLS' | 'IMPORTS_FROM' | 'INHERITS' | 'IMPLEMENTS' | 'CONTAINS' | 'TESTED_BY' | 'DEPENDS_ON'\n\ninterface GraphNode {\n id: number\n kind: NodeKind\n name: string\n qualifiedName: string\n filePath: string\n lineStart: number | null\n lineEnd: number | null\n language: string | null\n parentName: string | null\n params: string | null\n returnType: string | null\n modifiers: string | null\n isTest: boolean\n fileHash: string | null\n}\n\ninterface GraphEdge {\n id: number\n kind: EdgeKind\n sourceQualified: string\n targetQualified: string\n filePath: string\n line: number\n}\n\ninterface GraphStats {\n totalNodes: number\n totalEdges: number\n nodesByKind: Record<string, number>\n edgesByKind: Record<string, number>\n languages: string[]\n filesCount: number\n lastUpdated: string | null\n embeddingsCount: number\n}\n\ninterface IpcRequest {\n id: number\n method: string\n params: Record<string, unknown>\n}\n\ninterface IpcResponse {\n id: number\n result?: unknown\n error?: string\n}\n\n// ---------------------------------------------------------------------------\n// State\n// ---------------------------------------------------------------------------\n\nlet repo: SqliteGraphRepository | null = null\nlet currentDbPath: string | null = null\n\nfunction openRepo(dbPath: string): void {\n if (currentDbPath === dbPath && repo !== null) return\n try { repo?.close() } catch { /* ignore */ }\n repo = new SqliteGraphRepository(dbPath)\n currentDbPath = dbPath\n}\n\nfunction getRepo(): SqliteGraphRepository {\n if (!repo) throw new Error('No database open. Call open first.')\n return repo\n}\n\n// ---------------------------------------------------------------------------\n// Node/edge mapping helpers (SqliteGraphRepository uses domain types,\n// but we need the flat shape the extension expects)\n// ---------------------------------------------------------------------------\n\nfunction toGraphNode(n: {\n id: number\n kind: string\n name: string\n qualifiedName: string\n filePath: string\n lineStart: number | null\n lineEnd: number | null\n language: string | null\n parentName: string | null\n params: string | null\n returnType: string | null\n modifiers: string | null\n isTest: boolean\n fileHash: string | null\n}): GraphNode {\n return {\n id: n.id,\n kind: n.kind as NodeKind,\n name: n.name,\n qualifiedName: n.qualifiedName,\n filePath: n.filePath,\n lineStart: n.lineStart,\n lineEnd: n.lineEnd,\n language: n.language,\n parentName: n.parentName,\n params: n.params,\n returnType: n.returnType,\n modifiers: n.modifiers,\n isTest: n.isTest,\n fileHash: n.fileHash,\n }\n}\n\nfunction toGraphEdge(e: {\n id: number\n kind: string\n sourceQualified: string\n targetQualified: string\n filePath: string\n line: number\n}): GraphEdge {\n return {\n id: e.id,\n kind: e.kind as EdgeKind,\n sourceQualified: e.sourceQualified,\n targetQualified: e.targetQualified,\n filePath: e.filePath,\n line: e.line,\n }\n}\n\n// ---------------------------------------------------------------------------\n// BFS impact radius (mirrors logic from sqlite.ts)\n// ---------------------------------------------------------------------------\n\nfunction computeImpactRadius(\n changedFiles: string[],\n maxDepth: number,\n): { changedNodes: GraphNode[]; impactedNodes: GraphNode[]; impactedFiles: string[]; edges: GraphEdge[] } {\n const r = getRepo()\n const seeds = new Set<string>()\n for (const f of changedFiles) {\n for (const node of r.getNodesByFile(f)) {\n seeds.add(node.qualifiedName)\n }\n }\n\n const visited = new Set<string>()\n let frontier = new Set(seeds)\n const impacted = new Set<string>()\n let depth = 0\n\n while (frontier.size > 0 && depth < maxDepth) {\n const nextFrontier = new Set<string>()\n for (const qn of frontier) {\n visited.add(qn)\n for (const e of r.getEdgesBySource(qn)) {\n if (!visited.has(e.targetQualified)) {\n nextFrontier.add(e.targetQualified)\n impacted.add(e.targetQualified)\n }\n }\n for (const e of r.getEdgesByTarget(qn)) {\n if (!visited.has(e.sourceQualified)) {\n nextFrontier.add(e.sourceQualified)\n impacted.add(e.sourceQualified)\n }\n }\n }\n frontier = nextFrontier\n depth++\n }\n\n const changedNodes: GraphNode[] = []\n for (const qn of seeds) {\n const node = r.getNode(qn)\n if (node) changedNodes.push(toGraphNode(node))\n }\n\n const impactedNodes: GraphNode[] = []\n for (const qn of impacted) {\n if (seeds.has(qn)) continue\n const node = r.getNode(qn)\n if (node) impactedNodes.push(toGraphNode(node))\n }\n\n const impactedFiles = [...new Set(impactedNodes.map((n) => n.filePath))]\n const allQns = new Set([...seeds, ...impacted])\n const edges: GraphEdge[] = []\n if (allQns.size > 0) {\n for (const e of r.getEdgesAmong(allQns)) {\n edges.push(toGraphEdge(e))\n }\n }\n\n return { changedNodes, impactedNodes, impactedFiles, edges }\n}\n\n// ---------------------------------------------------------------------------\n// Dispatcher\n// ---------------------------------------------------------------------------\n\nasync function dispatch(method: string, params: Record<string, unknown>): Promise<unknown> {\n // --- lifecycle ---\n if (method === 'open') {\n const dbPath = params['dbPath'] as string\n openRepo(dbPath)\n const schemaErr = checkSchema()\n return { ok: true, schemaError: schemaErr ?? null }\n }\n\n if (method === 'ping') return { ok: true }\n\n // --- reads ---\n if (method === 'getStats') {\n const r = getRepo()\n const s = r.getStats()\n return s as GraphStats\n }\n\n if (method === 'checkSchemaCompatibility') {\n return checkSchema() ?? null\n }\n\n if (method === 'getAllFiles') {\n return getRepo().getAllFiles()\n }\n\n if (method === 'getNodesByFile') {\n const filePath = params['filePath'] as string\n return getRepo().getNodesByFile(filePath).map(toGraphNode)\n }\n\n if (method === 'getNode') {\n const qn = params['qualifiedName'] as string\n const node = getRepo().getNode(qn)\n return node ? toGraphNode(node) : null\n }\n\n if (method === 'getNodeAtCursor') {\n const filePath = params['filePath'] as string\n const line = params['line'] as number\n // Find the innermost node enclosing the cursor line\n const nodes = getRepo().getNodesByFile(filePath).filter(\n (n) => n.lineStart !== null && n.lineEnd !== null && n.lineStart <= line && n.lineEnd >= line,\n )\n if (nodes.length === 0) return null\n // Pick smallest span (innermost)\n nodes.sort((a, b) => ((a.lineEnd! - a.lineStart!) - (b.lineEnd! - b.lineStart!)))\n return toGraphNode(nodes[0])\n }\n\n if (method === 'searchNodes') {\n const query = params['query'] as string\n const limit = (params['limit'] as number | undefined) ?? 20\n return getRepo().searchNodes(query, limit).map(toGraphNode)\n }\n\n if (method === 'getEdgesBySource') {\n const qn = params['qualifiedName'] as string\n return getRepo().getEdgesBySource(qn).map(toGraphEdge)\n }\n\n if (method === 'getEdgesByTarget') {\n const qn = params['qualifiedName'] as string\n return getRepo().getEdgesByTarget(qn).map(toGraphEdge)\n }\n\n if (method === 'getEdgesAmong') {\n const qns = new Set(params['qualifiedNames'] as string[])\n return getRepo().getEdgesAmong(qns).map(toGraphEdge)\n }\n\n if (method === 'getImpactRadius') {\n const changedFiles = params['changedFiles'] as string[]\n const maxDepth = (params['maxDepth'] as number | undefined) ?? 2\n return computeImpactRadius(changedFiles, maxDepth)\n }\n\n if (method === 'getNodesBySize') {\n const minLines = (params['minLines'] as number | undefined) ?? 50\n const maxLines = params['maxLines'] as number | undefined\n const kind = params['kind'] as string | undefined\n const filePathPattern = params['filePathPattern'] as string | undefined\n const limit = (params['limit'] as number | undefined) ?? 50\n return getRepo().getNodesBySize(minLines, maxLines, kind, filePathPattern, limit).map((n) => ({\n ...toGraphNode(n),\n lineCount: n.lineCount,\n }))\n }\n\n // --- writes ---\n if (method === 'buildGraph') {\n const workspaceRoot = params['workspaceRoot'] as string\n const fullRebuild = (params['fullRebuild'] as boolean | undefined) ?? false\n const dbPath = getDbPath(workspaceRoot)\n const buildRepo = new SqliteGraphRepository(dbPath)\n const parser = new TreeSitterParser()\n try {\n const result = fullRebuild\n ? fullBuild(workspaceRoot, buildRepo, parser)\n : incrementalUpdate(workspaceRoot, buildRepo, parser)\n const verb = fullRebuild ? 'Full build' : 'Incremental update'\n const msg = `${verb}: ${result.filesUpdated} files, ${result.totalNodes} nodes, ${result.totalEdges} edges.`\n // Re-open reader on the new DB after build\n openRepo(dbPath)\n return { success: true, message: msg }\n } catch (err) {\n return { success: false, message: String(err) }\n } finally {\n buildRepo.close()\n }\n }\n\n if (method === 'updateGraph') {\n return dispatch('buildGraph', { ...params, fullRebuild: false })\n }\n\n if (method === 'embedGraph') {\n const workspaceRoot = params['workspaceRoot'] as string\n const dbPath = getDbPath(workspaceRoot)\n const embRepo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n const result = await embedGraphUseCase({ repo: embRepo, embStore })\n if ((result as { status?: string })['status'] === 'error') {\n return { success: false, message: String((result as { error?: unknown })['error']) }\n }\n return { success: true, message: String((result as { summary?: unknown })['summary'] ?? 'Embeddings complete.') }\n } catch (err) {\n return { success: false, message: String(err) }\n } finally {\n embStore.close()\n embRepo.close()\n }\n }\n\n throw new Error(`Unknown method: ${method}`)\n}\n\nfunction checkSchema(): string | undefined {\n if (!repo) return 'Database is not open'\n try {\n const stats = repo.getStats()\n void stats\n return undefined\n } catch (err) {\n return String(err)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main loop\n// ---------------------------------------------------------------------------\n\nfunction send(response: IpcResponse): void {\n process.stdout.write(JSON.stringify(response) + '\\n')\n}\n\nexport async function runIpcWorker(): Promise<void> {\n // Auto-open if --repo flag was passed\n const repoArgIdx = process.argv.indexOf('--repo')\n if (repoArgIdx !== -1 && process.argv[repoArgIdx + 1]) {\n const workspaceRoot = path.resolve(process.argv[repoArgIdx + 1])\n const dbPath = getDbPath(workspaceRoot)\n try { openRepo(dbPath) } catch { /* DB may not exist yet */ }\n }\n\n const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity })\n\n rl.on('line', (line) => {\n const trimmed = line.trim()\n if (!trimmed) return\n\n let req: IpcRequest\n try {\n req = JSON.parse(trimmed) as IpcRequest\n } catch {\n return // malformed — ignore\n }\n\n void dispatch(req.method, req.params ?? {})\n .then((result) => send({ id: req.id, result }))\n .catch((err) => send({ id: req.id, error: String(err) }))\n })\n\n rl.on('close', () => {\n try { repo?.close() } catch { /* ignore */ }\n process.exit(0)\n })\n\n // Signal readiness\n send({ id: 0, result: { ready: true } })\n}\n\n"],"mappings":";;;;;;;;;AAeA,OAAOA,SAAQ;AACf,OAAOC,YAAU;AACjB,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,eAAe;;;ACTxB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,cAAc;AAsBrB,IAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0DZ,IAAM,wBAAN,MAAwD;AAAA,EACrD;AAAA,EACA,WAAkC;AAAA,EACjC;AAAA,EAET,YAAY,QAAgB;AAC1B,SAAK,SAAS;AACd,UAAM,MAAM,KAAK,QAAQ,MAAM;AAC/B,QAAI,CAAC,GAAG,WAAW,GAAG,GAAG;AACvB,SAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAAA,IACvC;AAEA,SAAK,KAAK,IAAI,SAAS,MAAM;AAC7B,SAAK,GAAG,OAAO,oBAAoB;AACnC,SAAK,GA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AAE;AAC3C,YAAQ,IAAI,aAAa,MAAM,UAAU,EAAE;AAC3C,YAAQ,IAAI,aAAa,MAAM,UAAU,EAAE;AAC3C,YAAQ,IAAI,cAAc,MAAM,UAAU,KAAK,IAAI,CAAC,EAAE;AACtD,YAAQ,IAAI,iBAAiB,MAAM,eAAe,OAAO,EAAE;AAAA,EAC7D,UAAE;AACA,IAAAA,MAAK,MAAM;AAAA,EACb;AACF,CAAC;AAGH,QACG,QAAQ,WAAW,EACnB,YAAY,+CAA+C,EAC3D,OAAO,iBAAiB,iCAAiC,EACzD,OAAO,CAAC,SAA4B;AACnC,QAAM,WAAW,KAAK,OAAOF,OAAK,QAAQ,KAAK,IAAI,IAAI,gBAAgB;AACvE,QAAM,WAAWA,OAAK,KAAK,UAAU,cAAc,YAAY;AAC/D,UAAQ,IAAI,2DAA2D;AACvE,UAAQ,IAAI,mBAAmB,QAAQ,EAAE;AACzC,UAAQ;AAAA,IACN;AAAA,EACF;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;AAGH,QACG,QAAQ,OAAO,EACf,YAAY,oCAAoC,EAChD,OAAO,YAAY;AAClB,QAAM,aAAa;AACrB,CAAC;AAGH,QACG,QAAQ,KAAK,EACb,YAAY,kEAAkE,EAC9E,OAAO,iBAAiB,iCAAiC,EACzD,OAAO,YAAY;AAClB,QAAM,aAAa;AACrB,CAAC;AAEH,QAAQ,MAAM;","names":["fs","path","createRequire","fs","path","path","fs","fs","path","fs","path","crypto","fs","path","repo","path","fs","crypto","crypto","fs","path","repo","fs","path","crypto","fs","path","crypto","Database","createRequire","_require","Database","crypto","repo","path","repo","path","fs","path","repo","path","fs","repo","path","repo","repo","fs","path","path","repo","path","path","fs","repo","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions","path","computeImpactRadius","createRequire","path","fs","repo"]}
|