@oss-autopilot/core 0.52.0 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.bundle.cjs +50 -41
- package/dist/cli.js +19 -1
- package/dist/core/github.d.ts +5 -0
- package/dist/core/github.js +27 -22
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.js +1 -1
- package/dist/core/utils.d.ts +6 -0
- package/dist/core/utils.js +9 -0
- package/package.json +4 -2
- package/dist/cli.bundle.cjs.map +0 -7
- package/dist/core/test-utils.d.ts +0 -12
- package/dist/core/test-utils.js +0 -74
package/dist/cli.bundle.cjs.map
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js", "../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js", "../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js", "../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js", "../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js", "../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js", "../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js", "../src/core/types.ts", "../src/core/errors.ts", "../src/core/logger.ts", "../src/core/utils.ts", "../src/core/state-persistence.ts", "../src/core/repo-score-manager.ts", "../src/core/state.ts", "../../../node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js", "../../../node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js", "../../../node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js", "../../../node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js", "../../../node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js", "../../../node_modules/.pnpm/@octokit+endpoint@11.0.3/node_modules/@octokit/endpoint/dist-bundle/index.js", "../../../node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js", "../../../node_modules/.pnpm/json-with-bigint@3.5.7/node_modules/json-with-bigint/json-with-bigint.js", "../../../node_modules/.pnpm/@octokit+request-error@7.1.0/node_modules/@octokit/request-error/dist-src/index.js", "../../../node_modules/.pnpm/@octokit+request@10.0.8/node_modules/@octokit/request/dist-bundle/index.js", "../../../node_modules/.pnpm/@octokit+graphql@9.0.3/node_modules/@octokit/graphql/dist-bundle/index.js", "../../../node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js", "../../../node_modules/.pnpm/@octokit+core@7.0.6/node_modules/@octokit/core/dist-src/version.js", "../../../node_modules/.pnpm/@octokit+core@7.0.6/node_modules/@octokit/core/dist-src/index.js", "../../../node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.6/node_modules/@octokit/plugin-request-log/dist-src/version.js", "../../../node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.6/node_modules/@octokit/plugin-request-log/dist-src/index.js", "../../../node_modules/.pnpm/@octokit+plugin-paginate-rest@14.0.0_@octokit+core@7.0.6/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js", "../../../node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/src/version.ts", "../../../node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/src/generated/endpoints.ts", "../../../node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/src/endpoints-to-methods.ts", "../../../node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/src/index.ts", "../../../node_modules/.pnpm/@octokit+rest@22.0.1/node_modules/@octokit/rest/dist-src/version.js", "../../../node_modules/.pnpm/@octokit+rest@22.0.1/node_modules/@octokit/rest/dist-src/index.js", "../../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/light.js", "../../../node_modules/.pnpm/@octokit+plugin-throttling@11.0.3_@octokit+core@7.0.6/node_modules/@octokit/plugin-throttling/dist-bundle/index.js", "../src/core/github.ts", "../src/core/status-determination.ts", "../src/core/concurrency.ts", "../src/core/pagination.ts", "../src/core/http-cache.ts", "../src/core/ci-analysis.ts", "../src/core/comment-utils.ts", "../src/core/review-analysis.ts", "../src/core/checklist-analysis.ts", "../src/core/maintainer-analysis.ts", "../src/core/display-utils.ts", "../src/core/github-stats.ts", "../src/core/pr-monitor.ts", "../src/core/issue-filtering.ts", "../src/core/issue-scoring.ts", "../src/core/category-mapping.ts", "../src/core/issue-vetting.ts", "../src/core/issue-discovery.ts", "../src/core/issue-conversation.ts", "../src/core/daily-logic.ts", "../src/core/stats.ts", "../src/core/pr-template.ts", "../src/core/index.ts", "../src/formatters/json.ts", "../src/commands/dashboard-data.ts", "../src/commands/daily.ts", "../src/commands/status.ts", "../src/commands/search.ts", "../src/commands/validation.ts", "../src/commands/vet.ts", "../src/commands/track.ts", "../src/commands/read.ts", "../src/commands/comments.ts", "../src/commands/config.ts", "../src/commands/init.ts", "../src/commands/setup.ts", "../src/commands/dashboard-process.ts", "../src/commands/dashboard-lifecycle.ts", "../src/commands/startup.ts", "../src/commands/rate-limiter.ts", "../src/commands/move.ts", "../src/commands/dashboard-server.ts", "../src/commands/dashboard.ts", "../src/commands/parse-list.ts", "../src/commands/check-integration.ts", "../src/commands/local-repos.ts", "../src/commands/dismiss.ts", "../src/commands/pr-template.ts", "../src/commands/stats.ts", "../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/esm.mjs", "../src/cli.ts", "../src/cli-registry.ts"],
|
|
4
|
-
"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.endsWith('...')) {\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 _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\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._collectValue(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.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\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(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\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(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\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(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\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(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\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 const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\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 extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\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; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripColor(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\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 * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n\n/**\n * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.\n *\n * @param {string} str\n * @returns {string}\n * @package\n */\n\nfunction stripColor(str) {\n // eslint-disable-next-line no-control-regex\n const sgrPattern = /\\x1b\\[\\d*(;\\d*)*m/g;\n return str.replace(sgrPattern, '');\n}\n\nexports.Help = Help;\nexports.stripColor = stripColor;\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; // May be a short flag, undefined, or even a long flag (if option has two long flags).\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 this.helpGroupHeading = undefined; // soft initialised when option added to command\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 _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\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._collectValue(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 an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\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 // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\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\u2013Levenshtein_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, stripColor } = 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 = false;\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 this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripColor(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 /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\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 * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\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 this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\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|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\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?.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 if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.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 // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(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 this._initCommandGroup(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._initOptionGroup(option);\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._initCommandGroup(command);\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._collectValue(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('--pt, --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 this._prepareForParse();\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 this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n if (this._savedState === null) {\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\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 '${subcommandName}' 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 }\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 {\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 this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\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 this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\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 subCommand._prepareForParse();\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?.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?.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 * Side effects: modifies command by storing options. Does not reset state if called again.\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[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\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[i++];\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 (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\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\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${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 // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\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 unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\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/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\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 const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\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\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\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 outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\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 enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\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 this._initOptionGroup(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 = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\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 * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\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\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\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ 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\n/**\n * @returns {boolean | undefined}\n * @package\n */\nfunction useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n\nexports.Command = Command;\nexports.useColor = useColor; // exporting for tests\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", "/**\n * Core types for the Open Source Contribution Agent\n */\n\n/**\n * Lifecycle of a discovered issue through the contribution pipeline.\n * - `candidate` \u2014 Discovered but not yet claimed\n * - `claimed` \u2014 Contributor has claimed the issue (e.g., commented \"I'll work on this\")\n * - `in_progress` \u2014 Work is underway locally\n * - `pr_submitted` \u2014 A PR has been opened for this issue\n */\nexport type IssueStatus = 'candidate' | 'claimed' | 'in_progress' | 'pr_submitted';\n\n/** CI pipeline status for a PR's latest commit. */\nexport type CIStatus = 'passing' | 'failing' | 'pending' | 'unknown';\n\n/**\n * Classification of a CI check failure (#81).\n * - `actionable` \u2014 Real test/build failure the contributor should fix\n * - `fork_limitation` \u2014 Failure due to fork permissions (e.g., Vercel deploy, Netlify)\n * - `auth_gate` \u2014 Authorization/approval gate, not a real failure\n * - `infrastructure` \u2014 Runner timeout, dependency install failure, or other transient infra issue\n */\nexport type CIFailureCategory = 'actionable' | 'fork_limitation' | 'auth_gate' | 'infrastructure';\n\n/** A CI check with its failure classification (#81). */\nexport interface ClassifiedCheck {\n name: string;\n category: CIFailureCategory;\n conclusion?: string;\n}\n\n/** Return type for PRMonitor.getCIStatus(). */\nexport interface CIStatusResult {\n status: CIStatus;\n failingCheckNames: string[];\n failingCheckConclusions: Map<string, string>;\n}\n\n/**\n * PRs grouped by repository (#80).\n * Used to prevent parallel git state corruption when multiple PRs exist in the same repo.\n */\nexport interface RepoGroup {\n repo: string;\n prs: FetchedPR[];\n}\n\n/** GitHub's pull request review decision (from the reviewDecision GraphQL field). */\nexport type ReviewDecision = 'approved' | 'changes_requested' | 'review_required' | 'unknown';\n\n/** Input options for `determineStatus()` (see status-determination.ts). */\nexport interface DetermineStatusInput {\n ciStatus: CIStatus;\n hasMergeConflict: boolean;\n hasUnrespondedComment: boolean;\n hasIncompleteChecklist: boolean;\n reviewDecision: ReviewDecision;\n daysSinceActivity: number;\n dormantThreshold: number;\n approachingThreshold: number;\n latestCommitDate?: string;\n /** GitHub login of the HEAD commit's author (from `repos.getCommit`). */\n latestCommitAuthor?: string;\n /** GitHub login of the PR contributor (configured username). */\n contributorUsername?: string;\n lastMaintainerCommentDate?: string;\n latestChangesRequestedDate?: string;\n /** True if at least one failing CI check is classified as 'actionable'. */\n hasActionableCIFailure?: boolean;\n}\n\n/** Result of `determineStatus()` \u2014 the PR's computed status classification. */\nexport interface DetermineStatusResult {\n status: FetchedPRStatus;\n actionReason?: ActionReason;\n waitReason?: WaitReason;\n stalenessTier: StalenessTier;\n}\n\n/**\n * Granular reason why a PR needs addressing (contributor's turn).\n * Active values (produced by determineStatus): needs_response, needs_changes,\n * failing_ci, merge_conflict, incomplete_checklist.\n * Reserved (display mappings exist but detection not yet wired): ci_not_running,\n * needs_rebase, missing_required_files.\n */\nexport type ActionReason =\n | 'needs_response'\n | 'needs_changes'\n | 'failing_ci'\n | 'merge_conflict'\n | 'incomplete_checklist'\n | 'ci_not_running'\n | 'needs_rebase'\n | 'missing_required_files';\n\n/** Granular reason why a PR is waiting on the maintainer. */\nexport type WaitReason = 'pending_review' | 'pending_merge' | 'changes_addressed' | 'ci_blocked';\n\n/** How stale is the PR based on days since activity. Orthogonal to status. */\nexport type StalenessTier = 'active' | 'approaching_dormant' | 'dormant';\n\n/**\n * Top-level classification of a PR's state. Only two values:\n * - `needs_addressing` \u2014 Contributor's turn. See `actionReason` for what to do.\n * - `waiting_on_maintainer` \u2014 Maintainer's turn. See `waitReason` for why.\n *\n * Staleness (active/approaching_dormant/dormant) is tracked separately in `stalenessTier`.\n */\nexport type FetchedPRStatus = 'needs_addressing' | 'waiting_on_maintainer';\n\n/**\n * Hints about what a maintainer is asking for in their review comments.\n * Extracted from comment text by keyword matching.\n */\nexport type MaintainerActionHint =\n | 'demo_requested' // See extractMaintainerActionHints() in pr-monitor.ts for full keyword list\n | 'tests_requested' // See extractMaintainerActionHints() in pr-monitor.ts for full keyword list\n | 'changes_requested' // Generic code changes (from review decision)\n | 'docs_requested' // See extractMaintainerActionHints() in pr-monitor.ts for full keyword list\n | 'rebase_requested'; // See extractMaintainerActionHints() in pr-monitor.ts for full keyword list\n\n/**\n * Ephemeral PR data fetched fresh from GitHub on each run (v2 architecture).\n * This is never persisted in local state \u2014 it represents a point-in-time snapshot\n * of a PR's current condition.\n */\nexport interface FetchedPR {\n // Identity\n id: number;\n url: string;\n repo: string; // \"owner/repo\"\n number: number;\n title: string;\n\n /** Computed by `determineStatus()` based on the fields below. */\n status: FetchedPRStatus;\n /** Granular reason for needs_addressing status. Undefined when waiting_on_maintainer. */\n actionReason?: ActionReason;\n /** Granular reason for waiting_on_maintainer status. Undefined when needs_addressing. */\n waitReason?: WaitReason;\n /** How stale the PR is based on activity age. Independent of status \u2014 a PR can be both needs_addressing and dormant. */\n stalenessTier: StalenessTier;\n\n /** Human-readable status label for consistent display (#79). E.g., \"[CI Failing]\", \"[Needs Response]\". */\n displayLabel: string;\n /** Brief description of what's happening (#79). E.g., \"3 checks failed\", \"@maintainer commented\". */\n displayDescription: string;\n\n // Timestamps\n createdAt: string;\n updatedAt: string;\n\n /** Calendar days since the most recent activity (comment, commit, review). */\n daysSinceActivity: number;\n\n // CI and merge status\n ciStatus: CIStatus;\n /** Names of failing CI checks. Useful for distinguishing real CI failures from validation bots. */\n failingCheckNames: string[];\n /** Failing checks with category classification (#81). Separates actionable failures from fork limitations and auth gates. */\n classifiedChecks: ClassifiedCheck[];\n hasMergeConflict: boolean;\n reviewDecision: ReviewDecision;\n\n // Branch freshness\n /** How many commits the PR branch is behind the base branch. */\n commitsBehindUpstream?: number;\n headRefName?: string;\n /** Target branch name (e.g., \"main\", \"master\"). */\n baseRefName?: string;\n\n /** Absolute path to local clone, if the repo is cloned on this machine. */\n localRepoPath?: string;\n\n /** Required files the PR is missing (e.g., `[\"changeset\", \"CLA\"]`). */\n missingRequiredFiles?: string[];\n\n /** True when a maintainer commented after the contributor's last comment or commit. */\n hasUnrespondedComment: boolean;\n lastMaintainerComment?: {\n author: string;\n body: string;\n createdAt: string;\n };\n\n /** ISO timestamp of the latest commit. Used to determine if changes were pushed after review feedback. */\n latestCommitDate?: string;\n\n /** True when the PR body contains unchecked required checkboxes. */\n hasIncompleteChecklist: boolean;\n checklistStats?: {\n checked: number;\n total: number;\n };\n\n /** Hints extracted from maintainer comments about what actions they are requesting. */\n maintainerActionHints: MaintainerActionHint[];\n}\n\n/**\n * Lightweight reference used in {@link DailyDigest} for shelved and auto-unshelved PRs.\n * Contains only the fields needed for display, avoiding duplication of the full\n * {@link FetchedPR} objects already present in `openPRs` and the status-specific arrays.\n */\nexport interface ShelvedPRRef {\n number: number;\n url: string;\n title: string;\n repo: string;\n daysSinceActivity: number;\n status: FetchedPRStatus;\n}\n/** An issue tracked through the contribution pipeline from discovery to PR submission. */\nexport interface TrackedIssue {\n // Identity\n id: number;\n url: string;\n repo: string; // \"owner/repo\"\n number: number;\n title: string;\n\n status: IssueStatus;\n\n labels: string[];\n createdAt: string;\n updatedAt: string;\n\n /** Whether the issue has been through the vetting process (checking for existing PRs, activity, etc.). */\n vetted: boolean;\n vettingResult?: IssueVettingResult;\n}\n\n/**\n * Result of vetting an issue for contribution suitability.\n * An issue passes vetting when all checks are true (no existing PR, not claimed, etc.).\n */\nexport interface IssueVettingResult {\n passedAllChecks: boolean;\n checks: {\n noExistingPR: boolean;\n notClaimed: boolean;\n projectActive: boolean;\n clearRequirements: boolean;\n contributionGuidelinesFound: boolean;\n };\n contributionGuidelines?: ContributionGuidelines;\n /** Free-text observations from the vetting process (e.g., \"Issue has 3 linked PRs, all closed\"). */\n notes: string[];\n}\n\n/**\n * Structured representation of a project's contribution guidelines,\n * extracted from CONTRIBUTING.md or similar files during issue vetting.\n */\nexport interface ContributionGuidelines {\n // From CONTRIBUTING.md\n branchNamingConvention?: string;\n commitMessageFormat?: string;\n prTitleFormat?: string;\n requiredChecks?: string[];\n\n // Testing requirements\n testFramework?: string;\n testCoverageRequired?: boolean;\n /** Expected test file naming pattern (e.g., `\"*.test.ts\"`, `\"*_spec.rb\"`). */\n testFileNaming?: string;\n\n // Code style\n linter?: string;\n formatter?: string;\n styleGuideUrl?: string;\n\n // Process\n /** How to claim an issue (e.g., \"Comment on the issue before starting work\"). */\n issueClaimProcess?: string;\n reviewProcess?: string;\n claRequired?: boolean;\n\n /** Raw CONTRIBUTING.md content for reference when structured fields are insufficient. */\n rawContent?: string;\n}\n\n/** Health snapshot of a GitHub repository, used to determine if a project is worth contributing to. */\nexport interface ProjectHealth {\n repo: string;\n lastCommitAt: string;\n daysSinceLastCommit: number;\n openIssuesCount: number;\n /** Average number of days for maintainers to respond to issues. */\n avgIssueResponseDays: number;\n ciStatus: 'passing' | 'failing' | 'unknown';\n /** Whether the project is considered active based on recent commit history. */\n isActive: boolean;\n /** GitHub star count, used for repo quality scoring (#98). */\n stargazersCount?: number;\n /** GitHub fork count, used for repo quality scoring (#98). */\n forksCount?: number;\n /** True if the health check itself failed (e.g., API error). */\n checkFailed?: boolean;\n failureReason?: string;\n}\n\n/**\n * Quality score for a repository, used to prioritize issue search results.\n * Score is on a 1-10 scale: base 5, logarithmic merge bonus (max +5: 1->+2, 2->+3, 3->+4, 5+->+5),\n * -1 per closed-without-merge (max -3), +1 if lastMergedAt is set and within 90 days,\n * +1 if responsive, -2 if hostile.\n * Repos below `AgentConfig.minRepoScoreThreshold` are deprioritized.\n */\nexport interface RepoScore {\n repo: string;\n /** Overall score from 1 (avoid) to 10 (excellent track record). */\n score: number;\n /** Number of the contributor's PRs that were merged in this repo. */\n mergedPRCount: number;\n /** Number of the contributor's PRs closed without merge (indicates friction). */\n closedWithoutMergeCount: number;\n /** Average days for maintainers to respond; null if no data. */\n avgResponseDays: number | null;\n lastMergedAt?: string;\n lastEvaluatedAt: string;\n /** Qualitative signals about the repo's maintainer culture. */\n signals: RepoSignals;\n /** GitHub star count, fetched during daily check for dashboard filtering. */\n stargazersCount?: number;\n}\n\n/** Full set of qualitative signals about a repo's maintainer culture. */\nexport interface RepoSignals {\n hasActiveMaintainers: boolean;\n isResponsive: boolean;\n hasHostileComments: boolean;\n}\n\n/** Signals computed from observed open PR data, suitable for merging into RepoScore.signals. */\nexport type ComputedRepoSignals = Pick<RepoSignals, 'isResponsive' | 'hasActiveMaintainers'>;\n\n/**\n * Subset of RepoScore fields that callers may update via `updateRepoScore()`.\n * Excludes `score` (always derived), `repo` (immutable key), and `lastEvaluatedAt` (auto-set).\n * The `signals` field accepts a partial update \u2014 only provided fields are merged.\n */\nexport interface RepoScoreUpdate {\n mergedPRCount?: number;\n closedWithoutMergeCount?: number;\n avgResponseDays?: number | null;\n lastMergedAt?: string;\n signals?: Partial<RepoSignals>;\n stargazersCount?: number;\n}\n\n/**\n * Event types recorded in the {@link AgentState} audit log.\n * - `pr_tracked` \u2014 A new PR was added to tracking\n * - `pr_merged` \u2014 A tracked PR was merged\n * - `pr_closed` \u2014 A tracked PR was closed without merge\n * - `pr_dormant` \u2014 A PR crossed the dormant threshold\n * - `daily_check` \u2014 A daily digest run completed\n * - `comment_posted` \u2014 The agent posted a comment on a PR\n */\nexport type StateEventType = 'pr_tracked' | 'pr_merged' | 'pr_closed' | 'pr_dormant' | 'daily_check' | 'comment_posted';\n\n/** An entry in the state audit log. Events are append-only and used for history tracking. */\nexport interface StateEvent {\n id: string;\n type: StateEventType;\n /** ISO 8601 timestamp of when the event occurred. */\n at: string;\n /** Event-specific payload (e.g., `{ repo: \"owner/repo\", number: 42 }` for PR events). */\n data: Record<string, unknown>;\n}\n\n/** Minimal record of a PR that was closed without being merged, used in the daily digest and dashboard detail view. */\nexport interface ClosedPR {\n url: string;\n repo: string; // \"owner/repo\"\n number: number;\n title: string;\n closedAt: string;\n closedBy?: string;\n}\n\n/** Minimal merged PR data persisted in state.json. Repo/number derived from URL at display time. */\nexport interface StoredMergedPR {\n url: string;\n title: string;\n mergedAt: string; // ISO date \u2014 used for sorting + watermark\n}\n\n/** Minimal closed PR data persisted in state.json. Repo/number derived from URL at display time. */\nexport interface StoredClosedPR {\n url: string;\n title: string;\n closedAt: string; // ISO date \u2014 used for sorting + watermark\n}\n\n/** Minimal record of a PR that was merged, used in the daily digest and dashboard detail view. */\nexport interface MergedPR {\n url: string;\n repo: string; // \"owner/repo\"\n number: number;\n title: string;\n mergedAt: string;\n}\n\n/**\n * The daily report produced by `PRMonitor.generateDigest()`.\n * Contains all open PRs fetched fresh from GitHub, categorized by status,\n * plus recently closed PRs and summary statistics. This is persisted in\n * `AgentState.lastDigest` so the HTML dashboard can render it.\n */\nexport interface DailyDigest {\n generatedAt: string;\n\n /** All open PRs authored by the user, fetched from GitHub Search API. */\n openPRs: FetchedPR[];\n\n /** PRs where the contributor needs to take action. Subset of openPRs where status === 'needs_addressing'. */\n needsAddressingPRs: FetchedPR[];\n /** PRs waiting on the maintainer. Subset of openPRs where status === 'waiting_on_maintainer'. */\n waitingOnMaintainerPRs: FetchedPR[];\n\n /** PRs closed without merge in the last 7 days. Surfaced to alert the contributor. */\n recentlyClosedPRs: ClosedPR[];\n\n /** PRs merged in the last 7 days. Surfaced as wins in the dashboard. */\n recentlyMergedPRs: MergedPR[];\n\n /**\n * PRs manually shelved by the user (excluded from capacity and actionable issues).\n * Stored as lightweight references \u2014 full data is available in `openPRs`.\n */\n shelvedPRs: ShelvedPRRef[];\n /**\n * PRs that were auto-unshelved this run because a maintainer engaged.\n * Stored as lightweight references \u2014 full data is available in `openPRs`.\n */\n autoUnshelvedPRs: ShelvedPRRef[];\n\n summary: {\n totalActivePRs: number;\n /** Count of PRs requiring contributor action (response, CI fix, conflict resolution, etc.). */\n totalNeedingAttention: number;\n /** Lifetime merged PR count across all repos, derived from RepoScore data. */\n totalMergedAllTime: number;\n /** Percentage of all-time PRs that were merged (merged / (merged + closed)). */\n mergeRate: number;\n };\n}\n\n/**\n * Root state object persisted to `~/.oss-autopilot/state.json`.\n *\n * In v2 (current), PRs are fetched fresh from GitHub on each run via the Search API.\n * The primary runtime data lives in `lastDigest` and `repoScores`.\n */\nexport interface AgentState {\n /** Schema version. `2` = v2 fresh-fetch architecture. Used by `StateManager` for migrations. */\n version: number;\n\n /** Per-repo quality scores keyed by `\"owner/repo\"`. Used to prioritize issue search results. */\n repoScores: Record<string, RepoScore>;\n\n config: AgentConfig;\n\n /** Append-only audit log of significant events (PR merged, daily check, etc.). */\n events: StateEvent[];\n\n /** ISO timestamp of the last CLI invocation. */\n lastRunAt: string;\n /** ISO timestamp of the last daily digest generation. */\n lastDigestAt?: string;\n\n /** Cached daily digest so the HTML dashboard can render without re-fetching from GitHub. */\n lastDigest?: DailyDigest;\n\n /** Monthly merged PR counts keyed by `\"YYYY-MM\"`. Powers the contribution timeline chart. */\n monthlyMergedCounts?: Record<string, number>;\n\n /** Monthly closed (without merge) PR counts keyed by `\"YYYY-MM\"`. Powers the timeline and success rate charts. */\n monthlyClosedCounts?: Record<string, number>;\n\n /** Monthly opened PR counts keyed by `\"YYYY-MM\"`. Combines PRs opened across merged+closed+open sets. */\n monthlyOpenedCounts?: Record<string, number>;\n\n /** Daily activity counts keyed by `\"YYYY-MM-DD\"`. Powers the activity heatmap chart. */\n dailyActivityCounts?: Record<string, number>;\n\n /** Cached local repo scan results (#84). Avoids re-scanning the filesystem every session. */\n localRepoCache?: LocalRepoCache;\n\n /** All merged PRs stored incrementally. Source of truth for the merged PR detail view. */\n mergedPRs?: StoredMergedPR[];\n\n /** All closed PRs stored incrementally. Source of truth for the closed PR detail view. */\n closedPRs?: StoredClosedPR[];\n\n activeIssues: TrackedIssue[];\n}\n\n/** Cached results from scanning the filesystem for local git clones (#84). */\nexport interface LocalRepoCache {\n /** Map of \"owner/repo\" -> local repo info */\n repos: Record<string, { path: string; exists: boolean; currentBranch: string | null }>;\n /** Directories that were scanned */\n scanPaths: string[];\n /** ISO 8601 timestamp of when the scan was performed */\n cachedAt: string;\n}\n\n/** Filter for excluding repos below a minimum star count from PR count queries. */\nexport interface StarFilter {\n minStars: number;\n knownStarCounts: ReadonlyMap<string, number>;\n}\n\n/**\n * Check if a repo should be excluded based on its star count.\n * Returns true if the repo is below the threshold or has unknown star count.\n */\nexport function isBelowMinStars(stargazersCount: number | undefined, minStars: number): boolean {\n return stargazersCount === undefined || stargazersCount < minStars;\n}\n\n/** Manual status override for a PR, set via dashboard or CLI. Auto-clears when new activity is detected. */\nexport interface StatusOverride {\n status: FetchedPRStatus;\n setAt: string;\n /** PR's updatedAt at the time the override was set. Used to detect new activity for auto-clear. */\n lastActivityAt: string;\n}\n\n/** User-configurable settings, populated via `/setup-oss` and stored in {@link AgentState}. */\nexport interface AgentConfig {\n /** False until the user completes initial setup via `/setup-oss`. */\n setupComplete: boolean;\n setupCompletedAt?: string;\n\n // Limits\n maxActivePRs: number;\n /** Days of inactivity before a PR is marked `dormant`. Default 30. */\n dormantThresholdDays: number;\n /** Days of inactivity before a PR is marked `approaching_dormant`. Default 25. */\n approachingDormantDays: number;\n /** Issues older than this (by `updated_at`) are filtered from search results. Default 90. */\n maxIssueAgeDays: number;\n\n /** Programming languages to search for issues in (e.g., `[\"typescript\", \"javascript\"]`). */\n languages: string[];\n /** GitHub labels to filter issues by (e.g., `[\"good first issue\", \"help wanted\"]`). */\n labels: string[];\n /** Repos to exclude from issue discovery/search, in `\"owner/repo\"` format. */\n excludeRepos: string[];\n /** Organizations to exclude from issue discovery/search (case-insensitive match on owner segment). */\n excludeOrgs?: string[];\n\n /** Repos where the contributor has had PRs merged. Used for prioritization. */\n trustedProjects: string[];\n\n githubUsername: string;\n\n /** Minimum {@link RepoScore} to include a repo in search results. Default 4. */\n minRepoScoreThreshold: number;\n\n /** User's GitHub starred repos, fetched periodically for prioritized issue discovery. */\n starredRepos: string[];\n starredReposLastFetched?: string;\n\n /** Whether to show the health check notification on session start. Default true. */\n showHealthCheck?: boolean;\n\n /** Whether to squash commits before marking PR ready. `true` (default), `false`, or `\"ask\"`. */\n squashByDefault?: boolean | 'ask';\n\n /** Directories to scan for local git clones (#84). Falls back to default paths if not set. */\n localRepoScanPaths?: string[];\n\n /** Minimum GitHub star count for Phase 2 (general search) results. Default 50. Phases 0/1 are exempt. */\n minStars?: number;\n\n /** Whether to include documentation-only issues in search results. Default true. */\n includeDocIssues?: boolean;\n\n /** Repos known to have anti-AI contribution policies, in `\"owner/repo\"` format. Filtered from search results automatically. */\n aiPolicyBlocklist?: string[];\n\n /** PR URLs manually shelved by the user. Shelved PRs are excluded from capacity and actionable issues. Auto-unshelved when maintainers engage. */\n shelvedPRUrls?: string[];\n\n /** Issue URLs dismissed by the user, mapped to ISO timestamp of when dismissed. Issues with new responses after the dismiss timestamp resurface automatically. */\n dismissedIssues?: Record<string, string>;\n\n /** Manual status overrides for PRs. Maps PR URL to override metadata. Auto-clears when the PR has new activity. */\n statusOverrides?: Record<string, StatusOverride>;\n\n /** Project categories the user is interested in (e.g., devtools, nonprofit). Used to prioritize search results. */\n projectCategories?: ProjectCategory[];\n\n /** GitHub organizations the user wants to prioritize in issue search. Org names only (not owner/repo). */\n preferredOrgs?: string[];\n}\n\n/** Status of a user's comment thread on a GitHub issue. */\nexport type IssueConversationStatus =\n | 'new_response' // Someone responded after user's last comment (check isFromMaintainer to distinguish maintainer vs community)\n | 'waiting' // Last non-bot commenter is not the user; no substantive (non-acknowledgment) response found\n | 'acknowledged'; // User was the last non-bot commenter; no action needed\n\n/** Base fields shared by all issue conversation states. */\ninterface CommentedIssueBase {\n repo: string; // \"owner/repo\"\n number: number;\n title: string;\n url: string;\n userLastCommentedAt: string;\n labels: string[];\n daysSinceUserComment: number;\n}\n\n/** Issue where someone responded after the user's last comment. */\nexport interface CommentedIssueWithResponse extends CommentedIssueBase {\n status: 'new_response';\n lastResponseAuthor: string;\n lastResponseBody: string; // Truncated to 200 chars (+ \"...\" suffix when truncated)\n lastResponseAt: string;\n /**\n * True when the responder has OWNER, MEMBER, or COLLABORATOR author_association\n * on the repository (i.e., someone with repo-level permissions, not just a community user).\n */\n isFromMaintainer: boolean;\n}\n\n/** Issue where no substantive maintainer response was found. */\ninterface CommentedIssueWithoutResponse extends CommentedIssueBase {\n status: 'waiting' | 'acknowledged';\n lastResponseAuthor?: undefined;\n lastResponseBody?: undefined;\n lastResponseAt?: undefined;\n}\n\n/** A GitHub issue the user has commented on, with conversation state. */\nexport type CommentedIssue = CommentedIssueWithResponse | CommentedIssueWithoutResponse;\n\n/** Default configuration applied to new state files. All fields can be overridden via `/setup-oss`. */\nexport const DEFAULT_CONFIG: AgentConfig = {\n setupComplete: false,\n maxActivePRs: 10,\n dormantThresholdDays: 30,\n approachingDormantDays: 25,\n maxIssueAgeDays: 90,\n languages: ['typescript', 'javascript'],\n labels: ['good first issue', 'help wanted'],\n excludeRepos: [],\n trustedProjects: [],\n githubUsername: '',\n minRepoScoreThreshold: 4,\n starredRepos: [],\n squashByDefault: true,\n minStars: 50,\n includeDocIssues: true,\n aiPolicyBlocklist: ['matplotlib/matplotlib'],\n shelvedPRUrls: [],\n dismissedIssues: {},\n projectCategories: [],\n preferredOrgs: [],\n};\n\n/** Initial state written to `~/.oss-autopilot/state.json` on first run. Uses v2 architecture. */\nexport const INITIAL_STATE: AgentState = {\n version: 2, // v2: Fresh GitHub fetching\n activeIssues: [],\n repoScores: {},\n config: DEFAULT_CONFIG,\n events: [],\n lastRunAt: new Date().toISOString(),\n};\n\n// -- Project category types --\n\nexport const PROJECT_CATEGORIES = [\n 'nonprofit',\n 'devtools',\n 'infrastructure',\n 'web-frameworks',\n 'data-ml',\n 'education',\n] as const;\n\nexport type ProjectCategory = (typeof PROJECT_CATEGORIES)[number];\n\n// -- Issue discovery types (shared across issue-discovery, issue-vetting, issue-scoring) --\n\n/** Priority tier for issue search results. Ordered: merged_pr > preferred_org > starred > normal. */\nexport type SearchPriority = 'merged_pr' | 'preferred_org' | 'starred' | 'normal';\n\nexport interface IssueCandidate {\n issue: TrackedIssue;\n vettingResult: IssueVettingResult;\n projectHealth: ProjectHealth;\n recommendation: 'approve' | 'skip' | 'needs_review';\n reasonsToSkip: string[];\n reasonsToApprove: string[];\n viabilityScore: number; // 0-100 scale\n searchPriority: SearchPriority; // Priority level for sorting\n}\n", "/**\n * Custom error type hierarchy for oss-autopilot.\n * Provides structured error codes and specific error classes\n * for different failure categories.\n *\n * Error strategy: Rate-limit and auth errors (429, 401, 403+rate-limit) always\n * propagate to the caller via isRateLimitError/isRateLimitOrAuthError.\n * Other errors degrade gracefully \u2014 modules return partial results and log warnings.\n */\n\n/**\n * Base error for all oss-autopilot errors.\n */\nexport class OssAutopilotError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'OssAutopilotError';\n }\n}\n\n/**\n * Configuration errors (missing setup, invalid config).\n */\nexport class ConfigurationError extends OssAutopilotError {\n constructor(message: string) {\n super(message, 'CONFIGURATION_ERROR');\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Input validation errors (invalid URLs, out-of-range values).\n */\nexport class ValidationError extends OssAutopilotError {\n constructor(message: string) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Extract a human-readable message from an unknown error value.\n */\nexport function errorMessage(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Safely extract an HTTP status code from an unknown error (e.g. Octokit errors).\n * Returns undefined if the error doesn't have a numeric `status` property.\n */\nexport function getHttpStatusCode(error: unknown): number | undefined {\n if (error && typeof error === 'object' && 'status' in error) {\n const status = (error as { status: unknown }).status;\n return typeof status === 'number' && Number.isFinite(status) ? status : undefined;\n }\n return undefined;\n}\n\n/** Check if an error is a GitHub rate limit error (429 or rate-limit 403). */\nexport function isRateLimitError(error: unknown): boolean {\n const status = getHttpStatusCode(error);\n if (status === 429) return true;\n if (status === 403) {\n const msg = errorMessage(error).toLowerCase();\n return msg.includes('rate limit');\n }\n return false;\n}\n\n/** Return true for errors that should propagate (not degrade gracefully): rate limits, auth failures, abuse detection. */\nexport function isRateLimitOrAuthError(err: unknown): boolean {\n const status = getHttpStatusCode(err);\n if (status === 401 || status === 429) return true;\n if (status === 403) {\n const msg = errorMessage(err).toLowerCase();\n return msg.includes('rate limit') || msg.includes('abuse detection');\n }\n return false;\n}\n", "/**\n * Lightweight debug logger for oss-autopilot.\n * Activated by the global --debug CLI flag.\n *\n * All debug/warn output goes to stderr so it never contaminates\n * the --json stdout contract.\n */\n\nlet debugEnabled = false;\n\nexport function enableDebug(): void {\n debugEnabled = true;\n}\n\nexport function isDebugEnabled(): boolean {\n return debugEnabled;\n}\n\n/**\n * Log a debug message. Only outputs when --debug is enabled.\n */\nexport function debug(module: string, message: string, ...args: unknown[]): void {\n if (!debugEnabled) return;\n const timestamp = new Date().toISOString();\n console.error(`[${timestamp}] [DEBUG] [${module}] ${message}`, ...args);\n}\n\n/**\n * Log an informational message. Always outputs to stderr.\n * Use for user-facing progress indicators during long-running operations.\n */\nexport function info(module: string, message: string, ...args: unknown[]): void {\n const timestamp = new Date().toISOString();\n console.error(`[${timestamp}] [INFO] [${module}] ${message}`, ...args);\n}\n\n/**\n * Log a warning. Always outputs.\n */\nexport function warn(module: string, message: string, ...args: unknown[]): void {\n const timestamp = new Date().toISOString();\n console.error(`[${timestamp}] [WARN] [${module}] ${message}`, ...args);\n}\n\n/**\n * Time an async operation and log duration in debug mode.\n */\nexport async function timed<T>(module: string, label: string, fn: () => Promise<T>): Promise<T> {\n if (!debugEnabled) return fn();\n const start = performance.now();\n try {\n const result = await fn();\n const duration = (performance.now() - start).toFixed(0);\n debug(module, `${label} completed in ${duration}ms`);\n return result;\n } catch (err) {\n const duration = (performance.now() - start).toFixed(0);\n debug(module, `${label} failed after ${duration}ms`);\n throw err;\n }\n}\n", "/**\n * Shared utility functions\n */\n\n/** Default concurrency limit for parallel GitHub API requests. */\nexport const DEFAULT_CONCURRENCY = 5;\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { execFileSync, execFile } from 'child_process';\nimport { ConfigurationError } from './errors.js';\nimport { debug } from './logger.js';\n\nconst MODULE = 'utils';\n\n// Cached GitHub token (fetched once per session)\nlet cachedGitHubToken: string | null = null;\nlet tokenFetchAttempted = false;\n\n/**\n * Returns the oss-autopilot data directory path, creating it if it does not exist.\n *\n * The directory is located at `~/.oss-autopilot/` and serves as the root for\n * all persisted user data (state, backups, cache).\n *\n * @returns Absolute path to the data directory (e.g., `/Users/you/.oss-autopilot`)\n *\n * @example\n * const dir = getDataDir();\n * // \"/Users/you/.oss-autopilot\"\n */\nexport function getDataDir(): string {\n const dir = path.join(os.homedir(), '.oss-autopilot');\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n return dir;\n}\n\n/**\n * Returns the path to the state file (`~/.oss-autopilot/state.json`).\n *\n * Implicitly creates the data directory via {@link getDataDir} if it does not exist.\n *\n * @returns Absolute path to `state.json`\n *\n * @example\n * const statePath = getStatePath();\n * // \"/Users/you/.oss-autopilot/state.json\"\n */\nexport function getStatePath(): string {\n return path.join(getDataDir(), 'state.json');\n}\n\n/**\n * Returns the backup directory path, creating it if it does not exist.\n *\n * Located at `~/.oss-autopilot/backups/`. Used for automatic state backups\n * before each write operation.\n *\n * @returns Absolute path to the backups directory\n *\n * @example\n * const backupDir = getBackupDir();\n * // \"/Users/you/.oss-autopilot/backups\"\n */\nexport function getBackupDir(): string {\n const dir = path.join(getDataDir(), 'backups');\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n return dir;\n}\n\n/**\n * Returns the HTTP cache directory path, creating it if it does not exist.\n *\n * Located at `~/.oss-autopilot/cache/`. Used by {@link HttpCache} to store\n * ETag-based response caches for GitHub API endpoints.\n *\n * @returns Absolute path to the cache directory\n *\n * @example\n * const cacheDir = getCacheDir();\n * // \"/Users/you/.oss-autopilot/cache\"\n */\nexport function getCacheDir(): string {\n const dir = path.join(getDataDir(), 'cache');\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n return dir;\n}\n\n/**\n * Represents a parsed GitHub pull request or issue URL.\n *\n * @property owner - The repository owner (e.g., `\"facebook\"`)\n * @property repo - The repository name (e.g., `\"react\"`)\n * @property number - The PR or issue number\n * @property type - Whether the URL points to a pull request or an issue\n */\ninterface ParsedGitHubUrl {\n owner: string;\n repo: string;\n number: number;\n type: 'pull' | 'issues';\n}\n\n// Validation patterns for GitHub owner and repo names\nconst OWNER_PATTERN = /^[a-zA-Z0-9_-]+$/;\nconst REPO_PATTERN = /^[a-zA-Z0-9_.-]+$/;\n\n/**\n * Validate that owner and repo names contain only safe characters\n */\nfunction isValidOwnerRepo(owner: string, repo: string): boolean {\n return OWNER_PATTERN.test(owner) && REPO_PATTERN.test(repo);\n}\n\n/**\n * Parses a GitHub pull request or issue URL into its components.\n *\n * Only accepts HTTPS GitHub URLs (`https://github.com/...`). Returns `null` for\n * invalid URLs, non-GitHub URLs, or URLs with invalid owner/repo characters.\n *\n * @param url - Full GitHub URL (e.g., `\"https://github.com/owner/repo/pull/42\"`)\n * @returns Parsed URL components, or `null` if the URL is invalid or not a recognized GitHub PR/issue URL\n *\n * @example\n * parseGitHubUrl('https://github.com/facebook/react/pull/123')\n * // { owner: \"facebook\", repo: \"react\", number: 123, type: \"pull\" }\n *\n * @example\n * parseGitHubUrl('https://github.com/vercel/next.js/issues/456')\n * // { owner: \"vercel\", repo: \"next.js\", number: 456, type: \"issues\" }\n *\n * @example\n * parseGitHubUrl('https://example.com/not-github')\n * // null\n */\nexport function parseGitHubUrl(url: string): ParsedGitHubUrl | null {\n // URL must start with https://github.com/\n if (!url.startsWith('https://github.com/')) {\n return null;\n }\n\n const prMatch = url.match(/github\\.com\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)/);\n if (prMatch) {\n const owner = prMatch[1];\n const repo = prMatch[2];\n if (!isValidOwnerRepo(owner, repo)) {\n return null;\n }\n return {\n owner,\n repo,\n number: parseInt(prMatch[3], 10),\n type: 'pull',\n };\n }\n\n const issueMatch = url.match(/github\\.com\\/([^/]+)\\/([^/]+)\\/issues\\/(\\d+)/);\n if (issueMatch) {\n const owner = issueMatch[1];\n const repo = issueMatch[2];\n if (!isValidOwnerRepo(owner, repo)) {\n return null;\n }\n return {\n owner,\n repo,\n number: parseInt(issueMatch[3], 10),\n type: 'issues',\n };\n }\n\n return null;\n}\n\n/**\n * Extracts the owner and repo from a GitHub web URL\n * (e.g. `https://github.com/owner/repo/pull/42`, `https://github.com/owner/repo/`).\n *\n * Unlike {@link parseGitHubUrl}, this does **not** require a PR or issue number in the URL.\n * Like `parseGitHubUrl`, it enforces an `https://github.com/` prefix.\n *\n * @param url - An HTTPS GitHub URL containing at least `github.com/owner/repo`\n * @returns `{ owner, repo }` or `null` if the URL cannot be parsed or contains invalid owner/repo characters\n *\n * @example\n * extractOwnerRepo('https://github.com/facebook/react/pull/123')\n * // { owner: \"facebook\", repo: \"react\" }\n *\n * @example\n * extractOwnerRepo('https://github.com/vercel/next.js/')\n * // { owner: \"vercel\", repo: \"next.js\" }\n */\nexport function extractOwnerRepo(url: string): { owner: string; repo: string } | null {\n if (!url.startsWith('https://github.com/')) return null;\n const match = url.match(/github\\.com\\/([^/]+)\\/([^/]+)/);\n if (!match) return null;\n\n const owner = match[1];\n const repo = match[2];\n if (!isValidOwnerRepo(owner, repo)) return null;\n\n return { owner, repo };\n}\n\n/**\n * Calculates the number of whole days between two dates, using floor rounding.\n *\n * Can return negative values if `from` is after `to`. Partial days are truncated\n * (e.g., 1.9 days returns 1).\n *\n * @param from - The start date\n * @param to - The end date (defaults to the current date/time)\n * @returns Number of whole days between the two dates (may be negative)\n *\n * @example\n * daysBetween(new Date('2024-01-01'), new Date('2024-01-10'))\n * // 9\n *\n * @example\n * daysBetween(new Date('2024-01-10'), new Date('2024-01-01'))\n * // -9\n */\nexport function daysBetween(from: Date, to: Date = new Date()): number {\n return Math.max(0, Math.floor((to.getTime() - from.getTime()) / (1000 * 60 * 60 * 24)));\n}\n\n/**\n * Splits an `\"owner/repo\"` string into its owner and repo components.\n *\n * @param repoFullName - Full repository name in `\"owner/repo\"` format\n * @returns Object with `owner` and `repo` string properties\n * @throws {Error} If the input does not contain both an owner and repo separated by `/`\n *\n * @example\n * splitRepo('facebook/react')\n * // { owner: \"facebook\", repo: \"react\" }\n */\nexport function splitRepo(repoFullName: string): { owner: string; repo: string } {\n const [owner, repo] = repoFullName.split('/');\n if (!owner || !repo) {\n throw new Error(`Invalid repo format: expected \"owner/repo\", got \"${repoFullName}\"`);\n }\n return { owner, repo };\n}\n\n/**\n * Case-insensitive check whether a repo owner matches the given GitHub username.\n * Used to skip a user's own repos (PRs to your own repos aren't OSS contributions).\n */\nexport function isOwnRepo(owner: string, username: string): boolean {\n return owner.toLowerCase() === username.toLowerCase();\n}\n\n/**\n * Read the CLI package version from package.json relative to the running CLI bundle.\n * Resolves `../package.json` from `process.argv[1]` (the bundle entry point).\n * Falls back to '0.0.0' if the file is unreadable.\n */\nexport function getCLIVersion(): string {\n try {\n const pkgPath = path.join(path.dirname(process.argv[1]), '..', 'package.json');\n return JSON.parse(fs.readFileSync(pkgPath, 'utf-8')).version;\n } catch {\n return '0.0.0';\n }\n}\n\n/**\n * Formats a timestamp as a human-readable relative time string.\n *\n * Returns minutes for < 1 hour, hours for < 1 day, days for < 30 days,\n * and a locale-formatted date string for anything older.\n *\n * @param dateStr - ISO 8601 date string\n * @returns Relative time like `\"5m ago\"`, `\"3h ago\"`, `\"12d ago\"`, or a formatted date\n *\n * @example\n * formatRelativeTime('2024-01-20T10:00:00Z')\n * // \"5d ago\" (if called on Jan 25)\n *\n * @example\n * formatRelativeTime(new Date(Date.now() - 120000).toISOString())\n * // \"2m ago\"\n */\nexport function formatRelativeTime(dateStr: string): string {\n const date = new Date(dateStr);\n const diffMs = Date.now() - date.getTime();\n if (diffMs < 0) return 'just now';\n const diffMins = Math.floor(diffMs / 60000);\n const diffHours = Math.floor(diffMs / 3600000);\n const diffDays = Math.floor(diffMs / 86400000);\n\n if (diffMins < 60) return `${diffMins}m ago`;\n if (diffHours < 24) return `${diffHours}h ago`;\n if (diffDays < 30) return `${diffDays}d ago`;\n return date.toLocaleDateString();\n}\n\n/**\n * Creates a descending date comparator function for use with `Array.prototype.sort()`.\n *\n * Items with `null` or `undefined` dates are treated as epoch (sorted last).\n *\n * @param getDate - Accessor function that extracts a date value from each item\n * @returns A comparator function that sorts items from newest to oldest\n *\n * @example\n * const prs = [{ createdAt: '2024-01-01' }, { createdAt: '2024-06-15' }];\n * prs.sort(byDateDescending(pr => pr.createdAt));\n * // [{ createdAt: '2024-06-15' }, { createdAt: '2024-01-01' }]\n */\nexport function byDateDescending<T>(getDate: (item: T) => string | number | null | undefined) {\n return (a: T, b: T): number => {\n const dateA = new Date(getDate(a) || 0).getTime();\n const dateB = new Date(getDate(b) || 0).getTime();\n return dateB - dateA;\n };\n}\n\n/**\n * Retrieves a GitHub authentication token, checking sources in priority order.\n *\n * Checks `GITHUB_TOKEN` environment variable first, then falls back to `gh auth token`\n * from the GitHub CLI. The result is cached after the first successful lookup (or first\n * failed attempt), so subsequent calls are instant and do not spawn subprocesses.\n *\n * @returns The GitHub token string, or `null` if no token is available\n *\n * @example\n * const token = getGitHubToken();\n * if (token) {\n * // use token for API calls\n * }\n */\nexport function getGitHubToken(): string | null {\n // Return cached token if we already have one\n if (cachedGitHubToken) {\n return cachedGitHubToken;\n }\n\n // Don't retry if we already tried and failed\n if (tokenFetchAttempted) {\n return null;\n }\n\n tokenFetchAttempted = true;\n\n // 1. Check environment variable first\n if (process.env.GITHUB_TOKEN) {\n cachedGitHubToken = process.env.GITHUB_TOKEN;\n return cachedGitHubToken;\n }\n\n // 2. Try gh CLI (using execFileSync to avoid shell injection - no user input here anyway)\n try {\n const token = execFileSync('gh', ['auth', 'token'], {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'], // Suppress stderr\n timeout: 2000, // 2 second timeout\n }).trim();\n\n if (token && token.length > 0) {\n cachedGitHubToken = token;\n debug(MODULE, 'Using GitHub token from gh CLI');\n return cachedGitHubToken;\n }\n } catch (err) {\n // gh CLI not available or not authenticated \u2014 fall through to return null\n debug(MODULE, 'gh auth token failed (CLI unavailable or not authenticated)', err);\n }\n\n return null;\n}\n\n/**\n * Returns a GitHub token or throws an error with setup instructions.\n *\n * Delegates to {@link getGitHubToken} and throws if no token is found. Use this\n * in commands that cannot proceed without authentication.\n *\n * @returns The GitHub token string (guaranteed non-null)\n * @throws {ConfigurationError} If no token is available, with instructions for `gh auth login` or setting `GITHUB_TOKEN`\n *\n * @example\n * const token = requireGitHubToken(); // throws if not authenticated\n */\nexport function requireGitHubToken(): string {\n const token = getGitHubToken();\n\n if (!token) {\n throw new ConfigurationError(\n 'GitHub authentication required.\\n\\n' +\n 'Options:\\n' +\n ' 1. Use gh CLI: gh auth login\\n' +\n ' 2. Set GITHUB_TOKEN environment variable\\n\\n' +\n 'The gh CLI is recommended - install from https://cli.github.com',\n );\n }\n\n return token;\n}\n\n/**\n * Resets the cached GitHub token and fetch-attempted flag.\n *\n * Intended for use in tests to ensure a clean state between test cases.\n * After calling this, the next call to {@link getGitHubToken} will re-fetch the token.\n *\n * @example\n * afterEach(() => {\n * resetGitHubTokenCache();\n * });\n */\nexport function resetGitHubTokenCache(): void {\n cachedGitHubToken = null;\n tokenFetchAttempted = false;\n}\n\n/**\n * Asynchronous version of {@link getGitHubToken}.\n *\n * Uses `execFile` (non-blocking) instead of `execFileSync` to avoid blocking\n * the event loop during CLI cold start. Shares the same cache as the synchronous\n * version, so a successful async fetch makes subsequent sync calls instant.\n *\n * @returns The GitHub token string, or `null` if no token is available\n *\n * @example\n * const token = await getGitHubTokenAsync();\n * if (token) {\n * // use token for API calls\n * }\n */\nexport async function getGitHubTokenAsync(): Promise<string | null> {\n // Return cached token if we already have one\n if (cachedGitHubToken) {\n return cachedGitHubToken;\n }\n\n // Don't retry if we already tried and failed\n if (tokenFetchAttempted) {\n return null;\n }\n\n tokenFetchAttempted = true;\n\n // 1. Check environment variable first\n if (process.env.GITHUB_TOKEN) {\n cachedGitHubToken = process.env.GITHUB_TOKEN;\n return cachedGitHubToken;\n }\n\n // 2. Try gh CLI asynchronously (non-blocking)\n try {\n const token = await new Promise<string>((resolve, reject) => {\n execFile('gh', ['auth', 'token'], { encoding: 'utf-8', timeout: 2000 }, (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout.trim());\n }\n });\n });\n\n if (token && token.length > 0) {\n cachedGitHubToken = token;\n debug(MODULE, 'Using GitHub token from gh CLI (async)');\n return cachedGitHubToken;\n }\n } catch (err) {\n // gh CLI not available or not authenticated \u2014 fall through to return null\n debug(MODULE, 'gh auth token failed (CLI unavailable or not authenticated)', err);\n }\n\n return null;\n}\n\n/**\n * GitHub username validation pattern.\n * Usernames must start with an alphanumeric character, can contain hyphens\n * (but not consecutive ones and not at the end), and be 1-39 characters.\n */\nconst GITHUB_USERNAME_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/;\n\n/**\n * Detect the authenticated GitHub username via the `gh` CLI.\n *\n * Runs `gh api user --jq '.login'` asynchronously and validates the result\n * against GitHub's username rules. Never throws \u2014 returns `null` on any failure\n * (gh not installed, not authenticated, invalid output, etc.).\n *\n * @returns The GitHub username string, or `null` if detection fails\n *\n * @example\n * const username = await detectGitHubUsername();\n * if (username) {\n * console.log(`Logged in as ${username}`);\n * }\n */\nexport async function detectGitHubUsername(): Promise<string | null> {\n try {\n const login = await new Promise<string>((resolve, reject) => {\n execFile('gh', ['api', 'user', '--jq', '.login'], { encoding: 'utf-8', timeout: 5000 }, (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout.trim());\n }\n });\n });\n\n if (login && GITHUB_USERNAME_RE.test(login)) {\n debug(MODULE, `Detected GitHub username: ${login}`);\n return login;\n }\n\n debug(MODULE, `gh api user returned invalid username: \"${login}\"`);\n return null;\n } catch (err) {\n debug(MODULE, 'detectGitHubUsername failed', err);\n return null;\n }\n}\n", "/**\n * State persistence layer for the OSS Contribution Agent.\n * Handles file I/O, locking, backup/restore, and v1-to-v2 migration.\n * No module-level mutable state \u2014 functions accept/return AgentState objects.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AgentState, INITIAL_STATE } from './types.js';\nimport { getStatePath, getBackupDir, getDataDir } from './utils.js';\nimport { errorMessage } from './errors.js';\nimport { debug, warn } from './logger.js';\n\nconst MODULE = 'state';\n\n// Current state version\nconst CURRENT_STATE_VERSION = 2;\n\n// Lock file timeout: if a lock is older than this, it is considered stale\nconst LOCK_TIMEOUT_MS = 30_000; // 30 seconds\n\n// Legacy path for migration\nconst LEGACY_STATE_FILE = path.join(process.cwd(), 'data', 'state.json');\nconst LEGACY_BACKUP_DIR = path.join(process.cwd(), 'data', 'backups');\n\n/**\n * Check whether an existing lock file is stale (expired or corrupt).\n * Returns true if the lock should be considered stale and can be removed.\n */\nfunction isLockStale(lockPath: string): boolean {\n try {\n const existing = JSON.parse(fs.readFileSync(lockPath, 'utf-8'));\n return Date.now() - existing.timestamp > LOCK_TIMEOUT_MS;\n } catch (err) {\n // Lock file is unreadable or contains invalid JSON \u2014 treat as stale\n debug(MODULE, 'Lock file unreadable or invalid JSON, treating as stale', err);\n return true;\n }\n}\n\n/**\n * Acquire an advisory file lock using exclusive-create (`wx` flag).\n * If the lock file already exists but is stale (older than LOCK_TIMEOUT_MS or corrupt),\n * it is removed and re-acquired.\n * @throws Error if the lock is held by another active process.\n */\nexport function acquireLock(lockPath: string): void {\n const lockData = JSON.stringify({ pid: process.pid, timestamp: Date.now() });\n try {\n fs.writeFileSync(lockPath, lockData, { flag: 'wx' }); // Fails if file exists\n return;\n } catch (err) {\n // Lock file exists (EEXIST from 'wx' flag) \u2014 check if it is stale\n debug(MODULE, 'Lock file already exists, checking staleness', err);\n }\n\n if (!isLockStale(lockPath)) {\n throw new Error('State file is locked by another process');\n }\n\n // Stale lock detected \u2014 remove it and try to re-acquire\n try {\n fs.unlinkSync(lockPath);\n } catch (err) {\n // Another process may have removed the stale lock first \u2014 proceed to re-acquire regardless\n debug(MODULE, 'Stale lock already removed by another process', err);\n }\n try {\n fs.writeFileSync(lockPath, lockData, { flag: 'wx' });\n } catch (err) {\n // Another process grabbed the lock between unlink and write\n debug(MODULE, 'Lock re-acquire failed (race condition)', err);\n throw new Error('State file is locked by another process', { cause: err });\n }\n}\n\n/**\n * Release an advisory file lock, but only if this process owns it.\n * Silently ignores missing lock files or locks owned by other processes.\n */\nexport function releaseLock(lockPath: string): void {\n try {\n const data = JSON.parse(fs.readFileSync(lockPath, 'utf-8'));\n if (data.pid === process.pid) {\n fs.unlinkSync(lockPath);\n }\n } catch (err) {\n // Lock already removed or unreadable \u2014 nothing to do\n debug(MODULE, 'Lock file already removed or unreadable during release', err);\n }\n}\n\n/**\n * Write data to `filePath` atomically by first writing to a temporary file\n * in the same directory and then renaming. Rename is atomic on POSIX filesystems,\n * preventing partial/corrupt state files if the process crashes mid-write.\n */\nexport function atomicWriteFileSync(filePath: string, data: string, mode?: number): void {\n const tmpPath = filePath + '.tmp';\n fs.writeFileSync(tmpPath, data, { mode: mode ?? 0o600 });\n fs.renameSync(tmpPath, filePath);\n // Ensure permissions are correct (rename preserves the tmp file's mode,\n // but on some systems the mode from writeFileSync is masked by umask)\n if (mode !== undefined) {\n fs.chmodSync(filePath, mode);\n }\n}\n\n/**\n * Migrate state from v1 (local PR tracking) to v2 (fresh GitHub fetching).\n * Preserves repoScores and config; drops the legacy PR arrays.\n */\nfunction migrateV1ToV2(rawState: Record<string, unknown>): AgentState {\n debug(MODULE, 'Migrating state from v1 to v2 (fresh GitHub fetching)...');\n\n // Extract merged/closed PR arrays from v1 state to seed repo scores.\n // Don't increment counts here as the score may already reflect these PRs.\n const mergedPRs = (rawState.mergedPRs as Array<{ repo: string }> | undefined) || [];\n const closedPRs = (rawState.closedPRs as Array<{ repo: string }> | undefined) || [];\n\n // Ensure every repo referenced by historical PRs has a score record\n const repoScores = { ...((rawState.repoScores as AgentState['repoScores']) || {}) };\n for (const pr of [...mergedPRs, ...closedPRs]) {\n if (!repoScores[pr.repo]) {\n repoScores[pr.repo] = {\n repo: pr.repo,\n score: 5,\n mergedPRCount: 0,\n closedWithoutMergeCount: 0,\n avgResponseDays: null,\n lastEvaluatedAt: new Date().toISOString(),\n signals: {\n hasActiveMaintainers: true,\n isResponsive: false,\n hasHostileComments: false,\n },\n };\n }\n }\n\n const migratedState: AgentState = {\n version: 2,\n activeIssues: (rawState.activeIssues as AgentState['activeIssues']) || [],\n repoScores,\n config: rawState.config as AgentState['config'],\n events: (rawState.events as AgentState['events']) || [],\n lastRunAt: new Date().toISOString(),\n };\n\n debug(MODULE, `Migration complete. Preserved ${Object.keys(repoScores).length} repo scores.`);\n return migratedState;\n}\n\n/**\n * Validate that a loaded state has the required structure.\n * Handles both v1 (with PR arrays) and v2 (without).\n */\nfunction isValidState(state: unknown): state is AgentState {\n if (!state || typeof state !== 'object') return false;\n const s = state as Record<string, unknown>;\n\n // Migrate older states that don't have repoScores\n if (s.repoScores === undefined) {\n s.repoScores = {};\n }\n\n // Migrate older states that don't have events\n if (s.events === undefined) {\n s.events = [];\n }\n\n // Migrate older states that don't have mergedPRs\n if (s.mergedPRs === undefined) {\n s.mergedPRs = [];\n }\n\n // Base requirements for all versions\n const hasBaseFields =\n typeof s.version === 'number' &&\n typeof s.repoScores === 'object' &&\n s.repoScores !== null &&\n Array.isArray(s.events) &&\n typeof s.config === 'object' &&\n s.config !== null;\n\n if (!hasBaseFields) return false;\n\n // v1 requires base PR arrays to be present (they will be dropped during migration)\n if (s.version === 1) {\n return (\n Array.isArray(s.activePRs) &&\n Array.isArray(s.dormantPRs) &&\n Array.isArray(s.mergedPRs) &&\n Array.isArray(s.closedPRs)\n );\n }\n\n // v2+ doesn't require PR arrays\n return true;\n}\n\n/**\n * Create a fresh state (v2: fresh GitHub fetching).\n */\nexport function createFreshState(): AgentState {\n return {\n version: CURRENT_STATE_VERSION,\n activeIssues: [],\n repoScores: {},\n config: {\n ...INITIAL_STATE.config,\n setupComplete: false,\n languages: [...INITIAL_STATE.config.languages],\n labels: [...INITIAL_STATE.config.labels],\n excludeRepos: [],\n trustedProjects: [],\n shelvedPRUrls: [],\n dismissedIssues: {},\n },\n events: [],\n lastRunAt: new Date().toISOString(),\n };\n}\n\n/**\n * Migrate state from legacy ./data/ location to ~/.oss-autopilot/.\n * Returns true if migration was performed.\n */\nfunction migrateFromLegacyLocation(): boolean {\n const newStatePath = getStatePath();\n\n // If new state already exists, no migration needed\n if (fs.existsSync(newStatePath)) {\n return false;\n }\n\n // Check for legacy state file\n if (!fs.existsSync(LEGACY_STATE_FILE)) {\n return false;\n }\n\n debug(MODULE, 'Migrating state from ./data/ to ~/.oss-autopilot/...');\n\n try {\n // Ensure the new data directory exists\n getDataDir();\n\n // Copy state file\n fs.copyFileSync(LEGACY_STATE_FILE, newStatePath);\n debug(MODULE, `Migrated state file to ${newStatePath}`);\n\n // Copy backups if they exist\n if (fs.existsSync(LEGACY_BACKUP_DIR)) {\n const newBackupDir = getBackupDir();\n const backupFiles = fs\n .readdirSync(LEGACY_BACKUP_DIR)\n .filter((f) => f.startsWith('state-') && f.endsWith('.json'));\n\n for (const backupFile of backupFiles) {\n const srcPath = path.join(LEGACY_BACKUP_DIR, backupFile);\n const destPath = path.join(newBackupDir, backupFile);\n fs.copyFileSync(srcPath, destPath);\n }\n debug(MODULE, `Migrated ${backupFiles.length} backup files`);\n }\n\n // Remove legacy files\n fs.unlinkSync(LEGACY_STATE_FILE);\n debug(MODULE, 'Removed legacy state file');\n\n // Remove legacy backup files\n if (fs.existsSync(LEGACY_BACKUP_DIR)) {\n const backupFiles = fs.readdirSync(LEGACY_BACKUP_DIR);\n for (const file of backupFiles) {\n fs.unlinkSync(path.join(LEGACY_BACKUP_DIR, file));\n }\n fs.rmdirSync(LEGACY_BACKUP_DIR);\n }\n\n // Try to remove legacy data directory if empty\n const legacyDataDir = path.dirname(LEGACY_STATE_FILE);\n if (fs.existsSync(legacyDataDir)) {\n const remaining = fs.readdirSync(legacyDataDir);\n if (remaining.length === 0) {\n fs.rmdirSync(legacyDataDir);\n debug(MODULE, 'Removed empty legacy data directory');\n }\n }\n\n debug(MODULE, 'Migration complete!');\n return true;\n } catch (error) {\n warn(MODULE, `Failed to migrate state: ${errorMessage(error)}`);\n\n // Clean up partial migration to avoid inconsistent state\n if (fs.existsSync(newStatePath) && fs.existsSync(LEGACY_STATE_FILE)) {\n // If both files exist, the migration was partial - remove the new file\n try {\n fs.unlinkSync(newStatePath);\n debug(MODULE, 'Cleaned up partial migration - removed incomplete new state file');\n } catch (cleanupErr) {\n warn(MODULE, 'Could not clean up partial migration file');\n debug(MODULE, 'Partial migration cleanup failed', cleanupErr);\n }\n }\n\n warn(MODULE, 'To resolve this issue:');\n warn(MODULE, ' 1. Ensure you have write permissions to ~/.oss-autopilot/');\n warn(MODULE, ' 2. Check available disk space');\n warn(MODULE, ' 3. Manually copy ./data/state.json to ~/.oss-autopilot/state.json');\n warn(MODULE, ' 4. Or delete ./data/state.json to start fresh');\n\n return false;\n }\n}\n\n/**\n * Attempt to restore state from the most recent valid backup.\n * Returns the restored state if successful, or null if no valid backup is found.\n */\nfunction tryRestoreFromBackup(): AgentState | null {\n const backupDir = getBackupDir();\n\n if (!fs.existsSync(backupDir)) {\n return null;\n }\n\n // Get backup files sorted by name (most recent first, since names include timestamps)\n const backupFiles = fs\n .readdirSync(backupDir)\n .filter((f) => f.startsWith('state-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n for (const backupFile of backupFiles) {\n const backupPath = path.join(backupDir, backupFile);\n try {\n const data = fs.readFileSync(backupPath, 'utf-8');\n let state = JSON.parse(data) as AgentState;\n\n if (isValidState(state)) {\n debug(MODULE, `Successfully restored state from backup: ${backupFile}`);\n\n // Migrate from v1 to v2 if needed\n if (state.version === 1) {\n state = migrateV1ToV2(state as unknown as Record<string, unknown>);\n }\n\n const repoCount = Object.keys(state.repoScores).length;\n debug(MODULE, `Restored state v${state.version}: ${repoCount} repo scores`);\n\n // Overwrite the corrupted main state file with the restored backup (atomic write)\n const statePath = getStatePath();\n atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);\n debug(MODULE, 'Restored backup written to main state file');\n\n return state;\n }\n } catch (backupErr) {\n // This backup is also corrupted, try the next one\n warn(MODULE, `Backup ${backupFile} is corrupted, trying next...`);\n debug(MODULE, `Backup ${backupFile} parse failed`, backupErr);\n }\n }\n\n return null;\n}\n\n/**\n * Load state from file, or create initial state if none exists.\n * If the main state file is corrupted, attempts to restore from the most recent backup.\n * Performs migration from legacy ./data/ location if needed.\n * @returns Object with the loaded state and the file's mtime (for change detection).\n */\nexport function loadState(): { state: AgentState; mtimeMs: number } {\n // Try to migrate from legacy location first\n migrateFromLegacyLocation();\n\n const statePath = getStatePath();\n\n try {\n if (fs.existsSync(statePath)) {\n const data = fs.readFileSync(statePath, 'utf-8');\n let state = JSON.parse(data) as AgentState;\n\n // Validate required fields exist\n if (!isValidState(state)) {\n warn(MODULE, 'Invalid state file structure, attempting to restore from backup...');\n const restoredState = tryRestoreFromBackup();\n if (restoredState) {\n const mtimeMs = safeGetMtimeMs(statePath);\n return { state: restoredState, mtimeMs };\n }\n warn(MODULE, 'No valid backup found, starting fresh');\n return { state: createFreshState(), mtimeMs: 0 };\n }\n\n // Migrate from v1 to v2 if needed\n if (state.version === 1) {\n state = migrateV1ToV2(state as unknown as Record<string, unknown>);\n // Save the migrated state immediately (atomic write)\n atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);\n debug(MODULE, 'Migrated state saved');\n }\n\n // Strip legacy fields from persisted state (snoozedPRs and PR dismiss\n // entries were removed in the three-state PR model simplification)\n try {\n let needsCleanupSave = false;\n const rawConfig = state.config as unknown as Record<string, unknown>;\n if (rawConfig.snoozedPRs) {\n delete rawConfig.snoozedPRs;\n needsCleanupSave = true;\n }\n // Strip PR URLs from dismissedIssues (PR dismiss removed)\n if (state.config.dismissedIssues) {\n const PR_URL_RE = /\\/pull\\/\\d+$/;\n for (const url of Object.keys(state.config.dismissedIssues)) {\n if (PR_URL_RE.test(url)) {\n delete state.config.dismissedIssues[url];\n needsCleanupSave = true;\n }\n }\n }\n if (needsCleanupSave) {\n atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);\n warn(MODULE, 'Cleaned up removed features (snoozedPRs, dismissed PR URLs) from persisted state');\n }\n } catch (cleanupError) {\n warn(MODULE, `Failed to clean up removed features from state: ${errorMessage(cleanupError)}`);\n // Continue with loaded state \u2014 cleanup will be retried on next load\n }\n\n // Record file mtime so reloadIfChanged() can detect external writes\n const mtimeMs = safeGetMtimeMs(statePath);\n\n // Log appropriate message based on version\n const repoCount = Object.keys(state.repoScores).length;\n debug(MODULE, `Loaded state v${state.version}: ${repoCount} repo scores tracked`);\n return { state, mtimeMs };\n }\n } catch (error) {\n warn(MODULE, 'Error loading state:', error);\n warn(MODULE, 'Attempting to restore from backup...');\n const restoredState = tryRestoreFromBackup();\n if (restoredState) {\n const mtimeMs = safeGetMtimeMs(statePath);\n return { state: restoredState, mtimeMs };\n }\n warn(MODULE, 'No valid backup found, starting fresh');\n }\n\n debug(MODULE, 'No existing state found, initializing...');\n return { state: createFreshState(), mtimeMs: 0 };\n}\n\n/**\n * Safely read a file's mtime. Returns 0 if the stat call fails.\n */\nfunction safeGetMtimeMs(filePath: string): number {\n try {\n return fs.statSync(filePath).mtimeMs;\n } catch (error) {\n debug(MODULE, `Could not read state file mtime (reload detection will always trigger): ${errorMessage(error)}`);\n return 0;\n }\n}\n\n/**\n * Clean up old backup files, keeping only the 10 most recent.\n */\nfunction cleanupBackups(): void {\n const backupDir = getBackupDir();\n try {\n const files = fs\n .readdirSync(backupDir)\n .filter((f) => f.startsWith('state-'))\n .sort()\n .reverse();\n\n // Keep only the 10 most recent backups\n for (const file of files.slice(10)) {\n try {\n fs.unlinkSync(path.join(backupDir, file));\n } catch (error) {\n warn(MODULE, `Could not delete old backup ${file}:`, errorMessage(error));\n }\n }\n } catch (error) {\n warn(MODULE, 'Could not clean up backups:', errorMessage(error));\n }\n}\n\n/**\n * Persist state to disk, creating a timestamped backup of the previous\n * state file first. Retains at most 10 backup files.\n * @returns The file's mtime after writing (for change detection).\n */\nexport function saveState(state: Readonly<AgentState>): number {\n const statePath = getStatePath();\n const lockPath = statePath + '.lock';\n const backupDir = getBackupDir();\n\n // Acquire advisory lock to prevent concurrent writes\n acquireLock(lockPath);\n\n try {\n // Create backup of existing state (best-effort, non-fatal)\n try {\n if (fs.existsSync(statePath)) {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const randomSuffix = Math.random().toString(36).slice(2, 8).padEnd(6, '0');\n const backupFile = path.join(backupDir, `state-${timestamp}-${randomSuffix}.json`);\n fs.copyFileSync(statePath, backupFile);\n fs.chmodSync(backupFile, 0o600);\n\n // Keep only last 10 backups\n cleanupBackups();\n }\n } catch (backupErr) {\n warn(MODULE, `Could not create backup before save: ${errorMessage(backupErr)}`);\n // Continue with save \u2014 losing a backup is acceptable, losing the save is not\n }\n\n // Atomic write: write to temp file then rename to prevent corruption on crash\n atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);\n const mtimeMs = safeGetMtimeMs(statePath);\n debug(MODULE, 'State saved successfully');\n return mtimeMs;\n } finally {\n releaseLock(lockPath);\n }\n}\n\n/**\n * Re-read state from disk if the file has been modified since the last load/save.\n * Uses mtime comparison (single statSync call) to avoid unnecessary JSON parsing.\n * @returns The new state and mtime if reloaded, or null if no change detected.\n */\nexport function reloadStateIfChanged(lastLoadedMtimeMs: number): { state: AgentState; mtimeMs: number } | null {\n try {\n const statePath = getStatePath();\n const currentMtimeMs = fs.statSync(statePath).mtimeMs;\n if (currentMtimeMs === lastLoadedMtimeMs) return null;\n const result = loadState();\n // Ensure mtime is always current after reload (covers backup-restore and fresh-state paths)\n // to prevent repeated unnecessary reloads on every request.\n try {\n result.mtimeMs = fs.statSync(statePath).mtimeMs;\n } catch (err) {\n // If file was just loaded, stat should not fail. If it does,\n // next reloadIfChanged() will simply trigger another reload.\n debug(MODULE, 'Could not re-read mtime after reload (will retry next cycle)', err);\n }\n return result;\n } catch (error) {\n // statSync failure (file deleted) is benign \u2014 keep current in-memory state.\n warn(MODULE, `Failed to reload state from disk: ${errorMessage(error)}`);\n return null;\n }\n}\n", "/**\n * Repository scoring logic for the OSS Contribution Agent.\n * Functions that operate on AgentState for scoring, querying,\n * and computing aggregate statistics. Mutation functions modify\n * the passed state object in place; query functions are pure.\n */\n\nimport { AgentState, RepoScore, RepoScoreUpdate, isBelowMinStars } from './types.js';\nimport { debug, warn } from './logger.js';\n\nconst MODULE = 'scoring';\n\n/** Repo scores older than this are considered stale and excluded from low-scoring lists. */\nconst SCORE_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days\n\n/**\n * Create a default repo score for a new repository.\n */\nfunction createDefaultRepoScore(repo: string): RepoScore {\n return {\n repo,\n score: 5, // Base score\n mergedPRCount: 0,\n closedWithoutMergeCount: 0,\n avgResponseDays: null,\n lastEvaluatedAt: new Date().toISOString(),\n signals: {\n hasActiveMaintainers: true, // Assume positive by default\n isResponsive: false,\n hasHostileComments: false,\n },\n };\n}\n\n/**\n * Calculate the score based on the repo's metrics.\n * Base 5, logarithmic merge bonus (max +5), -1 per closed without merge (max -3),\n * +1 if recently merged (within 90 days), +1 if responsive, -2 if hostile. Clamp 1-10.\n */\nexport function calculateScore(repoScore: RepoScore): number {\n let score = 5; // Base score\n\n // Logarithmic merge bonus (max +5): 1\u2192+2, 2\u2192+3, 3\u2192+4, 4+\u2192+5\n if (repoScore.mergedPRCount > 0) {\n const mergedBonus = Math.min(Math.round(Math.log2(repoScore.mergedPRCount + 1) * 2), 5);\n score += mergedBonus;\n }\n\n // -1 per closed without merge (max -3)\n const closedPenalty = Math.min(repoScore.closedWithoutMergeCount, 3);\n score -= closedPenalty;\n\n // +1 if lastMergedAt is set and within 90 days (recency)\n if (repoScore.lastMergedAt) {\n const lastMergedDate = new Date(repoScore.lastMergedAt);\n if (isNaN(lastMergedDate.getTime())) {\n warn(\n MODULE,\n `Invalid lastMergedAt date for ${repoScore.repo}: \"${repoScore.lastMergedAt}\". Skipping recency bonus.`,\n );\n } else {\n const msPerDay = 1000 * 60 * 60 * 24;\n const daysSince = Math.floor((Date.now() - lastMergedDate.getTime()) / msPerDay);\n if (daysSince <= 90) {\n score += 1;\n }\n }\n }\n\n // +1 if responsive\n if (repoScore.signals.isResponsive) {\n score += 1;\n }\n\n // -2 if hostile\n if (repoScore.signals.hasHostileComments) {\n score -= 2;\n }\n\n // Clamp to 1-10\n return Math.max(1, Math.min(10, score));\n}\n\n/**\n * Get the score record for a repository.\n */\nexport function getRepoScore(state: Readonly<AgentState>, repo: string): Readonly<RepoScore> | undefined {\n return state.repoScores[repo];\n}\n\n/**\n * Update a repository's score with partial updates. If the repo has no existing score,\n * a default score record is created first (base score 5). After applying updates, the\n * numeric score is recalculated.\n */\nexport function updateRepoScore(state: AgentState, repo: string, updates: RepoScoreUpdate): void {\n if (!state.repoScores[repo]) {\n state.repoScores[repo] = createDefaultRepoScore(repo);\n }\n\n const repoScore = state.repoScores[repo];\n\n // Apply explicit field updates (skip undefined values to preserve existing data)\n if (updates.mergedPRCount !== undefined) repoScore.mergedPRCount = updates.mergedPRCount;\n if (updates.closedWithoutMergeCount !== undefined)\n repoScore.closedWithoutMergeCount = updates.closedWithoutMergeCount;\n if (updates.avgResponseDays !== undefined) repoScore.avgResponseDays = updates.avgResponseDays;\n if (updates.lastMergedAt !== undefined) repoScore.lastMergedAt = updates.lastMergedAt;\n if (updates.stargazersCount !== undefined) repoScore.stargazersCount = updates.stargazersCount;\n if (updates.signals) {\n repoScore.signals = { ...repoScore.signals, ...updates.signals };\n }\n\n // Recalculate score\n repoScore.score = calculateScore(repoScore);\n repoScore.lastEvaluatedAt = new Date().toISOString();\n\n debug(MODULE, `Updated repo score for ${repo}: ${repoScore.score}/10`);\n}\n\n/**\n * Increment the merged PR count for a repository and recalculate its score.\n */\nexport function incrementMergedCount(state: AgentState, repo: string): void {\n const newCount = (state.repoScores[repo]?.mergedPRCount ?? 0) + 1;\n updateRepoScore(state, repo, {\n mergedPRCount: newCount,\n lastMergedAt: new Date().toISOString(),\n });\n}\n\n/**\n * Increment the closed-without-merge count for a repository and recalculate its score.\n */\nexport function incrementClosedCount(state: AgentState, repo: string): void {\n const newCount = (state.repoScores[repo]?.closedWithoutMergeCount ?? 0) + 1;\n updateRepoScore(state, repo, { closedWithoutMergeCount: newCount });\n}\n\n/**\n * Mark a repository as having hostile maintainer comments and recalculate its score.\n * This applies a -2 penalty to the score. Creates a default score record if needed.\n */\nexport function markRepoHostile(state: AgentState, repo: string): void {\n updateRepoScore(state, repo, { signals: { hasHostileComments: true } });\n}\n\n/**\n * Get repositories where the user has at least one merged PR, sorted by merged count descending.\n */\nexport function getReposWithMergedPRs(state: Readonly<AgentState>): string[] {\n return Object.values(state.repoScores)\n .filter((rs) => rs.mergedPRCount > 0)\n .sort((a, b) => b.mergedPRCount - a.mergedPRCount)\n .map((rs) => rs.repo);\n}\n\n/**\n * Get repositories with a score record but no merge or closure outcomes yet\n * (typically repos with only open PRs), sorted by score descending.\n */\nexport function getReposWithOpenPRs(state: Readonly<AgentState>): string[] {\n return Object.values(state.repoScores)\n .filter((rs) => rs.mergedPRCount === 0 && rs.closedWithoutMergeCount === 0)\n .sort((a, b) => b.score - a.score)\n .map((rs) => rs.repo);\n}\n\n/**\n * Get repositories with a score at or above the given threshold, sorted highest first.\n */\nexport function getHighScoringRepos(state: Readonly<AgentState>, minScore?: number): string[] {\n const threshold = minScore ?? state.config.minRepoScoreThreshold;\n return Object.values(state.repoScores)\n .filter((rs) => rs.score >= threshold)\n .sort((a, b) => b.score - a.score)\n .map((rs) => rs.repo);\n}\n\n/**\n * Get repositories with a score at or below the given threshold, sorted lowest first.\n */\nexport function getLowScoringRepos(state: Readonly<AgentState>, maxScore?: number): string[] {\n const threshold = maxScore ?? state.config.minRepoScoreThreshold;\n const now = Date.now();\n return Object.values(state.repoScores)\n .filter((rs) => {\n if (rs.score > threshold) return false;\n // Stale scores (>30 days) should not permanently block repos (#487)\n const age = now - new Date(rs.lastEvaluatedAt).getTime();\n if (!Number.isFinite(age)) {\n warn(MODULE, `Invalid lastEvaluatedAt for repo ${rs.repo}: \"${rs.lastEvaluatedAt}\", treating as stale`);\n return false;\n }\n return age <= SCORE_TTL_MS;\n })\n .sort((a, b) => a.score - b.score)\n .map((rs) => rs.repo);\n}\n\n/**\n * Aggregate statistics returned by {@link getStats}.\n */\nexport interface Stats {\n /** Total merged PRs across scored repositories (above minStars threshold). */\n mergedPRs: number;\n /** Total PRs closed without merge across scored repositories (above minStars threshold). */\n closedPRs: number;\n /** Number of active issues. Always 0 in v2 (sourced from fresh fetch instead). */\n activeIssues: number;\n /** Number of trusted projects. */\n trustedProjects: number;\n /** Merge success rate as a percentage string (e.g. \"75.0%\"). */\n mergeRate: string;\n /** Number of scored repositories (above minStars threshold). */\n totalTracked: number;\n /** Number of PRs needing a response. Always 0 in v2 (sourced from fresh fetch instead). */\n needsResponse: number;\n}\n\n/**\n * Compute aggregate statistics from the current state.\n */\nexport function getStats(state: Readonly<AgentState>): Stats {\n let totalMerged = 0;\n let totalClosed = 0;\n let totalTracked = 0;\n\n for (const score of Object.values(state.repoScores)) {\n if (isBelowMinStars(score.stargazersCount, state.config.minStars ?? 50)) continue;\n totalTracked++;\n totalMerged += score.mergedPRCount;\n totalClosed += score.closedWithoutMergeCount;\n }\n\n const completed = totalMerged + totalClosed;\n const mergeRate = completed > 0 ? (totalMerged / completed) * 100 : 0;\n\n return {\n mergedPRs: totalMerged,\n closedPRs: totalClosed,\n activeIssues: 0,\n trustedProjects: state.config.trustedProjects.length,\n mergeRate: mergeRate.toFixed(1) + '%',\n totalTracked,\n needsResponse: 0,\n };\n}\n", "/**\n * State management for the OSS Contribution Agent.\n * Thin coordinator that delegates persistence to state-persistence.ts\n * and scoring logic to repo-score-manager.ts.\n */\n\nimport {\n AgentState,\n TrackedIssue,\n RepoScore,\n RepoScoreUpdate,\n StateEvent,\n StateEventType,\n DailyDigest,\n LocalRepoCache,\n StatusOverride,\n FetchedPRStatus,\n StoredMergedPR,\n StoredClosedPR,\n} from './types.js';\nimport { loadState, saveState, reloadStateIfChanged, createFreshState } from './state-persistence.js';\nimport * as repoScoring from './repo-score-manager.js';\nimport type { Stats } from './repo-score-manager.js';\nimport { debug } from './logger.js';\n\nexport { acquireLock, releaseLock, atomicWriteFileSync } from './state-persistence.js';\nexport type { Stats } from './repo-score-manager.js';\n\nconst MODULE = 'state';\n\n// Maximum number of events to retain in the event log\nconst MAX_EVENTS = 1000;\n\n/**\n * Singleton manager for persistent agent state stored in ~/.oss-autopilot/state.json.\n *\n * Delegates file I/O to state-persistence.ts and scoring logic to repo-score-manager.ts.\n * Retains lightweight CRUD operations for config, events, issues, shelving, dismissal,\n * and status overrides.\n */\nexport class StateManager {\n private state: AgentState;\n private readonly inMemoryOnly: boolean;\n private lastLoadedMtimeMs: number = 0;\n\n /**\n * Create a new StateManager instance.\n * @param inMemoryOnly - When true, state is held only in memory and never read from or\n * written to disk. Useful for unit tests that need isolated state without side effects.\n * Defaults to false (normal persistent mode).\n */\n constructor(inMemoryOnly = false) {\n this.inMemoryOnly = inMemoryOnly;\n if (inMemoryOnly) {\n this.state = createFreshState();\n } else {\n const result = loadState();\n this.state = result.state;\n this.lastLoadedMtimeMs = result.mtimeMs;\n }\n }\n\n /**\n * Check if initial setup has been completed.\n */\n isSetupComplete(): boolean {\n return this.state.config.setupComplete === true;\n }\n\n /**\n * Mark setup as complete and record the completion timestamp.\n */\n markSetupComplete(): void {\n this.state.config.setupComplete = true;\n this.state.config.setupCompletedAt = new Date().toISOString();\n }\n\n /**\n * Initialize state with sensible defaults for zero-config onboarding.\n * No-op if setup is already complete.\n */\n initializeWithDefaults(username: string): void {\n if (this.state.config.setupComplete) {\n debug(MODULE, `Setup already complete, skipping initializeWithDefaults for \"${username}\"`);\n return;\n }\n this.state.config.githubUsername = username;\n this.markSetupComplete();\n debug(MODULE, `Initialized with defaults for user \"${username}\"`);\n this.save();\n }\n\n /**\n * Persist the current state to disk, creating a timestamped backup of the previous\n * state file first. In in-memory mode, only updates `lastRunAt` without any file I/O.\n */\n save(): void {\n this.state.lastRunAt = new Date().toISOString();\n\n if (this.inMemoryOnly) {\n return;\n }\n\n this.lastLoadedMtimeMs = saveState(this.state);\n }\n\n /**\n * Get the current state as a read-only snapshot.\n */\n getState(): Readonly<AgentState> {\n return this.state;\n }\n\n /**\n * Re-read state from disk if the file has been modified since the last load/save.\n * Returns true if state was reloaded, false if unchanged or in-memory mode.\n */\n reloadIfChanged(): boolean {\n if (this.inMemoryOnly) return false;\n const result = reloadStateIfChanged(this.lastLoadedMtimeMs);\n if (!result) return false;\n this.state = result.state;\n this.lastLoadedMtimeMs = result.mtimeMs;\n return true;\n }\n\n // === Dashboard Data Setters ===\n\n setLastDigest(digest: DailyDigest): void {\n this.state.lastDigest = digest;\n this.state.lastDigestAt = digest.generatedAt;\n }\n\n setMonthlyMergedCounts(counts: Record<string, number>): void {\n this.state.monthlyMergedCounts = counts;\n }\n\n setMonthlyClosedCounts(counts: Record<string, number>): void {\n this.state.monthlyClosedCounts = counts;\n }\n\n setMonthlyOpenedCounts(counts: Record<string, number>): void {\n this.state.monthlyOpenedCounts = counts;\n }\n\n setDailyActivityCounts(counts: Record<string, number>): void {\n this.state.dailyActivityCounts = counts;\n }\n\n setLocalRepoCache(cache: LocalRepoCache): void {\n this.state.localRepoCache = cache;\n }\n\n // === Merged PR Storage ===\n\n getMergedPRs(): StoredMergedPR[] {\n return this.state.mergedPRs ?? [];\n }\n\n addMergedPRs(prs: StoredMergedPR[]): void {\n if (prs.length === 0) return;\n if (!this.state.mergedPRs) this.state.mergedPRs = [];\n const existingUrls = new Set(this.state.mergedPRs.map((pr) => pr.url));\n const newPRs = prs.filter((pr) => !existingUrls.has(pr.url));\n if (newPRs.length === 0) return;\n this.state.mergedPRs.push(...newPRs);\n this.state.mergedPRs.sort((a, b) => b.mergedAt.localeCompare(a.mergedAt));\n debug(MODULE, `Added ${newPRs.length} merged PRs (total: ${this.state.mergedPRs.length})`);\n }\n\n getMergedPRWatermark(): string | undefined {\n return this.state.mergedPRs?.[0]?.mergedAt || undefined;\n }\n\n // === Closed PR Storage ===\n\n getClosedPRs(): StoredClosedPR[] {\n return this.state.closedPRs ?? [];\n }\n\n addClosedPRs(prs: StoredClosedPR[]): void {\n if (prs.length === 0) return;\n if (!this.state.closedPRs) this.state.closedPRs = [];\n const existingUrls = new Set(this.state.closedPRs.map((pr) => pr.url));\n const newPRs = prs.filter((pr) => !existingUrls.has(pr.url));\n if (newPRs.length === 0) return;\n this.state.closedPRs.push(...newPRs);\n this.state.closedPRs.sort((a, b) => b.closedAt.localeCompare(a.closedAt));\n debug(MODULE, `Added ${newPRs.length} closed PRs (total: ${this.state.closedPRs.length})`);\n }\n\n getClosedPRWatermark(): string | undefined {\n return this.state.closedPRs?.[0]?.closedAt || undefined;\n }\n\n // === Configuration ===\n\n updateConfig(config: Partial<AgentState['config']>): void {\n this.state.config = { ...this.state.config, ...config };\n }\n\n // === Event Logging ===\n\n appendEvent(type: StateEventType, data: Record<string, unknown>): void {\n const event: StateEvent = {\n id: `evt_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,\n type,\n at: new Date().toISOString(),\n data,\n };\n this.state.events.push(event);\n\n // Cap the events array to prevent unbounded growth\n if (this.state.events.length > MAX_EVENTS) {\n this.state.events = this.state.events.slice(-MAX_EVENTS);\n }\n }\n\n getEventsByType(type: StateEventType): StateEvent[] {\n return this.state.events.filter((e) => e.type === type);\n }\n\n getEventsInRange(since: Date, until: Date = new Date()): StateEvent[] {\n return this.state.events.filter((e) => {\n const eventTime = new Date(e.at);\n return eventTime >= since && eventTime <= until;\n });\n }\n\n // === Issue Management ===\n\n addIssue(issue: TrackedIssue): void {\n const existing = this.state.activeIssues.find((i) => i.url === issue.url);\n if (existing) {\n debug(MODULE, `Issue ${issue.url} already tracked`);\n return;\n }\n\n this.state.activeIssues.push(issue);\n debug(MODULE, `Added issue: ${issue.repo}#${issue.number}`);\n }\n\n // === Trusted Projects ===\n\n addTrustedProject(repo: string): void {\n if (!this.state.config.trustedProjects.includes(repo)) {\n this.state.config.trustedProjects.push(repo);\n debug(MODULE, `Added trusted project: ${repo}`);\n }\n }\n\n private static matchesExclusion(repo: string, repos: string[], orgs?: string[]): boolean {\n const repoLower = repo.toLowerCase();\n if (repos.some((r) => r.toLowerCase() === repoLower)) return true;\n if (orgs?.some((o) => o.toLowerCase() === repoLower.split('/')[0])) return true;\n return false;\n }\n\n cleanupExcludedData(repos: string[], orgs: string[]): void {\n const matches = (repo: string): boolean => StateManager.matchesExclusion(repo, repos, orgs);\n\n const beforeTrusted = this.state.config.trustedProjects.length;\n this.state.config.trustedProjects = this.state.config.trustedProjects.filter((p) => !matches(p));\n const removedTrusted = beforeTrusted - this.state.config.trustedProjects.length;\n\n if (removedTrusted > 0) {\n debug(MODULE, `Removed ${removedTrusted} trusted project(s) for excluded repos/orgs`);\n }\n }\n\n // === Starred Repos Management ===\n\n getStarredRepos(): string[] {\n return this.state.config.starredRepos || [];\n }\n\n setStarredRepos(repos: string[]): void {\n this.state.config.starredRepos = repos;\n this.state.config.starredReposLastFetched = new Date().toISOString();\n debug(MODULE, `Updated starred repos: ${repos.length} repositories`);\n }\n\n isStarredReposStale(): boolean {\n const lastFetched = this.state.config.starredReposLastFetched;\n if (!lastFetched) {\n return true;\n }\n\n const staleThresholdMs = 24 * 60 * 60 * 1000; // 24 hours\n const lastFetchedDate = new Date(lastFetched);\n const now = new Date();\n return now.getTime() - lastFetchedDate.getTime() > staleThresholdMs;\n }\n\n // === Shelve/Unshelve ===\n\n shelvePR(url: string): boolean {\n if (!this.state.config.shelvedPRUrls) {\n this.state.config.shelvedPRUrls = [];\n }\n if (this.state.config.shelvedPRUrls.includes(url)) {\n return false;\n }\n this.state.config.shelvedPRUrls.push(url);\n return true;\n }\n\n unshelvePR(url: string): boolean {\n if (!this.state.config.shelvedPRUrls) {\n return false;\n }\n const index = this.state.config.shelvedPRUrls.indexOf(url);\n if (index === -1) {\n return false;\n }\n this.state.config.shelvedPRUrls.splice(index, 1);\n return true;\n }\n\n isPRShelved(url: string): boolean {\n return this.state.config.shelvedPRUrls?.includes(url) ?? false;\n }\n\n // === Dismiss / Undismiss Issues ===\n\n dismissIssue(url: string, timestamp: string): boolean {\n if (!this.state.config.dismissedIssues) {\n this.state.config.dismissedIssues = {};\n }\n if (url in this.state.config.dismissedIssues) {\n return false;\n }\n this.state.config.dismissedIssues[url] = timestamp;\n return true;\n }\n\n undismissIssue(url: string): boolean {\n if (!this.state.config.dismissedIssues || !(url in this.state.config.dismissedIssues)) {\n return false;\n }\n delete this.state.config.dismissedIssues[url];\n return true;\n }\n\n getIssueDismissedAt(url: string): string | undefined {\n return this.state.config.dismissedIssues?.[url];\n }\n\n // === Status Overrides ===\n\n setStatusOverride(url: string, status: FetchedPRStatus, lastActivityAt: string): void {\n if (!this.state.config.statusOverrides) {\n this.state.config.statusOverrides = {};\n }\n this.state.config.statusOverrides[url] = {\n status,\n setAt: new Date().toISOString(),\n lastActivityAt,\n };\n }\n\n clearStatusOverride(url: string): boolean {\n if (!this.state.config.statusOverrides || !(url in this.state.config.statusOverrides)) {\n return false;\n }\n delete this.state.config.statusOverrides[url];\n return true;\n }\n\n getStatusOverride(url: string, currentUpdatedAt?: string): StatusOverride | undefined {\n const override = this.state.config.statusOverrides?.[url];\n if (!override) return undefined;\n\n // Auto-clear if the PR has new activity since the override was set\n if (currentUpdatedAt && currentUpdatedAt > override.lastActivityAt) {\n this.clearStatusOverride(url);\n return undefined;\n }\n return override;\n }\n\n // === Repository Scoring (delegated to repo-score-manager) ===\n\n getRepoScore(repo: string): Readonly<RepoScore> | undefined {\n return repoScoring.getRepoScore(this.state, repo);\n }\n\n updateRepoScore(repo: string, updates: RepoScoreUpdate): void {\n repoScoring.updateRepoScore(this.state, repo, updates);\n }\n\n incrementMergedCount(repo: string): void {\n repoScoring.incrementMergedCount(this.state, repo);\n }\n\n incrementClosedCount(repo: string): void {\n repoScoring.incrementClosedCount(this.state, repo);\n }\n\n markRepoHostile(repo: string): void {\n repoScoring.markRepoHostile(this.state, repo);\n }\n\n getReposWithMergedPRs(): string[] {\n return repoScoring.getReposWithMergedPRs(this.state);\n }\n\n getReposWithOpenPRs(): string[] {\n return repoScoring.getReposWithOpenPRs(this.state);\n }\n\n getHighScoringRepos(minScore?: number): string[] {\n return repoScoring.getHighScoringRepos(this.state, minScore);\n }\n\n getLowScoringRepos(maxScore?: number): string[] {\n return repoScoring.getLowScoringRepos(this.state, maxScore);\n }\n\n getStats(): Stats {\n return repoScoring.getStats(this.state);\n }\n}\n\n// Singleton instance\nlet stateManager: StateManager | null = null;\n\n/**\n * Get the singleton StateManager instance, creating it on first call.\n */\nexport function getStateManager(): StateManager {\n if (!stateManager) {\n stateManager = new StateManager();\n }\n return stateManager;\n}\n\n/**\n * Reset the singleton StateManager instance to null. Intended for test isolation.\n */\nexport function resetStateManager(): void {\n stateManager = null;\n}\n", "export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${\n process.arch\n })`;\n }\n\n return \"<environment undetectable>\";\n}\n", "// @ts-check\n\nexport function register(state, name, method, options) {\n if (typeof method !== \"function\") {\n throw new Error(\"method for before hook must be a function\");\n }\n\n if (!options) {\n options = {};\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce((callback, name) => {\n return register.bind(null, state, name, callback, options);\n }, method)();\n }\n\n return Promise.resolve().then(() => {\n if (!state.registry[name]) {\n return method(options);\n }\n\n return state.registry[name].reduce((method, registered) => {\n return registered.hook.bind(null, method, options);\n }, method)();\n });\n}\n", "// @ts-check\n\nexport function addHook(state, kind, name, hook) {\n const orig = hook;\n if (!state.registry[name]) {\n state.registry[name] = [];\n }\n\n if (kind === \"before\") {\n hook = (method, options) => {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options));\n };\n }\n\n if (kind === \"after\") {\n hook = (method, options) => {\n let result;\n return Promise.resolve()\n .then(method.bind(null, options))\n .then((result_) => {\n result = result_;\n return orig(result, options);\n })\n .then(() => {\n return result;\n });\n };\n }\n\n if (kind === \"error\") {\n hook = (method, options) => {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch((error) => {\n return orig(error, options);\n });\n };\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig,\n });\n}\n", "// @ts-check\n\nexport function removeHook(state, name, method) {\n if (!state.registry[name]) {\n return;\n }\n\n const index = state.registry[name]\n .map((registered) => {\n return registered.orig;\n })\n .indexOf(method);\n\n if (index === -1) {\n return;\n }\n\n state.registry[name].splice(index, 1);\n}\n", "// @ts-check\n\nimport { register } from \"./lib/register.js\";\nimport { addHook } from \"./lib/add.js\";\nimport { removeHook } from \"./lib/remove.js\";\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nconst bind = Function.bind;\nconst bindable = bind.bind(bind);\n\nfunction bindApi(hook, state, name) {\n const removeHookRef = bindable(removeHook, null).apply(\n null,\n name ? [state, name] : [state]\n );\n hook.api = { remove: removeHookRef };\n hook.remove = removeHookRef;\n [\"before\", \"error\", \"after\", \"wrap\"].forEach((kind) => {\n const args = name ? [state, kind, name] : [state, kind];\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);\n });\n}\n\nfunction Singular() {\n const singularHookName = Symbol(\"Singular\");\n const singularHookState = {\n registry: {},\n };\n const singularHook = register.bind(null, singularHookState, singularHookName);\n bindApi(singularHook, singularHookState, singularHookName);\n return singularHook;\n}\n\nfunction Collection() {\n const state = {\n registry: {},\n };\n\n const hook = register.bind(null, state);\n bindApi(hook, state);\n\n return hook;\n}\n\nexport default { Singular, Collection };\n", "// pkg/dist-src/defaults.js\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/defaults.js\nvar userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;\nvar DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\"\n }\n};\n\n// pkg/dist-src/util/lowercase-keys.js\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\n// pkg/dist-src/util/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null) return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\") return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null) return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/util/merge-deep.js\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach((key) => {\n if (isPlainObject(options[key])) {\n if (!(key in defaults)) Object.assign(result, { [key]: options[key] });\n else result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, { [key]: options[key] });\n }\n });\n return result;\n}\n\n// pkg/dist-src/util/remove-undefined-properties.js\nfunction removeUndefinedProperties(obj) {\n for (const key in obj) {\n if (obj[key] === void 0) {\n delete obj[key];\n }\n }\n return obj;\n}\n\n// pkg/dist-src/merge.js\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? { method, url } : { url: method }, options);\n } else {\n options = Object.assign({}, route);\n }\n options.headers = lowercaseKeys(options.headers);\n removeUndefinedProperties(options);\n removeUndefinedProperties(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options);\n if (options.url === \"/graphql\") {\n if (defaults && defaults.mediaType.previews?.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(\n (preview) => !mergedOptions.mediaType.previews.includes(preview)\n ).concat(mergedOptions.mediaType.previews);\n }\n mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, \"\"));\n }\n return mergedOptions;\n}\n\n// pkg/dist-src/util/add-query-parameters.js\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n if (names.length === 0) {\n return url;\n }\n return url + separator + names.map((name) => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\n// pkg/dist-src/util/extract-url-variable-names.js\nvar urlVariableRegex = /\\{[^{}}]+\\}/g;\nfunction removeNonChars(variableName) {\n return variableName.replace(/(?:^\\W+)|(?:(?<!\\W)\\W+$)/g, \"\").split(/,/);\n}\nfunction extractUrlVariableNames(url) {\n const matches = url.match(urlVariableRegex);\n if (!matches) {\n return [];\n }\n return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);\n}\n\n// pkg/dist-src/util/omit.js\nfunction omit(object, keysToOmit) {\n const result = { __proto__: null };\n for (const key of Object.keys(object)) {\n if (keysToOmit.indexOf(key) === -1) {\n result[key] = object[key];\n }\n }\n return result;\n}\n\n// pkg/dist-src/util/url-template.js\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n return part;\n }).join(\"\");\n}\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\nfunction isDefined(value) {\n return value !== void 0 && value !== null;\n}\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\nfunction getValues(context, operator, key, modifier) {\n var value = context[key], result = [];\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") {\n value = value.toString();\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n result.push(\n encodeValue(operator, value, isKeyOperator(operator) ? key : \"\")\n );\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n result.push(\n encodeValue(operator, value2, isKeyOperator(operator) ? key : \"\")\n );\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n tmp.push(encodeValue(operator, value2));\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n return result;\n}\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n template = template.replace(\n /\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g,\n function(_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n expression.split(/,/g).forEach(function(variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n if (operator && operator !== \"+\") {\n var separator = \",\";\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n }\n );\n if (template === \"/\") {\n return template;\n } else {\n return template.replace(/\\/$/, \"\");\n }\n}\n\n// pkg/dist-src/parse.js\nfunction parse(options) {\n let method = options.method.toUpperCase();\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"mediaType\"\n ]);\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n headers.accept = headers.accept.split(/,/).map(\n (format) => format.replace(\n /application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/,\n `application/vnd$1$2.${options.mediaType.format}`\n )\n ).join(\",\");\n }\n if (url.endsWith(\"/graphql\")) {\n if (options.mediaType.previews?.length) {\n const previewsFromAcceptHeader = headers.accept.match(/(?<![\\w-])[\\w-]+(?=-preview)/g) || [];\n headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n }\n }\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n }\n }\n }\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n }\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n }\n return Object.assign(\n { method, url, headers },\n typeof body !== \"undefined\" ? { body } : null,\n options.request ? { request: options.request } : null\n );\n}\n\n// pkg/dist-src/endpoint-with-defaults.js\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS2 = merge(oldDefaults, newDefaults);\n const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);\n return Object.assign(endpoint2, {\n DEFAULTS: DEFAULTS2,\n defaults: withDefaults.bind(null, DEFAULTS2),\n merge: merge.bind(null, DEFAULTS2),\n parse\n });\n}\n\n// pkg/dist-src/index.js\nvar endpoint = withDefaults(null, DEFAULTS);\nexport {\n endpoint\n};\n", "'use strict'\n\nconst NullObject = function NullObject () { }\nNullObject.prototype = Object.create(null)\n\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter = token \"=\" ( token / quoted-string )\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text = %x80-FF\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nconst paramRE = /; *([!#$%&'*+.^\\w`|~-]+)=(\"(?:[\\v\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\v\\u0020-\\u00ff])*\"|[!#$%&'*+.^\\w`|~-]+) */gu\n\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text = %x80-FF\n */\nconst quotedPairRE = /\\\\([\\v\\u0020-\\u00ff])/gu\n\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type = token\n * subtype = token\n */\nconst mediaTypeRE = /^[!#$%&'*+.^\\w|~-]+\\/[!#$%&'*+.^\\w|~-]+$/u\n\n// default ContentType to prevent repeated object creation\nconst defaultContentType = { type: '', parameters: new NullObject() }\nObject.freeze(defaultContentType.parameters)\nObject.freeze(defaultContentType)\n\n/**\n * Parse media type to object.\n *\n * @param {string|object} header\n * @return {Object}\n * @public\n */\n\nfunction parse (header) {\n if (typeof header !== 'string') {\n throw new TypeError('argument header is required and must be a string')\n }\n\n let index = header.indexOf(';')\n const type = index !== -1\n ? header.slice(0, index).trim()\n : header.trim()\n\n if (mediaTypeRE.test(type) === false) {\n throw new TypeError('invalid media type')\n }\n\n const result = {\n type: type.toLowerCase(),\n parameters: new NullObject()\n }\n\n // parse parameters\n if (index === -1) {\n return result\n }\n\n let key\n let match\n let value\n\n paramRE.lastIndex = index\n\n while ((match = paramRE.exec(header))) {\n if (match.index !== index) {\n throw new TypeError('invalid parameter format')\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value[0] === '\"') {\n // remove quotes and escapes\n value = value\n .slice(1, value.length - 1)\n\n quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))\n }\n\n result.parameters[key] = value\n }\n\n if (index !== header.length) {\n throw new TypeError('invalid parameter format')\n }\n\n return result\n}\n\nfunction safeParse (header) {\n if (typeof header !== 'string') {\n return defaultContentType\n }\n\n let index = header.indexOf(';')\n const type = index !== -1\n ? header.slice(0, index).trim()\n : header.trim()\n\n if (mediaTypeRE.test(type) === false) {\n return defaultContentType\n }\n\n const result = {\n type: type.toLowerCase(),\n parameters: new NullObject()\n }\n\n // parse parameters\n if (index === -1) {\n return result\n }\n\n let key\n let match\n let value\n\n paramRE.lastIndex = index\n\n while ((match = paramRE.exec(header))) {\n if (match.index !== index) {\n return defaultContentType\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value[0] === '\"') {\n // remove quotes and escapes\n value = value\n .slice(1, value.length - 1)\n\n quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))\n }\n\n result.parameters[key] = value\n }\n\n if (index !== header.length) {\n return defaultContentType\n }\n\n return result\n}\n\nmodule.exports.default = { parse, safeParse }\nmodule.exports.parse = parse\nmodule.exports.safeParse = safeParse\nmodule.exports.defaultContentType = defaultContentType\n", "const intRegex = /^-?\\d+$/;\nconst noiseValue = /^-?\\d+n+$/; // Noise - strings that match the custom format before being converted to it\nconst originalStringify = JSON.stringify;\nconst originalParse = JSON.parse;\nconst customFormat = /^-?\\d+n$/;\n\nconst bigIntsStringify = /([\\[:])?\"(-?\\d+)n\"($|([\\\\n]|\\s)*(\\s|[\\\\n])*[,\\}\\]])/g;\nconst noiseStringify =\n /([\\[:])?(\"-?\\d+n+)n(\"$|\"([\\\\n]|\\s)*(\\s|[\\\\n])*[,\\}\\]])/g;\n\n/** @typedef {(key: string, value: any, context?: { source: string }) => any} Reviver */\n\n/**\n * Function to serialize value to a JSON string.\n * Converts BigInt values to a custom format (strings with digits and \"n\" at the end) and then converts them to proper big integers in a JSON string.\n * @param {*} value - The value to convert to a JSON string.\n * @param {(Function|Array<string>|null)} [replacer] - A function that alters the behavior of the stringification process, or an array of strings to indicate properties to exclude.\n * @param {(string|number)} [space] - A string or number to specify indentation or pretty-printing.\n * @returns {string} The JSON string representation.\n */\nconst JSONStringify = (value, replacer, space) => {\n if (\"rawJSON\" in JSON) {\n return originalStringify(\n value,\n (key, value) => {\n if (typeof value === \"bigint\") return JSON.rawJSON(value.toString());\n\n if (typeof replacer === \"function\") return replacer(key, value);\n\n if (Array.isArray(replacer) && replacer.includes(key)) return value;\n\n return value;\n },\n space,\n );\n }\n\n if (!value) return originalStringify(value, replacer, space);\n\n const convertedToCustomJSON = originalStringify(\n value,\n (key, value) => {\n const isNoise =\n typeof value === \"string\" && Boolean(value.match(noiseValue));\n\n if (isNoise) return value.toString() + \"n\"; // Mark noise values with additional \"n\" to offset the deletion of one \"n\" during the processing\n\n if (typeof value === \"bigint\") return value.toString() + \"n\";\n\n if (typeof replacer === \"function\") return replacer(key, value);\n\n if (Array.isArray(replacer) && replacer.includes(key)) return value;\n\n return value;\n },\n space,\n );\n const processedJSON = convertedToCustomJSON.replace(\n bigIntsStringify,\n \"$1$2$3\",\n ); // Delete one \"n\" off the end of every BigInt value\n const denoisedJSON = processedJSON.replace(noiseStringify, \"$1$2$3\"); // Remove one \"n\" off the end of every noisy string\n\n return denoisedJSON;\n};\n\n/**\n * Support for JSON.parse's context.source feature detection.\n * @type {boolean}\n */\nconst isContextSourceSupported = () =>\n JSON.parse(\"1\", (_, __, context) => !!context && context.source === \"1\");\n\n/**\n * Convert marked big numbers to BigInt\n * @type {Reviver}\n */\nconst convertMarkedBigIntsReviver = (key, value, context, userReviver) => {\n const isCustomFormatBigInt =\n typeof value === \"string\" && value.match(customFormat);\n if (isCustomFormatBigInt) return BigInt(value.slice(0, -1));\n\n const isNoiseValue = typeof value === \"string\" && value.match(noiseValue);\n if (isNoiseValue) return value.slice(0, -1);\n\n if (typeof userReviver !== \"function\") return value;\n return userReviver(key, value, context);\n};\n\n/**\n * Faster (2x) and simpler function to parse JSON.\n * Based on JSON.parse's context.source feature, which is not universally available now.\n * Does not support the legacy custom format, used in the first version of this library.\n */\nconst JSONParseV2 = (text, reviver) => {\n return JSON.parse(text, (key, value, context) => {\n const isBigNumber =\n typeof value === \"number\" &&\n (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER);\n const isInt = context && intRegex.test(context.source);\n const isBigInt = isBigNumber && isInt;\n\n if (isBigInt) return BigInt(context.source);\n\n if (typeof reviver !== \"function\") return value;\n\n return reviver(key, value, context);\n });\n};\n\nconst MAX_INT = Number.MAX_SAFE_INTEGER.toString();\nconst MAX_DIGITS = MAX_INT.length;\nconst stringsOrLargeNumbers =\n /\"(?:\\\\.|[^\"])*\"|-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?/g;\nconst noiseValueWithQuotes = /^\"-?\\d+n+\"$/; // Noise - strings that match the custom format before being converted to it\n\n/**\n * Function to parse JSON.\n * If JSON has number values greater than Number.MAX_SAFE_INTEGER, we convert those values to a custom format, then parse them to BigInt values.\n * Other types of values are not affected and parsed as native JSON.parse() would parse them.\n */\nconst JSONParse = (text, reviver) => {\n if (!text) return originalParse(text, reviver);\n\n if (isContextSourceSupported()) return JSONParseV2(text, reviver); // Shortcut to a faster (2x) and simpler version\n\n // Find and mark big numbers with \"n\"\n const serializedData = text.replace(\n stringsOrLargeNumbers,\n (text, digits, fractional, exponential) => {\n const isString = text[0] === '\"';\n const isNoise = isString && Boolean(text.match(noiseValueWithQuotes));\n\n if (isNoise) return text.substring(0, text.length - 1) + 'n\"'; // Mark noise values with additional \"n\" to offset the deletion of one \"n\" during the processing\n\n const isFractionalOrExponential = fractional || exponential;\n const isLessThanMaxSafeInt =\n digits &&\n (digits.length < MAX_DIGITS ||\n (digits.length === MAX_DIGITS && digits <= MAX_INT)); // With a fixed number of digits, we can correctly use lexicographical comparison to do a numeric comparison\n\n if (isString || isFractionalOrExponential || isLessThanMaxSafeInt)\n return text;\n\n return '\"' + text + 'n\"';\n },\n );\n\n return originalParse(serializedData, (key, value, context) =>\n convertMarkedBigIntsReviver(key, value, context, reviver),\n );\n};\n\nexport { JSONStringify, JSONParse };\n", "class RequestError extends Error {\n name;\n /**\n * http status code\n */\n status;\n /**\n * Request options that lead to the error.\n */\n request;\n /**\n * Response object if a response was received\n */\n response;\n constructor(message, statusCode, options) {\n super(message, { cause: options.cause });\n this.name = \"HttpError\";\n this.status = Number.parseInt(statusCode);\n if (Number.isNaN(this.status)) {\n this.status = 0;\n }\n /* v8 ignore else -- @preserve -- Bug with vitest coverage where it sees an else branch that doesn't exist */\n if (\"response\" in options) {\n this.response = options.response;\n }\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(\n /(?<! ) .*$/,\n \" [REDACTED]\"\n )\n });\n }\n requestCopy.url = requestCopy.url.replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\").replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n }\n}\nexport {\n RequestError\n};\n", "// pkg/dist-src/index.js\nimport { endpoint } from \"@octokit/endpoint\";\n\n// pkg/dist-src/defaults.js\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"10.0.8\";\n\n// pkg/dist-src/defaults.js\nvar defaults_default = {\n headers: {\n \"user-agent\": `octokit-request.js/${VERSION} ${getUserAgent()}`\n }\n};\n\n// pkg/dist-src/fetch-wrapper.js\nimport { safeParse } from \"fast-content-type-parse\";\nimport { JSONParse, JSONStringify } from \"json-with-bigint\";\n\n// pkg/dist-src/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null) return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\") return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null) return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/fetch-wrapper.js\nimport { RequestError } from \"@octokit/request-error\";\nvar noop = () => \"\";\nasync function fetchWrapper(requestOptions) {\n const fetch = requestOptions.request?.fetch || globalThis.fetch;\n if (!fetch) {\n throw new Error(\n \"fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing\"\n );\n }\n const log = requestOptions.request?.log || console;\n const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false;\n const body = isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body;\n const requestHeaders = Object.fromEntries(\n Object.entries(requestOptions.headers).map(([name, value]) => [\n name,\n String(value)\n ])\n );\n let fetchResponse;\n try {\n fetchResponse = await fetch(requestOptions.url, {\n method: requestOptions.method,\n body,\n redirect: requestOptions.request?.redirect,\n headers: requestHeaders,\n signal: requestOptions.request?.signal,\n // duplex must be set if request.body is ReadableStream or Async Iterables.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.\n ...requestOptions.body && { duplex: \"half\" }\n });\n } catch (error) {\n let message = \"Unknown Error\";\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n error.status = 500;\n throw error;\n }\n message = error.message;\n if (error.name === \"TypeError\" && \"cause\" in error) {\n if (error.cause instanceof Error) {\n message = error.cause.message;\n } else if (typeof error.cause === \"string\") {\n message = error.cause;\n }\n }\n }\n const requestError = new RequestError(message, 500, {\n request: requestOptions\n });\n requestError.cause = error;\n throw requestError;\n }\n const status = fetchResponse.status;\n const url = fetchResponse.url;\n const responseHeaders = {};\n for (const [key, value] of fetchResponse.headers) {\n responseHeaders[key] = value;\n }\n const octokitResponse = {\n url,\n status,\n headers: responseHeaders,\n data: \"\"\n };\n if (\"deprecation\" in responseHeaders) {\n const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel=\"deprecation\"/);\n const deprecationLink = matches && matches.pop();\n log.warn(\n `[@octokit/request] \"${requestOptions.method} ${requestOptions.url}\" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : \"\"}`\n );\n }\n if (status === 204 || status === 205) {\n return octokitResponse;\n }\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return octokitResponse;\n }\n throw new RequestError(fetchResponse.statusText, status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n if (status === 304) {\n octokitResponse.data = await getResponseData(fetchResponse);\n throw new RequestError(\"Not modified\", status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n if (status >= 400) {\n octokitResponse.data = await getResponseData(fetchResponse);\n throw new RequestError(toErrorMessage(octokitResponse.data), status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body;\n return octokitResponse;\n}\nasync function getResponseData(response) {\n const contentType = response.headers.get(\"content-type\");\n if (!contentType) {\n return response.text().catch(noop);\n }\n const mimetype = safeParse(contentType);\n if (isJSONResponse(mimetype)) {\n let text = \"\";\n try {\n text = await response.text();\n return JSONParse(text);\n } catch (err) {\n return text;\n }\n } else if (mimetype.type.startsWith(\"text/\") || mimetype.parameters.charset?.toLowerCase() === \"utf-8\") {\n return response.text().catch(noop);\n } else {\n return response.arrayBuffer().catch(\n /* v8 ignore next -- @preserve */\n () => new ArrayBuffer(0)\n );\n }\n}\nfunction isJSONResponse(mimetype) {\n return mimetype.type === \"application/json\" || mimetype.type === \"application/scim+json\";\n}\nfunction toErrorMessage(data) {\n if (typeof data === \"string\") {\n return data;\n }\n if (data instanceof ArrayBuffer) {\n return \"Unknown error\";\n }\n if (\"message\" in data) {\n const suffix = \"documentation_url\" in data ? ` - ${data.documentation_url}` : \"\";\n return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(\", \")}${suffix}` : `${data.message}${suffix}`;\n }\n return `Unknown error: ${JSON.stringify(data)}`;\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint2 = oldEndpoint.defaults(newDefaults);\n const newApi = function(route, parameters) {\n const endpointOptions = endpoint2.merge(route, parameters);\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint2.parse(endpointOptions));\n }\n const request2 = (route2, parameters2) => {\n return fetchWrapper(\n endpoint2.parse(endpoint2.merge(route2, parameters2))\n );\n };\n Object.assign(request2, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n return endpointOptions.request.hook(request2, endpointOptions);\n };\n return Object.assign(newApi, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n}\n\n// pkg/dist-src/index.js\nvar request = withDefaults(endpoint, defaults_default);\nexport {\n request\n};\n/* v8 ignore next -- @preserve */\n/* v8 ignore else -- @preserve */\n", "// pkg/dist-src/index.js\nimport { request } from \"@octokit/request\";\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/with-defaults.js\nimport { request as Request2 } from \"@octokit/request\";\n\n// pkg/dist-src/graphql.js\nimport { request as Request } from \"@octokit/request\";\n\n// pkg/dist-src/error.js\nfunction _buildMessageForResponseErrors(data) {\n return `Request failed due to following response errors:\n` + data.errors.map((e) => ` - ${e.message}`).join(\"\\n\");\n}\nvar GraphqlResponseError = class extends Error {\n constructor(request2, headers, response) {\n super(_buildMessageForResponseErrors(response));\n this.request = request2;\n this.headers = headers;\n this.response = response;\n this.errors = response.errors;\n this.data = response.data;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n name = \"GraphqlResponseError\";\n errors;\n data;\n};\n\n// pkg/dist-src/graphql.js\nvar NON_VARIABLE_OPTIONS = [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"query\",\n \"mediaType\",\n \"operationName\"\n];\nvar FORBIDDEN_VARIABLE_OPTIONS = [\"query\", \"method\", \"url\"];\nvar GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request2, query, options) {\n if (options) {\n if (typeof query === \"string\" && \"query\" in options) {\n return Promise.reject(\n new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`)\n );\n }\n for (const key in options) {\n if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;\n return Promise.reject(\n new Error(\n `[@octokit/graphql] \"${key}\" cannot be used as variable name`\n )\n );\n }\n }\n const parsedOptions = typeof query === \"string\" ? Object.assign({ query }, options) : query;\n const requestOptions = Object.keys(\n parsedOptions\n ).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n if (!result.variables) {\n result.variables = {};\n }\n result.variables[key] = parsedOptions[key];\n return result;\n }, {});\n const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n return request2(requestOptions).then((response) => {\n if (response.data.errors) {\n const headers = {};\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n throw new GraphqlResponseError(\n requestOptions,\n headers,\n response.data\n );\n }\n return response.data.data;\n });\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(request2, newDefaults) {\n const newRequest = request2.defaults(newDefaults);\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: newRequest.endpoint\n });\n}\n\n// pkg/dist-src/index.js\nvar graphql2 = withDefaults(request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${getUserAgent()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\nexport {\n GraphqlResponseError,\n graphql2 as graphql,\n withCustomRequest\n};\n", "// pkg/dist-src/is-jwt.js\nvar b64url = \"(?:[a-zA-Z0-9_-]+)\";\nvar sep = \"\\\\.\";\nvar jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);\nvar isJWT = jwtRE.test.bind(jwtRE);\n\n// pkg/dist-src/auth.js\nasync function auth(token) {\n const isApp = isJWT(token);\n const isInstallation = token.startsWith(\"v1.\") || token.startsWith(\"ghs_\");\n const isUserToServer = token.startsWith(\"ghu_\");\n const tokenType = isApp ? \"app\" : isInstallation ? \"installation\" : isUserToServer ? \"user-to-server\" : \"oauth\";\n return {\n type: \"token\",\n token,\n tokenType\n };\n}\n\n// pkg/dist-src/with-authorization-prefix.js\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n\n// pkg/dist-src/hook.js\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(\n route,\n parameters\n );\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\n// pkg/dist-src/index.js\nvar createTokenAuth = function createTokenAuth2(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\n \"[@octokit/auth-token] Token passed to createTokenAuth is not a string\"\n );\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\nexport {\n createTokenAuth\n};\n", "const VERSION = \"7.0.6\";\nexport {\n VERSION\n};\n", "import { getUserAgent } from \"universal-user-agent\";\nimport Hook from \"before-after-hook\";\nimport { request } from \"@octokit/request\";\nimport { withCustomRequest } from \"@octokit/graphql\";\nimport { createTokenAuth } from \"@octokit/auth-token\";\nimport { VERSION } from \"./version.js\";\nconst noop = () => {\n};\nconst consoleWarn = console.warn.bind(console);\nconst consoleError = console.error.bind(console);\nfunction createLogger(logger = {}) {\n if (typeof logger.debug !== \"function\") {\n logger.debug = noop;\n }\n if (typeof logger.info !== \"function\") {\n logger.info = noop;\n }\n if (typeof logger.warn !== \"function\") {\n logger.warn = consoleWarn;\n }\n if (typeof logger.error !== \"function\") {\n logger.error = consoleError;\n }\n return logger;\n}\nconst userAgentTrail = `octokit-core.js/${VERSION} ${getUserAgent()}`;\nclass Octokit {\n static VERSION = VERSION;\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n super(\n Object.assign(\n {},\n defaults,\n options,\n options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null\n )\n );\n }\n };\n return OctokitWithDefaults;\n }\n static plugins = [];\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n static plugin(...newPlugins) {\n const currentPlugins = this.plugins;\n const NewOctokit = class extends this {\n static plugins = currentPlugins.concat(\n newPlugins.filter((plugin) => !currentPlugins.includes(plugin))\n );\n };\n return NewOctokit;\n }\n constructor(options = {}) {\n const hook = new Hook.Collection();\n const requestDefaults = {\n baseUrl: request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n // @ts-ignore internal usage only, no need to type\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n };\n requestDefaults.headers[\"user-agent\"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n this.request = request.defaults(requestDefaults);\n this.graphql = withCustomRequest(this.request).defaults(requestDefaults);\n this.log = createLogger(options.log);\n this.hook = hook;\n if (!options.authStrategy) {\n if (!options.auth) {\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n const auth = createTokenAuth(options.auth);\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const { authStrategy, ...otherOptions } = options;\n const auth = authStrategy(\n Object.assign(\n {\n request: this.request,\n log: this.log,\n // we pass the current octokit instance as well as its constructor options\n // to allow for authentication strategies that return a new octokit instance\n // that shares the same internal state as the current one. The original\n // requirement for this was the \"event-octokit\" authentication strategy\n // of https://github.com/probot/octokit-auth-probot.\n octokit: this,\n octokitOptions: otherOptions\n },\n options.auth\n )\n );\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n const classConstructor = this.constructor;\n for (let i = 0; i < classConstructor.plugins.length; ++i) {\n Object.assign(this, classConstructor.plugins[i](this, options));\n }\n }\n // assigned during constructor\n request;\n graphql;\n log;\n hook;\n // TODO: type `octokit.auth` based on passed options.authStrategy\n auth;\n}\nexport {\n Octokit\n};\n", "const VERSION = \"6.0.0\";\nexport {\n VERSION\n};\n", "import { VERSION } from \"./version.js\";\nfunction requestLog(octokit) {\n octokit.hook.wrap(\"request\", (request, options) => {\n octokit.log.debug(\"request\", options);\n const start = Date.now();\n const requestOptions = octokit.request.endpoint.parse(options);\n const path = requestOptions.url.replace(options.baseUrl, \"\");\n return request(options).then((response) => {\n const requestId = response.headers[\"x-github-request-id\"];\n octokit.log.info(\n `${requestOptions.method} ${path} - ${response.status} with id ${requestId} in ${Date.now() - start}ms`\n );\n return response;\n }).catch((error) => {\n const requestId = error.response?.headers[\"x-github-request-id\"] || \"UNKNOWN\";\n octokit.log.error(\n `${requestOptions.method} ${path} - ${error.status} with id ${requestId} in ${Date.now() - start}ms`\n );\n throw error;\n });\n });\n}\nrequestLog.VERSION = VERSION;\nexport {\n requestLog\n};\n", "// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/normalize-paginated-list-response.js\nfunction normalizePaginatedListResponse(response) {\n if (!response.data) {\n return {\n ...response,\n data: []\n };\n }\n const responseNeedsNormalization = (\"total_count\" in response.data || \"total_commits\" in response.data) && !(\"url\" in response.data);\n if (!responseNeedsNormalization) return response;\n const incompleteResults = response.data.incomplete_results;\n const repositorySelection = response.data.repository_selection;\n const totalCount = response.data.total_count;\n const totalCommits = response.data.total_commits;\n delete response.data.incomplete_results;\n delete response.data.repository_selection;\n delete response.data.total_count;\n delete response.data.total_commits;\n const namespaceKey = Object.keys(response.data)[0];\n const data = response.data[namespaceKey];\n response.data = data;\n if (typeof incompleteResults !== \"undefined\") {\n response.data.incomplete_results = incompleteResults;\n }\n if (typeof repositorySelection !== \"undefined\") {\n response.data.repository_selection = repositorySelection;\n }\n response.data.total_count = totalCount;\n response.data.total_commits = totalCommits;\n return response;\n}\n\n// pkg/dist-src/iterator.js\nfunction iterator(octokit, route, parameters) {\n const options = typeof route === \"function\" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);\n const requestMethod = typeof route === \"function\" ? route : octokit.request;\n const method = options.method;\n const headers = options.headers;\n let url = options.url;\n return {\n [Symbol.asyncIterator]: () => ({\n async next() {\n if (!url) return { done: true };\n try {\n const response = await requestMethod({ method, url, headers });\n const normalizedResponse = normalizePaginatedListResponse(response);\n url = ((normalizedResponse.headers.link || \"\").match(\n /<([^<>]+)>;\\s*rel=\"next\"/\n ) || [])[1];\n if (!url && \"total_commits\" in normalizedResponse.data) {\n const parsedUrl = new URL(normalizedResponse.url);\n const params = parsedUrl.searchParams;\n const page = parseInt(params.get(\"page\") || \"1\", 10);\n const per_page = parseInt(params.get(\"per_page\") || \"250\", 10);\n if (page * per_page < normalizedResponse.data.total_commits) {\n params.set(\"page\", String(page + 1));\n url = parsedUrl.toString();\n }\n }\n return { value: normalizedResponse };\n } catch (error) {\n if (error.status !== 409) throw error;\n url = \"\";\n return {\n value: {\n status: 200,\n headers: {},\n data: []\n }\n };\n }\n }\n })\n };\n}\n\n// pkg/dist-src/paginate.js\nfunction paginate(octokit, route, parameters, mapFn) {\n if (typeof parameters === \"function\") {\n mapFn = parameters;\n parameters = void 0;\n }\n return gather(\n octokit,\n [],\n iterator(octokit, route, parameters)[Symbol.asyncIterator](),\n mapFn\n );\n}\nfunction gather(octokit, results, iterator2, mapFn) {\n return iterator2.next().then((result) => {\n if (result.done) {\n return results;\n }\n let earlyExit = false;\n function done() {\n earlyExit = true;\n }\n results = results.concat(\n mapFn ? mapFn(result.value, done) : result.value.data\n );\n if (earlyExit) {\n return results;\n }\n return gather(octokit, results, iterator2, mapFn);\n });\n}\n\n// pkg/dist-src/compose-paginate.js\nvar composePaginateRest = Object.assign(paginate, {\n iterator\n});\n\n// pkg/dist-src/generated/paginating-endpoints.js\nvar paginatingEndpoints = [\n \"GET /advisories\",\n \"GET /app/hook/deliveries\",\n \"GET /app/installation-requests\",\n \"GET /app/installations\",\n \"GET /assignments/{assignment_id}/accepted_assignments\",\n \"GET /classrooms\",\n \"GET /classrooms/{classroom_id}/assignments\",\n \"GET /enterprises/{enterprise}/code-security/configurations\",\n \"GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories\",\n \"GET /enterprises/{enterprise}/dependabot/alerts\",\n \"GET /enterprises/{enterprise}/teams\",\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships\",\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations\",\n \"GET /events\",\n \"GET /gists\",\n \"GET /gists/public\",\n \"GET /gists/starred\",\n \"GET /gists/{gist_id}/comments\",\n \"GET /gists/{gist_id}/commits\",\n \"GET /gists/{gist_id}/forks\",\n \"GET /installation/repositories\",\n \"GET /issues\",\n \"GET /licenses\",\n \"GET /marketplace_listing/plans\",\n \"GET /marketplace_listing/plans/{plan_id}/accounts\",\n \"GET /marketplace_listing/stubbed/plans\",\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\",\n \"GET /networks/{owner}/{repo}/events\",\n \"GET /notifications\",\n \"GET /organizations\",\n \"GET /organizations/{org}/dependabot/repository-access\",\n \"GET /orgs/{org}/actions/cache/usage-by-repository\",\n \"GET /orgs/{org}/actions/hosted-runners\",\n \"GET /orgs/{org}/actions/permissions/repositories\",\n \"GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories\",\n \"GET /orgs/{org}/actions/runner-groups\",\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners\",\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories\",\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners\",\n \"GET /orgs/{org}/actions/runners\",\n \"GET /orgs/{org}/actions/secrets\",\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/actions/variables\",\n \"GET /orgs/{org}/actions/variables/{name}/repositories\",\n \"GET /orgs/{org}/attestations/repositories\",\n \"GET /orgs/{org}/attestations/{subject_digest}\",\n \"GET /orgs/{org}/blocks\",\n \"GET /orgs/{org}/campaigns\",\n \"GET /orgs/{org}/code-scanning/alerts\",\n \"GET /orgs/{org}/code-security/configurations\",\n \"GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories\",\n \"GET /orgs/{org}/codespaces\",\n \"GET /orgs/{org}/codespaces/secrets\",\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/copilot/billing/seats\",\n \"GET /orgs/{org}/copilot/metrics\",\n \"GET /orgs/{org}/dependabot/alerts\",\n \"GET /orgs/{org}/dependabot/secrets\",\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/events\",\n \"GET /orgs/{org}/failed_invitations\",\n \"GET /orgs/{org}/hooks\",\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries\",\n \"GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}\",\n \"GET /orgs/{org}/insights/api/subject-stats\",\n \"GET /orgs/{org}/insights/api/user-stats/{user_id}\",\n \"GET /orgs/{org}/installations\",\n \"GET /orgs/{org}/invitations\",\n \"GET /orgs/{org}/invitations/{invitation_id}/teams\",\n \"GET /orgs/{org}/issues\",\n \"GET /orgs/{org}/members\",\n \"GET /orgs/{org}/members/{username}/codespaces\",\n \"GET /orgs/{org}/migrations\",\n \"GET /orgs/{org}/migrations/{migration_id}/repositories\",\n \"GET /orgs/{org}/organization-roles/{role_id}/teams\",\n \"GET /orgs/{org}/organization-roles/{role_id}/users\",\n \"GET /orgs/{org}/outside_collaborators\",\n \"GET /orgs/{org}/packages\",\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n \"GET /orgs/{org}/personal-access-token-requests\",\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\",\n \"GET /orgs/{org}/personal-access-tokens\",\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\",\n \"GET /orgs/{org}/private-registries\",\n \"GET /orgs/{org}/projects\",\n \"GET /orgs/{org}/projectsV2\",\n \"GET /orgs/{org}/projectsV2/{project_number}/fields\",\n \"GET /orgs/{org}/projectsV2/{project_number}/items\",\n \"GET /orgs/{org}/properties/values\",\n \"GET /orgs/{org}/public_members\",\n \"GET /orgs/{org}/repos\",\n \"GET /orgs/{org}/rulesets\",\n \"GET /orgs/{org}/rulesets/rule-suites\",\n \"GET /orgs/{org}/rulesets/{ruleset_id}/history\",\n \"GET /orgs/{org}/secret-scanning/alerts\",\n \"GET /orgs/{org}/security-advisories\",\n \"GET /orgs/{org}/settings/immutable-releases/repositories\",\n \"GET /orgs/{org}/settings/network-configurations\",\n \"GET /orgs/{org}/team/{team_slug}/copilot/metrics\",\n \"GET /orgs/{org}/teams\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/invitations\",\n \"GET /orgs/{org}/teams/{team_slug}/members\",\n \"GET /orgs/{org}/teams/{team_slug}/projects\",\n \"GET /orgs/{org}/teams/{team_slug}/repos\",\n \"GET /orgs/{org}/teams/{team_slug}/teams\",\n \"GET /projects/{project_id}/collaborators\",\n \"GET /repos/{owner}/{repo}/actions/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/caches\",\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\",\n \"GET /repos/{owner}/{repo}/actions/organization-variables\",\n \"GET /repos/{owner}/{repo}/actions/runners\",\n \"GET /repos/{owner}/{repo}/actions/runs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/secrets\",\n \"GET /repos/{owner}/{repo}/actions/variables\",\n \"GET /repos/{owner}/{repo}/actions/workflows\",\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\",\n \"GET /repos/{owner}/{repo}/activity\",\n \"GET /repos/{owner}/{repo}/assignees\",\n \"GET /repos/{owner}/{repo}/attestations/{subject_digest}\",\n \"GET /repos/{owner}/{repo}/branches\",\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\",\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n \"GET /repos/{owner}/{repo}/code-scanning/analyses\",\n \"GET /repos/{owner}/{repo}/codespaces\",\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\",\n \"GET /repos/{owner}/{repo}/codespaces/secrets\",\n \"GET /repos/{owner}/{repo}/collaborators\",\n \"GET /repos/{owner}/{repo}/comments\",\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/commits\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/status\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\",\n \"GET /repos/{owner}/{repo}/compare/{basehead}\",\n \"GET /repos/{owner}/{repo}/compare/{base}...{head}\",\n \"GET /repos/{owner}/{repo}/contributors\",\n \"GET /repos/{owner}/{repo}/dependabot/alerts\",\n \"GET /repos/{owner}/{repo}/dependabot/secrets\",\n \"GET /repos/{owner}/{repo}/deployments\",\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n \"GET /repos/{owner}/{repo}/environments\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/variables\",\n \"GET /repos/{owner}/{repo}/events\",\n \"GET /repos/{owner}/{repo}/forks\",\n \"GET /repos/{owner}/{repo}/hooks\",\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\",\n \"GET /repos/{owner}/{repo}/invitations\",\n \"GET /repos/{owner}/{repo}/issues\",\n \"GET /repos/{owner}/{repo}/issues/comments\",\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\",\n \"GET /repos/{owner}/{repo}/keys\",\n \"GET /repos/{owner}/{repo}/labels\",\n \"GET /repos/{owner}/{repo}/milestones\",\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\",\n \"GET /repos/{owner}/{repo}/notifications\",\n \"GET /repos/{owner}/{repo}/pages/builds\",\n \"GET /repos/{owner}/{repo}/projects\",\n \"GET /repos/{owner}/{repo}/pulls\",\n \"GET /repos/{owner}/{repo}/pulls/comments\",\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\",\n \"GET /repos/{owner}/{repo}/releases\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n \"GET /repos/{owner}/{repo}/rules/branches/{branch}\",\n \"GET /repos/{owner}/{repo}/rulesets\",\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites\",\n \"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\",\n \"GET /repos/{owner}/{repo}/security-advisories\",\n \"GET /repos/{owner}/{repo}/stargazers\",\n \"GET /repos/{owner}/{repo}/subscribers\",\n \"GET /repos/{owner}/{repo}/tags\",\n \"GET /repos/{owner}/{repo}/teams\",\n \"GET /repos/{owner}/{repo}/topics\",\n \"GET /repositories\",\n \"GET /search/code\",\n \"GET /search/commits\",\n \"GET /search/issues\",\n \"GET /search/labels\",\n \"GET /search/repositories\",\n \"GET /search/topics\",\n \"GET /search/users\",\n \"GET /teams/{team_id}/discussions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/reactions\",\n \"GET /teams/{team_id}/invitations\",\n \"GET /teams/{team_id}/members\",\n \"GET /teams/{team_id}/projects\",\n \"GET /teams/{team_id}/repos\",\n \"GET /teams/{team_id}/teams\",\n \"GET /user/blocks\",\n \"GET /user/codespaces\",\n \"GET /user/codespaces/secrets\",\n \"GET /user/emails\",\n \"GET /user/followers\",\n \"GET /user/following\",\n \"GET /user/gpg_keys\",\n \"GET /user/installations\",\n \"GET /user/installations/{installation_id}/repositories\",\n \"GET /user/issues\",\n \"GET /user/keys\",\n \"GET /user/marketplace_purchases\",\n \"GET /user/marketplace_purchases/stubbed\",\n \"GET /user/memberships/orgs\",\n \"GET /user/migrations\",\n \"GET /user/migrations/{migration_id}/repositories\",\n \"GET /user/orgs\",\n \"GET /user/packages\",\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n \"GET /user/public_emails\",\n \"GET /user/repos\",\n \"GET /user/repository_invitations\",\n \"GET /user/social_accounts\",\n \"GET /user/ssh_signing_keys\",\n \"GET /user/starred\",\n \"GET /user/subscriptions\",\n \"GET /user/teams\",\n \"GET /users\",\n \"GET /users/{username}/attestations/{subject_digest}\",\n \"GET /users/{username}/events\",\n \"GET /users/{username}/events/orgs/{org}\",\n \"GET /users/{username}/events/public\",\n \"GET /users/{username}/followers\",\n \"GET /users/{username}/following\",\n \"GET /users/{username}/gists\",\n \"GET /users/{username}/gpg_keys\",\n \"GET /users/{username}/keys\",\n \"GET /users/{username}/orgs\",\n \"GET /users/{username}/packages\",\n \"GET /users/{username}/projects\",\n \"GET /users/{username}/projectsV2\",\n \"GET /users/{username}/projectsV2/{project_number}/fields\",\n \"GET /users/{username}/projectsV2/{project_number}/items\",\n \"GET /users/{username}/received_events\",\n \"GET /users/{username}/received_events/public\",\n \"GET /users/{username}/repos\",\n \"GET /users/{username}/social_accounts\",\n \"GET /users/{username}/ssh_signing_keys\",\n \"GET /users/{username}/starred\",\n \"GET /users/{username}/subscriptions\"\n];\n\n// pkg/dist-src/paginating-endpoints.js\nfunction isPaginatingEndpoint(arg) {\n if (typeof arg === \"string\") {\n return paginatingEndpoints.includes(arg);\n } else {\n return false;\n }\n}\n\n// pkg/dist-src/index.js\nfunction paginateRest(octokit) {\n return {\n paginate: Object.assign(paginate.bind(null, octokit), {\n iterator: iterator.bind(null, octokit)\n })\n };\n}\npaginateRest.VERSION = VERSION;\nexport {\n composePaginateRest,\n isPaginatingEndpoint,\n paginateRest,\n paginatingEndpoints\n};\n", "export const VERSION = \"17.0.0\";\n", "import type { EndpointsDefaultsAndDecorations } from \"../types.js\";\nconst Endpoints: EndpointsDefaultsAndDecorations = {\n actions: {\n addCustomLabelsToSelfHostedRunnerForOrg: [\n \"POST /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n addCustomLabelsToSelfHostedRunnerForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n addRepoAccessToSelfHostedRunnerGroupInOrg: [\n \"PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}\",\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n addSelectedRepoToOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\",\n ],\n approveWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve\",\n ],\n cancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel\",\n ],\n createEnvironmentVariable: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/variables\",\n ],\n createHostedRunnerForOrg: [\"POST /orgs/{org}/actions/hosted-runners\"],\n createOrUpdateEnvironmentSecret: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}\",\n ],\n createOrUpdateOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}\"],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}\",\n ],\n createOrgVariable: [\"POST /orgs/{org}/actions/variables\"],\n createRegistrationTokenForOrg: [\n \"POST /orgs/{org}/actions/runners/registration-token\",\n ],\n createRegistrationTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/registration-token\",\n ],\n createRemoveTokenForOrg: [\"POST /orgs/{org}/actions/runners/remove-token\"],\n createRemoveTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/remove-token\",\n ],\n createRepoVariable: [\"POST /repos/{owner}/{repo}/actions/variables\"],\n createWorkflowDispatch: [\n \"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches\",\n ],\n deleteActionsCacheById: [\n \"DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}\",\n ],\n deleteActionsCacheByKey: [\n \"DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}\",\n ],\n deleteArtifact: [\n \"DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\",\n ],\n deleteCustomImageFromOrg: [\n \"DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}\",\n ],\n deleteCustomImageVersionFromOrg: [\n \"DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}\",\n ],\n deleteEnvironmentSecret: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}\",\n ],\n deleteEnvironmentVariable: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}\",\n ],\n deleteHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}\",\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}\"],\n deleteOrgVariable: [\"DELETE /orgs/{org}/actions/variables/{name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}\",\n ],\n deleteRepoVariable: [\n \"DELETE /repos/{owner}/{repo}/actions/variables/{name}\",\n ],\n deleteSelfHostedRunnerFromOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}\",\n ],\n deleteSelfHostedRunnerFromRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}\",\n ],\n deleteWorkflowRun: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n deleteWorkflowRunLogs: [\n \"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs\",\n ],\n disableSelectedRepositoryGithubActionsOrganization: [\n \"DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}\",\n ],\n disableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable\",\n ],\n downloadArtifact: [\n \"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}\",\n ],\n downloadJobLogsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs\",\n ],\n downloadWorkflowRunAttemptLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs\",\n ],\n downloadWorkflowRunLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs\",\n ],\n enableSelectedRepositoryGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories/{repository_id}\",\n ],\n enableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable\",\n ],\n forceCancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel\",\n ],\n generateRunnerJitconfigForOrg: [\n \"POST /orgs/{org}/actions/runners/generate-jitconfig\",\n ],\n generateRunnerJitconfigForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig\",\n ],\n getActionsCacheList: [\"GET /repos/{owner}/{repo}/actions/caches\"],\n getActionsCacheUsage: [\"GET /repos/{owner}/{repo}/actions/cache/usage\"],\n getActionsCacheUsageByRepoForOrg: [\n \"GET /orgs/{org}/actions/cache/usage-by-repository\",\n ],\n getActionsCacheUsageForOrg: [\"GET /orgs/{org}/actions/cache/usage\"],\n getAllowedActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/selected-actions\",\n ],\n getAllowedActionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/selected-actions\",\n ],\n getArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n getCustomImageForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}\",\n ],\n getCustomImageVersionForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}\",\n ],\n getCustomOidcSubClaimForRepo: [\n \"GET /repos/{owner}/{repo}/actions/oidc/customization/sub\",\n ],\n getEnvironmentPublicKey: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key\",\n ],\n getEnvironmentSecret: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}\",\n ],\n getEnvironmentVariable: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}\",\n ],\n getGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/workflow\",\n ],\n getGithubActionsDefaultWorkflowPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/workflow\",\n ],\n getGithubActionsPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions\",\n ],\n getGithubActionsPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions\",\n ],\n getHostedRunnerForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}\",\n ],\n getHostedRunnersGithubOwnedImagesForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/github-owned\",\n ],\n getHostedRunnersLimitsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/limits\",\n ],\n getHostedRunnersMachineSpecsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/machine-sizes\",\n ],\n getHostedRunnersPartnerImagesForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/partner\",\n ],\n getHostedRunnersPlatformsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/platforms\",\n ],\n getJobForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/actions/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}\"],\n getOrgVariable: [\"GET /orgs/{org}/actions/variables/{name}\"],\n getPendingDeploymentsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\",\n ],\n getRepoPermissions: [\n \"GET /repos/{owner}/{repo}/actions/permissions\",\n {},\n { renamed: [\"actions\", \"getGithubActionsPermissionsRepository\"] },\n ],\n getRepoPublicKey: [\"GET /repos/{owner}/{repo}/actions/secrets/public-key\"],\n getRepoSecret: [\"GET /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n getRepoVariable: [\"GET /repos/{owner}/{repo}/actions/variables/{name}\"],\n getReviewsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals\",\n ],\n getSelfHostedRunnerForOrg: [\"GET /orgs/{org}/actions/runners/{runner_id}\"],\n getSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}\",\n ],\n getWorkflow: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}\"],\n getWorkflowAccessToRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/access\",\n ],\n getWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n getWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}\",\n ],\n getWorkflowRunUsage: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing\",\n ],\n getWorkflowUsage: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing\",\n ],\n listArtifactsForRepo: [\"GET /repos/{owner}/{repo}/actions/artifacts\"],\n listCustomImageVersionsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions\",\n ],\n listCustomImagesForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom\",\n ],\n listEnvironmentSecrets: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets\",\n ],\n listEnvironmentVariables: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/variables\",\n ],\n listGithubHostedRunnersInGroupForOrg: [\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners\",\n ],\n listHostedRunnersForOrg: [\"GET /orgs/{org}/actions/hosted-runners\"],\n listJobsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\",\n ],\n listJobsForWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\",\n ],\n listLabelsForSelfHostedRunnerForOrg: [\n \"GET /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n listLabelsForSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n listOrgSecrets: [\"GET /orgs/{org}/actions/secrets\"],\n listOrgVariables: [\"GET /orgs/{org}/actions/variables\"],\n listRepoOrganizationSecrets: [\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\",\n ],\n listRepoOrganizationVariables: [\n \"GET /repos/{owner}/{repo}/actions/organization-variables\",\n ],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/actions/secrets\"],\n listRepoVariables: [\"GET /repos/{owner}/{repo}/actions/variables\"],\n listRepoWorkflows: [\"GET /repos/{owner}/{repo}/actions/workflows\"],\n listRunnerApplicationsForOrg: [\"GET /orgs/{org}/actions/runners/downloads\"],\n listRunnerApplicationsForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/downloads\",\n ],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n ],\n listSelectedReposForOrgVariable: [\n \"GET /orgs/{org}/actions/variables/{name}/repositories\",\n ],\n listSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/repositories\",\n ],\n listSelfHostedRunnersForOrg: [\"GET /orgs/{org}/actions/runners\"],\n listSelfHostedRunnersForRepo: [\"GET /repos/{owner}/{repo}/actions/runners\"],\n listWorkflowRunArtifacts: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\",\n ],\n listWorkflowRuns: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\",\n ],\n listWorkflowRunsForRepo: [\"GET /repos/{owner}/{repo}/actions/runs\"],\n reRunJobForWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun\",\n ],\n reRunWorkflow: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun\"],\n reRunWorkflowFailedJobs: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs\",\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n removeCustomLabelFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}\",\n ],\n removeCustomLabelFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}\",\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n removeSelectedRepoFromOrgVariable: [\n \"DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\",\n ],\n reviewCustomGatesForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule\",\n ],\n reviewPendingDeploymentsForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\",\n ],\n setAllowedActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/selected-actions\",\n ],\n setAllowedActionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/selected-actions\",\n ],\n setCustomLabelsForSelfHostedRunnerForOrg: [\n \"PUT /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n setCustomLabelsForSelfHostedRunnerForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n setCustomOidcSubClaimForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/oidc/customization/sub\",\n ],\n setGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/workflow\",\n ],\n setGithubActionsDefaultWorkflowPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/workflow\",\n ],\n setGithubActionsPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions\",\n ],\n setGithubActionsPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions\",\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n ],\n setSelectedReposForOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories\",\n ],\n setSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories\",\n ],\n setWorkflowAccessToRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/access\",\n ],\n updateEnvironmentVariable: [\n \"PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}\",\n ],\n updateHostedRunnerForOrg: [\n \"PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}\",\n ],\n updateOrgVariable: [\"PATCH /orgs/{org}/actions/variables/{name}\"],\n updateRepoVariable: [\n \"PATCH /repos/{owner}/{repo}/actions/variables/{name}\",\n ],\n },\n activity: {\n checkRepoIsStarredByAuthenticatedUser: [\"GET /user/starred/{owner}/{repo}\"],\n deleteRepoSubscription: [\"DELETE /repos/{owner}/{repo}/subscription\"],\n deleteThreadSubscription: [\n \"DELETE /notifications/threads/{thread_id}/subscription\",\n ],\n getFeeds: [\"GET /feeds\"],\n getRepoSubscription: [\"GET /repos/{owner}/{repo}/subscription\"],\n getThread: [\"GET /notifications/threads/{thread_id}\"],\n getThreadSubscriptionForAuthenticatedUser: [\n \"GET /notifications/threads/{thread_id}/subscription\",\n ],\n listEventsForAuthenticatedUser: [\"GET /users/{username}/events\"],\n listNotificationsForAuthenticatedUser: [\"GET /notifications\"],\n listOrgEventsForAuthenticatedUser: [\n \"GET /users/{username}/events/orgs/{org}\",\n ],\n listPublicEvents: [\"GET /events\"],\n listPublicEventsForRepoNetwork: [\"GET /networks/{owner}/{repo}/events\"],\n listPublicEventsForUser: [\"GET /users/{username}/events/public\"],\n listPublicOrgEvents: [\"GET /orgs/{org}/events\"],\n listReceivedEventsForUser: [\"GET /users/{username}/received_events\"],\n listReceivedPublicEventsForUser: [\n \"GET /users/{username}/received_events/public\",\n ],\n listRepoEvents: [\"GET /repos/{owner}/{repo}/events\"],\n listRepoNotificationsForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/notifications\",\n ],\n listReposStarredByAuthenticatedUser: [\"GET /user/starred\"],\n listReposStarredByUser: [\"GET /users/{username}/starred\"],\n listReposWatchedByUser: [\"GET /users/{username}/subscriptions\"],\n listStargazersForRepo: [\"GET /repos/{owner}/{repo}/stargazers\"],\n listWatchedReposForAuthenticatedUser: [\"GET /user/subscriptions\"],\n listWatchersForRepo: [\"GET /repos/{owner}/{repo}/subscribers\"],\n markNotificationsAsRead: [\"PUT /notifications\"],\n markRepoNotificationsAsRead: [\"PUT /repos/{owner}/{repo}/notifications\"],\n markThreadAsDone: [\"DELETE /notifications/threads/{thread_id}\"],\n markThreadAsRead: [\"PATCH /notifications/threads/{thread_id}\"],\n setRepoSubscription: [\"PUT /repos/{owner}/{repo}/subscription\"],\n setThreadSubscription: [\n \"PUT /notifications/threads/{thread_id}/subscription\",\n ],\n starRepoForAuthenticatedUser: [\"PUT /user/starred/{owner}/{repo}\"],\n unstarRepoForAuthenticatedUser: [\"DELETE /user/starred/{owner}/{repo}\"],\n },\n apps: {\n addRepoToInstallation: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"addRepoToInstallationForAuthenticatedUser\"] },\n ],\n addRepoToInstallationForAuthenticatedUser: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\",\n ],\n checkToken: [\"POST /applications/{client_id}/token\"],\n createFromManifest: [\"POST /app-manifests/{code}/conversions\"],\n createInstallationAccessToken: [\n \"POST /app/installations/{installation_id}/access_tokens\",\n ],\n deleteAuthorization: [\"DELETE /applications/{client_id}/grant\"],\n deleteInstallation: [\"DELETE /app/installations/{installation_id}\"],\n deleteToken: [\"DELETE /applications/{client_id}/token\"],\n getAuthenticated: [\"GET /app\"],\n getBySlug: [\"GET /apps/{app_slug}\"],\n getInstallation: [\"GET /app/installations/{installation_id}\"],\n getOrgInstallation: [\"GET /orgs/{org}/installation\"],\n getRepoInstallation: [\"GET /repos/{owner}/{repo}/installation\"],\n getSubscriptionPlanForAccount: [\n \"GET /marketplace_listing/accounts/{account_id}\",\n ],\n getSubscriptionPlanForAccountStubbed: [\n \"GET /marketplace_listing/stubbed/accounts/{account_id}\",\n ],\n getUserInstallation: [\"GET /users/{username}/installation\"],\n getWebhookConfigForApp: [\"GET /app/hook/config\"],\n getWebhookDelivery: [\"GET /app/hook/deliveries/{delivery_id}\"],\n listAccountsForPlan: [\"GET /marketplace_listing/plans/{plan_id}/accounts\"],\n listAccountsForPlanStubbed: [\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\",\n ],\n listInstallationReposForAuthenticatedUser: [\n \"GET /user/installations/{installation_id}/repositories\",\n ],\n listInstallationRequestsForAuthenticatedApp: [\n \"GET /app/installation-requests\",\n ],\n listInstallations: [\"GET /app/installations\"],\n listInstallationsForAuthenticatedUser: [\"GET /user/installations\"],\n listPlans: [\"GET /marketplace_listing/plans\"],\n listPlansStubbed: [\"GET /marketplace_listing/stubbed/plans\"],\n listReposAccessibleToInstallation: [\"GET /installation/repositories\"],\n listSubscriptionsForAuthenticatedUser: [\"GET /user/marketplace_purchases\"],\n listSubscriptionsForAuthenticatedUserStubbed: [\n \"GET /user/marketplace_purchases/stubbed\",\n ],\n listWebhookDeliveries: [\"GET /app/hook/deliveries\"],\n redeliverWebhookDelivery: [\n \"POST /app/hook/deliveries/{delivery_id}/attempts\",\n ],\n removeRepoFromInstallation: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"removeRepoFromInstallationForAuthenticatedUser\"] },\n ],\n removeRepoFromInstallationForAuthenticatedUser: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\",\n ],\n resetToken: [\"PATCH /applications/{client_id}/token\"],\n revokeInstallationAccessToken: [\"DELETE /installation/token\"],\n scopeToken: [\"POST /applications/{client_id}/token/scoped\"],\n suspendInstallation: [\"PUT /app/installations/{installation_id}/suspended\"],\n unsuspendInstallation: [\n \"DELETE /app/installations/{installation_id}/suspended\",\n ],\n updateWebhookConfigForApp: [\"PATCH /app/hook/config\"],\n },\n billing: {\n getGithubActionsBillingOrg: [\"GET /orgs/{org}/settings/billing/actions\"],\n getGithubActionsBillingUser: [\n \"GET /users/{username}/settings/billing/actions\",\n ],\n getGithubBillingPremiumRequestUsageReportOrg: [\n \"GET /organizations/{org}/settings/billing/premium_request/usage\",\n ],\n getGithubBillingPremiumRequestUsageReportUser: [\n \"GET /users/{username}/settings/billing/premium_request/usage\",\n ],\n getGithubBillingUsageReportOrg: [\n \"GET /organizations/{org}/settings/billing/usage\",\n ],\n getGithubBillingUsageReportUser: [\n \"GET /users/{username}/settings/billing/usage\",\n ],\n getGithubPackagesBillingOrg: [\"GET /orgs/{org}/settings/billing/packages\"],\n getGithubPackagesBillingUser: [\n \"GET /users/{username}/settings/billing/packages\",\n ],\n getSharedStorageBillingOrg: [\n \"GET /orgs/{org}/settings/billing/shared-storage\",\n ],\n getSharedStorageBillingUser: [\n \"GET /users/{username}/settings/billing/shared-storage\",\n ],\n },\n campaigns: {\n createCampaign: [\"POST /orgs/{org}/campaigns\"],\n deleteCampaign: [\"DELETE /orgs/{org}/campaigns/{campaign_number}\"],\n getCampaignSummary: [\"GET /orgs/{org}/campaigns/{campaign_number}\"],\n listOrgCampaigns: [\"GET /orgs/{org}/campaigns\"],\n updateCampaign: [\"PATCH /orgs/{org}/campaigns/{campaign_number}\"],\n },\n checks: {\n create: [\"POST /repos/{owner}/{repo}/check-runs\"],\n createSuite: [\"POST /repos/{owner}/{repo}/check-suites\"],\n get: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n getSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}\"],\n listAnnotations: [\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\",\n ],\n listForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\"],\n listForSuite: [\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\",\n ],\n listSuitesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\"],\n rerequestRun: [\n \"POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest\",\n ],\n rerequestSuite: [\n \"POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest\",\n ],\n setSuitesPreferences: [\n \"PATCH /repos/{owner}/{repo}/check-suites/preferences\",\n ],\n update: [\"PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n },\n codeScanning: {\n commitAutofix: [\n \"POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits\",\n ],\n createAutofix: [\n \"POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix\",\n ],\n createVariantAnalysis: [\n \"POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses\",\n ],\n deleteAnalysis: [\n \"DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}\",\n ],\n deleteCodeqlDatabase: [\n \"DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}\",\n ],\n getAlert: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\",\n {},\n { renamedParameters: { alert_id: \"alert_number\" } },\n ],\n getAnalysis: [\n \"GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}\",\n ],\n getAutofix: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix\",\n ],\n getCodeqlDatabase: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}\",\n ],\n getDefaultSetup: [\"GET /repos/{owner}/{repo}/code-scanning/default-setup\"],\n getSarif: [\"GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}\"],\n getVariantAnalysis: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}\",\n ],\n getVariantAnalysisRepoTask: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}\",\n ],\n listAlertInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/code-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/code-scanning/alerts\"],\n listAlertsInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n {},\n { renamed: [\"codeScanning\", \"listAlertInstances\"] },\n ],\n listCodeqlDatabases: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases\",\n ],\n listRecentAnalyses: [\"GET /repos/{owner}/{repo}/code-scanning/analyses\"],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\",\n ],\n updateDefaultSetup: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/default-setup\",\n ],\n uploadSarif: [\"POST /repos/{owner}/{repo}/code-scanning/sarifs\"],\n },\n codeSecurity: {\n attachConfiguration: [\n \"POST /orgs/{org}/code-security/configurations/{configuration_id}/attach\",\n ],\n attachEnterpriseConfiguration: [\n \"POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach\",\n ],\n createConfiguration: [\"POST /orgs/{org}/code-security/configurations\"],\n createConfigurationForEnterprise: [\n \"POST /enterprises/{enterprise}/code-security/configurations\",\n ],\n deleteConfiguration: [\n \"DELETE /orgs/{org}/code-security/configurations/{configuration_id}\",\n ],\n deleteConfigurationForEnterprise: [\n \"DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}\",\n ],\n detachConfiguration: [\n \"DELETE /orgs/{org}/code-security/configurations/detach\",\n ],\n getConfiguration: [\n \"GET /orgs/{org}/code-security/configurations/{configuration_id}\",\n ],\n getConfigurationForRepository: [\n \"GET /repos/{owner}/{repo}/code-security-configuration\",\n ],\n getConfigurationsForEnterprise: [\n \"GET /enterprises/{enterprise}/code-security/configurations\",\n ],\n getConfigurationsForOrg: [\"GET /orgs/{org}/code-security/configurations\"],\n getDefaultConfigurations: [\n \"GET /orgs/{org}/code-security/configurations/defaults\",\n ],\n getDefaultConfigurationsForEnterprise: [\n \"GET /enterprises/{enterprise}/code-security/configurations/defaults\",\n ],\n getRepositoriesForConfiguration: [\n \"GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories\",\n ],\n getRepositoriesForEnterpriseConfiguration: [\n \"GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories\",\n ],\n getSingleConfigurationForEnterprise: [\n \"GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}\",\n ],\n setConfigurationAsDefault: [\n \"PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults\",\n ],\n setConfigurationAsDefaultForEnterprise: [\n \"PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults\",\n ],\n updateConfiguration: [\n \"PATCH /orgs/{org}/code-security/configurations/{configuration_id}\",\n ],\n updateEnterpriseConfiguration: [\n \"PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}\",\n ],\n },\n codesOfConduct: {\n getAllCodesOfConduct: [\"GET /codes_of_conduct\"],\n getConductCode: [\"GET /codes_of_conduct/{key}\"],\n },\n codespaces: {\n addRepositoryForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n checkPermissionsForDevcontainer: [\n \"GET /repos/{owner}/{repo}/codespaces/permissions_check\",\n ],\n codespaceMachinesForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/machines\",\n ],\n createForAuthenticatedUser: [\"POST /user/codespaces\"],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}\",\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\",\n ],\n createOrUpdateSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}\",\n ],\n createWithPrForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces\",\n ],\n createWithRepoForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/codespaces\",\n ],\n deleteForAuthenticatedUser: [\"DELETE /user/codespaces/{codespace_name}\"],\n deleteFromOrganization: [\n \"DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}\",\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/codespaces/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\",\n ],\n deleteSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}\",\n ],\n exportForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/exports\",\n ],\n getCodespacesForUserInOrg: [\n \"GET /orgs/{org}/members/{username}/codespaces\",\n ],\n getExportDetailsForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/exports/{export_id}\",\n ],\n getForAuthenticatedUser: [\"GET /user/codespaces/{codespace_name}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/codespaces/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/codespaces/secrets/{secret_name}\"],\n getPublicKeyForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/public-key\",\n ],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/public-key\",\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\",\n ],\n getSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}\",\n ],\n listDevcontainersInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\",\n ],\n listForAuthenticatedUser: [\"GET /user/codespaces\"],\n listInOrganization: [\n \"GET /orgs/{org}/codespaces\",\n {},\n { renamedParameters: { org_id: \"org\" } },\n ],\n listInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces\",\n ],\n listOrgSecrets: [\"GET /orgs/{org}/codespaces/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/codespaces/secrets\"],\n listRepositoriesForSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}/repositories\",\n ],\n listSecretsForAuthenticatedUser: [\"GET /user/codespaces/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n ],\n preFlightWithRepoForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/new\",\n ],\n publishForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/publish\",\n ],\n removeRepositoryForSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n repoMachinesForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/machines\",\n ],\n setRepositoriesForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories\",\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n ],\n startForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/start\"],\n stopForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/stop\"],\n stopInOrganization: [\n \"POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop\",\n ],\n updateForAuthenticatedUser: [\"PATCH /user/codespaces/{codespace_name}\"],\n },\n copilot: {\n addCopilotSeatsForTeams: [\n \"POST /orgs/{org}/copilot/billing/selected_teams\",\n ],\n addCopilotSeatsForUsers: [\n \"POST /orgs/{org}/copilot/billing/selected_users\",\n ],\n cancelCopilotSeatAssignmentForTeams: [\n \"DELETE /orgs/{org}/copilot/billing/selected_teams\",\n ],\n cancelCopilotSeatAssignmentForUsers: [\n \"DELETE /orgs/{org}/copilot/billing/selected_users\",\n ],\n copilotMetricsForOrganization: [\"GET /orgs/{org}/copilot/metrics\"],\n copilotMetricsForTeam: [\"GET /orgs/{org}/team/{team_slug}/copilot/metrics\"],\n getCopilotOrganizationDetails: [\"GET /orgs/{org}/copilot/billing\"],\n getCopilotSeatDetailsForUser: [\n \"GET /orgs/{org}/members/{username}/copilot\",\n ],\n listCopilotSeats: [\"GET /orgs/{org}/copilot/billing/seats\"],\n },\n credentials: { revoke: [\"POST /credentials/revoke\"] },\n dependabot: {\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}\",\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\",\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/dependabot/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\",\n ],\n getAlert: [\"GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/dependabot/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/dependabot/secrets/{secret_name}\"],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/public-key\",\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\",\n ],\n listAlertsForEnterprise: [\n \"GET /enterprises/{enterprise}/dependabot/alerts\",\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/dependabot/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/dependabot/alerts\"],\n listOrgSecrets: [\"GET /orgs/{org}/dependabot/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/dependabot/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n repositoryAccessForOrg: [\n \"GET /organizations/{org}/dependabot/repository-access\",\n ],\n setRepositoryAccessDefaultLevel: [\n \"PUT /organizations/{org}/dependabot/repository-access/default-level\",\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\",\n ],\n updateRepositoryAccessForOrg: [\n \"PATCH /organizations/{org}/dependabot/repository-access\",\n ],\n },\n dependencyGraph: {\n createRepositorySnapshot: [\n \"POST /repos/{owner}/{repo}/dependency-graph/snapshots\",\n ],\n diffRange: [\n \"GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}\",\n ],\n exportSbom: [\"GET /repos/{owner}/{repo}/dependency-graph/sbom\"],\n },\n emojis: { get: [\"GET /emojis\"] },\n enterpriseTeamMemberships: {\n add: [\n \"PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}\",\n ],\n bulkAdd: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add\",\n ],\n bulkRemove: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove\",\n ],\n get: [\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}\",\n ],\n list: [\"GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships\"],\n remove: [\n \"DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}\",\n ],\n },\n enterpriseTeamOrganizations: {\n add: [\n \"PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}\",\n ],\n bulkAdd: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add\",\n ],\n bulkRemove: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove\",\n ],\n delete: [\n \"DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}\",\n ],\n getAssignment: [\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}\",\n ],\n getAssignments: [\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations\",\n ],\n },\n enterpriseTeams: {\n create: [\"POST /enterprises/{enterprise}/teams\"],\n delete: [\"DELETE /enterprises/{enterprise}/teams/{team_slug}\"],\n get: [\"GET /enterprises/{enterprise}/teams/{team_slug}\"],\n list: [\"GET /enterprises/{enterprise}/teams\"],\n update: [\"PATCH /enterprises/{enterprise}/teams/{team_slug}\"],\n },\n gists: {\n checkIsStarred: [\"GET /gists/{gist_id}/star\"],\n create: [\"POST /gists\"],\n createComment: [\"POST /gists/{gist_id}/comments\"],\n delete: [\"DELETE /gists/{gist_id}\"],\n deleteComment: [\"DELETE /gists/{gist_id}/comments/{comment_id}\"],\n fork: [\"POST /gists/{gist_id}/forks\"],\n get: [\"GET /gists/{gist_id}\"],\n getComment: [\"GET /gists/{gist_id}/comments/{comment_id}\"],\n getRevision: [\"GET /gists/{gist_id}/{sha}\"],\n list: [\"GET /gists\"],\n listComments: [\"GET /gists/{gist_id}/comments\"],\n listCommits: [\"GET /gists/{gist_id}/commits\"],\n listForUser: [\"GET /users/{username}/gists\"],\n listForks: [\"GET /gists/{gist_id}/forks\"],\n listPublic: [\"GET /gists/public\"],\n listStarred: [\"GET /gists/starred\"],\n star: [\"PUT /gists/{gist_id}/star\"],\n unstar: [\"DELETE /gists/{gist_id}/star\"],\n update: [\"PATCH /gists/{gist_id}\"],\n updateComment: [\"PATCH /gists/{gist_id}/comments/{comment_id}\"],\n },\n git: {\n createBlob: [\"POST /repos/{owner}/{repo}/git/blobs\"],\n createCommit: [\"POST /repos/{owner}/{repo}/git/commits\"],\n createRef: [\"POST /repos/{owner}/{repo}/git/refs\"],\n createTag: [\"POST /repos/{owner}/{repo}/git/tags\"],\n createTree: [\"POST /repos/{owner}/{repo}/git/trees\"],\n deleteRef: [\"DELETE /repos/{owner}/{repo}/git/refs/{ref}\"],\n getBlob: [\"GET /repos/{owner}/{repo}/git/blobs/{file_sha}\"],\n getCommit: [\"GET /repos/{owner}/{repo}/git/commits/{commit_sha}\"],\n getRef: [\"GET /repos/{owner}/{repo}/git/ref/{ref}\"],\n getTag: [\"GET /repos/{owner}/{repo}/git/tags/{tag_sha}\"],\n getTree: [\"GET /repos/{owner}/{repo}/git/trees/{tree_sha}\"],\n listMatchingRefs: [\"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\"],\n updateRef: [\"PATCH /repos/{owner}/{repo}/git/refs/{ref}\"],\n },\n gitignore: {\n getAllTemplates: [\"GET /gitignore/templates\"],\n getTemplate: [\"GET /gitignore/templates/{name}\"],\n },\n hostedCompute: {\n createNetworkConfigurationForOrg: [\n \"POST /orgs/{org}/settings/network-configurations\",\n ],\n deleteNetworkConfigurationFromOrg: [\n \"DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}\",\n ],\n getNetworkConfigurationForOrg: [\n \"GET /orgs/{org}/settings/network-configurations/{network_configuration_id}\",\n ],\n getNetworkSettingsForOrg: [\n \"GET /orgs/{org}/settings/network-settings/{network_settings_id}\",\n ],\n listNetworkConfigurationsForOrg: [\n \"GET /orgs/{org}/settings/network-configurations\",\n ],\n updateNetworkConfigurationForOrg: [\n \"PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}\",\n ],\n },\n interactions: {\n getRestrictionsForAuthenticatedUser: [\"GET /user/interaction-limits\"],\n getRestrictionsForOrg: [\"GET /orgs/{org}/interaction-limits\"],\n getRestrictionsForRepo: [\"GET /repos/{owner}/{repo}/interaction-limits\"],\n getRestrictionsForYourPublicRepos: [\n \"GET /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"getRestrictionsForAuthenticatedUser\"] },\n ],\n removeRestrictionsForAuthenticatedUser: [\"DELETE /user/interaction-limits\"],\n removeRestrictionsForOrg: [\"DELETE /orgs/{org}/interaction-limits\"],\n removeRestrictionsForRepo: [\n \"DELETE /repos/{owner}/{repo}/interaction-limits\",\n ],\n removeRestrictionsForYourPublicRepos: [\n \"DELETE /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"removeRestrictionsForAuthenticatedUser\"] },\n ],\n setRestrictionsForAuthenticatedUser: [\"PUT /user/interaction-limits\"],\n setRestrictionsForOrg: [\"PUT /orgs/{org}/interaction-limits\"],\n setRestrictionsForRepo: [\"PUT /repos/{owner}/{repo}/interaction-limits\"],\n setRestrictionsForYourPublicRepos: [\n \"PUT /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"setRestrictionsForAuthenticatedUser\"] },\n ],\n },\n issues: {\n addAssignees: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/assignees\",\n ],\n addBlockedByDependency: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by\",\n ],\n addLabels: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n addSubIssue: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues\",\n ],\n checkUserCanBeAssigned: [\"GET /repos/{owner}/{repo}/assignees/{assignee}\"],\n checkUserCanBeAssignedToIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}\",\n ],\n create: [\"POST /repos/{owner}/{repo}/issues\"],\n createComment: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/comments\",\n ],\n createLabel: [\"POST /repos/{owner}/{repo}/labels\"],\n createMilestone: [\"POST /repos/{owner}/{repo}/milestones\"],\n deleteComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}\",\n ],\n deleteLabel: [\"DELETE /repos/{owner}/{repo}/labels/{name}\"],\n deleteMilestone: [\n \"DELETE /repos/{owner}/{repo}/milestones/{milestone_number}\",\n ],\n get: [\"GET /repos/{owner}/{repo}/issues/{issue_number}\"],\n getComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n getEvent: [\"GET /repos/{owner}/{repo}/issues/events/{event_id}\"],\n getLabel: [\"GET /repos/{owner}/{repo}/labels/{name}\"],\n getMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n getParent: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/parent\"],\n list: [\"GET /issues\"],\n listAssignees: [\"GET /repos/{owner}/{repo}/assignees\"],\n listComments: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n listCommentsForRepo: [\"GET /repos/{owner}/{repo}/issues/comments\"],\n listDependenciesBlockedBy: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by\",\n ],\n listDependenciesBlocking: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking\",\n ],\n listEvents: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/events\"],\n listEventsForRepo: [\"GET /repos/{owner}/{repo}/issues/events\"],\n listEventsForTimeline: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\",\n ],\n listForAuthenticatedUser: [\"GET /user/issues\"],\n listForOrg: [\"GET /orgs/{org}/issues\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/issues\"],\n listLabelsForMilestone: [\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\",\n ],\n listLabelsForRepo: [\"GET /repos/{owner}/{repo}/labels\"],\n listLabelsOnIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n ],\n listMilestones: [\"GET /repos/{owner}/{repo}/milestones\"],\n listSubIssues: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues\",\n ],\n lock: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n removeAllLabels: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n ],\n removeAssignees: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees\",\n ],\n removeDependencyBlockedBy: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}\",\n ],\n removeLabel: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\",\n ],\n removeSubIssue: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue\",\n ],\n reprioritizeSubIssue: [\n \"PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority\",\n ],\n setLabels: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n unlock: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n update: [\"PATCH /repos/{owner}/{repo}/issues/{issue_number}\"],\n updateComment: [\"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n updateLabel: [\"PATCH /repos/{owner}/{repo}/labels/{name}\"],\n updateMilestone: [\n \"PATCH /repos/{owner}/{repo}/milestones/{milestone_number}\",\n ],\n },\n licenses: {\n get: [\"GET /licenses/{license}\"],\n getAllCommonlyUsed: [\"GET /licenses\"],\n getForRepo: [\"GET /repos/{owner}/{repo}/license\"],\n },\n markdown: {\n render: [\"POST /markdown\"],\n renderRaw: [\n \"POST /markdown/raw\",\n { headers: { \"content-type\": \"text/plain; charset=utf-8\" } },\n ],\n },\n meta: {\n get: [\"GET /meta\"],\n getAllVersions: [\"GET /versions\"],\n getOctocat: [\"GET /octocat\"],\n getZen: [\"GET /zen\"],\n root: [\"GET /\"],\n },\n migrations: {\n deleteArchiveForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/archive\",\n ],\n deleteArchiveForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/archive\",\n ],\n downloadArchiveForOrg: [\n \"GET /orgs/{org}/migrations/{migration_id}/archive\",\n ],\n getArchiveForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/archive\",\n ],\n getStatusForAuthenticatedUser: [\"GET /user/migrations/{migration_id}\"],\n getStatusForOrg: [\"GET /orgs/{org}/migrations/{migration_id}\"],\n listForAuthenticatedUser: [\"GET /user/migrations\"],\n listForOrg: [\"GET /orgs/{org}/migrations\"],\n listReposForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/repositories\",\n ],\n listReposForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/repositories\"],\n listReposForUser: [\n \"GET /user/migrations/{migration_id}/repositories\",\n {},\n { renamed: [\"migrations\", \"listReposForAuthenticatedUser\"] },\n ],\n startForAuthenticatedUser: [\"POST /user/migrations\"],\n startForOrg: [\"POST /orgs/{org}/migrations\"],\n unlockRepoForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock\",\n ],\n unlockRepoForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock\",\n ],\n },\n oidc: {\n getOidcCustomSubTemplateForOrg: [\n \"GET /orgs/{org}/actions/oidc/customization/sub\",\n ],\n updateOidcCustomSubTemplateForOrg: [\n \"PUT /orgs/{org}/actions/oidc/customization/sub\",\n ],\n },\n orgs: {\n addSecurityManagerTeam: [\n \"PUT /orgs/{org}/security-managers/teams/{team_slug}\",\n {},\n {\n deprecated:\n \"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team\",\n },\n ],\n assignTeamToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\",\n ],\n assignUserToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/users/{username}/{role_id}\",\n ],\n blockUser: [\"PUT /orgs/{org}/blocks/{username}\"],\n cancelInvitation: [\"DELETE /orgs/{org}/invitations/{invitation_id}\"],\n checkBlockedUser: [\"GET /orgs/{org}/blocks/{username}\"],\n checkMembershipForUser: [\"GET /orgs/{org}/members/{username}\"],\n checkPublicMembershipForUser: [\"GET /orgs/{org}/public_members/{username}\"],\n convertMemberToOutsideCollaborator: [\n \"PUT /orgs/{org}/outside_collaborators/{username}\",\n ],\n createArtifactStorageRecord: [\n \"POST /orgs/{org}/artifacts/metadata/storage-record\",\n ],\n createInvitation: [\"POST /orgs/{org}/invitations\"],\n createIssueType: [\"POST /orgs/{org}/issue-types\"],\n createWebhook: [\"POST /orgs/{org}/hooks\"],\n customPropertiesForOrgsCreateOrUpdateOrganizationValues: [\n \"PATCH /organizations/{org}/org-properties/values\",\n ],\n customPropertiesForOrgsGetOrganizationValues: [\n \"GET /organizations/{org}/org-properties/values\",\n ],\n customPropertiesForReposCreateOrUpdateOrganizationDefinition: [\n \"PUT /orgs/{org}/properties/schema/{custom_property_name}\",\n ],\n customPropertiesForReposCreateOrUpdateOrganizationDefinitions: [\n \"PATCH /orgs/{org}/properties/schema\",\n ],\n customPropertiesForReposCreateOrUpdateOrganizationValues: [\n \"PATCH /orgs/{org}/properties/values\",\n ],\n customPropertiesForReposDeleteOrganizationDefinition: [\n \"DELETE /orgs/{org}/properties/schema/{custom_property_name}\",\n ],\n customPropertiesForReposGetOrganizationDefinition: [\n \"GET /orgs/{org}/properties/schema/{custom_property_name}\",\n ],\n customPropertiesForReposGetOrganizationDefinitions: [\n \"GET /orgs/{org}/properties/schema\",\n ],\n customPropertiesForReposGetOrganizationValues: [\n \"GET /orgs/{org}/properties/values\",\n ],\n delete: [\"DELETE /orgs/{org}\"],\n deleteAttestationsBulk: [\"POST /orgs/{org}/attestations/delete-request\"],\n deleteAttestationsById: [\n \"DELETE /orgs/{org}/attestations/{attestation_id}\",\n ],\n deleteAttestationsBySubjectDigest: [\n \"DELETE /orgs/{org}/attestations/digest/{subject_digest}\",\n ],\n deleteIssueType: [\"DELETE /orgs/{org}/issue-types/{issue_type_id}\"],\n deleteWebhook: [\"DELETE /orgs/{org}/hooks/{hook_id}\"],\n disableSelectedRepositoryImmutableReleasesOrganization: [\n \"DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}\",\n ],\n enableSelectedRepositoryImmutableReleasesOrganization: [\n \"PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}\",\n ],\n get: [\"GET /orgs/{org}\"],\n getImmutableReleasesSettings: [\n \"GET /orgs/{org}/settings/immutable-releases\",\n ],\n getImmutableReleasesSettingsRepositories: [\n \"GET /orgs/{org}/settings/immutable-releases/repositories\",\n ],\n getMembershipForAuthenticatedUser: [\"GET /user/memberships/orgs/{org}\"],\n getMembershipForUser: [\"GET /orgs/{org}/memberships/{username}\"],\n getOrgRole: [\"GET /orgs/{org}/organization-roles/{role_id}\"],\n getOrgRulesetHistory: [\"GET /orgs/{org}/rulesets/{ruleset_id}/history\"],\n getOrgRulesetVersion: [\n \"GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}\",\n ],\n getWebhook: [\"GET /orgs/{org}/hooks/{hook_id}\"],\n getWebhookConfigForOrg: [\"GET /orgs/{org}/hooks/{hook_id}/config\"],\n getWebhookDelivery: [\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}\",\n ],\n list: [\"GET /organizations\"],\n listAppInstallations: [\"GET /orgs/{org}/installations\"],\n listArtifactStorageRecords: [\n \"GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records\",\n ],\n listAttestationRepositories: [\"GET /orgs/{org}/attestations/repositories\"],\n listAttestations: [\"GET /orgs/{org}/attestations/{subject_digest}\"],\n listAttestationsBulk: [\n \"POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}\",\n ],\n listBlockedUsers: [\"GET /orgs/{org}/blocks\"],\n listFailedInvitations: [\"GET /orgs/{org}/failed_invitations\"],\n listForAuthenticatedUser: [\"GET /user/orgs\"],\n listForUser: [\"GET /users/{username}/orgs\"],\n listInvitationTeams: [\"GET /orgs/{org}/invitations/{invitation_id}/teams\"],\n listIssueTypes: [\"GET /orgs/{org}/issue-types\"],\n listMembers: [\"GET /orgs/{org}/members\"],\n listMembershipsForAuthenticatedUser: [\"GET /user/memberships/orgs\"],\n listOrgRoleTeams: [\"GET /orgs/{org}/organization-roles/{role_id}/teams\"],\n listOrgRoleUsers: [\"GET /orgs/{org}/organization-roles/{role_id}/users\"],\n listOrgRoles: [\"GET /orgs/{org}/organization-roles\"],\n listOrganizationFineGrainedPermissions: [\n \"GET /orgs/{org}/organization-fine-grained-permissions\",\n ],\n listOutsideCollaborators: [\"GET /orgs/{org}/outside_collaborators\"],\n listPatGrantRepositories: [\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\",\n ],\n listPatGrantRequestRepositories: [\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\",\n ],\n listPatGrantRequests: [\"GET /orgs/{org}/personal-access-token-requests\"],\n listPatGrants: [\"GET /orgs/{org}/personal-access-tokens\"],\n listPendingInvitations: [\"GET /orgs/{org}/invitations\"],\n listPublicMembers: [\"GET /orgs/{org}/public_members\"],\n listSecurityManagerTeams: [\n \"GET /orgs/{org}/security-managers\",\n {},\n {\n deprecated:\n \"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams\",\n },\n ],\n listWebhookDeliveries: [\"GET /orgs/{org}/hooks/{hook_id}/deliveries\"],\n listWebhooks: [\"GET /orgs/{org}/hooks\"],\n pingWebhook: [\"POST /orgs/{org}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\",\n ],\n removeMember: [\"DELETE /orgs/{org}/members/{username}\"],\n removeMembershipForUser: [\"DELETE /orgs/{org}/memberships/{username}\"],\n removeOutsideCollaborator: [\n \"DELETE /orgs/{org}/outside_collaborators/{username}\",\n ],\n removePublicMembershipForAuthenticatedUser: [\n \"DELETE /orgs/{org}/public_members/{username}\",\n ],\n removeSecurityManagerTeam: [\n \"DELETE /orgs/{org}/security-managers/teams/{team_slug}\",\n {},\n {\n deprecated:\n \"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team\",\n },\n ],\n reviewPatGrantRequest: [\n \"POST /orgs/{org}/personal-access-token-requests/{pat_request_id}\",\n ],\n reviewPatGrantRequestsInBulk: [\n \"POST /orgs/{org}/personal-access-token-requests\",\n ],\n revokeAllOrgRolesTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}\",\n ],\n revokeAllOrgRolesUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}\",\n ],\n revokeOrgRoleTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\",\n ],\n revokeOrgRoleUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}\",\n ],\n setImmutableReleasesSettings: [\n \"PUT /orgs/{org}/settings/immutable-releases\",\n ],\n setImmutableReleasesSettingsRepositories: [\n \"PUT /orgs/{org}/settings/immutable-releases/repositories\",\n ],\n setMembershipForUser: [\"PUT /orgs/{org}/memberships/{username}\"],\n setPublicMembershipForAuthenticatedUser: [\n \"PUT /orgs/{org}/public_members/{username}\",\n ],\n unblockUser: [\"DELETE /orgs/{org}/blocks/{username}\"],\n update: [\"PATCH /orgs/{org}\"],\n updateIssueType: [\"PUT /orgs/{org}/issue-types/{issue_type_id}\"],\n updateMembershipForAuthenticatedUser: [\n \"PATCH /user/memberships/orgs/{org}\",\n ],\n updatePatAccess: [\"POST /orgs/{org}/personal-access-tokens/{pat_id}\"],\n updatePatAccesses: [\"POST /orgs/{org}/personal-access-tokens\"],\n updateWebhook: [\"PATCH /orgs/{org}/hooks/{hook_id}\"],\n updateWebhookConfigForOrg: [\"PATCH /orgs/{org}/hooks/{hook_id}/config\"],\n },\n packages: {\n deletePackageForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}\",\n ],\n deletePackageForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}\",\n ],\n deletePackageForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}\",\n ],\n deletePackageVersionForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n deletePackageVersionForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n deletePackageVersionForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n getAllPackageVersionsForAPackageOwnedByAnOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n {},\n { renamed: [\"packages\", \"getAllPackageVersionsForPackageOwnedByOrg\"] },\n ],\n getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n {},\n {\n renamed: [\n \"packages\",\n \"getAllPackageVersionsForPackageOwnedByAuthenticatedUser\",\n ],\n },\n ],\n getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n ],\n getAllPackageVersionsForPackageOwnedByOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n ],\n getAllPackageVersionsForPackageOwnedByUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions\",\n ],\n getPackageForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}\",\n ],\n getPackageForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}\",\n ],\n getPackageForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}\",\n ],\n getPackageVersionForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n getPackageVersionForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n getPackageVersionForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n listDockerMigrationConflictingPackagesForAuthenticatedUser: [\n \"GET /user/docker/conflicts\",\n ],\n listDockerMigrationConflictingPackagesForOrganization: [\n \"GET /orgs/{org}/docker/conflicts\",\n ],\n listDockerMigrationConflictingPackagesForUser: [\n \"GET /users/{username}/docker/conflicts\",\n ],\n listPackagesForAuthenticatedUser: [\"GET /user/packages\"],\n listPackagesForOrganization: [\"GET /orgs/{org}/packages\"],\n listPackagesForUser: [\"GET /users/{username}/packages\"],\n restorePackageForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/restore{?token}\",\n ],\n restorePackageForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}\",\n ],\n restorePackageForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}\",\n ],\n restorePackageVersionForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\",\n ],\n restorePackageVersionForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\",\n ],\n restorePackageVersionForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\",\n ],\n },\n privateRegistries: {\n createOrgPrivateRegistry: [\"POST /orgs/{org}/private-registries\"],\n deleteOrgPrivateRegistry: [\n \"DELETE /orgs/{org}/private-registries/{secret_name}\",\n ],\n getOrgPrivateRegistry: [\"GET /orgs/{org}/private-registries/{secret_name}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/private-registries/public-key\"],\n listOrgPrivateRegistries: [\"GET /orgs/{org}/private-registries\"],\n updateOrgPrivateRegistry: [\n \"PATCH /orgs/{org}/private-registries/{secret_name}\",\n ],\n },\n projects: {\n addItemForOrg: [\"POST /orgs/{org}/projectsV2/{project_number}/items\"],\n addItemForUser: [\n \"POST /users/{username}/projectsV2/{project_number}/items\",\n ],\n deleteItemForOrg: [\n \"DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}\",\n ],\n deleteItemForUser: [\n \"DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}\",\n ],\n getFieldForOrg: [\n \"GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}\",\n ],\n getFieldForUser: [\n \"GET /users/{username}/projectsV2/{project_number}/fields/{field_id}\",\n ],\n getForOrg: [\"GET /orgs/{org}/projectsV2/{project_number}\"],\n getForUser: [\"GET /users/{username}/projectsV2/{project_number}\"],\n getOrgItem: [\"GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}\"],\n getUserItem: [\n \"GET /users/{username}/projectsV2/{project_number}/items/{item_id}\",\n ],\n listFieldsForOrg: [\"GET /orgs/{org}/projectsV2/{project_number}/fields\"],\n listFieldsForUser: [\n \"GET /users/{username}/projectsV2/{project_number}/fields\",\n ],\n listForOrg: [\"GET /orgs/{org}/projectsV2\"],\n listForUser: [\"GET /users/{username}/projectsV2\"],\n listItemsForOrg: [\"GET /orgs/{org}/projectsV2/{project_number}/items\"],\n listItemsForUser: [\n \"GET /users/{username}/projectsV2/{project_number}/items\",\n ],\n updateItemForOrg: [\n \"PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}\",\n ],\n updateItemForUser: [\n \"PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}\",\n ],\n },\n pulls: {\n checkIfMerged: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n create: [\"POST /repos/{owner}/{repo}/pulls\"],\n createReplyForReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\",\n ],\n createReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n createReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n ],\n deletePendingReview: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\",\n ],\n deleteReviewComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}\",\n ],\n dismissReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals\",\n ],\n get: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}\"],\n getReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\",\n ],\n getReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n list: [\"GET /repos/{owner}/{repo}/pulls\"],\n listCommentsForReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\",\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\"],\n listFiles: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\"],\n listRequestedReviewers: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\",\n ],\n listReviewComments: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n ],\n listReviewCommentsForRepo: [\"GET /repos/{owner}/{repo}/pulls/comments\"],\n listReviews: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n merge: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n removeRequestedReviewers: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\",\n ],\n requestReviewers: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\",\n ],\n submitReview: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events\",\n ],\n update: [\"PATCH /repos/{owner}/{repo}/pulls/{pull_number}\"],\n updateBranch: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch\",\n ],\n updateReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\",\n ],\n updateReviewComment: [\n \"PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}\",\n ],\n },\n rateLimit: { get: [\"GET /rate_limit\"] },\n reactions: {\n createForCommitComment: [\n \"POST /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n ],\n createForIssue: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/reactions\",\n ],\n createForIssueComment: [\n \"POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n ],\n createForPullRequestReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n ],\n createForRelease: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n ],\n createForTeamDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n ],\n createForTeamDiscussionInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n ],\n deleteForCommitComment: [\n \"DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}\",\n ],\n deleteForIssue: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}\",\n ],\n deleteForIssueComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}\",\n ],\n deleteForPullRequestComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}\",\n ],\n deleteForRelease: [\n \"DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}\",\n ],\n deleteForTeamDiscussion: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}\",\n ],\n deleteForTeamDiscussionComment: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}\",\n ],\n listForCommitComment: [\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n ],\n listForIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\"],\n listForIssueComment: [\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n ],\n listForPullRequestReviewComment: [\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n ],\n listForRelease: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n ],\n listForTeamDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n ],\n listForTeamDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n ],\n },\n repos: {\n acceptInvitation: [\n \"PATCH /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"acceptInvitationForAuthenticatedUser\"] },\n ],\n acceptInvitationForAuthenticatedUser: [\n \"PATCH /user/repository_invitations/{invitation_id}\",\n ],\n addAppAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" },\n ],\n addCollaborator: [\"PUT /repos/{owner}/{repo}/collaborators/{username}\"],\n addStatusCheckContexts: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" },\n ],\n addTeamAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" },\n ],\n addUserAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" },\n ],\n cancelPagesDeployment: [\n \"POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel\",\n ],\n checkAutomatedSecurityFixes: [\n \"GET /repos/{owner}/{repo}/automated-security-fixes\",\n ],\n checkCollaborator: [\"GET /repos/{owner}/{repo}/collaborators/{username}\"],\n checkImmutableReleases: [\"GET /repos/{owner}/{repo}/immutable-releases\"],\n checkPrivateVulnerabilityReporting: [\n \"GET /repos/{owner}/{repo}/private-vulnerability-reporting\",\n ],\n checkVulnerabilityAlerts: [\n \"GET /repos/{owner}/{repo}/vulnerability-alerts\",\n ],\n codeownersErrors: [\"GET /repos/{owner}/{repo}/codeowners/errors\"],\n compareCommits: [\"GET /repos/{owner}/{repo}/compare/{base}...{head}\"],\n compareCommitsWithBasehead: [\n \"GET /repos/{owner}/{repo}/compare/{basehead}\",\n ],\n createAttestation: [\"POST /repos/{owner}/{repo}/attestations\"],\n createAutolink: [\"POST /repos/{owner}/{repo}/autolinks\"],\n createCommitComment: [\n \"POST /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n ],\n createCommitSignatureProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\",\n ],\n createCommitStatus: [\"POST /repos/{owner}/{repo}/statuses/{sha}\"],\n createDeployKey: [\"POST /repos/{owner}/{repo}/keys\"],\n createDeployment: [\"POST /repos/{owner}/{repo}/deployments\"],\n createDeploymentBranchPolicy: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n ],\n createDeploymentProtectionRule: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\",\n ],\n createDeploymentStatus: [\n \"POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n ],\n createDispatchEvent: [\"POST /repos/{owner}/{repo}/dispatches\"],\n createForAuthenticatedUser: [\"POST /user/repos\"],\n createFork: [\"POST /repos/{owner}/{repo}/forks\"],\n createInOrg: [\"POST /orgs/{org}/repos\"],\n createOrUpdateEnvironment: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}\",\n ],\n createOrUpdateFileContents: [\"PUT /repos/{owner}/{repo}/contents/{path}\"],\n createOrgRuleset: [\"POST /orgs/{org}/rulesets\"],\n createPagesDeployment: [\"POST /repos/{owner}/{repo}/pages/deployments\"],\n createPagesSite: [\"POST /repos/{owner}/{repo}/pages\"],\n createRelease: [\"POST /repos/{owner}/{repo}/releases\"],\n createRepoRuleset: [\"POST /repos/{owner}/{repo}/rulesets\"],\n createUsingTemplate: [\n \"POST /repos/{template_owner}/{template_repo}/generate\",\n ],\n createWebhook: [\"POST /repos/{owner}/{repo}/hooks\"],\n customPropertiesForReposCreateOrUpdateRepositoryValues: [\n \"PATCH /repos/{owner}/{repo}/properties/values\",\n ],\n customPropertiesForReposGetRepositoryValues: [\n \"GET /repos/{owner}/{repo}/properties/values\",\n ],\n declineInvitation: [\n \"DELETE /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"declineInvitationForAuthenticatedUser\"] },\n ],\n declineInvitationForAuthenticatedUser: [\n \"DELETE /user/repository_invitations/{invitation_id}\",\n ],\n delete: [\"DELETE /repos/{owner}/{repo}\"],\n deleteAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\",\n ],\n deleteAdminBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\",\n ],\n deleteAnEnvironment: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}\",\n ],\n deleteAutolink: [\"DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n deleteBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection\",\n ],\n deleteCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}\"],\n deleteCommitSignatureProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\",\n ],\n deleteDeployKey: [\"DELETE /repos/{owner}/{repo}/keys/{key_id}\"],\n deleteDeployment: [\n \"DELETE /repos/{owner}/{repo}/deployments/{deployment_id}\",\n ],\n deleteDeploymentBranchPolicy: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\",\n ],\n deleteFile: [\"DELETE /repos/{owner}/{repo}/contents/{path}\"],\n deleteInvitation: [\n \"DELETE /repos/{owner}/{repo}/invitations/{invitation_id}\",\n ],\n deleteOrgRuleset: [\"DELETE /orgs/{org}/rulesets/{ruleset_id}\"],\n deletePagesSite: [\"DELETE /repos/{owner}/{repo}/pages\"],\n deletePullRequestReviewProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\",\n ],\n deleteRelease: [\"DELETE /repos/{owner}/{repo}/releases/{release_id}\"],\n deleteReleaseAsset: [\n \"DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}\",\n ],\n deleteRepoRuleset: [\"DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n deleteWebhook: [\"DELETE /repos/{owner}/{repo}/hooks/{hook_id}\"],\n disableAutomatedSecurityFixes: [\n \"DELETE /repos/{owner}/{repo}/automated-security-fixes\",\n ],\n disableDeploymentProtectionRule: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\",\n ],\n disableImmutableReleases: [\n \"DELETE /repos/{owner}/{repo}/immutable-releases\",\n ],\n disablePrivateVulnerabilityReporting: [\n \"DELETE /repos/{owner}/{repo}/private-vulnerability-reporting\",\n ],\n disableVulnerabilityAlerts: [\n \"DELETE /repos/{owner}/{repo}/vulnerability-alerts\",\n ],\n downloadArchive: [\n \"GET /repos/{owner}/{repo}/zipball/{ref}\",\n {},\n { renamed: [\"repos\", \"downloadZipballArchive\"] },\n ],\n downloadTarballArchive: [\"GET /repos/{owner}/{repo}/tarball/{ref}\"],\n downloadZipballArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\"],\n enableAutomatedSecurityFixes: [\n \"PUT /repos/{owner}/{repo}/automated-security-fixes\",\n ],\n enableImmutableReleases: [\"PUT /repos/{owner}/{repo}/immutable-releases\"],\n enablePrivateVulnerabilityReporting: [\n \"PUT /repos/{owner}/{repo}/private-vulnerability-reporting\",\n ],\n enableVulnerabilityAlerts: [\n \"PUT /repos/{owner}/{repo}/vulnerability-alerts\",\n ],\n generateReleaseNotes: [\n \"POST /repos/{owner}/{repo}/releases/generate-notes\",\n ],\n get: [\"GET /repos/{owner}/{repo}\"],\n getAccessRestrictions: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\",\n ],\n getAdminBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\",\n ],\n getAllDeploymentProtectionRules: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\",\n ],\n getAllEnvironments: [\"GET /repos/{owner}/{repo}/environments\"],\n getAllStatusCheckContexts: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n ],\n getAllTopics: [\"GET /repos/{owner}/{repo}/topics\"],\n getAppsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n ],\n getAutolink: [\"GET /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n getBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}\"],\n getBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection\",\n ],\n getBranchRules: [\"GET /repos/{owner}/{repo}/rules/branches/{branch}\"],\n getClones: [\"GET /repos/{owner}/{repo}/traffic/clones\"],\n getCodeFrequencyStats: [\"GET /repos/{owner}/{repo}/stats/code_frequency\"],\n getCollaboratorPermissionLevel: [\n \"GET /repos/{owner}/{repo}/collaborators/{username}/permission\",\n ],\n getCombinedStatusForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/status\"],\n getCommit: [\"GET /repos/{owner}/{repo}/commits/{ref}\"],\n getCommitActivityStats: [\"GET /repos/{owner}/{repo}/stats/commit_activity\"],\n getCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}\"],\n getCommitSignatureProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\",\n ],\n getCommunityProfileMetrics: [\"GET /repos/{owner}/{repo}/community/profile\"],\n getContent: [\"GET /repos/{owner}/{repo}/contents/{path}\"],\n getContributorsStats: [\"GET /repos/{owner}/{repo}/stats/contributors\"],\n getCustomDeploymentProtectionRule: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\",\n ],\n getDeployKey: [\"GET /repos/{owner}/{repo}/keys/{key_id}\"],\n getDeployment: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n getDeploymentBranchPolicy: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\",\n ],\n getDeploymentStatus: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}\",\n ],\n getEnvironment: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}\",\n ],\n getLatestPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/latest\"],\n getLatestRelease: [\"GET /repos/{owner}/{repo}/releases/latest\"],\n getOrgRuleSuite: [\"GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}\"],\n getOrgRuleSuites: [\"GET /orgs/{org}/rulesets/rule-suites\"],\n getOrgRuleset: [\"GET /orgs/{org}/rulesets/{ruleset_id}\"],\n getOrgRulesets: [\"GET /orgs/{org}/rulesets\"],\n getPages: [\"GET /repos/{owner}/{repo}/pages\"],\n getPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/{build_id}\"],\n getPagesDeployment: [\n \"GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}\",\n ],\n getPagesHealthCheck: [\"GET /repos/{owner}/{repo}/pages/health\"],\n getParticipationStats: [\"GET /repos/{owner}/{repo}/stats/participation\"],\n getPullRequestReviewProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\",\n ],\n getPunchCardStats: [\"GET /repos/{owner}/{repo}/stats/punch_card\"],\n getReadme: [\"GET /repos/{owner}/{repo}/readme\"],\n getReadmeInDirectory: [\"GET /repos/{owner}/{repo}/readme/{dir}\"],\n getRelease: [\"GET /repos/{owner}/{repo}/releases/{release_id}\"],\n getReleaseAsset: [\"GET /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n getReleaseByTag: [\"GET /repos/{owner}/{repo}/releases/tags/{tag}\"],\n getRepoRuleSuite: [\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}\",\n ],\n getRepoRuleSuites: [\"GET /repos/{owner}/{repo}/rulesets/rule-suites\"],\n getRepoRuleset: [\"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n getRepoRulesetHistory: [\n \"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history\",\n ],\n getRepoRulesetVersion: [\n \"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}\",\n ],\n getRepoRulesets: [\"GET /repos/{owner}/{repo}/rulesets\"],\n getStatusChecksProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n ],\n getTeamsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n ],\n getTopPaths: [\"GET /repos/{owner}/{repo}/traffic/popular/paths\"],\n getTopReferrers: [\"GET /repos/{owner}/{repo}/traffic/popular/referrers\"],\n getUsersWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n ],\n getViews: [\"GET /repos/{owner}/{repo}/traffic/views\"],\n getWebhook: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}\"],\n getWebhookConfigForRepo: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/config\",\n ],\n getWebhookDelivery: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}\",\n ],\n listActivities: [\"GET /repos/{owner}/{repo}/activity\"],\n listAttestations: [\n \"GET /repos/{owner}/{repo}/attestations/{subject_digest}\",\n ],\n listAutolinks: [\"GET /repos/{owner}/{repo}/autolinks\"],\n listBranches: [\"GET /repos/{owner}/{repo}/branches\"],\n listBranchesForHeadCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head\",\n ],\n listCollaborators: [\"GET /repos/{owner}/{repo}/collaborators\"],\n listCommentsForCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n ],\n listCommitCommentsForRepo: [\"GET /repos/{owner}/{repo}/comments\"],\n listCommitStatusesForRef: [\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\",\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/commits\"],\n listContributors: [\"GET /repos/{owner}/{repo}/contributors\"],\n listCustomDeploymentRuleIntegrations: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\",\n ],\n listDeployKeys: [\"GET /repos/{owner}/{repo}/keys\"],\n listDeploymentBranchPolicies: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n ],\n listDeploymentStatuses: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n ],\n listDeployments: [\"GET /repos/{owner}/{repo}/deployments\"],\n listForAuthenticatedUser: [\"GET /user/repos\"],\n listForOrg: [\"GET /orgs/{org}/repos\"],\n listForUser: [\"GET /users/{username}/repos\"],\n listForks: [\"GET /repos/{owner}/{repo}/forks\"],\n listInvitations: [\"GET /repos/{owner}/{repo}/invitations\"],\n listInvitationsForAuthenticatedUser: [\"GET /user/repository_invitations\"],\n listLanguages: [\"GET /repos/{owner}/{repo}/languages\"],\n listPagesBuilds: [\"GET /repos/{owner}/{repo}/pages/builds\"],\n listPublic: [\"GET /repositories\"],\n listPullRequestsAssociatedWithCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\",\n ],\n listReleaseAssets: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\",\n ],\n listReleases: [\"GET /repos/{owner}/{repo}/releases\"],\n listTags: [\"GET /repos/{owner}/{repo}/tags\"],\n listTeams: [\"GET /repos/{owner}/{repo}/teams\"],\n listWebhookDeliveries: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\",\n ],\n listWebhooks: [\"GET /repos/{owner}/{repo}/hooks\"],\n merge: [\"POST /repos/{owner}/{repo}/merges\"],\n mergeUpstream: [\"POST /repos/{owner}/{repo}/merge-upstream\"],\n pingWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\",\n ],\n removeAppAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" },\n ],\n removeCollaborator: [\n \"DELETE /repos/{owner}/{repo}/collaborators/{username}\",\n ],\n removeStatusCheckContexts: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" },\n ],\n removeStatusCheckProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n ],\n removeTeamAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" },\n ],\n removeUserAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" },\n ],\n renameBranch: [\"POST /repos/{owner}/{repo}/branches/{branch}/rename\"],\n replaceAllTopics: [\"PUT /repos/{owner}/{repo}/topics\"],\n requestPagesBuild: [\"POST /repos/{owner}/{repo}/pages/builds\"],\n setAdminBranchProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\",\n ],\n setAppAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" },\n ],\n setStatusCheckContexts: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" },\n ],\n setTeamAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" },\n ],\n setUserAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" },\n ],\n testPushWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/tests\"],\n transfer: [\"POST /repos/{owner}/{repo}/transfer\"],\n update: [\"PATCH /repos/{owner}/{repo}\"],\n updateBranchProtection: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection\",\n ],\n updateCommitComment: [\"PATCH /repos/{owner}/{repo}/comments/{comment_id}\"],\n updateDeploymentBranchPolicy: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\",\n ],\n updateInformationAboutPagesSite: [\"PUT /repos/{owner}/{repo}/pages\"],\n updateInvitation: [\n \"PATCH /repos/{owner}/{repo}/invitations/{invitation_id}\",\n ],\n updateOrgRuleset: [\"PUT /orgs/{org}/rulesets/{ruleset_id}\"],\n updatePullRequestReviewProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\",\n ],\n updateRelease: [\"PATCH /repos/{owner}/{repo}/releases/{release_id}\"],\n updateReleaseAsset: [\n \"PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}\",\n ],\n updateRepoRuleset: [\"PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n updateStatusCheckPotection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n {},\n { renamed: [\"repos\", \"updateStatusCheckProtection\"] },\n ],\n updateStatusCheckProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n ],\n updateWebhook: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}\"],\n updateWebhookConfigForRepo: [\n \"PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config\",\n ],\n uploadReleaseAsset: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}\",\n { baseUrl: \"https://uploads.github.com\" },\n ],\n },\n search: {\n code: [\"GET /search/code\"],\n commits: [\"GET /search/commits\"],\n issuesAndPullRequests: [\"GET /search/issues\"],\n labels: [\"GET /search/labels\"],\n repos: [\"GET /search/repositories\"],\n topics: [\"GET /search/topics\"],\n users: [\"GET /search/users\"],\n },\n secretScanning: {\n createPushProtectionBypass: [\n \"POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses\",\n ],\n getAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\",\n ],\n getScanHistory: [\"GET /repos/{owner}/{repo}/secret-scanning/scan-history\"],\n listAlertsForOrg: [\"GET /orgs/{org}/secret-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts\"],\n listLocationsForAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\",\n ],\n listOrgPatternConfigs: [\n \"GET /orgs/{org}/secret-scanning/pattern-configurations\",\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\",\n ],\n updateOrgPatternConfigs: [\n \"PATCH /orgs/{org}/secret-scanning/pattern-configurations\",\n ],\n },\n securityAdvisories: {\n createFork: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks\",\n ],\n createPrivateVulnerabilityReport: [\n \"POST /repos/{owner}/{repo}/security-advisories/reports\",\n ],\n createRepositoryAdvisory: [\n \"POST /repos/{owner}/{repo}/security-advisories\",\n ],\n createRepositoryAdvisoryCveRequest: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve\",\n ],\n getGlobalAdvisory: [\"GET /advisories/{ghsa_id}\"],\n getRepositoryAdvisory: [\n \"GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}\",\n ],\n listGlobalAdvisories: [\"GET /advisories\"],\n listOrgRepositoryAdvisories: [\"GET /orgs/{org}/security-advisories\"],\n listRepositoryAdvisories: [\"GET /repos/{owner}/{repo}/security-advisories\"],\n updateRepositoryAdvisory: [\n \"PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}\",\n ],\n },\n teams: {\n addOrUpdateMembershipForUserInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/memberships/{username}\",\n ],\n addOrUpdateRepoPermissionsInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\",\n ],\n checkPermissionsForRepoInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\",\n ],\n create: [\"POST /orgs/{org}/teams\"],\n createDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n ],\n createDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions\"],\n deleteDiscussionCommentInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\",\n ],\n deleteDiscussionInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\",\n ],\n deleteInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}\"],\n getByName: [\"GET /orgs/{org}/teams/{team_slug}\"],\n getDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\",\n ],\n getDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\",\n ],\n getMembershipForUserInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/memberships/{username}\",\n ],\n list: [\"GET /orgs/{org}/teams\"],\n listChildInOrg: [\"GET /orgs/{org}/teams/{team_slug}/teams\"],\n listDiscussionCommentsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n ],\n listDiscussionsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions\"],\n listForAuthenticatedUser: [\"GET /user/teams\"],\n listMembersInOrg: [\"GET /orgs/{org}/teams/{team_slug}/members\"],\n listPendingInvitationsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/invitations\",\n ],\n listReposInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos\"],\n removeMembershipForUserInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}\",\n ],\n removeRepoInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\",\n ],\n updateDiscussionCommentInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\",\n ],\n updateDiscussionInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\",\n ],\n updateInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}\"],\n },\n users: {\n addEmailForAuthenticated: [\n \"POST /user/emails\",\n {},\n { renamed: [\"users\", \"addEmailForAuthenticatedUser\"] },\n ],\n addEmailForAuthenticatedUser: [\"POST /user/emails\"],\n addSocialAccountForAuthenticatedUser: [\"POST /user/social_accounts\"],\n block: [\"PUT /user/blocks/{username}\"],\n checkBlocked: [\"GET /user/blocks/{username}\"],\n checkFollowingForUser: [\"GET /users/{username}/following/{target_user}\"],\n checkPersonIsFollowedByAuthenticated: [\"GET /user/following/{username}\"],\n createGpgKeyForAuthenticated: [\n \"POST /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"createGpgKeyForAuthenticatedUser\"] },\n ],\n createGpgKeyForAuthenticatedUser: [\"POST /user/gpg_keys\"],\n createPublicSshKeyForAuthenticated: [\n \"POST /user/keys\",\n {},\n { renamed: [\"users\", \"createPublicSshKeyForAuthenticatedUser\"] },\n ],\n createPublicSshKeyForAuthenticatedUser: [\"POST /user/keys\"],\n createSshSigningKeyForAuthenticatedUser: [\"POST /user/ssh_signing_keys\"],\n deleteAttestationsBulk: [\n \"POST /users/{username}/attestations/delete-request\",\n ],\n deleteAttestationsById: [\n \"DELETE /users/{username}/attestations/{attestation_id}\",\n ],\n deleteAttestationsBySubjectDigest: [\n \"DELETE /users/{username}/attestations/digest/{subject_digest}\",\n ],\n deleteEmailForAuthenticated: [\n \"DELETE /user/emails\",\n {},\n { renamed: [\"users\", \"deleteEmailForAuthenticatedUser\"] },\n ],\n deleteEmailForAuthenticatedUser: [\"DELETE /user/emails\"],\n deleteGpgKeyForAuthenticated: [\n \"DELETE /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"deleteGpgKeyForAuthenticatedUser\"] },\n ],\n deleteGpgKeyForAuthenticatedUser: [\"DELETE /user/gpg_keys/{gpg_key_id}\"],\n deletePublicSshKeyForAuthenticated: [\n \"DELETE /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"deletePublicSshKeyForAuthenticatedUser\"] },\n ],\n deletePublicSshKeyForAuthenticatedUser: [\"DELETE /user/keys/{key_id}\"],\n deleteSocialAccountForAuthenticatedUser: [\"DELETE /user/social_accounts\"],\n deleteSshSigningKeyForAuthenticatedUser: [\n \"DELETE /user/ssh_signing_keys/{ssh_signing_key_id}\",\n ],\n follow: [\"PUT /user/following/{username}\"],\n getAuthenticated: [\"GET /user\"],\n getById: [\"GET /user/{account_id}\"],\n getByUsername: [\"GET /users/{username}\"],\n getContextForUser: [\"GET /users/{username}/hovercard\"],\n getGpgKeyForAuthenticated: [\n \"GET /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"getGpgKeyForAuthenticatedUser\"] },\n ],\n getGpgKeyForAuthenticatedUser: [\"GET /user/gpg_keys/{gpg_key_id}\"],\n getPublicSshKeyForAuthenticated: [\n \"GET /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"getPublicSshKeyForAuthenticatedUser\"] },\n ],\n getPublicSshKeyForAuthenticatedUser: [\"GET /user/keys/{key_id}\"],\n getSshSigningKeyForAuthenticatedUser: [\n \"GET /user/ssh_signing_keys/{ssh_signing_key_id}\",\n ],\n list: [\"GET /users\"],\n listAttestations: [\"GET /users/{username}/attestations/{subject_digest}\"],\n listAttestationsBulk: [\n \"POST /users/{username}/attestations/bulk-list{?per_page,before,after}\",\n ],\n listBlockedByAuthenticated: [\n \"GET /user/blocks\",\n {},\n { renamed: [\"users\", \"listBlockedByAuthenticatedUser\"] },\n ],\n listBlockedByAuthenticatedUser: [\"GET /user/blocks\"],\n listEmailsForAuthenticated: [\n \"GET /user/emails\",\n {},\n { renamed: [\"users\", \"listEmailsForAuthenticatedUser\"] },\n ],\n listEmailsForAuthenticatedUser: [\"GET /user/emails\"],\n listFollowedByAuthenticated: [\n \"GET /user/following\",\n {},\n { renamed: [\"users\", \"listFollowedByAuthenticatedUser\"] },\n ],\n listFollowedByAuthenticatedUser: [\"GET /user/following\"],\n listFollowersForAuthenticatedUser: [\"GET /user/followers\"],\n listFollowersForUser: [\"GET /users/{username}/followers\"],\n listFollowingForUser: [\"GET /users/{username}/following\"],\n listGpgKeysForAuthenticated: [\n \"GET /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"listGpgKeysForAuthenticatedUser\"] },\n ],\n listGpgKeysForAuthenticatedUser: [\"GET /user/gpg_keys\"],\n listGpgKeysForUser: [\"GET /users/{username}/gpg_keys\"],\n listPublicEmailsForAuthenticated: [\n \"GET /user/public_emails\",\n {},\n { renamed: [\"users\", \"listPublicEmailsForAuthenticatedUser\"] },\n ],\n listPublicEmailsForAuthenticatedUser: [\"GET /user/public_emails\"],\n listPublicKeysForUser: [\"GET /users/{username}/keys\"],\n listPublicSshKeysForAuthenticated: [\n \"GET /user/keys\",\n {},\n { renamed: [\"users\", \"listPublicSshKeysForAuthenticatedUser\"] },\n ],\n listPublicSshKeysForAuthenticatedUser: [\"GET /user/keys\"],\n listSocialAccountsForAuthenticatedUser: [\"GET /user/social_accounts\"],\n listSocialAccountsForUser: [\"GET /users/{username}/social_accounts\"],\n listSshSigningKeysForAuthenticatedUser: [\"GET /user/ssh_signing_keys\"],\n listSshSigningKeysForUser: [\"GET /users/{username}/ssh_signing_keys\"],\n setPrimaryEmailVisibilityForAuthenticated: [\n \"PATCH /user/email/visibility\",\n {},\n { renamed: [\"users\", \"setPrimaryEmailVisibilityForAuthenticatedUser\"] },\n ],\n setPrimaryEmailVisibilityForAuthenticatedUser: [\n \"PATCH /user/email/visibility\",\n ],\n unblock: [\"DELETE /user/blocks/{username}\"],\n unfollow: [\"DELETE /user/following/{username}\"],\n updateAuthenticated: [\"PATCH /user\"],\n },\n};\n\nexport default Endpoints;\n", "import type { Octokit } from \"@octokit/core\";\nimport type { EndpointOptions, RequestParameters, Route } from \"@octokit/types\";\nimport ENDPOINTS from \"./generated/endpoints.js\";\nimport type { RestEndpointMethods } from \"./generated/method-types.js\";\nimport type { EndpointDecorations } from \"./types.js\";\n\n// The following code was refactored in: https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/622\n// to optimise the runtime performance of Octokit initialization.\n//\n// This optimization involves two key changes:\n// 1. Pre-Computation: The endpoint methods are pre-computed once at module load\n// time instead of each invocation of `endpointsToMethods()`.\n// 2. Lazy initialization and caching: We use a Proxy for each scope to only\n// initialize methods that are actually called. This reduces runtime overhead\n// as the initialization involves deep merging of objects. The initialized\n// methods are then cached for future use.\n\nconst endpointMethodsMap = new Map();\nfor (const [scope, endpoints] of Object.entries(ENDPOINTS)) {\n for (const [methodName, endpoint] of Object.entries(endpoints)) {\n const [route, defaults, decorations] = endpoint;\n const [method, url] = route.split(/ /);\n const endpointDefaults = Object.assign(\n {\n method,\n url,\n },\n defaults,\n );\n\n if (!endpointMethodsMap.has(scope)) {\n endpointMethodsMap.set(scope, new Map());\n }\n\n endpointMethodsMap.get(scope).set(methodName, {\n scope,\n methodName,\n endpointDefaults,\n decorations,\n });\n }\n}\n\ntype ProxyTarget = {\n octokit: Octokit;\n scope: string;\n cache: Record<string, (...args: any[]) => any>;\n};\n\nconst handler = {\n has({ scope }: ProxyTarget, methodName: string) {\n return endpointMethodsMap.get(scope).has(methodName);\n },\n getOwnPropertyDescriptor(target: ProxyTarget, methodName: string) {\n return {\n value: this.get(target, methodName), // ensures method is in the cache\n configurable: true,\n writable: true,\n enumerable: true,\n };\n },\n defineProperty(\n target: ProxyTarget,\n methodName: string,\n descriptor: PropertyDescriptor,\n ) {\n Object.defineProperty(target.cache, methodName, descriptor);\n return true;\n },\n deleteProperty(target: ProxyTarget, methodName: string) {\n delete target.cache[methodName];\n return true;\n },\n ownKeys({ scope }: ProxyTarget) {\n return [...endpointMethodsMap.get(scope).keys()];\n },\n set(target: ProxyTarget, methodName: string, value: any) {\n return (target.cache[methodName] = value);\n },\n get({ octokit, scope, cache }: ProxyTarget, methodName: string) {\n if (cache[methodName]) {\n return cache[methodName];\n }\n\n const method = endpointMethodsMap.get(scope).get(methodName);\n if (!method) {\n return undefined;\n }\n\n const { endpointDefaults, decorations } = method;\n\n if (decorations) {\n cache[methodName] = decorate(\n octokit,\n scope,\n methodName,\n endpointDefaults,\n decorations,\n );\n } else {\n cache[methodName] = octokit.request.defaults(endpointDefaults);\n }\n\n return cache[methodName];\n },\n};\n\nexport function endpointsToMethods(octokit: Octokit): RestEndpointMethods {\n const newMethods = {} as { [key: string]: object };\n\n for (const scope of endpointMethodsMap.keys()) {\n newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);\n }\n\n return newMethods as RestEndpointMethods;\n}\n\nfunction decorate(\n octokit: Octokit,\n scope: string,\n methodName: string,\n defaults: EndpointOptions,\n decorations: EndpointDecorations,\n) {\n const requestWithDefaults = octokit.request.defaults(defaults);\n\n /* istanbul ignore next */\n function withDecorations(\n ...args: [Route, RequestParameters?] | [EndpointOptions]\n ) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n let options = requestWithDefaults.endpoint.merge(...args);\n\n // There are currently no other decorations than `.mapToData`\n if (decorations.mapToData) {\n options = Object.assign({}, options, {\n data: options[decorations.mapToData],\n [decorations.mapToData]: undefined,\n });\n return requestWithDefaults(options);\n }\n\n if (decorations.renamed) {\n const [newScope, newMethodName] = decorations.renamed;\n octokit.log.warn(\n `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`,\n );\n }\n if (decorations.deprecated) {\n octokit.log.warn(decorations.deprecated);\n }\n\n if (decorations.renamedParameters) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n const options = requestWithDefaults.endpoint.merge(...args);\n\n for (const [name, alias] of Object.entries(\n decorations.renamedParameters,\n )) {\n if (name in options) {\n octokit.log.warn(\n `\"${name}\" parameter is deprecated for \"octokit.${scope}.${methodName}()\". Use \"${alias}\" instead`,\n );\n if (!(alias in options)) {\n options[alias] = options[name];\n }\n delete options[name];\n }\n }\n return requestWithDefaults(options);\n }\n\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n return requestWithDefaults(...args);\n }\n return Object.assign(withDecorations, requestWithDefaults);\n}\n", "import type { Octokit } from \"@octokit/core\";\n\nexport type { RestEndpointMethodTypes } from \"./generated/parameters-and-response-types.js\";\nimport { VERSION } from \"./version.js\";\nimport type { Api } from \"./types.js\";\nimport { endpointsToMethods } from \"./endpoints-to-methods.js\";\n\n// Export the type for downstream users in order to fix a TypeScript error\n// The inferred type of 'Octokit' cannot be named without a reference to '../node_modules/@octokit/plugin-rest-endpoint-methods/dist-types/types.js'. This is likely not portable. A type annotation is necessary.\nexport type { Api };\n\nexport function restEndpointMethods(octokit: Octokit): Api {\n const api = endpointsToMethods(octokit);\n return {\n rest: api,\n };\n}\nrestEndpointMethods.VERSION = VERSION;\n\nexport function legacyRestEndpointMethods(octokit: Octokit): Api[\"rest\"] & Api {\n const api = endpointsToMethods(octokit);\n return {\n ...api,\n rest: api,\n };\n}\nlegacyRestEndpointMethods.VERSION = VERSION;\n", "const VERSION = \"22.0.1\";\nexport {\n VERSION\n};\n", "import { Octokit as Core } from \"@octokit/core\";\nimport { requestLog } from \"@octokit/plugin-request-log\";\nimport {\n paginateRest\n} from \"@octokit/plugin-paginate-rest\";\nimport { legacyRestEndpointMethods } from \"@octokit/plugin-rest-endpoint-methods\";\nimport { VERSION } from \"./version.js\";\nconst Octokit = Core.plugin(requestLog, legacyRestEndpointMethods, paginateRest).defaults(\n {\n userAgent: `octokit-rest.js/${VERSION}`\n }\n);\nexport {\n Octokit\n};\n", "/**\n * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support.\n * https://github.com/SGrondin/bottleneck\n */\n(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.Bottleneck = factory());\n}(this, (function () { 'use strict';\n\n\tvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\n\tfunction getCjsExportFromNamespace (n) {\n\t\treturn n && n['default'] || n;\n\t}\n\n\tvar load = function(received, defaults, onto = {}) {\n\t var k, ref, v;\n\t for (k in defaults) {\n\t v = defaults[k];\n\t onto[k] = (ref = received[k]) != null ? ref : v;\n\t }\n\t return onto;\n\t};\n\n\tvar overwrite = function(received, defaults, onto = {}) {\n\t var k, v;\n\t for (k in received) {\n\t v = received[k];\n\t if (defaults[k] !== void 0) {\n\t onto[k] = v;\n\t }\n\t }\n\t return onto;\n\t};\n\n\tvar parser = {\n\t\tload: load,\n\t\toverwrite: overwrite\n\t};\n\n\tvar DLList;\n\n\tDLList = class DLList {\n\t constructor(incr, decr) {\n\t this.incr = incr;\n\t this.decr = decr;\n\t this._first = null;\n\t this._last = null;\n\t this.length = 0;\n\t }\n\n\t push(value) {\n\t var node;\n\t this.length++;\n\t if (typeof this.incr === \"function\") {\n\t this.incr();\n\t }\n\t node = {\n\t value,\n\t prev: this._last,\n\t next: null\n\t };\n\t if (this._last != null) {\n\t this._last.next = node;\n\t this._last = node;\n\t } else {\n\t this._first = this._last = node;\n\t }\n\t return void 0;\n\t }\n\n\t shift() {\n\t var value;\n\t if (this._first == null) {\n\t return;\n\t } else {\n\t this.length--;\n\t if (typeof this.decr === \"function\") {\n\t this.decr();\n\t }\n\t }\n\t value = this._first.value;\n\t if ((this._first = this._first.next) != null) {\n\t this._first.prev = null;\n\t } else {\n\t this._last = null;\n\t }\n\t return value;\n\t }\n\n\t first() {\n\t if (this._first != null) {\n\t return this._first.value;\n\t }\n\t }\n\n\t getArray() {\n\t var node, ref, results;\n\t node = this._first;\n\t results = [];\n\t while (node != null) {\n\t results.push((ref = node, node = node.next, ref.value));\n\t }\n\t return results;\n\t }\n\n\t forEachShift(cb) {\n\t var node;\n\t node = this.shift();\n\t while (node != null) {\n\t (cb(node), node = this.shift());\n\t }\n\t return void 0;\n\t }\n\n\t debug() {\n\t var node, ref, ref1, ref2, results;\n\t node = this._first;\n\t results = [];\n\t while (node != null) {\n\t results.push((ref = node, node = node.next, {\n\t value: ref.value,\n\t prev: (ref1 = ref.prev) != null ? ref1.value : void 0,\n\t next: (ref2 = ref.next) != null ? ref2.value : void 0\n\t }));\n\t }\n\t return results;\n\t }\n\n\t};\n\n\tvar DLList_1 = DLList;\n\n\tvar Events;\n\n\tEvents = class Events {\n\t constructor(instance) {\n\t this.instance = instance;\n\t this._events = {};\n\t if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) {\n\t throw new Error(\"An Emitter already exists for this object\");\n\t }\n\t this.instance.on = (name, cb) => {\n\t return this._addListener(name, \"many\", cb);\n\t };\n\t this.instance.once = (name, cb) => {\n\t return this._addListener(name, \"once\", cb);\n\t };\n\t this.instance.removeAllListeners = (name = null) => {\n\t if (name != null) {\n\t return delete this._events[name];\n\t } else {\n\t return this._events = {};\n\t }\n\t };\n\t }\n\n\t _addListener(name, status, cb) {\n\t var base;\n\t if ((base = this._events)[name] == null) {\n\t base[name] = [];\n\t }\n\t this._events[name].push({cb, status});\n\t return this.instance;\n\t }\n\n\t listenerCount(name) {\n\t if (this._events[name] != null) {\n\t return this._events[name].length;\n\t } else {\n\t return 0;\n\t }\n\t }\n\n\t async trigger(name, ...args) {\n\t var e, promises;\n\t try {\n\t if (name !== \"debug\") {\n\t this.trigger(\"debug\", `Event triggered: ${name}`, args);\n\t }\n\t if (this._events[name] == null) {\n\t return;\n\t }\n\t this._events[name] = this._events[name].filter(function(listener) {\n\t return listener.status !== \"none\";\n\t });\n\t promises = this._events[name].map(async(listener) => {\n\t var e, returned;\n\t if (listener.status === \"none\") {\n\t return;\n\t }\n\t if (listener.status === \"once\") {\n\t listener.status = \"none\";\n\t }\n\t try {\n\t returned = typeof listener.cb === \"function\" ? listener.cb(...args) : void 0;\n\t if (typeof (returned != null ? returned.then : void 0) === \"function\") {\n\t return (await returned);\n\t } else {\n\t return returned;\n\t }\n\t } catch (error) {\n\t e = error;\n\t {\n\t this.trigger(\"error\", e);\n\t }\n\t return null;\n\t }\n\t });\n\t return ((await Promise.all(promises))).find(function(x) {\n\t return x != null;\n\t });\n\t } catch (error) {\n\t e = error;\n\t {\n\t this.trigger(\"error\", e);\n\t }\n\t return null;\n\t }\n\t }\n\n\t};\n\n\tvar Events_1 = Events;\n\n\tvar DLList$1, Events$1, Queues;\n\n\tDLList$1 = DLList_1;\n\n\tEvents$1 = Events_1;\n\n\tQueues = class Queues {\n\t constructor(num_priorities) {\n\t var i;\n\t this.Events = new Events$1(this);\n\t this._length = 0;\n\t this._lists = (function() {\n\t var j, ref, results;\n\t results = [];\n\t for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) {\n\t results.push(new DLList$1((() => {\n\t return this.incr();\n\t }), (() => {\n\t return this.decr();\n\t })));\n\t }\n\t return results;\n\t }).call(this);\n\t }\n\n\t incr() {\n\t if (this._length++ === 0) {\n\t return this.Events.trigger(\"leftzero\");\n\t }\n\t }\n\n\t decr() {\n\t if (--this._length === 0) {\n\t return this.Events.trigger(\"zero\");\n\t }\n\t }\n\n\t push(job) {\n\t return this._lists[job.options.priority].push(job);\n\t }\n\n\t queued(priority) {\n\t if (priority != null) {\n\t return this._lists[priority].length;\n\t } else {\n\t return this._length;\n\t }\n\t }\n\n\t shiftAll(fn) {\n\t return this._lists.forEach(function(list) {\n\t return list.forEachShift(fn);\n\t });\n\t }\n\n\t getFirst(arr = this._lists) {\n\t var j, len, list;\n\t for (j = 0, len = arr.length; j < len; j++) {\n\t list = arr[j];\n\t if (list.length > 0) {\n\t return list;\n\t }\n\t }\n\t return [];\n\t }\n\n\t shiftLastFrom(priority) {\n\t return this.getFirst(this._lists.slice(priority).reverse()).shift();\n\t }\n\n\t};\n\n\tvar Queues_1 = Queues;\n\n\tvar BottleneckError;\n\n\tBottleneckError = class BottleneckError extends Error {};\n\n\tvar BottleneckError_1 = BottleneckError;\n\n\tvar BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1;\n\n\tNUM_PRIORITIES = 10;\n\n\tDEFAULT_PRIORITY = 5;\n\n\tparser$1 = parser;\n\n\tBottleneckError$1 = BottleneckError_1;\n\n\tJob = class Job {\n\t constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) {\n\t this.task = task;\n\t this.args = args;\n\t this.rejectOnDrop = rejectOnDrop;\n\t this.Events = Events;\n\t this._states = _states;\n\t this.Promise = Promise;\n\t this.options = parser$1.load(options, jobDefaults);\n\t this.options.priority = this._sanitizePriority(this.options.priority);\n\t if (this.options.id === jobDefaults.id) {\n\t this.options.id = `${this.options.id}-${this._randomIndex()}`;\n\t }\n\t this.promise = new this.Promise((_resolve, _reject) => {\n\t this._resolve = _resolve;\n\t this._reject = _reject;\n\t });\n\t this.retryCount = 0;\n\t }\n\n\t _sanitizePriority(priority) {\n\t var sProperty;\n\t sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;\n\t if (sProperty < 0) {\n\t return 0;\n\t } else if (sProperty > NUM_PRIORITIES - 1) {\n\t return NUM_PRIORITIES - 1;\n\t } else {\n\t return sProperty;\n\t }\n\t }\n\n\t _randomIndex() {\n\t return Math.random().toString(36).slice(2);\n\t }\n\n\t doDrop({error, message = \"This job has been dropped by Bottleneck\"} = {}) {\n\t if (this._states.remove(this.options.id)) {\n\t if (this.rejectOnDrop) {\n\t this._reject(error != null ? error : new BottleneckError$1(message));\n\t }\n\t this.Events.trigger(\"dropped\", {args: this.args, options: this.options, task: this.task, promise: this.promise});\n\t return true;\n\t } else {\n\t return false;\n\t }\n\t }\n\n\t _assertStatus(expected) {\n\t var status;\n\t status = this._states.jobStatus(this.options.id);\n\t if (!(status === expected || (expected === \"DONE\" && status === null))) {\n\t throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`);\n\t }\n\t }\n\n\t doReceive() {\n\t this._states.start(this.options.id);\n\t return this.Events.trigger(\"received\", {args: this.args, options: this.options});\n\t }\n\n\t doQueue(reachedHWM, blocked) {\n\t this._assertStatus(\"RECEIVED\");\n\t this._states.next(this.options.id);\n\t return this.Events.trigger(\"queued\", {args: this.args, options: this.options, reachedHWM, blocked});\n\t }\n\n\t doRun() {\n\t if (this.retryCount === 0) {\n\t this._assertStatus(\"QUEUED\");\n\t this._states.next(this.options.id);\n\t } else {\n\t this._assertStatus(\"EXECUTING\");\n\t }\n\t return this.Events.trigger(\"scheduled\", {args: this.args, options: this.options});\n\t }\n\n\t async doExecute(chained, clearGlobalState, run, free) {\n\t var error, eventInfo, passed;\n\t if (this.retryCount === 0) {\n\t this._assertStatus(\"RUNNING\");\n\t this._states.next(this.options.id);\n\t } else {\n\t this._assertStatus(\"EXECUTING\");\n\t }\n\t eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};\n\t this.Events.trigger(\"executing\", eventInfo);\n\t try {\n\t passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args)));\n\t if (clearGlobalState()) {\n\t this.doDone(eventInfo);\n\t await free(this.options, eventInfo);\n\t this._assertStatus(\"DONE\");\n\t return this._resolve(passed);\n\t }\n\t } catch (error1) {\n\t error = error1;\n\t return this._onFailure(error, eventInfo, clearGlobalState, run, free);\n\t }\n\t }\n\n\t doExpire(clearGlobalState, run, free) {\n\t var error, eventInfo;\n\t if (this._states.jobStatus(this.options.id === \"RUNNING\")) {\n\t this._states.next(this.options.id);\n\t }\n\t this._assertStatus(\"EXECUTING\");\n\t eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};\n\t error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`);\n\t return this._onFailure(error, eventInfo, clearGlobalState, run, free);\n\t }\n\n\t async _onFailure(error, eventInfo, clearGlobalState, run, free) {\n\t var retry, retryAfter;\n\t if (clearGlobalState()) {\n\t retry = (await this.Events.trigger(\"failed\", error, eventInfo));\n\t if (retry != null) {\n\t retryAfter = ~~retry;\n\t this.Events.trigger(\"retry\", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo);\n\t this.retryCount++;\n\t return run(retryAfter);\n\t } else {\n\t this.doDone(eventInfo);\n\t await free(this.options, eventInfo);\n\t this._assertStatus(\"DONE\");\n\t return this._reject(error);\n\t }\n\t }\n\t }\n\n\t doDone(eventInfo) {\n\t this._assertStatus(\"EXECUTING\");\n\t this._states.next(this.options.id);\n\t return this.Events.trigger(\"done\", eventInfo);\n\t }\n\n\t};\n\n\tvar Job_1 = Job;\n\n\tvar BottleneckError$2, LocalDatastore, parser$2;\n\n\tparser$2 = parser;\n\n\tBottleneckError$2 = BottleneckError_1;\n\n\tLocalDatastore = class LocalDatastore {\n\t constructor(instance, storeOptions, storeInstanceOptions) {\n\t this.instance = instance;\n\t this.storeOptions = storeOptions;\n\t this.clientId = this.instance._randomIndex();\n\t parser$2.load(storeInstanceOptions, storeInstanceOptions, this);\n\t this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now();\n\t this._running = 0;\n\t this._done = 0;\n\t this._unblockTime = 0;\n\t this.ready = this.Promise.resolve();\n\t this.clients = {};\n\t this._startHeartbeat();\n\t }\n\n\t _startHeartbeat() {\n\t var base;\n\t if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) {\n\t return typeof (base = (this.heartbeat = setInterval(() => {\n\t var amount, incr, maximum, now, reservoir;\n\t now = Date.now();\n\t if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) {\n\t this._lastReservoirRefresh = now;\n\t this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount;\n\t this.instance._drainAll(this.computeCapacity());\n\t }\n\t if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) {\n\t ({\n\t reservoirIncreaseAmount: amount,\n\t reservoirIncreaseMaximum: maximum,\n\t reservoir\n\t } = this.storeOptions);\n\t this._lastReservoirIncrease = now;\n\t incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount;\n\t if (incr > 0) {\n\t this.storeOptions.reservoir += incr;\n\t return this.instance._drainAll(this.computeCapacity());\n\t }\n\t }\n\t }, this.heartbeatInterval))).unref === \"function\" ? base.unref() : void 0;\n\t } else {\n\t return clearInterval(this.heartbeat);\n\t }\n\t }\n\n\t async __publish__(message) {\n\t await this.yieldLoop();\n\t return this.instance.Events.trigger(\"message\", message.toString());\n\t }\n\n\t async __disconnect__(flush) {\n\t await this.yieldLoop();\n\t clearInterval(this.heartbeat);\n\t return this.Promise.resolve();\n\t }\n\n\t yieldLoop(t = 0) {\n\t return new this.Promise(function(resolve, reject) {\n\t return setTimeout(resolve, t);\n\t });\n\t }\n\n\t computePenalty() {\n\t var ref;\n\t return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000;\n\t }\n\n\t async __updateSettings__(options) {\n\t await this.yieldLoop();\n\t parser$2.overwrite(options, options, this.storeOptions);\n\t this._startHeartbeat();\n\t this.instance._drainAll(this.computeCapacity());\n\t return true;\n\t }\n\n\t async __running__() {\n\t await this.yieldLoop();\n\t return this._running;\n\t }\n\n\t async __queued__() {\n\t await this.yieldLoop();\n\t return this.instance.queued();\n\t }\n\n\t async __done__() {\n\t await this.yieldLoop();\n\t return this._done;\n\t }\n\n\t async __groupCheck__(time) {\n\t await this.yieldLoop();\n\t return (this._nextRequest + this.timeout) < time;\n\t }\n\n\t computeCapacity() {\n\t var maxConcurrent, reservoir;\n\t ({maxConcurrent, reservoir} = this.storeOptions);\n\t if ((maxConcurrent != null) && (reservoir != null)) {\n\t return Math.min(maxConcurrent - this._running, reservoir);\n\t } else if (maxConcurrent != null) {\n\t return maxConcurrent - this._running;\n\t } else if (reservoir != null) {\n\t return reservoir;\n\t } else {\n\t return null;\n\t }\n\t }\n\n\t conditionsCheck(weight) {\n\t var capacity;\n\t capacity = this.computeCapacity();\n\t return (capacity == null) || weight <= capacity;\n\t }\n\n\t async __incrementReservoir__(incr) {\n\t var reservoir;\n\t await this.yieldLoop();\n\t reservoir = this.storeOptions.reservoir += incr;\n\t this.instance._drainAll(this.computeCapacity());\n\t return reservoir;\n\t }\n\n\t async __currentReservoir__() {\n\t await this.yieldLoop();\n\t return this.storeOptions.reservoir;\n\t }\n\n\t isBlocked(now) {\n\t return this._unblockTime >= now;\n\t }\n\n\t check(weight, now) {\n\t return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0;\n\t }\n\n\t async __check__(weight) {\n\t var now;\n\t await this.yieldLoop();\n\t now = Date.now();\n\t return this.check(weight, now);\n\t }\n\n\t async __register__(index, weight, expiration) {\n\t var now, wait;\n\t await this.yieldLoop();\n\t now = Date.now();\n\t if (this.conditionsCheck(weight)) {\n\t this._running += weight;\n\t if (this.storeOptions.reservoir != null) {\n\t this.storeOptions.reservoir -= weight;\n\t }\n\t wait = Math.max(this._nextRequest - now, 0);\n\t this._nextRequest = now + wait + this.storeOptions.minTime;\n\t return {\n\t success: true,\n\t wait,\n\t reservoir: this.storeOptions.reservoir\n\t };\n\t } else {\n\t return {\n\t success: false\n\t };\n\t }\n\t }\n\n\t strategyIsBlock() {\n\t return this.storeOptions.strategy === 3;\n\t }\n\n\t async __submit__(queueLength, weight) {\n\t var blocked, now, reachedHWM;\n\t await this.yieldLoop();\n\t if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) {\n\t throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);\n\t }\n\t now = Date.now();\n\t reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now);\n\t blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now));\n\t if (blocked) {\n\t this._unblockTime = now + this.computePenalty();\n\t this._nextRequest = this._unblockTime + this.storeOptions.minTime;\n\t this.instance._dropAllQueued();\n\t }\n\t return {\n\t reachedHWM,\n\t blocked,\n\t strategy: this.storeOptions.strategy\n\t };\n\t }\n\n\t async __free__(index, weight) {\n\t await this.yieldLoop();\n\t this._running -= weight;\n\t this._done += weight;\n\t this.instance._drainAll(this.computeCapacity());\n\t return {\n\t running: this._running\n\t };\n\t }\n\n\t};\n\n\tvar LocalDatastore_1 = LocalDatastore;\n\n\tvar BottleneckError$3, States;\n\n\tBottleneckError$3 = BottleneckError_1;\n\n\tStates = class States {\n\t constructor(status1) {\n\t this.status = status1;\n\t this._jobs = {};\n\t this.counts = this.status.map(function() {\n\t return 0;\n\t });\n\t }\n\n\t next(id) {\n\t var current, next;\n\t current = this._jobs[id];\n\t next = current + 1;\n\t if ((current != null) && next < this.status.length) {\n\t this.counts[current]--;\n\t this.counts[next]++;\n\t return this._jobs[id]++;\n\t } else if (current != null) {\n\t this.counts[current]--;\n\t return delete this._jobs[id];\n\t }\n\t }\n\n\t start(id) {\n\t var initial;\n\t initial = 0;\n\t this._jobs[id] = initial;\n\t return this.counts[initial]++;\n\t }\n\n\t remove(id) {\n\t var current;\n\t current = this._jobs[id];\n\t if (current != null) {\n\t this.counts[current]--;\n\t delete this._jobs[id];\n\t }\n\t return current != null;\n\t }\n\n\t jobStatus(id) {\n\t var ref;\n\t return (ref = this.status[this._jobs[id]]) != null ? ref : null;\n\t }\n\n\t statusJobs(status) {\n\t var k, pos, ref, results, v;\n\t if (status != null) {\n\t pos = this.status.indexOf(status);\n\t if (pos < 0) {\n\t throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`);\n\t }\n\t ref = this._jobs;\n\t results = [];\n\t for (k in ref) {\n\t v = ref[k];\n\t if (v === pos) {\n\t results.push(k);\n\t }\n\t }\n\t return results;\n\t } else {\n\t return Object.keys(this._jobs);\n\t }\n\t }\n\n\t statusCounts() {\n\t return this.counts.reduce(((acc, v, i) => {\n\t acc[this.status[i]] = v;\n\t return acc;\n\t }), {});\n\t }\n\n\t};\n\n\tvar States_1 = States;\n\n\tvar DLList$2, Sync;\n\n\tDLList$2 = DLList_1;\n\n\tSync = class Sync {\n\t constructor(name, Promise) {\n\t this.schedule = this.schedule.bind(this);\n\t this.name = name;\n\t this.Promise = Promise;\n\t this._running = 0;\n\t this._queue = new DLList$2();\n\t }\n\n\t isEmpty() {\n\t return this._queue.length === 0;\n\t }\n\n\t async _tryToRun() {\n\t var args, cb, error, reject, resolve, returned, task;\n\t if ((this._running < 1) && this._queue.length > 0) {\n\t this._running++;\n\t ({task, args, resolve, reject} = this._queue.shift());\n\t cb = (await (async function() {\n\t try {\n\t returned = (await task(...args));\n\t return function() {\n\t return resolve(returned);\n\t };\n\t } catch (error1) {\n\t error = error1;\n\t return function() {\n\t return reject(error);\n\t };\n\t }\n\t })());\n\t this._running--;\n\t this._tryToRun();\n\t return cb();\n\t }\n\t }\n\n\t schedule(task, ...args) {\n\t var promise, reject, resolve;\n\t resolve = reject = null;\n\t promise = new this.Promise(function(_resolve, _reject) {\n\t resolve = _resolve;\n\t return reject = _reject;\n\t });\n\t this._queue.push({task, args, resolve, reject});\n\t this._tryToRun();\n\t return promise;\n\t }\n\n\t};\n\n\tvar Sync_1 = Sync;\n\n\tvar version = \"2.19.5\";\n\tvar version$1 = {\n\t\tversion: version\n\t};\n\n\tvar version$2 = /*#__PURE__*/Object.freeze({\n\t\tversion: version,\n\t\tdefault: version$1\n\t});\n\n\tvar require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3;\n\n\tparser$3 = parser;\n\n\tEvents$2 = Events_1;\n\n\tRedisConnection$1 = require$$2;\n\n\tIORedisConnection$1 = require$$3;\n\n\tScripts$1 = require$$4;\n\n\tGroup = (function() {\n\t class Group {\n\t constructor(limiterOptions = {}) {\n\t this.deleteKey = this.deleteKey.bind(this);\n\t this.limiterOptions = limiterOptions;\n\t parser$3.load(this.limiterOptions, this.defaults, this);\n\t this.Events = new Events$2(this);\n\t this.instances = {};\n\t this.Bottleneck = Bottleneck_1;\n\t this._startAutoCleanup();\n\t this.sharedConnection = this.connection != null;\n\t if (this.connection == null) {\n\t if (this.limiterOptions.datastore === \"redis\") {\n\t this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));\n\t } else if (this.limiterOptions.datastore === \"ioredis\") {\n\t this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));\n\t }\n\t }\n\t }\n\n\t key(key = \"\") {\n\t var ref;\n\t return (ref = this.instances[key]) != null ? ref : (() => {\n\t var limiter;\n\t limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, {\n\t id: `${this.id}-${key}`,\n\t timeout: this.timeout,\n\t connection: this.connection\n\t }));\n\t this.Events.trigger(\"created\", limiter, key);\n\t return limiter;\n\t })();\n\t }\n\n\t async deleteKey(key = \"\") {\n\t var deleted, instance;\n\t instance = this.instances[key];\n\t if (this.connection) {\n\t deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)]));\n\t }\n\t if (instance != null) {\n\t delete this.instances[key];\n\t await instance.disconnect();\n\t }\n\t return (instance != null) || deleted > 0;\n\t }\n\n\t limiters() {\n\t var k, ref, results, v;\n\t ref = this.instances;\n\t results = [];\n\t for (k in ref) {\n\t v = ref[k];\n\t results.push({\n\t key: k,\n\t limiter: v\n\t });\n\t }\n\t return results;\n\t }\n\n\t keys() {\n\t return Object.keys(this.instances);\n\t }\n\n\t async clusterKeys() {\n\t var cursor, end, found, i, k, keys, len, next, start;\n\t if (this.connection == null) {\n\t return this.Promise.resolve(this.keys());\n\t }\n\t keys = [];\n\t cursor = null;\n\t start = `b_${this.id}-`.length;\n\t end = \"_settings\".length;\n\t while (cursor !== 0) {\n\t [next, found] = (await this.connection.__runCommand__([\"scan\", cursor != null ? cursor : 0, \"match\", `b_${this.id}-*_settings`, \"count\", 10000]));\n\t cursor = ~~next;\n\t for (i = 0, len = found.length; i < len; i++) {\n\t k = found[i];\n\t keys.push(k.slice(start, -end));\n\t }\n\t }\n\t return keys;\n\t }\n\n\t _startAutoCleanup() {\n\t var base;\n\t clearInterval(this.interval);\n\t return typeof (base = (this.interval = setInterval(async() => {\n\t var e, k, ref, results, time, v;\n\t time = Date.now();\n\t ref = this.instances;\n\t results = [];\n\t for (k in ref) {\n\t v = ref[k];\n\t try {\n\t if ((await v._store.__groupCheck__(time))) {\n\t results.push(this.deleteKey(k));\n\t } else {\n\t results.push(void 0);\n\t }\n\t } catch (error) {\n\t e = error;\n\t results.push(v.Events.trigger(\"error\", e));\n\t }\n\t }\n\t return results;\n\t }, this.timeout / 2))).unref === \"function\" ? base.unref() : void 0;\n\t }\n\n\t updateSettings(options = {}) {\n\t parser$3.overwrite(options, this.defaults, this);\n\t parser$3.overwrite(options, options, this.limiterOptions);\n\t if (options.timeout != null) {\n\t return this._startAutoCleanup();\n\t }\n\t }\n\n\t disconnect(flush = true) {\n\t var ref;\n\t if (!this.sharedConnection) {\n\t return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;\n\t }\n\t }\n\n\t }\n\t Group.prototype.defaults = {\n\t timeout: 1000 * 60 * 5,\n\t connection: null,\n\t Promise: Promise,\n\t id: \"group-key\"\n\t };\n\n\t return Group;\n\n\t}).call(commonjsGlobal);\n\n\tvar Group_1 = Group;\n\n\tvar Batcher, Events$3, parser$4;\n\n\tparser$4 = parser;\n\n\tEvents$3 = Events_1;\n\n\tBatcher = (function() {\n\t class Batcher {\n\t constructor(options = {}) {\n\t this.options = options;\n\t parser$4.load(this.options, this.defaults, this);\n\t this.Events = new Events$3(this);\n\t this._arr = [];\n\t this._resetPromise();\n\t this._lastFlush = Date.now();\n\t }\n\n\t _resetPromise() {\n\t return this._promise = new this.Promise((res, rej) => {\n\t return this._resolve = res;\n\t });\n\t }\n\n\t _flush() {\n\t clearTimeout(this._timeout);\n\t this._lastFlush = Date.now();\n\t this._resolve();\n\t this.Events.trigger(\"batch\", this._arr);\n\t this._arr = [];\n\t return this._resetPromise();\n\t }\n\n\t add(data) {\n\t var ret;\n\t this._arr.push(data);\n\t ret = this._promise;\n\t if (this._arr.length === this.maxSize) {\n\t this._flush();\n\t } else if ((this.maxTime != null) && this._arr.length === 1) {\n\t this._timeout = setTimeout(() => {\n\t return this._flush();\n\t }, this.maxTime);\n\t }\n\t return ret;\n\t }\n\n\t }\n\t Batcher.prototype.defaults = {\n\t maxTime: null,\n\t maxSize: null,\n\t Promise: Promise\n\t };\n\n\t return Batcher;\n\n\t}).call(commonjsGlobal);\n\n\tvar Batcher_1 = Batcher;\n\n\tvar require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar require$$8 = getCjsExportFromNamespace(version$2);\n\n\tvar Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5,\n\t splice = [].splice;\n\n\tNUM_PRIORITIES$1 = 10;\n\n\tDEFAULT_PRIORITY$1 = 5;\n\n\tparser$5 = parser;\n\n\tQueues$1 = Queues_1;\n\n\tJob$1 = Job_1;\n\n\tLocalDatastore$1 = LocalDatastore_1;\n\n\tRedisDatastore$1 = require$$4$1;\n\n\tEvents$4 = Events_1;\n\n\tStates$1 = States_1;\n\n\tSync$1 = Sync_1;\n\n\tBottleneck = (function() {\n\t class Bottleneck {\n\t constructor(options = {}, ...invalid) {\n\t var storeInstanceOptions, storeOptions;\n\t this._addToQueue = this._addToQueue.bind(this);\n\t this._validateOptions(options, invalid);\n\t parser$5.load(options, this.instanceDefaults, this);\n\t this._queues = new Queues$1(NUM_PRIORITIES$1);\n\t this._scheduled = {};\n\t this._states = new States$1([\"RECEIVED\", \"QUEUED\", \"RUNNING\", \"EXECUTING\"].concat(this.trackDoneStatus ? [\"DONE\"] : []));\n\t this._limiter = null;\n\t this.Events = new Events$4(this);\n\t this._submitLock = new Sync$1(\"submit\", this.Promise);\n\t this._registerLock = new Sync$1(\"register\", this.Promise);\n\t storeOptions = parser$5.load(options, this.storeDefaults, {});\n\t this._store = (function() {\n\t if (this.datastore === \"redis\" || this.datastore === \"ioredis\" || (this.connection != null)) {\n\t storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {});\n\t return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);\n\t } else if (this.datastore === \"local\") {\n\t storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {});\n\t return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);\n\t } else {\n\t throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`);\n\t }\n\t }).call(this);\n\t this._queues.on(\"leftzero\", () => {\n\t var ref;\n\t return (ref = this._store.heartbeat) != null ? typeof ref.ref === \"function\" ? ref.ref() : void 0 : void 0;\n\t });\n\t this._queues.on(\"zero\", () => {\n\t var ref;\n\t return (ref = this._store.heartbeat) != null ? typeof ref.unref === \"function\" ? ref.unref() : void 0 : void 0;\n\t });\n\t }\n\n\t _validateOptions(options, invalid) {\n\t if (!((options != null) && typeof options === \"object\" && invalid.length === 0)) {\n\t throw new Bottleneck.prototype.BottleneckError(\"Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.\");\n\t }\n\t }\n\n\t ready() {\n\t return this._store.ready;\n\t }\n\n\t clients() {\n\t return this._store.clients;\n\t }\n\n\t channel() {\n\t return `b_${this.id}`;\n\t }\n\n\t channel_client() {\n\t return `b_${this.id}_${this._store.clientId}`;\n\t }\n\n\t publish(message) {\n\t return this._store.__publish__(message);\n\t }\n\n\t disconnect(flush = true) {\n\t return this._store.__disconnect__(flush);\n\t }\n\n\t chain(_limiter) {\n\t this._limiter = _limiter;\n\t return this;\n\t }\n\n\t queued(priority) {\n\t return this._queues.queued(priority);\n\t }\n\n\t clusterQueued() {\n\t return this._store.__queued__();\n\t }\n\n\t empty() {\n\t return this.queued() === 0 && this._submitLock.isEmpty();\n\t }\n\n\t running() {\n\t return this._store.__running__();\n\t }\n\n\t done() {\n\t return this._store.__done__();\n\t }\n\n\t jobStatus(id) {\n\t return this._states.jobStatus(id);\n\t }\n\n\t jobs(status) {\n\t return this._states.statusJobs(status);\n\t }\n\n\t counts() {\n\t return this._states.statusCounts();\n\t }\n\n\t _randomIndex() {\n\t return Math.random().toString(36).slice(2);\n\t }\n\n\t check(weight = 1) {\n\t return this._store.__check__(weight);\n\t }\n\n\t _clearGlobalState(index) {\n\t if (this._scheduled[index] != null) {\n\t clearTimeout(this._scheduled[index].expiration);\n\t delete this._scheduled[index];\n\t return true;\n\t } else {\n\t return false;\n\t }\n\t }\n\n\t async _free(index, job, options, eventInfo) {\n\t var e, running;\n\t try {\n\t ({running} = (await this._store.__free__(index, options.weight)));\n\t this.Events.trigger(\"debug\", `Freed ${options.id}`, eventInfo);\n\t if (running === 0 && this.empty()) {\n\t return this.Events.trigger(\"idle\");\n\t }\n\t } catch (error1) {\n\t e = error1;\n\t return this.Events.trigger(\"error\", e);\n\t }\n\t }\n\n\t _run(index, job, wait) {\n\t var clearGlobalState, free, run;\n\t job.doRun();\n\t clearGlobalState = this._clearGlobalState.bind(this, index);\n\t run = this._run.bind(this, index, job);\n\t free = this._free.bind(this, index, job);\n\t return this._scheduled[index] = {\n\t timeout: setTimeout(() => {\n\t return job.doExecute(this._limiter, clearGlobalState, run, free);\n\t }, wait),\n\t expiration: job.options.expiration != null ? setTimeout(function() {\n\t return job.doExpire(clearGlobalState, run, free);\n\t }, wait + job.options.expiration) : void 0,\n\t job: job\n\t };\n\t }\n\n\t _drainOne(capacity) {\n\t return this._registerLock.schedule(() => {\n\t var args, index, next, options, queue;\n\t if (this.queued() === 0) {\n\t return this.Promise.resolve(null);\n\t }\n\t queue = this._queues.getFirst();\n\t ({options, args} = next = queue.first());\n\t if ((capacity != null) && options.weight > capacity) {\n\t return this.Promise.resolve(null);\n\t }\n\t this.Events.trigger(\"debug\", `Draining ${options.id}`, {args, options});\n\t index = this._randomIndex();\n\t return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => {\n\t var empty;\n\t this.Events.trigger(\"debug\", `Drained ${options.id}`, {success, args, options});\n\t if (success) {\n\t queue.shift();\n\t empty = this.empty();\n\t if (empty) {\n\t this.Events.trigger(\"empty\");\n\t }\n\t if (reservoir === 0) {\n\t this.Events.trigger(\"depleted\", empty);\n\t }\n\t this._run(index, next, wait);\n\t return this.Promise.resolve(options.weight);\n\t } else {\n\t return this.Promise.resolve(null);\n\t }\n\t });\n\t });\n\t }\n\n\t _drainAll(capacity, total = 0) {\n\t return this._drainOne(capacity).then((drained) => {\n\t var newCapacity;\n\t if (drained != null) {\n\t newCapacity = capacity != null ? capacity - drained : capacity;\n\t return this._drainAll(newCapacity, total + drained);\n\t } else {\n\t return this.Promise.resolve(total);\n\t }\n\t }).catch((e) => {\n\t return this.Events.trigger(\"error\", e);\n\t });\n\t }\n\n\t _dropAllQueued(message) {\n\t return this._queues.shiftAll(function(job) {\n\t return job.doDrop({message});\n\t });\n\t }\n\n\t stop(options = {}) {\n\t var done, waitForExecuting;\n\t options = parser$5.load(options, this.stopDefaults);\n\t waitForExecuting = (at) => {\n\t var finished;\n\t finished = () => {\n\t var counts;\n\t counts = this._states.counts;\n\t return (counts[0] + counts[1] + counts[2] + counts[3]) === at;\n\t };\n\t return new this.Promise((resolve, reject) => {\n\t if (finished()) {\n\t return resolve();\n\t } else {\n\t return this.on(\"done\", () => {\n\t if (finished()) {\n\t this.removeAllListeners(\"done\");\n\t return resolve();\n\t }\n\t });\n\t }\n\t });\n\t };\n\t done = options.dropWaitingJobs ? (this._run = function(index, next) {\n\t return next.doDrop({\n\t message: options.dropErrorMessage\n\t });\n\t }, this._drainOne = () => {\n\t return this.Promise.resolve(null);\n\t }, this._registerLock.schedule(() => {\n\t return this._submitLock.schedule(() => {\n\t var k, ref, v;\n\t ref = this._scheduled;\n\t for (k in ref) {\n\t v = ref[k];\n\t if (this.jobStatus(v.job.options.id) === \"RUNNING\") {\n\t clearTimeout(v.timeout);\n\t clearTimeout(v.expiration);\n\t v.job.doDrop({\n\t message: options.dropErrorMessage\n\t });\n\t }\n\t }\n\t this._dropAllQueued(options.dropErrorMessage);\n\t return waitForExecuting(0);\n\t });\n\t })) : this.schedule({\n\t priority: NUM_PRIORITIES$1 - 1,\n\t weight: 0\n\t }, () => {\n\t return waitForExecuting(1);\n\t });\n\t this._receive = function(job) {\n\t return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage));\n\t };\n\t this.stop = () => {\n\t return this.Promise.reject(new Bottleneck.prototype.BottleneckError(\"stop() has already been called\"));\n\t };\n\t return done;\n\t }\n\n\t async _addToQueue(job) {\n\t var args, blocked, error, options, reachedHWM, shifted, strategy;\n\t ({args, options} = job);\n\t try {\n\t ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight)));\n\t } catch (error1) {\n\t error = error1;\n\t this.Events.trigger(\"debug\", `Could not queue ${options.id}`, {args, options, error});\n\t job.doDrop({error});\n\t return false;\n\t }\n\t if (blocked) {\n\t job.doDrop();\n\t return true;\n\t } else if (reachedHWM) {\n\t shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;\n\t if (shifted != null) {\n\t shifted.doDrop();\n\t }\n\t if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) {\n\t if (shifted == null) {\n\t job.doDrop();\n\t }\n\t return reachedHWM;\n\t }\n\t }\n\t job.doQueue(reachedHWM, blocked);\n\t this._queues.push(job);\n\t await this._drainAll();\n\t return reachedHWM;\n\t }\n\n\t _receive(job) {\n\t if (this._states.jobStatus(job.options.id) != null) {\n\t job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`));\n\t return false;\n\t } else {\n\t job.doReceive();\n\t return this._submitLock.schedule(this._addToQueue, job);\n\t }\n\t }\n\n\t submit(...args) {\n\t var cb, fn, job, options, ref, ref1, task;\n\t if (typeof args[0] === \"function\") {\n\t ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1);\n\t options = parser$5.load({}, this.jobDefaults);\n\t } else {\n\t ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1);\n\t options = parser$5.load(options, this.jobDefaults);\n\t }\n\t task = (...args) => {\n\t return new this.Promise(function(resolve, reject) {\n\t return fn(...args, function(...args) {\n\t return (args[0] != null ? reject : resolve)(args);\n\t });\n\t });\n\t };\n\t job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);\n\t job.promise.then(function(args) {\n\t return typeof cb === \"function\" ? cb(...args) : void 0;\n\t }).catch(function(args) {\n\t if (Array.isArray(args)) {\n\t return typeof cb === \"function\" ? cb(...args) : void 0;\n\t } else {\n\t return typeof cb === \"function\" ? cb(args) : void 0;\n\t }\n\t });\n\t return this._receive(job);\n\t }\n\n\t schedule(...args) {\n\t var job, options, task;\n\t if (typeof args[0] === \"function\") {\n\t [task, ...args] = args;\n\t options = {};\n\t } else {\n\t [options, task, ...args] = args;\n\t }\n\t job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);\n\t this._receive(job);\n\t return job.promise;\n\t }\n\n\t wrap(fn) {\n\t var schedule, wrapped;\n\t schedule = this.schedule.bind(this);\n\t wrapped = function(...args) {\n\t return schedule(fn.bind(this), ...args);\n\t };\n\t wrapped.withOptions = function(options, ...args) {\n\t return schedule(options, fn, ...args);\n\t };\n\t return wrapped;\n\t }\n\n\t async updateSettings(options = {}) {\n\t await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults));\n\t parser$5.overwrite(options, this.instanceDefaults, this);\n\t return this;\n\t }\n\n\t currentReservoir() {\n\t return this._store.__currentReservoir__();\n\t }\n\n\t incrementReservoir(incr = 0) {\n\t return this._store.__incrementReservoir__(incr);\n\t }\n\n\t }\n\t Bottleneck.default = Bottleneck;\n\n\t Bottleneck.Events = Events$4;\n\n\t Bottleneck.version = Bottleneck.prototype.version = require$$8.version;\n\n\t Bottleneck.strategy = Bottleneck.prototype.strategy = {\n\t LEAK: 1,\n\t OVERFLOW: 2,\n\t OVERFLOW_PRIORITY: 4,\n\t BLOCK: 3\n\t };\n\n\t Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;\n\n\t Bottleneck.Group = Bottleneck.prototype.Group = Group_1;\n\n\t Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2;\n\n\t Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3;\n\n\t Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;\n\n\t Bottleneck.prototype.jobDefaults = {\n\t priority: DEFAULT_PRIORITY$1,\n\t weight: 1,\n\t expiration: null,\n\t id: \"<no-id>\"\n\t };\n\n\t Bottleneck.prototype.storeDefaults = {\n\t maxConcurrent: null,\n\t minTime: 0,\n\t highWater: null,\n\t strategy: Bottleneck.prototype.strategy.LEAK,\n\t penalty: null,\n\t reservoir: null,\n\t reservoirRefreshInterval: null,\n\t reservoirRefreshAmount: null,\n\t reservoirIncreaseInterval: null,\n\t reservoirIncreaseAmount: null,\n\t reservoirIncreaseMaximum: null\n\t };\n\n\t Bottleneck.prototype.localStoreDefaults = {\n\t Promise: Promise,\n\t timeout: null,\n\t heartbeatInterval: 250\n\t };\n\n\t Bottleneck.prototype.redisStoreDefaults = {\n\t Promise: Promise,\n\t timeout: null,\n\t heartbeatInterval: 5000,\n\t clientTimeout: 10000,\n\t Redis: null,\n\t clientOptions: {},\n\t clusterNodes: null,\n\t clearDatastore: false,\n\t connection: null\n\t };\n\n\t Bottleneck.prototype.instanceDefaults = {\n\t datastore: \"local\",\n\t connection: null,\n\t id: \"<no-id>\",\n\t rejectOnDrop: true,\n\t trackDoneStatus: false,\n\t Promise: Promise\n\t };\n\n\t Bottleneck.prototype.stopDefaults = {\n\t enqueueErrorMessage: \"This limiter has been stopped and cannot accept new jobs.\",\n\t dropWaitingJobs: true,\n\t dropErrorMessage: \"This limiter has been stopped.\"\n\t };\n\n\t return Bottleneck;\n\n\t}).call(commonjsGlobal);\n\n\tvar Bottleneck_1 = Bottleneck;\n\n\tvar lib = Bottleneck_1;\n\n\treturn lib;\n\n})));\n", "// pkg/dist-src/index.js\nimport BottleneckLight from \"bottleneck/light.js\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/wrap-request.js\nvar noop = () => Promise.resolve();\nfunction wrapRequest(state, request, options) {\n return state.retryLimiter.schedule(doRequest, state, request, options);\n}\nasync function doRequest(state, request, options) {\n const { pathname } = new URL(options.url, \"http://github.test\");\n const isAuth = isAuthRequest(options.method, pathname);\n const isWrite = !isAuth && options.method !== \"GET\" && options.method !== \"HEAD\";\n const isSearch = options.method === \"GET\" && pathname.startsWith(\"/search/\");\n const isGraphQL = pathname.startsWith(\"/graphql\");\n const retryCount = ~~request.retryCount;\n const jobOptions = retryCount > 0 ? { priority: 0, weight: 0 } : {};\n if (state.clustering) {\n jobOptions.expiration = 1e3 * 60;\n }\n if (isWrite || isGraphQL) {\n await state.write.key(state.id).schedule(jobOptions, noop);\n }\n if (isWrite && state.triggersNotification(pathname)) {\n await state.notifications.key(state.id).schedule(jobOptions, noop);\n }\n if (isSearch) {\n await state.search.key(state.id).schedule(jobOptions, noop);\n }\n const req = (isAuth ? state.auth : state.global).key(state.id).schedule(jobOptions, request, options);\n if (isGraphQL) {\n const res = await req;\n if (res.data.errors != null && res.data.errors.some((error) => error.type === \"RATE_LIMITED\")) {\n const error = Object.assign(new Error(\"GraphQL Rate Limit Exceeded\"), {\n response: res,\n data: res.data\n });\n throw error;\n }\n }\n return req;\n}\nfunction isAuthRequest(method, pathname) {\n return method === \"PATCH\" && // https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-a-scoped-access-token\n /^\\/applications\\/[^/]+\\/token\\/scoped$/.test(pathname) || method === \"POST\" && // https://docs.github.com/en/rest/apps/oauth-applications?apiVersion=2022-11-28#reset-a-token\n (/^\\/applications\\/[^/]+\\/token$/.test(pathname) || // https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app\n /^\\/app\\/installations\\/[^/]+\\/access_tokens$/.test(pathname) || // https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps\n pathname === \"/login/oauth/access_token\");\n}\n\n// pkg/dist-src/generated/triggers-notification-paths.js\nvar triggers_notification_paths_default = [\n \"/orgs/{org}/invitations\",\n \"/orgs/{org}/invitations/{invitation_id}\",\n \"/orgs/{org}/teams/{team_slug}/discussions\",\n \"/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n \"/repos/{owner}/{repo}/collaborators/{username}\",\n \"/repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n \"/repos/{owner}/{repo}/issues\",\n \"/repos/{owner}/{repo}/issues/{issue_number}/comments\",\n \"/repos/{owner}/{repo}/issues/{issue_number}/sub_issue\",\n \"/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority\",\n \"/repos/{owner}/{repo}/pulls\",\n \"/repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n \"/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\",\n \"/repos/{owner}/{repo}/pulls/{pull_number}/merge\",\n \"/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\",\n \"/repos/{owner}/{repo}/pulls/{pull_number}/reviews\",\n \"/repos/{owner}/{repo}/releases\",\n \"/teams/{team_id}/discussions\",\n \"/teams/{team_id}/discussions/{discussion_number}/comments\"\n];\n\n// pkg/dist-src/route-matcher.js\nfunction routeMatcher(paths) {\n const regexes = paths.map(\n (path) => path.split(\"/\").map((c) => c.startsWith(\"{\") ? \"(?:.+?)\" : c).join(\"/\")\n );\n const regex2 = `^(?:${regexes.map((r) => `(?:${r})`).join(\"|\")})[^/]*$`;\n return new RegExp(regex2, \"i\");\n}\n\n// pkg/dist-src/index.js\nvar regex = routeMatcher(triggers_notification_paths_default);\nvar triggersNotification = regex.test.bind(regex);\nvar groups = {};\nvar createGroups = function(Bottleneck, common) {\n groups.global = new Bottleneck.Group({\n id: \"octokit-global\",\n maxConcurrent: 10,\n ...common\n });\n groups.auth = new Bottleneck.Group({\n id: \"octokit-auth\",\n maxConcurrent: 1,\n ...common\n });\n groups.search = new Bottleneck.Group({\n id: \"octokit-search\",\n maxConcurrent: 1,\n minTime: 2e3,\n ...common\n });\n groups.write = new Bottleneck.Group({\n id: \"octokit-write\",\n maxConcurrent: 1,\n minTime: 1e3,\n ...common\n });\n groups.notifications = new Bottleneck.Group({\n id: \"octokit-notifications\",\n maxConcurrent: 1,\n minTime: 3e3,\n ...common\n });\n};\nfunction throttling(octokit, octokitOptions) {\n const {\n enabled = true,\n Bottleneck = BottleneckLight,\n id = \"no-id\",\n timeout = 1e3 * 60 * 2,\n // Redis TTL: 2 minutes\n connection\n } = octokitOptions.throttle || {};\n if (!enabled) {\n return {};\n }\n const common = { timeout };\n if (typeof connection !== \"undefined\") {\n common.connection = connection;\n }\n if (groups.global == null) {\n createGroups(Bottleneck, common);\n }\n const state = Object.assign(\n {\n clustering: connection != null,\n triggersNotification,\n fallbackSecondaryRateRetryAfter: 60,\n retryAfterBaseValue: 1e3,\n retryLimiter: new Bottleneck(),\n id,\n ...groups\n },\n octokitOptions.throttle\n );\n if (typeof state.onSecondaryRateLimit !== \"function\" || typeof state.onRateLimit !== \"function\") {\n throw new Error(`octokit/plugin-throttling error:\n You must pass the onSecondaryRateLimit and onRateLimit error handlers.\n See https://octokit.github.io/rest.js/#throttling\n\n const octokit = new Octokit({\n throttle: {\n onSecondaryRateLimit: (retryAfter, options) => {/* ... */},\n onRateLimit: (retryAfter, options) => {/* ... */}\n }\n })\n `);\n }\n const events = {};\n const emitter = new Bottleneck.Events(events);\n events.on(\"secondary-limit\", state.onSecondaryRateLimit);\n events.on(\"rate-limit\", state.onRateLimit);\n events.on(\n \"error\",\n (e) => octokit.log.warn(\"Error in throttling-plugin limit handler\", e)\n );\n state.retryLimiter.on(\"failed\", async function(error, info) {\n const [state2, request, options] = info.args;\n const { pathname } = new URL(options.url, \"http://github.test\");\n const shouldRetryGraphQL = pathname.startsWith(\"/graphql\") && error.status !== 401;\n if (!(shouldRetryGraphQL || error.status === 403 || error.status === 429)) {\n return;\n }\n const retryCount = ~~request.retryCount;\n request.retryCount = retryCount;\n options.request.retryCount = retryCount;\n const { wantRetry, retryAfter = 0 } = await (async function() {\n if (/\\bsecondary rate\\b/i.test(error.message)) {\n const retryAfter2 = Number(error.response.headers[\"retry-after\"]) || state2.fallbackSecondaryRateRetryAfter;\n const wantRetry2 = await emitter.trigger(\n \"secondary-limit\",\n retryAfter2,\n options,\n octokit,\n retryCount\n );\n return { wantRetry: wantRetry2, retryAfter: retryAfter2 };\n }\n if (error.response.headers != null && error.response.headers[\"x-ratelimit-remaining\"] === \"0\" || (error.response.data?.errors ?? []).some(\n (error2) => error2.type === \"RATE_LIMITED\"\n )) {\n const rateLimitReset = new Date(\n ~~error.response.headers[\"x-ratelimit-reset\"] * 1e3\n ).getTime();\n const retryAfter2 = Math.max(\n // Add one second so we retry _after_ the reset time\n // https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#exceeding-the-rate-limit\n Math.ceil((rateLimitReset - Date.now()) / 1e3) + 1,\n 0\n );\n const wantRetry2 = await emitter.trigger(\n \"rate-limit\",\n retryAfter2,\n options,\n octokit,\n retryCount\n );\n return { wantRetry: wantRetry2, retryAfter: retryAfter2 };\n }\n return {};\n })();\n if (wantRetry) {\n request.retryCount++;\n return retryAfter * state2.retryAfterBaseValue;\n }\n });\n octokit.hook.wrap(\"request\", wrapRequest.bind(null, state));\n return {};\n}\nthrottling.VERSION = VERSION;\nthrottling.triggersNotification = triggersNotification;\nexport {\n throttling\n};\n", "/**\n * Shared GitHub API client with rate limiting and throttling\n */\n\nimport { Octokit } from '@octokit/rest';\nimport { throttling } from '@octokit/plugin-throttling';\nimport { warn } from './logger.js';\n\nconst MODULE = 'github';\n\nconst ThrottledOctokit = Octokit.plugin(throttling);\n\n/** Rate limit info returned by {@link checkRateLimit}. */\nexport interface RateLimitInfo {\n /** Remaining search API requests in current window. */\n remaining: number;\n /** Total search API request limit per window. */\n limit: number;\n /** ISO timestamp when the rate limit window resets. */\n resetAt: string;\n}\n\nlet _octokit: Octokit | null = null;\nlet _currentToken: string | null = null;\n\n/** Format a Date as HH:MM:SS for log messages. */\nfunction formatResetTime(date: Date): string {\n return date.toLocaleTimeString('en-US', { hour12: false });\n}\n\nexport function getOctokit(token: string): Octokit {\n // Return cached instance only if token matches\n if (_octokit && _currentToken === token) return _octokit;\n\n _octokit = new ThrottledOctokit({\n auth: token,\n throttle: {\n onRateLimit: (retryAfter, options, _octokit, retryCount) => {\n const opts = options as { method: string; url: string };\n const resetAt = new Date(Date.now() + retryAfter * 1000);\n if (retryCount < 2) {\n warn(\n MODULE,\n `Rate limit hit (retry ${retryCount + 1}/2, waiting ${retryAfter}s, resets at ${formatResetTime(resetAt)}) \u2014 ${opts.method} ${opts.url}`,\n );\n return true;\n }\n warn(\n MODULE,\n `Rate limit exceeded, not retrying \u2014 ${opts.method} ${opts.url} (resets at ${formatResetTime(resetAt)})`,\n );\n return false;\n },\n onSecondaryRateLimit: (retryAfter, options, _octokit, retryCount) => {\n const opts = options as { method: string; url: string };\n const resetAt = new Date(Date.now() + retryAfter * 1000);\n if (retryCount < 1) {\n warn(\n MODULE,\n `Secondary rate limit hit (retry ${retryCount + 1}/1, waiting ${retryAfter}s, resets at ${formatResetTime(resetAt)}) \u2014 ${opts.method} ${opts.url}`,\n );\n return true;\n }\n warn(\n MODULE,\n `Secondary rate limit exceeded, not retrying \u2014 ${opts.method} ${opts.url} (resets at ${formatResetTime(resetAt)})`,\n );\n return false;\n },\n },\n });\n\n _currentToken = token;\n return _octokit;\n}\n\n/**\n * Check the GitHub Search API rate limit quota.\n * Returns the remaining requests, total limit, and reset time for the search endpoint.\n */\nexport async function checkRateLimit(token: string): Promise<RateLimitInfo> {\n const octokit = getOctokit(token);\n const { data } = await octokit.rateLimit.get();\n const search = data.resources.search;\n return {\n remaining: search.remaining,\n limit: search.limit,\n resetAt: new Date(search.reset * 1000).toISOString(),\n };\n}\n", "/**\n * Status determination logic for PRs \u2014 extracted from PRMonitor (#263).\n *\n * Computes the top-level status (needs_addressing vs waiting_on_maintainer),\n * granular action/wait reasons, and staleness tier for a single PR based on\n * its CI, review, merge-conflict, and timeline signals.\n */\n\nimport type { DetermineStatusInput, DetermineStatusResult, StalenessTier } from './types.js';\n\n/**\n * CI-fix bots that push commits as a direct result of the contributor's push (#568).\n * Their commits represent contributor work and should count as addressing feedback.\n * This is intentionally an allowlist \u2014 not all `[bot]` accounts are CI-fix bots\n * (e.g. dependabot[bot] and renovate[bot] open their own PRs).\n * Values must be lowercase \u2014 lookup uses .toLowerCase() for case-insensitive matching.\n */\nexport const CI_FIX_BOTS: ReadonlySet<string> = new Set(['autofix-ci[bot]', 'prettier-ci[bot]', 'pre-commit-ci[bot]']);\n\n/** Minimum gap (ms) between maintainer comment and contributor commit for\n * the commit to count as \"addressing\" the feedback (#547). Prevents false\n * positives from race conditions, clock skew, and in-flight pushes. */\nexport const MIN_RESPONSE_GAP_MS = 2 * 60 * 1000; // 2 minutes\n\n/**\n * Check whether the HEAD commit was authored by the contributor (#547).\n * Returns true when the author matches, when the author is a known CI-fix\n * bot (#568), or when author info is unavailable (graceful degradation).\n */\nexport function isContributorCommit(commitAuthor?: string, contributorUsername?: string): boolean {\n if (!commitAuthor || !contributorUsername) return true; // degrade gracefully\n const author = commitAuthor.toLowerCase();\n if (CI_FIX_BOTS.has(author)) return true; // CI-fix bots act on behalf of the contributor (#568)\n return author === contributorUsername.toLowerCase();\n}\n\n/**\n * Check whether the contributor's commit is meaningfully after the maintainer's\n * comment \u2014 i.e. the commit timestamp is at least MIN_RESPONSE_GAP_MS later (#547).\n */\nexport function isCommitAfterComment(commitDate: string, commentDate: string): boolean {\n const commitMs = new Date(commitDate).getTime();\n const commentMs = new Date(commentDate).getTime();\n if (Number.isNaN(commitMs) || Number.isNaN(commentMs)) {\n // Fall back to simple string comparison (pre-#547 behavior)\n return commitDate > commentDate;\n }\n return commitMs - commentMs >= MIN_RESPONSE_GAP_MS;\n}\n\n/**\n * Determine the overall status of a PR based on its signals.\n */\nexport function determineStatus(input: DetermineStatusInput): DetermineStatusResult {\n const {\n ciStatus,\n hasMergeConflict,\n hasUnrespondedComment,\n hasIncompleteChecklist,\n reviewDecision,\n daysSinceActivity,\n dormantThreshold,\n approachingThreshold,\n latestCommitDate: rawCommitDate,\n latestCommitAuthor,\n contributorUsername,\n lastMaintainerCommentDate,\n latestChangesRequestedDate,\n hasActionableCIFailure = true,\n } = input;\n\n // Compute staleness tier (independent of status)\n let stalenessTier: StalenessTier = 'active';\n if (daysSinceActivity >= dormantThreshold) stalenessTier = 'dormant';\n else if (daysSinceActivity >= approachingThreshold) stalenessTier = 'approaching_dormant';\n\n // Only count the latest commit if it was authored by the contributor or a\n // CI bot (#547, #568). Non-contributor commits (maintainer merge commits,\n // GitHub suggestion commits) should not mask unaddressed feedback.\n const latestCommitDate =\n rawCommitDate && isContributorCommit(latestCommitAuthor, contributorUsername) ? rawCommitDate : undefined;\n\n // Priority order: needs_addressing (response/changes/ci/conflict/checklist) > waiting_on_maintainer (review/merge/addressed/ci_blocked)\n\n if (hasUnrespondedComment) {\n // If the contributor pushed a commit after the maintainer's comment,\n // the changes have been addressed \u2014 waiting for maintainer re-review.\n // Require a minimum 2-minute gap to avoid false positives from race\n // conditions (pushing while review is being submitted) (#547).\n if (\n latestCommitDate &&\n lastMaintainerCommentDate &&\n isCommitAfterComment(latestCommitDate, lastMaintainerCommentDate)\n ) {\n // Safety net (#431): if a CHANGES_REQUESTED review was submitted after\n // the commit, the maintainer still expects changes \u2014 don't mask it\n if (latestChangesRequestedDate && latestCommitDate < latestChangesRequestedDate) {\n return { status: 'needs_addressing', actionReason: 'needs_response', stalenessTier };\n }\n if (ciStatus === 'failing' && hasActionableCIFailure)\n return { status: 'needs_addressing', actionReason: 'failing_ci', stalenessTier };\n // Non-actionable CI failures (infrastructure, fork, auth) don't block changes_addressed \u2014\n // the contributor can't fix them, so the relevant status is \"waiting for re-review\" (#502)\n return { status: 'waiting_on_maintainer', waitReason: 'changes_addressed', stalenessTier };\n }\n return { status: 'needs_addressing', actionReason: 'needs_response', stalenessTier };\n }\n\n // Review requested changes but no unresponded comment.\n // If the latest commit is before the review, the contributor hasn't addressed it yet.\n if (reviewDecision === 'changes_requested' && latestChangesRequestedDate) {\n if (!latestCommitDate || latestCommitDate < latestChangesRequestedDate) {\n return { status: 'needs_addressing', actionReason: 'needs_changes', stalenessTier };\n }\n // Commit is after review \u2014 changes have been addressed\n if (ciStatus === 'failing' && hasActionableCIFailure)\n return { status: 'needs_addressing', actionReason: 'failing_ci', stalenessTier };\n // Non-actionable CI failures don't block changes_addressed (#502)\n return { status: 'waiting_on_maintainer', waitReason: 'changes_addressed', stalenessTier };\n }\n\n if (ciStatus === 'failing') {\n return hasActionableCIFailure\n ? { status: 'needs_addressing', actionReason: 'failing_ci', stalenessTier }\n : { status: 'waiting_on_maintainer', waitReason: 'ci_blocked', stalenessTier };\n }\n\n if (hasMergeConflict) {\n return { status: 'needs_addressing', actionReason: 'merge_conflict', stalenessTier };\n }\n\n if (hasIncompleteChecklist) {\n return { status: 'needs_addressing', actionReason: 'incomplete_checklist', stalenessTier };\n }\n\n // Approved and CI passing/unknown = waiting on maintainer to merge\n if (reviewDecision === 'approved' && (ciStatus === 'passing' || ciStatus === 'unknown')) {\n return { status: 'waiting_on_maintainer', waitReason: 'pending_merge', stalenessTier };\n }\n\n // Default: no actionable issues found. Covers pending CI, no reviews yet, etc.\n return { status: 'waiting_on_maintainer', waitReason: 'pending_review', stalenessTier };\n}\n", "/**\n * Runs a worker pool that processes items with bounded concurrency.\n * N workers consume from a shared index. On any worker error, remaining\n * workers are aborted via a shared flag and the error is propagated.\n */\nexport async function runWorkerPool<T>(\n items: T[],\n worker: (item: T) => Promise<void>,\n concurrency: number,\n): Promise<void> {\n let index = 0;\n let aborted = false;\n const poolWorker = async () => {\n while (index < items.length) {\n if (aborted) break;\n const item = items[index++];\n try {\n await worker(item);\n } catch (err) {\n aborted = true;\n throw err;\n }\n }\n };\n const workerCount = Math.min(concurrency, items.length);\n await Promise.all(Array.from({ length: workerCount }, () => poolWorker()));\n}\n", "/** Maximum pages to fetch to prevent runaway pagination */\nconst MAX_PAGES = 10;\n\n/**\n * Auto-paginate an Octokit list endpoint. Fetches additional pages when\n * the result count equals per_page (indicating more data may exist).\n *\n * @param fetchPage Function that fetches a single page given a page number\n * @param perPage Items per page (default 100)\n * @param maxPages Maximum pages to fetch (default 10 = 1000 items)\n */\nexport async function paginateAll<T>(\n fetchPage: (page: number) => Promise<{ data: T[] }>,\n perPage = 100,\n maxPages = MAX_PAGES,\n): Promise<T[]> {\n const allItems: T[] = [];\n for (let page = 1; page <= maxPages; page++) {\n const { data } = await fetchPage(page);\n allItems.push(...data);\n if (data.length < perPage) break; // No more pages\n }\n return allItems;\n}\n", "/**\n * HTTP caching with ETags for GitHub API responses.\n *\n * Stores ETags and response bodies for cacheable GET endpoints in\n * `~/.oss-autopilot/cache/`. On subsequent requests, sends `If-None-Match`\n * headers \u2014 304 responses don't count against GitHub rate limits.\n *\n * Also provides in-flight request deduplication so that concurrent calls\n * for the same endpoint (e.g., star counts for two PRs in the same repo)\n * share a single HTTP round-trip.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport { getCacheDir } from './utils.js';\nimport { debug } from './logger.js';\nimport { getHttpStatusCode } from './errors.js';\n\nconst MODULE = 'http-cache';\n\n/** Shape of a single cache entry on disk. */\nexport interface CacheEntry {\n etag: string;\n url: string;\n body: unknown;\n cachedAt: string;\n}\n\n/**\n * Maximum age (in ms) before a cache entry is considered stale and eligible for\n * eviction during cleanup. Defaults to 24 hours. Entries older than this are\n * still *usable* for conditional requests (the ETag may still be valid), but\n * `evictStale()` will remove them.\n */\nconst DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * File-based HTTP cache backed by `~/.oss-autopilot/cache/`.\n *\n * Each cache entry is stored as a separate JSON file keyed by the SHA-256\n * hash of the request URL. This avoids filesystem issues with URL-based\n * filenames and keeps lookup O(1).\n */\nexport class HttpCache {\n private readonly cacheDir: string;\n\n /** In-flight request deduplication map: URL -> Promise<response>. */\n private readonly inflightRequests = new Map<string, Promise<unknown>>();\n\n constructor(cacheDir?: string) {\n this.cacheDir = cacheDir ?? getCacheDir();\n }\n\n /** Derive a filesystem-safe cache key from a URL. */\n private keyFor(url: string): string {\n return crypto.createHash('sha256').update(url).digest('hex');\n }\n\n /** Full path to the cache file for a given URL. */\n private pathFor(url: string): string {\n return path.join(this.cacheDir, `${this.keyFor(url)}.json`);\n }\n\n /**\n * Return the cached body if the entry exists and is younger than `maxAgeMs`.\n * Useful for time-based caching where ETag validation isn't applicable\n * (e.g., caching aggregated results from paginated API calls).\n */\n getIfFresh(key: string, maxAgeMs: number): unknown | null {\n const entry = this.get(key);\n if (!entry) return null;\n const age = Date.now() - new Date(entry.cachedAt).getTime();\n if (!Number.isFinite(age) || age < 0 || age > maxAgeMs) return null;\n return entry.body;\n }\n\n /**\n * Look up a cached response. Returns `null` if no cache entry exists.\n */\n get(url: string): CacheEntry | null {\n const filePath = this.pathFor(url);\n try {\n const raw = fs.readFileSync(filePath, 'utf-8');\n const entry = JSON.parse(raw) as CacheEntry;\n // Sanity-check: the file should contain the URL we asked for\n if (entry.url !== url) {\n debug(MODULE, `Cache collision detected for ${url}, ignoring`);\n return null;\n }\n return entry;\n } catch {\n return null;\n }\n }\n\n /**\n * Store a response with its ETag.\n */\n set(url: string, etag: string, body: unknown): void {\n const entry: CacheEntry = {\n etag,\n url,\n body,\n cachedAt: new Date().toISOString(),\n };\n try {\n fs.writeFileSync(this.pathFor(url), JSON.stringify(entry), { encoding: 'utf-8', mode: 0o600 });\n debug(MODULE, `Cached response for ${url}`);\n } catch (err) {\n // Non-fatal: cache write failure should not break the request\n debug(MODULE, `Failed to write cache for ${url}`, err);\n }\n }\n\n /**\n * Check whether a URL has an in-flight request.\n */\n hasInflight(url: string): boolean {\n return this.inflightRequests.has(url);\n }\n\n /**\n * Get the in-flight promise for a URL (for deduplication).\n */\n getInflight(url: string): Promise<unknown> | undefined {\n return this.inflightRequests.get(url);\n }\n\n /**\n * Register an in-flight request for deduplication.\n * Returns a cleanup function to call when the request completes.\n */\n setInflight(url: string, promise: Promise<unknown>): () => void {\n this.inflightRequests.set(url, promise);\n return () => {\n this.inflightRequests.delete(url);\n };\n }\n\n /**\n * Remove stale entries older than `maxAgeMs` from the cache directory.\n * Intended to be called periodically (e.g., once per daily run).\n */\n evictStale(maxAgeMs: number = DEFAULT_MAX_AGE_MS): number {\n let evicted = 0;\n try {\n const files = fs.readdirSync(this.cacheDir);\n const now = Date.now();\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const filePath = path.join(this.cacheDir, file);\n try {\n const raw = fs.readFileSync(filePath, 'utf-8');\n const entry = JSON.parse(raw) as CacheEntry;\n const age = now - new Date(entry.cachedAt).getTime();\n if (age > maxAgeMs) {\n fs.unlinkSync(filePath);\n evicted++;\n }\n } catch {\n // Corrupt entry \u2014 remove it\n try {\n fs.unlinkSync(filePath);\n evicted++;\n } catch {\n // Ignore\n }\n }\n }\n } catch {\n // Cache dir might not exist yet \u2014 that's fine\n }\n if (evicted > 0) {\n debug(MODULE, `Evicted ${evicted} stale cache entries`);\n }\n return evicted;\n }\n\n /**\n * Remove all entries from the cache.\n */\n clear(): void {\n try {\n const files = fs.readdirSync(this.cacheDir);\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n fs.unlinkSync(path.join(this.cacheDir, file));\n }\n debug(MODULE, 'Cache cleared');\n } catch {\n // Cache dir might not exist yet \u2014 that's fine\n }\n }\n\n /**\n * Return the number of entries currently in the cache.\n */\n size(): number {\n try {\n return fs.readdirSync(this.cacheDir).filter((f) => f.endsWith('.json')).length;\n } catch {\n return 0;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Singleton\n// ---------------------------------------------------------------------------\n\nlet _httpCache: HttpCache | null = null;\n\n/**\n * Get (or create) the shared HttpCache singleton.\n * The singleton is lazily initialized on first access.\n */\nexport function getHttpCache(): HttpCache {\n if (!_httpCache) {\n _httpCache = new HttpCache();\n }\n return _httpCache;\n}\n\n// ---------------------------------------------------------------------------\n// Octokit integration helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps an Octokit `repos.get`-style call with ETag caching and request\n * deduplication.\n *\n * Usage:\n * ```ts\n * const data = await cachedRequest(cache, octokit, '/repos/owner/repo', () =>\n * octokit.repos.get({ owner, repo: name }),\n * );\n * ```\n *\n * 1. If an identical request is already in-flight, returns the existing promise\n * (request deduplication).\n * 2. If a cached ETag exists, sends `If-None-Match`. On 304, returns the\n * cached body without consuming a rate-limit point.\n * 3. On a fresh 200, caches the ETag + body for next time.\n */\nexport async function cachedRequest<T>(\n cache: HttpCache,\n url: string,\n fetcher: (headers: Record<string, string>) => Promise<{ data: T; headers?: Record<string, string> }>,\n): Promise<T> {\n // --- Deduplication ---\n const existing = cache.getInflight(url);\n if (existing) {\n debug(MODULE, `Dedup hit for ${url}`);\n return (await existing) as T;\n }\n\n const doFetch = async (): Promise<T> => {\n const extraHeaders: Record<string, string> = {};\n const cached = cache.get(url);\n if (cached) {\n extraHeaders['if-none-match'] = cached.etag;\n }\n\n try {\n const response = await fetcher(extraHeaders);\n // Store ETag if present (headers may be absent in test mocks)\n const etag = response.headers?.['etag'];\n if (etag) {\n cache.set(url, etag, response.data);\n }\n return response.data;\n } catch (err: unknown) {\n // Check for 304 Not Modified \u2014 re-read cache to avoid stale closure snapshot\n if (isNotModifiedError(err)) {\n const freshCached = cache.get(url);\n if (freshCached) {\n debug(MODULE, `304 cache hit for ${url}`);\n return freshCached.body as T;\n }\n }\n throw err;\n }\n };\n\n const promise = doFetch();\n const cleanup = cache.setInflight(url, promise);\n\n try {\n const result = await promise;\n return result;\n } finally {\n cleanup();\n }\n}\n\n/**\n * Time-based cache wrapper (no ETag / conditional requests).\n *\n * If a cached result exists and is younger than `maxAgeMs`, returns it.\n * Otherwise calls `fetcher`, caches the result, and returns it.\n *\n * Use this for expensive operations whose results change slowly\n * (e.g. search queries, project health checks).\n */\nexport async function cachedTimeBased<T>(\n cache: HttpCache,\n key: string,\n maxAgeMs: number,\n fetcher: () => Promise<T>,\n): Promise<T> {\n const cached = cache.getIfFresh(key, maxAgeMs);\n if (cached) {\n debug(MODULE, `Time-based cache hit for ${key}`);\n return cached as T;\n }\n\n const result = await fetcher();\n cache.set(key, '', result);\n return result;\n}\n\n/**\n * Detect whether an error is a 304 Not Modified response.\n * Octokit throws a RequestError with status 304 for conditional requests.\n */\nfunction isNotModifiedError(err: unknown): boolean {\n return getHttpStatusCode(err) === 304;\n}\n", "/**\n * CI Analysis - Classification and analysis of CI check runs and combined statuses.\n * Extracted from PRMonitor to isolate CI-related logic (#263).\n */\n\nimport { CIFailureCategory, ClassifiedCheck, CIStatusResult } from './types.js';\n\n/**\n * Known CI check name patterns that indicate fork limitations rather than real failures (#81).\n * These are deployment/preview services that require repo-level secrets unavailable in forks.\n */\nconst FORK_LIMITATION_PATTERNS: RegExp[] = [\n /vercel/i,\n /netlify/i,\n /\\bpreview\\s*deploy/i,\n /\\bdeploy\\s*preview/i,\n /storybook/i,\n /chromatic/i,\n /percy/i,\n /cloudflare pages/i,\n];\n\n/**\n * Known CI check name patterns that indicate authorization gates (#81).\n * These require maintainer approval and are not real failures.\n */\nconst AUTH_GATE_PATTERNS: RegExp[] = [/authoriz/i, /approval/i, /\\bcla\\b/i, /license\\/cla/i];\n\n/**\n * Known CI check name patterns that indicate infrastructure/transient failures (#145).\n * These are runner issues, dependency install problems, or service outages \u2014 not code failures.\n */\nconst INFRASTRUCTURE_PATTERNS: RegExp[] = [\n /\\binstall\\s*(os\\s*)?dep(endenc|s\\b)/i,\n /\\bsetup\\s+fail(ed|ure)?\\b/i,\n /\\bservice\\s*unavailable/i,\n /\\binfrastructure/i,\n];\n\n/**\n * Classify a failing CI check as actionable, fork_limitation, auth_gate, or infrastructure (#81, #145).\n * Default is 'actionable' \u2014 only known patterns get reclassified.\n * When conclusion is provided (cancelled, timed_out), the check is classified as infrastructure.\n */\nexport function classifyCICheck(name: string, description?: string, conclusion?: string): CIFailureCategory {\n // Infrastructure: cancelled or timed_out jobs are transient failures (#145)\n if (conclusion === 'cancelled' || conclusion === 'timed_out') return 'infrastructure';\n\n const nameLower = name.toLowerCase();\n\n // Check name first (more reliable than description)\n if (AUTH_GATE_PATTERNS.some((p) => p.test(nameLower))) return 'auth_gate';\n if (FORK_LIMITATION_PATTERNS.some((p) => p.test(nameLower))) return 'fork_limitation';\n if (INFRASTRUCTURE_PATTERNS.some((p) => p.test(nameLower))) return 'infrastructure';\n\n // Fall through to description only if name was not classified\n if (description) {\n const descLower = description.toLowerCase();\n if (AUTH_GATE_PATTERNS.some((p) => p.test(descLower))) return 'auth_gate';\n if (FORK_LIMITATION_PATTERNS.some((p) => p.test(descLower))) return 'fork_limitation';\n if (INFRASTRUCTURE_PATTERNS.some((p) => p.test(descLower))) return 'infrastructure';\n }\n\n return 'actionable';\n}\n\n/**\n * Classify all failing checks and return both the flat names array and classified array (#81, #145).\n * Accepts optional conclusion data to detect infrastructure failures.\n */\nexport function classifyFailingChecks(\n failingCheckNames: string[],\n conclusions?: Map<string, string>,\n): ClassifiedCheck[] {\n return failingCheckNames.map((name) => {\n const conclusion = conclusions?.get(name);\n return {\n name,\n category: classifyCICheck(name, undefined, conclusion),\n conclusion,\n };\n });\n}\n\n/**\n * Analyze check runs (GitHub Actions, etc.) and categorize them.\n * Returns flags for failing/pending/success and lists of failing check names + conclusions.\n */\nexport function analyzeCheckRuns(checkRuns: Array<{ name: string; conclusion: string | null; status: string }>): {\n hasFailingChecks: boolean;\n hasPendingChecks: boolean;\n hasSuccessfulChecks: boolean;\n failingCheckNames: string[];\n failingCheckConclusions: Map<string, string>;\n} {\n let hasFailingChecks = false;\n let hasPendingChecks = false;\n let hasSuccessfulChecks = false;\n const failingCheckNames: string[] = [];\n const failingCheckConclusions = new Map<string, string>();\n\n for (const check of checkRuns) {\n if (check.conclusion === 'failure' || check.conclusion === 'cancelled' || check.conclusion === 'timed_out') {\n hasFailingChecks = true;\n failingCheckNames.push(check.name);\n failingCheckConclusions.set(check.name, check.conclusion);\n } else if (check.conclusion === 'action_required') {\n hasPendingChecks = true; // Maintainer approval gate, not a real failure\n } else if (check.status === 'in_progress' || check.status === 'queued') {\n hasPendingChecks = true;\n } else if (check.conclusion === 'success') {\n hasSuccessfulChecks = true;\n }\n }\n\n return { hasFailingChecks, hasPendingChecks, hasSuccessfulChecks, failingCheckNames, failingCheckConclusions };\n}\n\n/** Result shape from analyzeCheckRuns, used by mergeStatuses. */\ninterface CheckRunAnalysis {\n hasFailingChecks: boolean;\n hasPendingChecks: boolean;\n hasSuccessfulChecks: boolean;\n failingCheckNames: string[];\n failingCheckConclusions: Map<string, string>;\n}\n\n/** Result shape from analyzeCombinedStatus, used by mergeStatuses. */\ninterface CombinedStatusAnalysis {\n effectiveCombinedState: string;\n hasStatuses: boolean;\n failingStatusNames: string[];\n}\n\n/**\n * Analyze combined status API results (Travis, CircleCI, etc.).\n * Filters out authorization-gate statuses and determines the effective combined state.\n * Returns failing status context names in the result (does not mutate caller arrays).\n */\nexport function analyzeCombinedStatus(combinedStatus: {\n state: string;\n statuses: Array<{ state: string; context: string; description: string | null }>;\n}): CombinedStatusAnalysis {\n // Filter out authorization-gate statuses (e.g., Vercel \"Authorization required to deploy\")\n // These are permission gates, not real CI failures\n const realStatuses = combinedStatus.statuses.filter((s) => {\n const desc = (s.description || '').toLowerCase();\n return !(s.state === 'failure' && (desc.includes('authorization required') || desc.includes('authorize')));\n });\n\n const hasRealFailure = realStatuses.some((s) => s.state === 'failure' || s.state === 'error');\n const hasRealPending = realStatuses.some((s) => s.state === 'pending');\n const hasRealSuccess = realStatuses.some((s) => s.state === 'success');\n const effectiveCombinedState = hasRealFailure\n ? 'failure'\n : hasRealPending\n ? 'pending'\n : hasRealSuccess\n ? 'success'\n : realStatuses.length === 0\n ? 'success' // All statuses were auth gates; don't inherit original failure\n : combinedStatus.state;\n const hasStatuses = combinedStatus.statuses.length > 0;\n\n // Collect failing status names from combined status API\n const failingStatusNames: string[] = [];\n for (const s of realStatuses) {\n if (s.state === 'failure' || s.state === 'error') {\n failingStatusNames.push(s.context);\n }\n }\n\n return { effectiveCombinedState, hasStatuses, failingStatusNames };\n}\n\n/**\n * Merge check run analysis and combined status analysis into a final CIStatusResult.\n * Priority: failing > pending > passing > unknown.\n */\nexport function mergeStatuses(\n checkRunAnalysis: CheckRunAnalysis,\n combinedAnalysis: CombinedStatusAnalysis,\n checkRunCount: number,\n): CIStatusResult {\n const { hasFailingChecks, hasPendingChecks, hasSuccessfulChecks, failingCheckNames, failingCheckConclusions } =\n checkRunAnalysis;\n const { effectiveCombinedState, hasStatuses, failingStatusNames } = combinedAnalysis;\n\n // Merge failing names from both check runs and combined statuses\n const allFailingNames = [...failingCheckNames, ...failingStatusNames];\n\n // Safety net: If we have ANY failing checks, report as failing\n if (hasFailingChecks || effectiveCombinedState === 'failure' || effectiveCombinedState === 'error') {\n return { status: 'failing', failingCheckNames: allFailingNames, failingCheckConclusions };\n }\n\n if (hasPendingChecks || effectiveCombinedState === 'pending') {\n return { status: 'pending', failingCheckNames: [], failingCheckConclusions: new Map() };\n }\n\n if (hasSuccessfulChecks || effectiveCombinedState === 'success') {\n return { status: 'passing', failingCheckNames: [], failingCheckConclusions: new Map() };\n }\n\n // No checks found at all - this is common for repos without CI\n if (!hasStatuses && checkRunCount === 0) {\n return { status: 'unknown', failingCheckNames: [], failingCheckConclusions: new Map() };\n }\n\n return { status: 'unknown', failingCheckNames: [], failingCheckConclusions: new Map() };\n}\n", "/**\n * Shared comment utility functions used by both PRMonitor and IssueConversationMonitor.\n * Extracted to avoid circular dependencies between the two modules.\n */\n\n// Bot accounts that don't follow the [bot] suffix convention\nconst KNOWN_BOT_USERNAMES = new Set([\n 'allcontributors',\n 'changeset-bot',\n 'claassistant',\n 'codecov-commenter',\n 'greenkeeper',\n 'imgbot',\n 'netlify',\n 'renovate',\n 'snyk-bot',\n 'sonarcloud',\n 'stale',\n 'vercel',\n]);\n\n/**\n * Check if a comment author is a bot account.\n * Matches the [bot] suffix convention and known bot usernames (case-insensitive).\n */\nexport function isBotAuthor(author: string): boolean {\n return author.includes('[bot]') || KNOWN_BOT_USERNAMES.has(author.toLowerCase());\n}\n\n/**\n * Detect acknowledgment comments that don't require a response.\n * Returns true only when: no question mark, matches an acknowledgment keyword, and under 100 chars.\n * Conservative -- missing a real acknowledgment (false negative) is safer than suppressing a substantive response (false positive).\n */\nexport function isAcknowledgmentComment(body: string): boolean {\n if (!body || body.length > 100) return false;\n if (body.includes('?')) return false;\n\n const lower = body.toLowerCase();\n const ackKeywords = [\n 'thanks',\n 'thank you',\n 'lgtm',\n 'looks good',\n 'will review',\n \"we'll review\",\n \"we'll get to this\",\n 'noted',\n 'got it',\n 'will look',\n 'will check',\n ];\n\n return ackKeywords.some((kw) => lower.includes(kw));\n}\n", "/**\n * Review Analysis - Review decision computation, unresponded comment detection,\n * and self-reply filtering for PR reviews.\n * Extracted from PRMonitor to isolate review-related logic (#263).\n */\n\nimport { FetchedPR, ReviewDecision } from './types.js';\nimport { isBotAuthor, isAcknowledgmentComment } from './comment-utils.js';\n\n/** Inline review comment shape used for self-reply detection and body extraction (#199). */\nexport interface ReviewComment {\n id: number;\n user?: { login?: string } | null;\n body?: string | null;\n created_at: string;\n in_reply_to_id?: number;\n pull_request_review_id?: number | null;\n}\n\n/**\n * Determine review decision from reviews list.\n * Groups reviews by user, keeping only the latest from each user,\n * then checks for CHANGES_REQUESTED or APPROVED states.\n */\nexport function determineReviewDecision(\n reviews: Array<{ state?: string | null; user?: { login?: string } | null }>,\n): ReviewDecision {\n if (reviews.length === 0) {\n return 'review_required';\n }\n\n // Group reviews by user, keeping only the latest from each user\n const latestByUser = new Map<string, string>();\n for (const review of reviews) {\n const login = review.user?.login;\n const state = review.state;\n if (login && state) {\n latestByUser.set(login, state);\n }\n }\n\n const states = Array.from(latestByUser.values());\n\n if (states.includes('CHANGES_REQUESTED')) {\n return 'changes_requested';\n }\n\n if (states.includes('APPROVED')) {\n return 'approved';\n }\n\n return 'review_required';\n}\n\n/**\n * Get the date of the latest CHANGES_REQUESTED review (from any reviewer).\n * Used to detect needs_changes status when review feedback is in inline comments.\n */\nexport function getLatestChangesRequestedDate(\n reviews: Array<{ state?: string | null; submitted_at?: string | null }>,\n): string | undefined {\n let latest: string | undefined;\n for (const review of reviews) {\n if (review.state === 'CHANGES_REQUESTED' && review.submitted_at) {\n if (!latest || review.submitted_at > latest) {\n latest = review.submitted_at;\n }\n }\n }\n return latest;\n}\n\n/**\n * Check if all inline comments in a COMMENTED review are self-replies.\n * A self-reply is when an author replies to their own earlier inline comment.\n * Used to filter out informational follow-ups that don't require contributor action (#199).\n */\nexport function isAllSelfReplies(reviewId: number, reviewComments: ReviewComment[]): boolean {\n const commentsForReview = reviewComments.filter((c) => c.pull_request_review_id === reviewId);\n\n if (commentsForReview.length === 0) return false;\n\n // Build map of ALL comment IDs -> lowercase author for parent lookup\n const authorMap = new Map<number, string>();\n for (const c of reviewComments) {\n if (c.user?.login) {\n authorMap.set(c.id, c.user.login.toLowerCase());\n }\n }\n\n return commentsForReview.every((comment) => {\n if (!comment.in_reply_to_id) return false; // New thread, not a reply\n const parentAuthor = authorMap.get(comment.in_reply_to_id);\n const commentAuthor = comment.user?.login?.toLowerCase();\n if (parentAuthor == null || commentAuthor == null || parentAuthor !== commentAuthor) return false;\n // A self-reply containing a question mark is likely a follow-up question\n // directed at the PR author, not an informational addendum (#498).\n // Null/empty body on a self-reply is anomalous \u2014 surface it rather than\n // silently filtering, since the safe direction is to notify.\n if (!comment.body) return false;\n if (comment.body.includes('?')) return false;\n return true;\n });\n}\n\n/**\n * Get the body text of inline review comments for a COMMENTED review.\n * Returns the first non-empty comment body, or undefined.\n * Enables the acknowledgment filter to evaluate real content instead of\n * synthetic placeholders (#199).\n */\nexport function getInlineCommentBody(reviewId: number, reviewComments: ReviewComment[]): string | undefined {\n return reviewComments.find((c) => c.pull_request_review_id === reviewId && c.body?.trim())?.body?.trim();\n}\n\n/**\n * Check if there are unresponded comments from maintainers.\n * Combines issue comments and review comments into a timeline,\n * then finds maintainer comments after the user's last comment.\n */\nexport function checkUnrespondedComments(\n comments: Array<{ user?: { login?: string } | null; body?: string | null; created_at: string }>,\n reviews: Array<{\n user?: { login?: string } | null;\n body?: string | null;\n submitted_at?: string | null;\n state?: string | null;\n id?: number;\n }>,\n reviewComments: ReviewComment[],\n username: string,\n): { hasUnrespondedComment: boolean; lastMaintainerComment?: FetchedPR['lastMaintainerComment'] } {\n // Combine comments and reviews into a timeline\n const timeline: Array<{ author: string; body: string; createdAt: string; isUser: boolean }> = [];\n const usernameLower = username.toLowerCase();\n\n for (const comment of comments) {\n const author = comment.user?.login || 'unknown';\n timeline.push({\n author,\n body: comment.body || '',\n createdAt: comment.created_at,\n isUser: author.toLowerCase() === usernameLower,\n });\n }\n\n for (const review of reviews) {\n if (!review.submitted_at) continue;\n const body = (review.body || '').trim();\n // Include COMMENTED and CHANGES_REQUESTED reviews even without body text \u2014\n // they indicate inline review comments were posted and need a response (#151, #431).\n // CHANGES_REQUESTED with only inline comments is actionable maintainer feedback.\n // Skip other empty-body reviews (APPROVED, DISMISSED) as those are state changes.\n if (!body && review.state !== 'COMMENTED' && review.state !== 'CHANGES_REQUESTED') continue;\n const author = review.user?.login || 'unknown';\n\n // For inline-only COMMENTED reviews, skip pure self-replies (#199).\n // CHANGES_REQUESTED reviews are always actionable regardless of self-replies.\n if (!body && review.state === 'COMMENTED' && review.id != null) {\n if (isAllSelfReplies(review.id, reviewComments)) {\n continue;\n }\n }\n\n // Resolve body: prefer actual text, then inline comment text, then synthetic placeholder\n const resolvedBody =\n body ||\n (review.id != null ? getInlineCommentBody(review.id, reviewComments) : undefined) ||\n (review.state === 'CHANGES_REQUESTED'\n ? '(requested changes via inline review comments)'\n : '(posted inline review comments)');\n\n timeline.push({\n author,\n body: resolvedBody,\n createdAt: review.submitted_at,\n isUser: author.toLowerCase() === usernameLower,\n });\n }\n\n // Sort by date\n timeline.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n\n // Find the last user comment\n let lastUserCommentTime: Date | null = null;\n for (const item of timeline) {\n if (item.isUser) {\n lastUserCommentTime = new Date(item.createdAt);\n }\n }\n\n // Find maintainer comments after the user's last comment\n let lastMaintainerComment: FetchedPR['lastMaintainerComment'] | undefined;\n\n for (const item of timeline) {\n if (item.isUser) continue; // Skip user's own comments\n if (item.author === 'unknown') continue; // Skip deleted/null accounts\n if (isBotAuthor(item.author)) continue; // Skip bots\n\n const itemTime = new Date(item.createdAt);\n if (!lastUserCommentTime || itemTime > lastUserCommentTime) {\n lastMaintainerComment = {\n author: item.author,\n body: item.body.slice(0, 200) + (item.body.length > 200 ? '...' : ''),\n createdAt: item.createdAt,\n };\n }\n }\n\n // Filter out pure acknowledgment comments that don't require a response\n if (lastMaintainerComment && isAcknowledgmentComment(lastMaintainerComment.body)) {\n lastMaintainerComment = undefined;\n }\n\n return {\n hasUnrespondedComment: !!lastMaintainerComment,\n lastMaintainerComment,\n };\n}\n", "/**\n * Checklist Analysis - PR body checklist detection and conditional item filtering.\n * Extracted from PRMonitor to isolate checklist-related logic (#263).\n */\n\nimport { FetchedPR } from './types.js';\n\n/**\n * Detect conditional checklist items that are intentionally left unchecked (#152).\n * Matches patterns like \"(if the PR is ...)\", \"if applicable\", \"N/A\", \"optional\", etc.\n * Conservative \u2014 only skips items with clear conditional language.\n */\nconst CONDITIONAL_CHECKLIST_PATTERN =\n /\\(if\\s|\\bif applicable\\b|\\bif needed\\b|\\bif relevant\\b|\\bonly if\\b|\\bwhen applicable\\b|\\(optional\\)|- \\[ \\]\\s*optional\\b|\\bn\\/a\\b|\\bnot applicable\\b|\\bif required\\b|\\bif necessary\\b/;\n\nexport function isConditionalChecklistItem(line: string): boolean {\n return CONDITIONAL_CHECKLIST_PATTERN.test(line.toLowerCase());\n}\n\n/**\n * Analyze PR body for incomplete checklists (unchecked markdown checkboxes).\n * Looks for patterns like \"- [ ]\" (unchecked) vs \"- [x]\" (checked).\n * Only flags if there ARE checkboxes and some are unchecked.\n * Conditional items (containing \"if applicable\", \"(if ...)\", etc.) are\n * excluded from the incomplete count (#152).\n */\nexport function analyzeChecklist(body: string): {\n hasIncompleteChecklist: boolean;\n checklistStats?: FetchedPR['checklistStats'];\n} {\n if (!body) return { hasIncompleteChecklist: false };\n\n const checkedPattern = /- \\[x\\]/gi;\n const uncheckedLinePattern = /^.*- \\[ \\].*$/gm;\n\n const checkedMatches = body.match(checkedPattern) || [];\n const uncheckedLines = body.match(uncheckedLinePattern) || [];\n\n const checked = checkedMatches.length;\n const total = checked + uncheckedLines.length;\n\n // No checkboxes at all - not a checklist PR\n if (total === 0) return { hasIncompleteChecklist: false };\n\n // Filter out conditional checklist items that are intentionally unchecked\n const nonConditionalUnchecked = uncheckedLines.filter((line) => !isConditionalChecklistItem(line));\n\n // Use consistent total that excludes conditional items (matches hasIncompleteChecklist logic)\n const effectiveTotal = checked + nonConditionalUnchecked.length;\n\n return {\n hasIncompleteChecklist: nonConditionalUnchecked.length > 0,\n checklistStats: { checked, total: effectiveTotal },\n };\n}\n", "/**\n * Maintainer Analysis - Action hint extraction from maintainer comments.\n * Extracted from PRMonitor to isolate maintainer-comment-related logic (#263).\n */\n\nimport { MaintainerActionHint, ReviewDecision } from './types.js';\n\n/**\n * Extract action hints from maintainer comments using keyword matching.\n * Returns an array of hints about what the maintainer is asking for.\n */\nexport function extractMaintainerActionHints(\n commentBody: string | undefined,\n reviewDecision: ReviewDecision,\n): MaintainerActionHint[] {\n const hints: MaintainerActionHint[] = [];\n\n if (reviewDecision === 'changes_requested') {\n hints.push('changes_requested');\n }\n\n if (!commentBody) return hints;\n\n const lower = commentBody.toLowerCase();\n\n // Demo/screenshot requests\n const demoKeywords = [\n 'screenshot',\n 'demo',\n 'recording',\n 'screen recording',\n 'before/after',\n 'before and after',\n 'gif',\n 'video',\n 'screencast',\n 'show me',\n 'can you show',\n ];\n if (demoKeywords.some((kw) => lower.includes(kw))) {\n hints.push('demo_requested');\n }\n\n // Test requests\n const testKeywords = [\n 'add test',\n 'test coverage',\n 'unit test',\n 'missing test',\n 'add a test',\n 'write test',\n 'needs test',\n 'need test',\n ];\n if (testKeywords.some((kw) => lower.includes(kw))) {\n hints.push('tests_requested');\n }\n\n // Documentation requests\n const docKeywords = ['documentation', 'readme', 'jsdoc', 'docstring', 'add docs', 'update docs', 'document this'];\n if (docKeywords.some((kw) => lower.includes(kw))) {\n hints.push('docs_requested');\n }\n\n // Rebase requests\n const rebaseKeywords = ['rebase', 'merge conflict', 'out of date', 'behind main', 'behind master'];\n if (rebaseKeywords.some((kw) => lower.includes(kw))) {\n hints.push('rebase_requested');\n }\n\n return hints;\n}\n", "/**\n * Display Utils - Human-readable display label computation for PR statuses.\n * Extracted from PRMonitor to isolate presentation logic (#263).\n *\n * Uses two reason-keyed maps (ACTION_DISPLAY / WAIT_DISPLAY) instead of a\n * single status-keyed map, reflecting the 2-status taxonomy where the\n * granular reason lives in `actionReason` / `waitReason`.\n */\n\nimport { FetchedPR, ActionReason, WaitReason } from './types.js';\nimport { warn } from './logger.js';\n\nconst ACTION_DISPLAY: Record<ActionReason, { label: string; description: (pr: FetchedPR) => string }> = {\n needs_response: {\n label: '[Needs Response]',\n description: (pr) =>\n pr.lastMaintainerComment ? `@${pr.lastMaintainerComment.author} commented` : 'Maintainer awaiting response',\n },\n needs_changes: {\n label: '[Needs Changes]',\n description: () => 'Review requested changes \u2014 push commits to address',\n },\n failing_ci: {\n label: '[CI Failing]',\n description: (pr) => {\n const checks = pr.classifiedChecks || [];\n const actionable = checks.filter((c) => c.category === 'actionable');\n if (actionable.length > 0)\n return `${actionable.length} check${actionable.length === 1 ? '' : 's'} failed: ${actionable.map((c) => c.name).join(', ')}`;\n const infrastructure = checks.filter((c) => c.category === 'infrastructure');\n if (infrastructure.length > 0)\n return `${infrastructure.length} check${infrastructure.length === 1 ? '' : 's'} cancelled/timed out (infrastructure)`;\n const failingNames = pr.failingCheckNames || [];\n if (failingNames.length > 0) return `${failingNames.length} check${failingNames.length === 1 ? '' : 's'} failed`;\n return 'One or more CI checks are failing';\n },\n },\n merge_conflict: {\n label: '[Merge Conflict]',\n description: () => 'PR has merge conflicts with the base branch',\n },\n incomplete_checklist: {\n label: '[Incomplete Checklist]',\n description: (pr) =>\n pr.checklistStats\n ? `${pr.checklistStats.checked}/${pr.checklistStats.total} items checked`\n : 'PR body has unchecked required checkboxes',\n },\n ci_not_running: {\n label: '[CI Not Running]',\n description: () => 'No CI checks have been triggered',\n },\n needs_rebase: {\n label: '[Needs Rebase]',\n description: () => 'PR branch is significantly behind upstream',\n },\n missing_required_files: {\n label: '[Missing Files]',\n description: (pr) =>\n pr.missingRequiredFiles ? `Missing: ${pr.missingRequiredFiles.join(', ')}` : 'Required files are missing',\n },\n};\n\nconst WAIT_DISPLAY: Record<WaitReason, { label: string; description: (pr: FetchedPR) => string }> = {\n pending_review: {\n label: '[Waiting on Maintainer]',\n description: () => 'Awaiting review',\n },\n pending_merge: {\n label: '[Waiting on Maintainer]',\n description: () => 'Approved and CI passes \u2014 waiting for merge',\n },\n changes_addressed: {\n label: '[Waiting on Maintainer]',\n description: (pr) => {\n if (pr.hasUnrespondedComment && pr.lastMaintainerComment) {\n return `Changes addressed \u2014 waiting for @${pr.lastMaintainerComment.author} to re-review`;\n }\n return 'Changes addressed \u2014 awaiting re-review';\n },\n },\n ci_blocked: {\n label: '[CI Blocked]',\n description: (pr) => {\n const checks = pr.classifiedChecks || [];\n if (checks.length > 0 && checks.every((c) => c.category !== 'actionable')) {\n const categories = [...new Set(checks.map((c) => c.category))];\n return `All failing checks are non-actionable (${categories.join(', ')})`;\n }\n return 'CI checks are failing but no action is needed from you';\n },\n },\n};\n\n/** Compute display label and description for a FetchedPR (#79). */\nexport function computeDisplayLabel(pr: FetchedPR): { displayLabel: string; displayDescription: string } {\n if (pr.status === 'needs_addressing' && pr.actionReason) {\n const entry = ACTION_DISPLAY[pr.actionReason];\n if (entry) return { displayLabel: entry.label, displayDescription: entry.description(pr) };\n }\n if (pr.status === 'waiting_on_maintainer' && pr.waitReason) {\n const entry = WAIT_DISPLAY[pr.waitReason];\n if (entry) return { displayLabel: entry.label, displayDescription: entry.description(pr) };\n }\n // Fallback for missing reason \u2014 log so we can identify data issues\n warn(\n 'display-utils',\n `PR ${pr.url} has status \"${pr.status}\" but no matching reason (actionReason=${pr.actionReason}, waitReason=${pr.waitReason})`,\n );\n if (pr.status === 'needs_addressing') {\n return { displayLabel: '[Needs Addressing]', displayDescription: 'Action required' };\n }\n return { displayLabel: '[Waiting on Maintainer]', displayDescription: 'Awaiting maintainer action' };\n}\n", "/**\n * GitHub Stats - Fetching merged/closed PR counts and repository star counts.\n * Extracted from PRMonitor to isolate statistics-gathering API calls (#263).\n */\n\nimport { Octokit } from '@octokit/rest';\nimport { extractOwnerRepo, parseGitHubUrl, isOwnRepo } from './utils.js';\nimport { ClosedPR, MergedPR, StoredMergedPR, StoredClosedPR, isBelowMinStars, type StarFilter } from './types.js';\nimport { debug, warn } from './logger.js';\nimport { getHttpCache } from './http-cache.js';\n\nconst MODULE = 'github-stats';\n\n/** TTL for cached PR count results (24 hours \u2014 these stats change slowly). */\nexport const PR_COUNTS_CACHE_TTL_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Maximum number of pages to fetch during paginated PR count searches.\n * GitHub's Search API becomes unreliable (500s, ECONNRESET) at deep pages (4-5+).\n * 3 pages \u00D7 100 per_page = 300 results, which covers the vast majority of users.\n */\nconst MAX_PAGINATION_PAGES = 3;\n\n/** Shape of a search result item from octokit.search.issuesAndPullRequests. */\ntype SearchItem = {\n html_url: string;\n created_at?: string;\n closed_at: string | null;\n pull_request?: { merged_at?: string | null };\n};\n\n/** Return type shared by both merged and closed PR count functions. */\nexport interface PRCountsResult<R> {\n repos: Map<string, R>;\n monthlyCounts: Record<string, number>;\n monthlyOpenedCounts: Record<string, number>;\n dailyActivityCounts: Record<string, number>;\n}\n\n/** Returns an empty PRCountsResult. Used as the fallback when stats fetches fail or username is empty. */\nexport function emptyPRCountsResult<R>(): PRCountsResult<R> {\n return { repos: new Map(), monthlyCounts: {}, monthlyOpenedCounts: {}, dailyActivityCounts: {} };\n}\n\n/** Serialized shape of a cached PRCountsResult (Map stored as entries array). */\ninterface CachedPRCounts {\n reposEntries: [string, unknown][];\n monthlyCounts: Record<string, number>;\n monthlyOpenedCounts: Record<string, number>;\n dailyActivityCounts: Record<string, number>;\n}\n\n/** Type guard for deserialized cache data \u2014 prevents crashes on corrupt/stale cache. */\nfunction isCachedPRCounts(v: unknown): v is CachedPRCounts {\n if (typeof v !== 'object' || v === null) return false;\n const obj = v as Record<string, unknown>;\n return (\n Array.isArray(obj.reposEntries) &&\n typeof obj.monthlyCounts === 'object' &&\n obj.monthlyCounts !== null &&\n typeof obj.monthlyOpenedCounts === 'object' &&\n obj.monthlyOpenedCounts !== null &&\n typeof obj.dailyActivityCounts === 'object' &&\n obj.dailyActivityCounts !== null\n );\n}\n\n/**\n * Shared paginated search for user PR counts with histogram tracking.\n *\n * Handles: pagination, owner extraction, skip-own-repos, monthly/daily histograms.\n * The `accumulateRepo` callback handles per-repo data and returns the primary date\n * string (e.g. mergedAt or closedAt) used for monthly counts and daily activity.\n * Return an empty string to skip histogram tracking for that item.\n */\nasync function fetchUserPRCounts<R>(\n octokit: Octokit,\n githubUsername: string,\n query: string,\n label: string,\n accumulateRepo: (repos: Map<string, R>, repo: string, item: SearchItem) => string,\n starFilter?: StarFilter,\n): Promise<PRCountsResult<R>> {\n if (!githubUsername) {\n return emptyPRCountsResult<R>();\n }\n\n // Check for a fresh cached result (avoids 10-20 paginated API calls)\n const cache = getHttpCache();\n const minStarsSuffix = starFilter ? `:stars${starFilter.minStars}` : '';\n const cacheKey = `pr-counts:v3:${label}:${githubUsername}${minStarsSuffix}`;\n const cached = cache.getIfFresh(cacheKey, PR_COUNTS_CACHE_TTL_MS);\n if (cached && isCachedPRCounts(cached)) {\n debug(MODULE, `Using cached ${label} PR counts for @${githubUsername}`);\n return {\n repos: new Map(cached.reposEntries as [string, R][]),\n monthlyCounts: cached.monthlyCounts,\n monthlyOpenedCounts: cached.monthlyOpenedCounts,\n dailyActivityCounts: cached.dailyActivityCounts,\n };\n }\n\n debug(MODULE, `Fetching ${label} PR counts for @${githubUsername}...`);\n\n const repos = new Map<string, R>();\n const monthlyCounts: Record<string, number> = {};\n const monthlyOpenedCounts: Record<string, number> = {};\n const dailyActivityCounts: Record<string, number> = {};\n let page = 1;\n let fetched = 0;\n let totalCount!: number;\n\n while (true) {\n const { data } = await octokit.search.issuesAndPullRequests({\n q: `is:pr ${query} author:${githubUsername} -user:${githubUsername}`,\n sort: 'updated',\n order: 'desc',\n per_page: 100,\n page,\n });\n\n totalCount = data.total_count;\n\n for (const item of data.items) {\n const parsed = extractOwnerRepo(item.html_url);\n if (!parsed) {\n warn(MODULE, `Skipping ${label} PR with unparseable URL: ${item.html_url}`);\n continue;\n }\n\n const { owner } = parsed;\n const repo = `${owner}/${parsed.repo}`;\n\n // Skip own repos (PRs to your own repos aren't OSS contributions)\n if (isOwnRepo(owner, githubUsername)) continue;\n\n // Skip repos below the minimum star threshold (#576).\n // Repos with unknown star counts (not yet fetched) are also excluded (fail-closed).\n if (starFilter && isBelowMinStars(starFilter.knownStarCounts.get(repo), starFilter.minStars)) {\n continue;\n }\n\n // Per-repo accumulation + get primary date for histograms\n const primaryDate = accumulateRepo(repos, repo, item);\n\n // Monthly histogram for primary date (merged/closed)\n if (primaryDate) {\n const month = primaryDate.slice(0, 7); // \"YYYY-MM\"\n monthlyCounts[month] = (monthlyCounts[month] || 0) + 1;\n // Daily activity for primary date\n const day = primaryDate.slice(0, 10);\n if (day.length === 10) dailyActivityCounts[day] = (dailyActivityCounts[day] || 0) + 1;\n }\n\n // Track when this PR was opened (for monthly opened histogram + daily activity)\n if (item.created_at) {\n const openedMonth = item.created_at.slice(0, 7); // \"YYYY-MM\"\n monthlyOpenedCounts[openedMonth] = (monthlyOpenedCounts[openedMonth] || 0) + 1;\n const openedDay = item.created_at.slice(0, 10);\n if (openedDay.length === 10) dailyActivityCounts[openedDay] = (dailyActivityCounts[openedDay] || 0) + 1;\n }\n }\n\n fetched += data.items.length;\n\n // Stop if we've fetched all results, hit the API limit (1000), or reached max pages\n // GitHub Search API returns 500/ECONNRESET on deep pagination (page 4-5+),\n // so we cap at MAX_PAGINATION_PAGES to avoid taking down the entire startup flow.\n if (fetched >= data.total_count || fetched >= 1000 || data.items.length === 0 || page >= MAX_PAGINATION_PAGES) {\n break;\n }\n\n page++;\n }\n\n if (fetched < totalCount && page >= MAX_PAGINATION_PAGES) {\n warn(\n MODULE,\n `Pagination capped at ${MAX_PAGINATION_PAGES} pages: fetched ${fetched} of ${totalCount} ${label} PRs. Stats may be incomplete for prolific contributors.`,\n );\n }\n\n debug(MODULE, `Found ${fetched} ${label} PRs across ${repos.size} repos`);\n\n // Cache the aggregated result (Map \u2192 entries array for JSON serialization).\n // Note: truncated results (from pagination cap) are cached with the same TTL. This is an\n // accepted tradeoff \u2014 prolific contributors (300+ PRs) may see slightly incomplete stats\n // for up to 24 hours, but these are cosmetic and self-heal on the next cache expiry.\n cache.set(cacheKey, '', {\n reposEntries: Array.from(repos.entries()),\n monthlyCounts,\n monthlyOpenedCounts,\n dailyActivityCounts,\n });\n\n return { repos, monthlyCounts, monthlyOpenedCounts, dailyActivityCounts };\n}\n\n/**\n * Fetch merged PR counts and latest merge dates per repository for the configured user.\n * Also builds a monthly histogram of all merges for the contribution timeline.\n */\nexport function fetchUserMergedPRCounts(\n octokit: Octokit,\n githubUsername: string,\n starFilter?: StarFilter,\n): Promise<PRCountsResult<{ count: number; lastMergedAt: string }>> {\n return fetchUserPRCounts(\n octokit,\n githubUsername,\n 'is:merged',\n 'merged',\n (repos, repo, item) => {\n if (!item.pull_request?.merged_at) {\n warn(\n MODULE,\n `merged_at missing for merged PR ${item.html_url}${item.closed_at ? ', falling back to closed_at' : ', no date available'}`,\n );\n }\n const mergedAt = item.pull_request?.merged_at || item.closed_at || '';\n\n const existing = repos.get(repo);\n if (existing) {\n existing.count += 1;\n if (mergedAt && mergedAt > existing.lastMergedAt) {\n existing.lastMergedAt = mergedAt;\n }\n } else {\n repos.set(repo, { count: 1, lastMergedAt: mergedAt });\n }\n\n return mergedAt;\n },\n starFilter,\n );\n}\n\n/**\n * Fetch closed-without-merge PR counts per repository for the configured user.\n * Used to populate closedWithoutMergeCount in repo scores for accurate merge rate.\n */\nexport function fetchUserClosedPRCounts(\n octokit: Octokit,\n githubUsername: string,\n starFilter?: StarFilter,\n): Promise<PRCountsResult<number>> {\n return fetchUserPRCounts(\n octokit,\n githubUsername,\n 'is:closed is:unmerged',\n 'closed',\n (repos, repo, item) => {\n repos.set(repo, (repos.get(repo) || 0) + 1);\n return item.closed_at || '';\n },\n starFilter,\n );\n}\n\n/**\n * Shared helper: search for recent PRs and filter out own repos.\n */\nasync function fetchRecentPRs<T>(\n octokit: Octokit,\n config: { githubUsername: string },\n query: string,\n label: string,\n days: number,\n mapItem: (\n item: { html_url: string; title: string; closed_at: string | null; pull_request?: { merged_at?: string | null } },\n parsed: { owner: string; repo: string; number: number },\n ) => T,\n): Promise<T[]> {\n if (!config.githubUsername) {\n warn(MODULE, `Skipping recently ${label} PRs fetch: no githubUsername configured. Run /setup-oss to configure.`);\n return [];\n }\n\n const sinceDate = new Date();\n sinceDate.setDate(sinceDate.getDate() - days);\n const since = sinceDate.toISOString().split('T')[0]; // YYYY-MM-DD\n\n debug(MODULE, `Fetching recently ${label} PRs for @${config.githubUsername} (since ${since})...`);\n\n const { data } = await octokit.search.issuesAndPullRequests({\n q: query.replace('{username}', config.githubUsername).replace('{since}', since),\n sort: 'updated',\n order: 'desc',\n per_page: 100,\n });\n\n const results: T[] = [];\n\n for (const item of data.items) {\n const parsed = parseGitHubUrl(item.html_url);\n if (!parsed) {\n warn(MODULE, `Could not parse GitHub URL from API response: ${item.html_url}`);\n continue;\n }\n\n const repo = `${parsed.owner}/${parsed.repo}`;\n\n // Skip own repos\n if (isOwnRepo(parsed.owner, config.githubUsername)) continue;\n\n results.push(mapItem(item, { owner: parsed.owner, repo, number: parsed.number }));\n }\n\n debug(MODULE, `Found ${results.length} recently ${label} PRs`);\n return results;\n}\n\n/**\n * Fetch PRs closed without merge in the last N days.\n * Returns lightweight ClosedPR objects for surfacing in the daily digest.\n */\nexport async function fetchRecentlyClosedPRs(\n octokit: Octokit,\n config: { githubUsername: string },\n days: number = 7,\n): Promise<ClosedPR[]> {\n return fetchRecentPRs<ClosedPR>(\n octokit,\n config,\n 'is:pr is:closed is:unmerged author:{username} closed:>={since}',\n 'closed',\n days,\n (item, { repo, number }) => ({\n url: item.html_url,\n repo,\n number,\n title: item.title,\n closedAt: item.closed_at || '',\n }),\n );\n}\n\n/**\n * Fetch PRs merged in the last N days.\n * Returns lightweight MergedPR objects for surfacing as wins in the dashboard.\n */\nexport async function fetchRecentlyMergedPRs(\n octokit: Octokit,\n config: { githubUsername: string },\n days: number = 7,\n): Promise<MergedPR[]> {\n return fetchRecentPRs<MergedPR>(\n octokit,\n config,\n 'is:pr is:merged author:{username} merged:>={since}',\n 'merged',\n days,\n (item, { repo, number }) => {\n const mergedAt = item.pull_request?.merged_at;\n if (!mergedAt) {\n warn(\n MODULE,\n `merged_at missing for merged PR ${item.html_url}${item.closed_at ? ', falling back to closed_at' : ', no date available'}`,\n );\n }\n return {\n url: item.html_url,\n repo,\n number,\n title: item.title,\n mergedAt: mergedAt || item.closed_at || '',\n };\n },\n );\n}\n\n/**\n * Fetch merged PRs since a watermark date for incremental storage.\n * If no watermark is provided (first-ever fetch), fetches all merged PRs (up to pagination cap).\n * Returns StoredMergedPR[] (minimal: url, title, mergedAt) for state persistence.\n */\nexport async function fetchMergedPRsSince(\n octokit: Octokit,\n config: { githubUsername: string },\n since?: string,\n): Promise<StoredMergedPR[]> {\n if (!config.githubUsername) {\n warn(MODULE, 'Skipping merged PRs fetch: no githubUsername configured.');\n return [];\n }\n\n const dateFilter = since ? ` merged:>${since}` : '';\n const q = `is:pr is:merged author:${config.githubUsername} -user:${config.githubUsername}${dateFilter}`;\n\n debug(MODULE, `Fetching merged PRs${since ? ` since ${since}` : ' (all time)'}...`);\n\n const results: StoredMergedPR[] = [];\n let page = 1;\n let fetched = 0;\n\n while (true) {\n const { data } = await octokit.search.issuesAndPullRequests({\n q,\n sort: 'updated',\n order: 'desc',\n per_page: 100,\n page,\n });\n\n for (const item of data.items) {\n const parsed = parseGitHubUrl(item.html_url);\n if (!parsed) {\n warn(MODULE, `Skipping merged PR with unparseable URL: ${item.html_url}`);\n continue;\n }\n if (isOwnRepo(parsed.owner, config.githubUsername)) continue;\n\n const mergedAt = item.pull_request?.merged_at || item.closed_at || '';\n if (!mergedAt) {\n warn(MODULE, `Skipping merged PR with no merge date: ${item.html_url}`);\n continue;\n }\n results.push({\n url: item.html_url,\n title: item.title,\n mergedAt,\n });\n }\n\n fetched += data.items.length;\n\n if (fetched >= data.total_count || fetched >= 1000 || data.items.length === 0 || page >= MAX_PAGINATION_PAGES) {\n break;\n }\n\n page++;\n }\n\n debug(MODULE, `Fetched ${results.length} merged PRs${since ? ' (incremental)' : ' (initial)'}`);\n return results;\n}\n\n/**\n * Fetch closed-without-merge PRs since a watermark date for incremental storage.\n * If no watermark is provided (first-ever fetch), fetches all closed PRs (up to pagination cap).\n * Returns StoredClosedPR[] (minimal: url, title, closedAt) for state persistence.\n * Uses `is:unmerged` to exclude merged PRs (which are also \"closed\" in GitHub's model).\n */\nexport async function fetchClosedPRsSince(\n octokit: Octokit,\n config: { githubUsername: string },\n since?: string,\n): Promise<StoredClosedPR[]> {\n if (!config.githubUsername) {\n warn(MODULE, 'Skipping closed PRs fetch: no githubUsername configured.');\n return [];\n }\n\n const dateFilter = since ? ` closed:>${since}` : '';\n const q = `is:pr is:closed is:unmerged author:${config.githubUsername} -user:${config.githubUsername}${dateFilter}`;\n\n debug(MODULE, `Fetching closed PRs${since ? ` since ${since}` : ' (all time)'}...`);\n\n const results: StoredClosedPR[] = [];\n let page = 1;\n let fetched = 0;\n let totalCount: number;\n\n while (true) {\n const { data } = await octokit.search.issuesAndPullRequests({\n q,\n sort: 'updated',\n order: 'desc',\n per_page: 100,\n page,\n });\n\n totalCount = data.total_count;\n\n for (const item of data.items) {\n const parsed = parseGitHubUrl(item.html_url);\n if (!parsed) {\n warn(MODULE, `Skipping closed PR with unparseable URL: ${item.html_url}`);\n continue;\n }\n if (isOwnRepo(parsed.owner, config.githubUsername)) continue;\n\n const closedAt = item.closed_at || '';\n if (!closedAt) {\n warn(MODULE, `Skipping closed PR with no close date: ${item.html_url}`);\n continue;\n }\n results.push({\n url: item.html_url,\n title: item.title,\n closedAt,\n });\n }\n\n fetched += data.items.length;\n\n if (fetched >= totalCount || fetched >= 1000 || data.items.length === 0 || page >= MAX_PAGINATION_PAGES) {\n break;\n }\n\n page++;\n }\n\n if (fetched < totalCount && page >= MAX_PAGINATION_PAGES) {\n warn(\n MODULE,\n `Pagination capped at ${MAX_PAGINATION_PAGES} pages: fetched ${fetched} of ${totalCount} closed PRs. Oldest PRs may be missing.`,\n );\n }\n\n debug(MODULE, `Fetched ${results.length} closed PRs${since ? ' (incremental)' : ' (initial)'}`);\n return results;\n}\n", "/**\n * PR Monitor - Fetches and checks PR status from GitHub.\n * v2: fetchUserOpenPRs() is stateless (no local PR tracking),\n * Score methods still write to state.\n *\n * Decomposed into focused modules (#263):\n * - ci-analysis.ts: CI check classification and analysis\n * - review-analysis.ts: Review decision and comment detection\n * - checklist-analysis.ts: PR body checklist analysis\n * - maintainer-analysis.ts: Maintainer action hint extraction\n * - display-utils.ts: Display label computation\n * - github-stats.ts: Merged/closed PR counts and star fetching\n * - status-determination.ts: PR status classification logic\n */\n\nimport { Octokit } from '@octokit/rest';\nimport { getOctokit } from './github.js';\nimport { getStateManager } from './state.js';\nimport { daysBetween, parseGitHubUrl, extractOwnerRepo, isOwnRepo, DEFAULT_CONCURRENCY } from './utils.js';\nimport { FetchedPR, CIStatusResult, DailyDigest, ClosedPR, MergedPR, StarFilter } from './types.js';\nimport { determineStatus } from './status-determination.js';\nimport { runWorkerPool } from './concurrency.js';\nimport { ConfigurationError, ValidationError, errorMessage, getHttpStatusCode } from './errors.js';\nimport { paginateAll } from './pagination.js';\nimport { debug, warn, timed } from './logger.js';\nimport { getHttpCache, cachedRequest } from './http-cache.js';\n\n// Extracted modules\nimport { classifyFailingChecks, analyzeCheckRuns, analyzeCombinedStatus, mergeStatuses } from './ci-analysis.js';\nimport {\n type ReviewComment,\n determineReviewDecision,\n getLatestChangesRequestedDate,\n checkUnrespondedComments,\n} from './review-analysis.js';\nimport { analyzeChecklist } from './checklist-analysis.js';\nimport { extractMaintainerActionHints } from './maintainer-analysis.js';\nimport { computeDisplayLabel } from './display-utils.js';\nimport {\n type PRCountsResult,\n fetchUserMergedPRCounts as fetchUserMergedPRCountsImpl,\n fetchUserClosedPRCounts as fetchUserClosedPRCountsImpl,\n fetchRecentlyClosedPRs as fetchRecentlyClosedPRsImpl,\n fetchRecentlyMergedPRs as fetchRecentlyMergedPRsImpl,\n} from './github-stats.js';\n\n// Re-export so existing consumers can still import from pr-monitor\nexport { computeDisplayLabel } from './display-utils.js';\nexport { classifyCICheck, classifyFailingChecks } from './ci-analysis.js';\nexport { isConditionalChecklistItem } from './checklist-analysis.js';\nexport { determineStatus } from './status-determination.js';\n\nconst MODULE = 'pr-monitor';\n\nconst MAX_CONCURRENT_REQUESTS = DEFAULT_CONCURRENCY;\n\nexport interface PRCheckFailure {\n prUrl: string;\n error: string;\n}\n\nexport interface FetchPRsResult {\n prs: FetchedPR[];\n failures: PRCheckFailure[];\n}\n\nexport class PRMonitor {\n private octokit: Octokit;\n private stateManager: ReturnType<typeof getStateManager>;\n\n constructor(githubToken: string) {\n this.octokit = getOctokit(githubToken);\n this.stateManager = getStateManager();\n }\n\n /**\n * Fetch all open PRs for the configured user fresh from GitHub\n * This is the main entry point for the v2 architecture\n */\n async fetchUserOpenPRs(): Promise<FetchPRsResult> {\n const config = this.stateManager.getState().config;\n\n if (!config.githubUsername) {\n throw new ConfigurationError('No GitHub username configured. Run setup first.');\n }\n\n debug('pr-monitor', `Fetching open PRs for @${config.githubUsername}...`);\n\n // Search for all open PRs authored by the user with pagination\n const allItems: typeof firstPage.data.items = [];\n let page = 1;\n const perPage = 100;\n\n const firstPage = await this.octokit.search.issuesAndPullRequests({\n q: `is:pr is:open author:${config.githubUsername}`,\n sort: 'updated',\n order: 'desc',\n per_page: perPage,\n page: 1,\n });\n\n allItems.push(...firstPage.data.items);\n const totalCount = firstPage.data.total_count;\n debug('pr-monitor', `Found ${totalCount} open PRs`);\n\n // Fetch remaining pages if needed (GitHub search API returns max 1000 results)\n const totalPages = Math.min(Math.ceil(totalCount / perPage), 10); // Cap at 1000 results\n while (page < totalPages) {\n page++;\n const nextPage = await this.octokit.search.issuesAndPullRequests({\n q: `is:pr is:open author:${config.githubUsername}`,\n sort: 'updated',\n order: 'desc',\n per_page: perPage,\n page,\n });\n allItems.push(...nextPage.data.items);\n }\n\n // Filter items to only PRs worth fetching\n const prs: FetchedPR[] = [];\n const failures: PRCheckFailure[] = [];\n\n const filteredItems = allItems.filter((item) => {\n if (!item.pull_request) return false;\n // Skip PRs to repos owned by the user (not OSS contributions)\n const parsed = extractOwnerRepo(item.html_url);\n if (!parsed) {\n warn('pr-monitor', `Skipping PR with unparseable URL: ${item.html_url}`);\n return false;\n }\n if (isOwnRepo(parsed.owner, config.githubUsername)) return false;\n return true;\n });\n\n debug('pr-monitor', `Filtered to ${filteredItems.length} PRs after excluding own repos`);\n\n // Fetch detailed info using a worker pool for bounded concurrency.\n await timed('pr-monitor', `Fetch details for ${filteredItems.length} PRs`, async () => {\n await runWorkerPool(\n filteredItems,\n async (item) => {\n try {\n debug('pr-monitor', `Fetching details for ${item.html_url}`);\n const pr = await this.fetchPRDetails(item.html_url);\n if (pr) prs.push(pr);\n } catch (error) {\n const errMsg = errorMessage(error);\n warn('pr-monitor', `Error fetching ${item.html_url}: ${errMsg}`);\n failures.push({ prUrl: item.html_url, error: errMsg });\n }\n },\n MAX_CONCURRENT_REQUESTS,\n );\n });\n\n // Sort by status (needs_addressing first, then waiting_on_maintainer)\n prs.sort((a, b) => {\n if (a.status === b.status) return 0;\n return a.status === 'needs_addressing' ? -1 : 1;\n });\n\n return { prs, failures };\n }\n\n /**\n * Fetch detailed information for a single PR\n */\n private async fetchPRDetails(prUrl: string): Promise<FetchedPR | null> {\n const parsed = parseGitHubUrl(prUrl);\n if (!parsed || parsed.type !== 'pull') {\n throw new ValidationError(`Invalid PR URL format: ${prUrl}`);\n }\n\n const { owner, repo, number } = parsed;\n const config = this.stateManager.getState().config;\n\n // Fetch PR data, comments, reviews, and inline review comments in parallel.\n // listReviewComments is non-critical (used for self-reply detection), so degrade\n // gracefully on failure rather than dropping the entire PR (#199).\n const [prResponse, comments, reviewsResponse, reviewComments] = await Promise.all([\n this.octokit.pulls.get({ owner, repo, pull_number: number }),\n paginateAll((page) =>\n this.octokit.issues.listComments({ owner, repo, issue_number: number, per_page: 100, page }),\n ),\n this.octokit.pulls.listReviews({ owner, repo, pull_number: number }),\n paginateAll((page) =>\n this.octokit.pulls.listReviewComments({ owner, repo, pull_number: number, per_page: 100, page }),\n ).catch((err: unknown) => {\n const status = getHttpStatusCode(err);\n // Rate limit errors must propagate \u2014 silently swallowing them hides\n // a systemic problem and produces misleading results (#229).\n if (status === 429) {\n throw err;\n }\n if (status === 403) {\n const msg = errorMessage(err).toLowerCase();\n if (msg.includes('rate limit') || msg.includes('abuse detection')) {\n throw err;\n }\n // Non-rate-limit 403 (DMCA, private repo, SSO) \u2014 degrade gracefully\n warn('pr-monitor', `403 fetching review comments for ${owner}/${repo}#${number}: ${msg}`);\n return [] as ReviewComment[];\n }\n if (status === 404) {\n debug('pr-monitor', `Review comments 404 for ${owner}/${repo}#${number} (likely no inline comments)`);\n } else {\n warn(\n 'pr-monitor',\n `Failed to fetch review comments for ${owner}/${repo}#${number} (status ${status ?? 'unknown'}): self-reply detection will be skipped`,\n );\n }\n return [] as ReviewComment[];\n }),\n ]);\n\n const ghPR = prResponse.data;\n const reviews = reviewsResponse.data;\n\n // Determine review decision (delegated to review-analysis module)\n const reviewDecision = determineReviewDecision(reviews);\n\n // Check for merge conflict\n const hasMergeConflict = this.hasMergeConflict(ghPR.mergeable, ghPR.mergeable_state);\n\n // Check if there's an unresponded maintainer comment (delegated to review-analysis module)\n const { hasUnrespondedComment, lastMaintainerComment } = checkUnrespondedComments(\n comments,\n reviews,\n reviewComments,\n config.githubUsername,\n );\n\n // Fetch CI status and (conditionally) latest commit date in parallel\n // We need the commit date when hasUnrespondedComment is true (to distinguish\n // \"needs_response\" from \"waiting_on_maintainer\") OR when reviewDecision is \"changes_requested\"\n // (to detect needs_changes: review requested changes but no new commits pushed)\n const ciPromise = this.getCIStatus(owner, repo, ghPR.head.sha);\n const needCommitDate = hasUnrespondedComment || reviewDecision === 'changes_requested';\n const commitInfoPromise = needCommitDate\n ? this.octokit.repos\n .getCommit({ owner, repo, ref: ghPR.head.sha })\n .then((res) => ({\n date: res.data.commit.author?.date,\n // GitHub user login of the commit author (may differ from git author)\n author: res.data.author?.login,\n }))\n .catch((err: unknown) => {\n // Rate limit errors must propagate \u2014 silently swallowing them produces\n // misleading status (e.g. needs_changes when changes were addressed) (#469).\n const status = getHttpStatusCode(err);\n if (status === 429) throw err;\n if (status === 403) {\n const msg = errorMessage(err).toLowerCase();\n if (msg.includes('rate limit') || msg.includes('abuse detection')) throw err;\n // Non-rate-limit 403 (DMCA, private repo, SSO) \u2014 degrade gracefully\n warn(\n 'pr-monitor',\n `403 fetching commit date for ${owner}/${repo}@${ghPR.head.sha.slice(0, 7)}: ${errorMessage(err)}`,\n );\n return undefined;\n }\n warn(\n 'pr-monitor',\n `Failed to fetch commit date for ${owner}/${repo}@${ghPR.head.sha.slice(0, 7)}: ${errorMessage(err)}`,\n );\n return undefined;\n })\n : Promise.resolve(undefined);\n\n const [{ status: ciStatus, failingCheckNames, failingCheckConclusions }, commitInfo] = await Promise.all([\n ciPromise,\n commitInfoPromise,\n ]);\n const latestCommitDate = commitInfo?.date;\n const latestCommitAuthor = commitInfo?.author;\n\n // Analyze PR body for incomplete checklists (delegated to checklist-analysis module)\n const { hasIncompleteChecklist, checklistStats } = analyzeChecklist(ghPR.body || '');\n\n // Extract maintainer action hints from comments (delegated to maintainer-analysis module)\n const maintainerActionHints = extractMaintainerActionHints(lastMaintainerComment?.body, reviewDecision);\n\n // Calculate days since activity\n const daysSinceActivity = daysBetween(new Date(ghPR.updated_at), new Date());\n\n // Find the date of the latest changes_requested review (delegated to review-analysis module)\n const latestChangesRequestedDate = getLatestChangesRequestedDate(reviews);\n\n // Classify failing checks (delegated to ci-analysis module)\n const classifiedChecks = classifyFailingChecks(failingCheckNames, failingCheckConclusions);\n\n // Determine status\n const hasActionableCIFailure = ciStatus === 'failing' && classifiedChecks.some((c) => c.category === 'actionable');\n const { status, actionReason, waitReason, stalenessTier } = determineStatus({\n ciStatus,\n hasMergeConflict,\n hasUnrespondedComment,\n hasIncompleteChecklist,\n reviewDecision,\n daysSinceActivity,\n dormantThreshold: config.dormantThresholdDays,\n approachingThreshold: config.approachingDormantDays,\n latestCommitDate,\n latestCommitAuthor,\n contributorUsername: config.githubUsername,\n lastMaintainerCommentDate: lastMaintainerComment?.createdAt,\n latestChangesRequestedDate,\n hasActionableCIFailure,\n });\n\n return this.buildFetchedPR({\n id: ghPR.id,\n url: prUrl,\n repo: `${owner}/${repo}`,\n number,\n title: ghPR.title,\n status,\n actionReason,\n waitReason,\n stalenessTier,\n createdAt: ghPR.created_at,\n updatedAt: ghPR.updated_at,\n daysSinceActivity,\n ciStatus,\n failingCheckNames,\n classifiedChecks,\n hasMergeConflict,\n reviewDecision,\n hasUnrespondedComment,\n lastMaintainerComment,\n latestCommitDate,\n hasIncompleteChecklist,\n checklistStats,\n maintainerActionHints,\n });\n }\n\n /**\n * Build a FetchedPR object from computed fields and attach display labels.\n * Centralizes PR construction and display label computation (#79).\n */\n private buildFetchedPR(fields: Omit<FetchedPR, 'displayLabel' | 'displayDescription'>): FetchedPR {\n const pr: FetchedPR = {\n ...fields,\n displayLabel: '', // computed below\n displayDescription: '', // computed below\n };\n\n // Compute display labels (#79) \u2014 delegated to display-utils module\n const { displayLabel, displayDescription } = computeDisplayLabel(pr);\n pr.displayLabel = displayLabel;\n pr.displayDescription = displayDescription;\n\n return pr;\n }\n\n /**\n * Check if PR has merge conflict\n */\n private hasMergeConflict(mergeable: boolean | null, mergeableState: string | null): boolean {\n return mergeable === false || mergeableState === 'dirty';\n }\n\n /**\n * Get CI status from combined status API and check runs.\n * Returns status and names of failing checks for diagnostics.\n * Delegates analysis to ci-analysis module.\n */\n private async getCIStatus(owner: string, repo: string, sha: string): Promise<CIStatusResult> {\n if (!sha) return { status: 'unknown', failingCheckNames: [], failingCheckConclusions: new Map() };\n\n try {\n // Fetch both combined status and check runs in parallel\n const [statusResponse, checksResponse] = await Promise.all([\n this.octokit.repos.getCombinedStatusForRef({ owner, repo, ref: sha }),\n // 404 is expected for repos without check runs configured; log other errors for debugging\n this.octokit.checks.listForRef({ owner, repo, ref: sha }).catch((err: unknown) => {\n const status = getHttpStatusCode(err);\n // Rate limit errors must propagate \u2014 matches listReviewComments pattern (#481)\n if (status === 429) throw err;\n if (status === 403) {\n const msg = errorMessage(err).toLowerCase();\n if (msg.includes('rate limit') || msg.includes('abuse detection')) throw err;\n }\n if (status === 404) {\n debug('pr-monitor', `Check runs 404 for ${owner}/${repo}@${sha.slice(0, 7)} (no checks configured)`);\n } else {\n warn(\n 'pr-monitor',\n `Non-404 error fetching check runs for ${owner}/${repo}@${sha.slice(0, 7)}: ${status ?? err}`,\n );\n }\n return null;\n }),\n ]);\n\n const combinedStatus = statusResponse.data;\n const allCheckRuns = checksResponse?.data?.check_runs || [];\n\n // Deduplicate check runs by name, keeping only the most recent run per unique name.\n // GitHub returns all historical runs (including re-runs), so without deduplication\n // a superseded failure will incorrectly flag the PR as failing even after a re-run passes.\n const latestCheckRunsByName = new Map<string, (typeof allCheckRuns)[0]>();\n for (const check of allCheckRuns) {\n const existing = latestCheckRunsByName.get(check.name);\n if (!existing || new Date(check.started_at ?? 0) > new Date(existing.started_at ?? 0)) {\n latestCheckRunsByName.set(check.name, check);\n }\n }\n const checkRuns = [...latestCheckRunsByName.values()];\n\n // Delegate analysis to ci-analysis module\n const checkRunAnalysis = analyzeCheckRuns(checkRuns);\n const combinedAnalysis = analyzeCombinedStatus(combinedStatus);\n\n return mergeStatuses(checkRunAnalysis, combinedAnalysis, checkRuns.length);\n } catch (error) {\n const statusCode = getHttpStatusCode(error);\n\n if (statusCode === 401 || statusCode === 403 || statusCode === 429) {\n throw error;\n } else if (statusCode === 404) {\n // Repo might not have CI configured, this is normal\n debug('pr-monitor', `CI check 404 for ${owner}/${repo} (no CI configured)`);\n return { status: 'unknown', failingCheckNames: [], failingCheckConclusions: new Map() };\n } else {\n warn('pr-monitor', `Failed to check CI for ${owner}/${repo}@${sha.slice(0, 7)}: ${errorMessage(error)}`);\n }\n return { status: 'unknown', failingCheckNames: [], failingCheckConclusions: new Map() };\n }\n }\n\n /**\n * Fetch merged PR counts and latest merge dates per repository for the configured user.\n * Delegates to github-stats module.\n */\n async fetchUserMergedPRCounts(\n starFilter?: StarFilter,\n ): Promise<PRCountsResult<{ count: number; lastMergedAt: string }>> {\n const config = this.stateManager.getState().config;\n return fetchUserMergedPRCountsImpl(this.octokit, config.githubUsername, starFilter);\n }\n\n /**\n * Fetch closed-without-merge PR counts per repository for the configured user.\n * Delegates to github-stats module.\n */\n async fetchUserClosedPRCounts(starFilter?: StarFilter): Promise<PRCountsResult<number>> {\n const config = this.stateManager.getState().config;\n return fetchUserClosedPRCountsImpl(this.octokit, config.githubUsername, starFilter);\n }\n\n /**\n * Fetch GitHub star counts for a list of repositories.\n * Delegates to github-stats module.\n */\n async fetchRepoStarCounts(repos: string[]): Promise<Map<string, number>> {\n if (repos.length === 0) return new Map();\n\n debug(MODULE, `Fetching star counts for ${repos.length} repos...`);\n const results = new Map<string, number>();\n const cache = getHttpCache();\n\n // Deduplicate repos to avoid fetching the same repo twice\n const uniqueRepos = [...new Set(repos)];\n\n // Fetch in parallel chunks to avoid overwhelming the API\n const chunkSize = 10;\n for (let i = 0; i < uniqueRepos.length; i += chunkSize) {\n const chunk = uniqueRepos.slice(i, i + chunkSize);\n const settled = await Promise.allSettled(\n chunk.map(async (repo) => {\n const parts = repo.split('/');\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new ValidationError(`Malformed repo identifier: \"${repo}\"`);\n }\n const [owner, name] = parts;\n const url = `/repos/${owner}/${name}`;\n const data = await cachedRequest(\n cache,\n url,\n (headers) =>\n this.octokit.repos.get({\n owner,\n repo: name,\n headers,\n }) as Promise<{ data: { stargazers_count: number }; headers: Record<string, string> }>,\n );\n return { repo, stars: data.stargazers_count };\n }),\n );\n let chunkFailures = 0;\n for (let j = 0; j < settled.length; j++) {\n const result = settled[j];\n if (result.status === 'fulfilled') {\n results.set(result.value.repo, result.value.stars);\n } else {\n chunkFailures++;\n warn(MODULE, `Failed to fetch stars for ${chunk[j]}: ${errorMessage(result.reason)}`);\n }\n }\n // If entire chunk failed, likely a systemic issue (rate limit, auth, outage) \u2014 abort remaining\n if (chunkFailures === chunk.length && chunk.length > 0) {\n const remaining = uniqueRepos.length - i - chunkSize;\n if (remaining > 0) {\n warn(MODULE, `Entire chunk failed, aborting remaining ${remaining} repos`);\n }\n break;\n }\n }\n\n debug(MODULE, `Fetched star counts for ${results.size}/${repos.length} repos`);\n return results;\n }\n\n /**\n * Fetch PRs closed without merge in the last N days.\n * Delegates to github-stats module.\n */\n async fetchRecentlyClosedPRs(days: number = 7): Promise<ClosedPR[]> {\n const config = this.stateManager.getState().config;\n return fetchRecentlyClosedPRsImpl(this.octokit, config, days);\n }\n\n /**\n * Fetch PRs merged in the last N days.\n * Delegates to github-stats module.\n */\n async fetchRecentlyMergedPRs(days: number = 7): Promise<MergedPR[]> {\n const config = this.stateManager.getState().config;\n return fetchRecentlyMergedPRsImpl(this.octokit, config, days);\n }\n\n /**\n * Generate a daily digest from fetched PRs\n */\n generateDigest(\n prs: FetchedPR[],\n recentlyClosedPRs: ClosedPR[] = [],\n recentlyMergedPRs: MergedPR[] = [],\n ): DailyDigest {\n const now = new Date().toISOString();\n\n // Categorize PRs\n const needsAddressingPRs = prs.filter((pr) => pr.status === 'needs_addressing');\n const waitingOnMaintainerPRs = prs.filter((pr) => pr.status === 'waiting_on_maintainer');\n\n // Get stats from state manager (historical data from repo scores)\n const stats = this.stateManager.getStats();\n\n return {\n generatedAt: now,\n openPRs: prs,\n needsAddressingPRs,\n waitingOnMaintainerPRs,\n recentlyClosedPRs,\n recentlyMergedPRs,\n shelvedPRs: [],\n autoUnshelvedPRs: [],\n summary: {\n totalActivePRs: prs.length,\n totalNeedingAttention: needsAddressingPRs.length,\n totalMergedAllTime: stats.mergedPRs,\n mergeRate: parseFloat(stats.mergeRate),\n },\n };\n }\n\n /**\n * Update repository scores based on observed PR (called when we detect merged/closed PRs)\n */\n async updateRepoScoreFromObservedPR(repo: string, wasMerged: boolean): Promise<void> {\n if (wasMerged) {\n this.stateManager.incrementMergedCount(repo);\n } else {\n this.stateManager.incrementClosedCount(repo);\n }\n }\n}\n", "/**\n * Issue Filtering \u2014 pure functions for filtering and spam detection on search results.\n *\n * Extracted from issue-discovery.ts (#356) to isolate filtering logic:\n * label farming detection, doc-only filtering, per-repo caps, templated title detection.\n */\n\n/** Minimal shape of a GitHub search result item (from octokit.search.issuesAndPullRequests) */\nexport interface GitHubSearchItem {\n html_url: string;\n repository_url: string;\n updated_at: string;\n title?: string;\n labels?: Array<{ name?: string } | string>;\n [key: string]: unknown;\n}\n\n/** Labels that indicate documentation-only issues (#105). */\nexport const DOC_ONLY_LABELS = new Set(['documentation', 'docs', 'typo', 'spelling']);\n\n/**\n * Check if an issue's labels are ALL documentation-related (#105).\n * Issues with mixed labels (e.g., \"good first issue\" + \"documentation\") pass through.\n * Issues with no labels are not considered doc-only.\n */\nexport function isDocOnlyIssue(item: GitHubSearchItem): boolean {\n if (!item.labels || !Array.isArray(item.labels) || item.labels.length === 0) return false;\n const labelNames = item.labels.map((l) => (typeof l === 'string' ? l : l.name || '').toLowerCase());\n // Filter out empty label names before checking\n const nonEmptyLabels = labelNames.filter((n) => n.length > 0);\n if (nonEmptyLabels.length === 0) return false;\n return nonEmptyLabels.every((n) => DOC_ONLY_LABELS.has(n));\n}\n\n/** Known beginner-type label names used to detect label-farming repos (#97). */\nexport const BEGINNER_LABELS = new Set([\n 'good first issue',\n 'hacktoberfest',\n 'easy',\n 'up-for-grabs',\n 'first-timers-only',\n 'beginner-friendly',\n 'beginner',\n 'starter',\n 'newbie',\n 'low-hanging-fruit',\n 'community',\n]);\n\n/** Check if a single issue has an excessive number of beginner labels (>= 5). */\nexport function isLabelFarming(item: GitHubSearchItem): boolean {\n if (!item.labels || !Array.isArray(item.labels)) return false;\n const labelNames = item.labels.map((l) => (typeof l === 'string' ? l : l.name || '').toLowerCase());\n const beginnerCount = labelNames.filter((n) => BEGINNER_LABELS.has(n)).length;\n return beginnerCount >= 5;\n}\n\n/** Detect mass-created issue titles like \"Add Trivia Question 61\" or \"Create Entry #5\". */\nexport function hasTemplatedTitle(title: string): boolean {\n if (!title) return false;\n // Matches \"<anything> <category-noun> <number>\" where category nouns are typical\n // of mass-created templated issues. This avoids false positives on legitimate titles\n // like \"Add support for Python 3\" or \"Implement RFC 7231\" which lack category nouns.\n return /^.+\\s+(question|fact|point|item|task|entry|post|challenge|exercise|example|problem|tip|recipe|snippet)\\s+#?\\d+$/i.test(\n title,\n );\n}\n\n/**\n * Batch-analyze search items to detect label-farming repositories (#97).\n * Returns a Set of repo full names (owner/repo) that appear to be spam.\n *\n * A repo is flagged if:\n * - ANY single issue has >= 5 beginner labels (strong individual signal), OR\n * - It has >= 3 issues with templated titles (batch signal)\n */\nexport function detectLabelFarmingRepos(items: GitHubSearchItem[]): Set<string> {\n const spamRepos = new Set<string>();\n const repoSpamCounts = new Map<string, number>();\n\n for (const item of items) {\n const repoFullName = item.repository_url.split('/').slice(-2).join('/');\n\n // Strong signal: single issue with 5+ beginner labels\n if (isLabelFarming(item)) {\n spamRepos.add(repoFullName);\n continue;\n }\n\n // Weaker signal: templated title\n if (item.title && hasTemplatedTitle(item.title)) {\n repoSpamCounts.set(repoFullName, (repoSpamCounts.get(repoFullName) || 0) + 1);\n }\n }\n\n // Flag repos with 3+ templated-title issues\n for (const [repo, count] of repoSpamCounts) {\n if (count >= 3) {\n spamRepos.add(repo);\n }\n }\n\n return spamRepos;\n}\n\n/**\n * Apply per-repo cap to candidates (#105).\n * Keeps at most `maxPerRepo` issues from any single repo.\n * Maintains the existing sort order \u2014 first N from each repo are kept,\n * excess issues from over-represented repos are dropped.\n */\nexport function applyPerRepoCap<T extends { issue: { repo: string } }>(candidates: T[], maxPerRepo: number): T[] {\n const repoCounts = new Map<string, number>();\n const kept: T[] = [];\n\n for (const c of candidates) {\n const count = repoCounts.get(c.issue.repo) || 0;\n if (count < maxPerRepo) {\n kept.push(c);\n repoCounts.set(c.issue.repo, count + 1);\n }\n }\n\n return kept;\n}\n", "/**\n * Issue Scoring \u2014 pure functions for computing viability scores and quality bonuses.\n *\n * Extracted from issue-discovery.ts (#356) to isolate scoring logic.\n */\n\nimport { daysBetween } from './utils.js';\n\n/**\n * Calculate a quality bonus based on repo star and fork counts (#98).\n * Stars: <50 \u2192 0, 50-499 \u2192 +3, 500-4999 \u2192 +5, 5000+ \u2192 +8\n * Forks: 50+ \u2192 +2, 500+ \u2192 +4\n * Natural max is 12 (8 stars + 4 forks).\n */\nexport function calculateRepoQualityBonus(stargazersCount: number, forksCount: number): number {\n let bonus = 0;\n\n // Star tiers\n if (stargazersCount >= 5000) bonus += 8;\n else if (stargazersCount >= 500) bonus += 5;\n else if (stargazersCount >= 50) bonus += 3;\n\n // Fork tiers\n if (forksCount >= 500) bonus += 4;\n else if (forksCount >= 50) bonus += 2;\n\n return bonus;\n}\n\nexport interface ViabilityScoreParams {\n repoScore: number | null;\n hasExistingPR: boolean;\n isClaimed: boolean;\n clearRequirements: boolean;\n hasContributionGuidelines: boolean;\n issueUpdatedAt: string;\n closedWithoutMergeCount: number;\n mergedPRCount: number;\n orgHasMergedPRs: boolean;\n repoQualityBonus?: number;\n /** True when the repo matches one of the user's preferred project categories. */\n matchesPreferredCategory?: boolean;\n}\n\n/**\n * Calculate viability score for an issue (0-100 scale)\n * Scoring:\n * - Base: 50 points\n * - +repoScore*2 (up to +20 for score of 10)\n * - +repoQualityBonus (up to +12 for established repos, from star/fork counts) (#98)\n * - +15 for merged PR in this repo (direct proven relationship) (#99)\n * - +15 for clear requirements (clarity)\n * - +15 for freshness (recently updated)\n * - +10 for contribution guidelines\n * - +5 for org affinity (merged PRs in same org)\n * - +5 for category preference (matches user's project categories)\n * - -30 if existing PR\n * - -20 if claimed\n * - -15 if closed-without-merge history with no merges\n */\nexport function calculateViabilityScore(params: ViabilityScoreParams): number {\n let score = 50; // Base score\n\n // Add repo score contribution (up to +20)\n if (params.repoScore !== null) {\n score += params.repoScore * 2;\n }\n\n // Repo quality bonus from star/fork counts (#98, up to +12)\n score += params.repoQualityBonus ?? 0;\n\n // Merged PR bonus (+15) \u2014 direct proven relationship with this repo (#99)\n if (params.mergedPRCount > 0) {\n score += 15;\n }\n\n // Clarity bonus (+15)\n if (params.clearRequirements) {\n score += 15;\n }\n\n // Freshness bonus (+15 for issues updated within last 14 days)\n const updatedAt = new Date(params.issueUpdatedAt);\n const daysSinceUpdate = daysBetween(updatedAt);\n if (daysSinceUpdate <= 14) {\n score += 15;\n } else if (daysSinceUpdate <= 30) {\n // Partial bonus for 15-30 days\n score += Math.round(15 * (1 - (daysSinceUpdate - 14) / 16));\n }\n\n // Contribution guidelines bonus (+10)\n if (params.hasContributionGuidelines) {\n score += 10;\n }\n\n // Org affinity bonus (+5) \u2014 user has merged PRs in another repo under same org\n if (params.orgHasMergedPRs) {\n score += 5;\n }\n\n // Category preference bonus (+5) \u2014 repo matches user's preferred project categories\n if (params.matchesPreferredCategory) {\n score += 5;\n }\n\n // Penalty for existing PR (-30)\n if (params.hasExistingPR) {\n score -= 30;\n }\n\n // Penalty for claimed issue (-20)\n if (params.isClaimed) {\n score -= 20;\n }\n\n // Penalty for closed-without-merge history with no successful merges (-15)\n if (params.closedWithoutMergeCount > 0 && params.mergedPRCount === 0) {\n score -= 15;\n }\n\n // Clamp to 0-100\n return Math.max(0, Math.min(100, score));\n}\n", "/**\n * Category Mapping \u2014 static mappings from project categories to GitHub topics and organizations.\n *\n * Used by issue discovery to prioritize repos matching user's category preferences.\n */\n\nimport type { ProjectCategory } from './types.js';\n\n/** GitHub topics associated with each project category, used for `topic:` search queries. */\nexport const CATEGORY_TOPICS: Record<ProjectCategory, string[]> = {\n nonprofit: ['nonprofit', 'social-good', 'humanitarian', 'charity', 'social-impact', 'civic-tech'],\n devtools: ['developer-tools', 'devtools', 'cli', 'sdk', 'linter', 'formatter', 'build-tool'],\n infrastructure: ['infrastructure', 'cloud', 'kubernetes', 'docker', 'devops', 'monitoring', 'observability'],\n 'web-frameworks': ['web-framework', 'frontend', 'backend', 'fullstack', 'nextjs', 'react', 'vue'],\n 'data-ml': ['machine-learning', 'data-science', 'deep-learning', 'nlp', 'data-pipeline', 'analytics'],\n education: ['education', 'learning', 'tutorial', 'courseware', 'edtech', 'teaching'],\n};\n\n/** Well-known GitHub organizations associated with each project category. */\nexport const CATEGORY_ORGS: Record<ProjectCategory, string[]> = {\n nonprofit: ['code-for-america', 'opengovfoundation', 'ushahidi', 'hotosm', 'openfn', 'democracyearth'],\n devtools: ['eslint', 'prettier', 'vitejs', 'biomejs', 'oxc-project', 'ast-grep', 'turbot'],\n infrastructure: ['kubernetes', 'hashicorp', 'grafana', 'prometheus', 'open-telemetry', 'envoyproxy', 'cncf'],\n 'web-frameworks': ['vercel', 'remix-run', 'sveltejs', 'nuxt', 'astro', 'redwoodjs', 'blitz-js'],\n 'data-ml': ['huggingface', 'mlflow', 'apache', 'dbt-labs', 'dagster-io', 'prefecthq', 'langchain-ai'],\n education: ['freeCodeCamp', 'TheOdinProject', 'exercism', 'codecademy', 'oppia', 'Khan'],\n};\n\n/**\n * Check if a repo belongs to any of the given categories based on its owner matching a category org.\n * Comparison is case-insensitive.\n */\nexport function repoBelongsToCategory(repoFullName: string, categories: ProjectCategory[]): boolean {\n if (categories.length === 0) return false;\n const owner = repoFullName.split('/')[0]?.toLowerCase();\n if (!owner) return false;\n\n for (const category of categories) {\n const orgs = CATEGORY_ORGS[category];\n if (!orgs) continue; // Guard against invalid categories from hand-edited state.json\n if (orgs.some((org) => org.toLowerCase() === owner)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Get deduplicated GitHub topics for the given categories, for use in `topic:` search queries.\n */\nexport function getTopicsForCategories(categories: ProjectCategory[]): string[] {\n const topics = new Set<string>();\n for (const category of categories) {\n const categoryTopics = CATEGORY_TOPICS[category];\n if (!categoryTopics) continue; // Guard against invalid categories from hand-edited state.json\n for (const topic of categoryTopics) {\n topics.add(topic);\n }\n }\n return [...topics];\n}\n", "/**\n * Issue Vetting \u2014 checks individual issues for claimability, existing PRs,\n * project health, contribution guidelines, and requirement clarity.\n *\n * Extracted from issue-discovery.ts (#356) to isolate vetting logic.\n */\n\nimport { Octokit } from '@octokit/rest';\nimport { paginateAll } from './pagination.js';\nimport { parseGitHubUrl, daysBetween, DEFAULT_CONCURRENCY } from './utils.js';\nimport {\n TrackedIssue,\n IssueVettingResult,\n ContributionGuidelines,\n ProjectHealth,\n type SearchPriority,\n type IssueCandidate,\n} from './types.js';\nimport { ValidationError, errorMessage, isRateLimitError } from './errors.js';\nimport { warn } from './logger.js';\nimport { getHttpCache, cachedRequest, cachedTimeBased } from './http-cache.js';\nimport { getStateManager } from './state.js';\nimport { calculateRepoQualityBonus, calculateViabilityScore } from './issue-scoring.js';\nimport { repoBelongsToCategory } from './category-mapping.js';\n\nconst MODULE = 'issue-vetting';\n\nconst MAX_CONCURRENT_REQUESTS = DEFAULT_CONCURRENCY;\n\n/** Result of a vetting check that may be inconclusive due to API errors. */\nexport interface CheckResult {\n passed: boolean;\n inconclusive?: boolean;\n reason?: string;\n}\n\n// Cache for contribution guidelines (expires after 1 hour, max 100 entries)\nconst guidelinesCache = new Map<string, { guidelines: ContributionGuidelines | undefined; fetchedAt: number }>();\nconst CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour\n/** TTL for cached project health results (4 hours). Health data (stars, commits, CI) changes slowly. */\nconst HEALTH_CACHE_TTL_MS = 4 * 60 * 60 * 1000;\nconst CACHE_MAX_SIZE = 100;\n\nfunction pruneCache(): void {\n const now = Date.now();\n\n // First, remove expired entries (older than CACHE_TTL_MS)\n for (const [key, value] of guidelinesCache.entries()) {\n if (now - value.fetchedAt > CACHE_TTL_MS) {\n guidelinesCache.delete(key);\n }\n }\n\n // Then, if still over size limit, remove oldest entries\n if (guidelinesCache.size > CACHE_MAX_SIZE) {\n const entries = Array.from(guidelinesCache.entries()).sort((a, b) => a[1].fetchedAt - b[1].fetchedAt);\n\n const toRemove = entries.slice(0, guidelinesCache.size - CACHE_MAX_SIZE);\n for (const [key] of toRemove) {\n guidelinesCache.delete(key);\n }\n }\n}\n\nexport class IssueVetter {\n private octokit: Octokit;\n private stateManager: ReturnType<typeof getStateManager>;\n\n constructor(octokit: Octokit, stateManager: ReturnType<typeof getStateManager>) {\n this.octokit = octokit;\n this.stateManager = stateManager;\n }\n\n /**\n * Vet a specific issue \u2014 runs all checks and computes recommendation + viability score.\n */\n async vetIssue(issueUrl: string): Promise<IssueCandidate> {\n // Parse URL\n const parsed = parseGitHubUrl(issueUrl);\n if (!parsed || parsed.type !== 'issues') {\n throw new ValidationError(`Invalid issue URL: ${issueUrl}`);\n }\n\n const { owner, repo, number } = parsed;\n const repoFullName = `${owner}/${repo}`;\n\n // Fetch issue data\n const { data: ghIssue } = await this.octokit.issues.get({\n owner,\n repo,\n issue_number: number,\n });\n\n // Run all vetting checks in parallel\n const [existingPRCheck, claimCheck, projectHealth, contributionGuidelines, userMergedPRCount] = await Promise.all([\n this.checkNoExistingPR(owner, repo, number),\n this.checkNotClaimed(owner, repo, number, ghIssue.comments),\n this.checkProjectHealth(owner, repo),\n this.fetchContributionGuidelines(owner, repo),\n this.checkUserMergedPRsInRepo(owner, repo),\n ]);\n\n const noExistingPR = existingPRCheck.passed;\n const notClaimed = claimCheck.passed;\n\n // Analyze issue quality\n const clearRequirements = this.analyzeRequirements(ghIssue.body || '');\n\n // When the health check itself failed (API error), use a neutral default:\n // don't penalize the repo as inactive, but don't credit it as active either.\n const projectActive = projectHealth.checkFailed ? true : projectHealth.isActive;\n\n const vettingResult: IssueVettingResult = {\n passedAllChecks: noExistingPR && notClaimed && projectActive && clearRequirements,\n checks: {\n noExistingPR,\n notClaimed,\n projectActive,\n clearRequirements,\n contributionGuidelinesFound: !!contributionGuidelines,\n },\n contributionGuidelines,\n notes: [],\n };\n\n // Build notes\n if (!noExistingPR) vettingResult.notes.push('Existing PR found for this issue');\n if (!notClaimed) vettingResult.notes.push('Issue appears to be claimed by someone');\n if (existingPRCheck.inconclusive) {\n vettingResult.notes.push(`Could not verify absence of existing PRs: ${existingPRCheck.reason || 'API error'}`);\n }\n if (claimCheck.inconclusive) {\n vettingResult.notes.push(`Could not verify claim status: ${claimCheck.reason || 'API error'}`);\n }\n if (projectHealth.checkFailed) {\n vettingResult.notes.push(`Could not verify project activity: ${projectHealth.failureReason || 'API error'}`);\n } else if (!projectHealth.isActive) {\n vettingResult.notes.push('Project may be inactive');\n }\n if (!clearRequirements) vettingResult.notes.push('Issue requirements are unclear');\n if (!contributionGuidelines) vettingResult.notes.push('No CONTRIBUTING.md found');\n\n // Create tracked issue\n const trackedIssue: TrackedIssue = {\n id: ghIssue.id,\n url: issueUrl,\n repo: repoFullName,\n number,\n title: ghIssue.title,\n status: 'candidate',\n labels: ghIssue.labels.map((l) => (typeof l === 'string' ? l : l.name || '')),\n createdAt: ghIssue.created_at,\n updatedAt: ghIssue.updated_at,\n vetted: true,\n vettingResult,\n };\n\n // Determine recommendation\n const reasonsToSkip: string[] = [];\n const reasonsToApprove: string[] = [];\n\n if (!noExistingPR) reasonsToSkip.push('Has existing PR');\n if (!notClaimed) reasonsToSkip.push('Already claimed');\n if (!projectHealth.isActive && !projectHealth.checkFailed) reasonsToSkip.push('Inactive project');\n if (!clearRequirements) reasonsToSkip.push('Unclear requirements');\n\n if (noExistingPR) reasonsToApprove.push('No existing PR');\n if (notClaimed) reasonsToApprove.push('Not claimed');\n if (projectHealth.isActive && !projectHealth.checkFailed) reasonsToApprove.push('Active project');\n if (clearRequirements) reasonsToApprove.push('Clear requirements');\n if (contributionGuidelines) reasonsToApprove.push('Has contribution guidelines');\n\n // Determine effective merged PR count: prefer local state (authoritative if present),\n // fall back to live GitHub API count to detect contributions made before using oss-autopilot (#373)\n const config = this.stateManager.getState().config;\n const repoScoreRecord = this.stateManager.getRepoScore(repoFullName);\n const effectiveMergedCount =\n repoScoreRecord && repoScoreRecord.mergedPRCount > 0 ? repoScoreRecord.mergedPRCount : userMergedPRCount;\n if (effectiveMergedCount > 0) {\n reasonsToApprove.push(\n `Trusted project (${effectiveMergedCount} PR${effectiveMergedCount > 1 ? 's' : ''} merged)`,\n );\n } else if (config.trustedProjects.includes(repoFullName)) {\n reasonsToApprove.push('Trusted project (previous PR merged)');\n }\n\n // Check for closed/rejected PR history in this repo\n // Use effectiveMergedCount to avoid contradictory signals when API data\n // shows merges that local state doesn't know about (#373)\n if (repoScoreRecord) {\n if (repoScoreRecord.closedWithoutMergeCount > 0 && effectiveMergedCount === 0) {\n reasonsToSkip.push('User has rejected PR(s) in this repo with no successful merges');\n } else if (repoScoreRecord.closedWithoutMergeCount > 0 && effectiveMergedCount > 0) {\n vettingResult.notes.push(\n `Mixed history: ${effectiveMergedCount} merged, ${repoScoreRecord.closedWithoutMergeCount} closed without merge`,\n );\n }\n }\n\n // Check for org-level affinity (user has merged PRs in another repo under same org)\n const orgName = repoFullName.split('/')[0];\n let orgHasMergedPRs = false;\n if (orgName && repoFullName.includes('/')) {\n orgHasMergedPRs = Object.values(this.stateManager.getState().repoScores).some(\n (rs) => rs.repo && rs.mergedPRCount > 0 && rs.repo.startsWith(orgName + '/') && rs.repo !== repoFullName,\n );\n }\n if (orgHasMergedPRs) {\n reasonsToApprove.push(`Org affinity (merged PRs in other ${orgName} repos)`);\n }\n\n // Check for category preference match\n const projectCategories = config.projectCategories ?? [];\n const matchesCategory = repoBelongsToCategory(repoFullName, projectCategories);\n if (matchesCategory) {\n reasonsToApprove.push('Matches preferred project category');\n }\n\n let recommendation: 'approve' | 'skip' | 'needs_review';\n if (vettingResult.passedAllChecks) {\n recommendation = 'approve';\n } else if (reasonsToSkip.length > 2) {\n recommendation = 'skip';\n } else {\n recommendation = 'needs_review';\n }\n\n // Downgrade to needs_review if any check was inconclusive \u2014\n // \"approve\" should only be given when all checks actually passed, not when they were skipped.\n const hasInconclusiveChecks = projectHealth.checkFailed || existingPRCheck.inconclusive || claimCheck.inconclusive;\n if (recommendation === 'approve' && hasInconclusiveChecks) {\n recommendation = 'needs_review';\n vettingResult.notes.push('Recommendation downgraded: one or more checks were inconclusive');\n }\n\n // Calculate repo quality bonus from star/fork counts (#98)\n const repoQualityBonus = calculateRepoQualityBonus(\n projectHealth.stargazersCount ?? 0,\n projectHealth.forksCount ?? 0,\n );\n if (projectHealth.checkFailed && repoQualityBonus === 0) {\n vettingResult.notes.push('Repo quality bonus unavailable: could not fetch star/fork counts due to API error');\n }\n\n const repoScore = this.getRepoScore(repoFullName);\n const viabilityScore = calculateViabilityScore({\n repoScore,\n hasExistingPR: !noExistingPR,\n isClaimed: !notClaimed,\n clearRequirements,\n hasContributionGuidelines: !!contributionGuidelines,\n issueUpdatedAt: ghIssue.updated_at,\n closedWithoutMergeCount: repoScoreRecord?.closedWithoutMergeCount ?? 0,\n mergedPRCount: effectiveMergedCount,\n orgHasMergedPRs,\n repoQualityBonus,\n matchesPreferredCategory: matchesCategory,\n });\n\n const starredRepos = this.stateManager.getStarredRepos();\n const preferredOrgs = config.preferredOrgs ?? [];\n let searchPriority: SearchPriority = 'normal';\n if (effectiveMergedCount > 0) {\n searchPriority = 'merged_pr';\n } else if (preferredOrgs.some((o) => o.toLowerCase() === orgName?.toLowerCase())) {\n searchPriority = 'preferred_org';\n } else if (starredRepos.includes(repoFullName)) {\n searchPriority = 'starred';\n }\n\n return {\n issue: trackedIssue,\n vettingResult,\n projectHealth,\n recommendation,\n reasonsToSkip,\n reasonsToApprove,\n viabilityScore,\n searchPriority,\n };\n }\n\n /**\n * Vet multiple issues in parallel with concurrency limit\n */\n async vetIssuesParallel(\n urls: string[],\n maxResults: number,\n priority?: SearchPriority,\n ): Promise<{ candidates: IssueCandidate[]; allFailed: boolean; rateLimitHit: boolean }> {\n const candidates: IssueCandidate[] = [];\n const pending = new Map<string, Promise<void>>();\n let failedVettingCount = 0;\n let rateLimitFailures = 0;\n let attemptedCount = 0;\n\n for (const url of urls) {\n if (candidates.length >= maxResults) break;\n attemptedCount++;\n\n const task = this.vetIssue(url)\n .then((candidate) => {\n if (candidates.length < maxResults) {\n // Override the priority if provided\n if (priority) {\n candidate.searchPriority = priority;\n }\n candidates.push(candidate);\n }\n })\n .catch((error) => {\n failedVettingCount++;\n if (isRateLimitError(error)) {\n rateLimitFailures++;\n }\n warn(MODULE, `Error vetting issue ${url}:`, errorMessage(error));\n })\n .finally(() => pending.delete(url));\n\n pending.set(url, task);\n\n // Limit concurrency \u2014 wait for at least one to complete before launching more\n if (pending.size >= MAX_CONCURRENT_REQUESTS) {\n await Promise.race(pending.values());\n }\n }\n\n // Wait for remaining\n await Promise.allSettled(pending.values());\n\n const allFailed = failedVettingCount === attemptedCount && attemptedCount > 0;\n if (allFailed) {\n warn(\n MODULE,\n `All ${attemptedCount} issue(s) failed vetting. ` +\n `This may indicate a systemic issue (rate limit, auth, network).`,\n );\n }\n\n return { candidates: candidates.slice(0, maxResults), allFailed, rateLimitHit: rateLimitFailures > 0 };\n }\n\n async checkNoExistingPR(owner: string, repo: string, issueNumber: number): Promise<CheckResult> {\n try {\n // Search for PRs that mention this issue\n const { data } = await this.octokit.search.issuesAndPullRequests({\n q: `repo:${owner}/${repo} is:pr ${issueNumber}`,\n per_page: 5,\n });\n\n // Also check timeline for linked PRs\n const timeline = await paginateAll((page) =>\n this.octokit.issues.listEventsForTimeline({\n owner,\n repo,\n issue_number: issueNumber,\n per_page: 100,\n page,\n }),\n );\n\n const linkedPRs = timeline.filter((event) => {\n const e = event as { event?: string; source?: { issue?: { pull_request?: unknown } } };\n return e.event === 'cross-referenced' && e.source?.issue?.pull_request;\n });\n\n return { passed: data.total_count === 0 && linkedPRs.length === 0 };\n } catch (error) {\n const errMsg = errorMessage(error);\n warn(\n MODULE,\n `Failed to check for existing PRs on ${owner}/${repo}#${issueNumber}: ${errMsg}. Assuming no existing PR.`,\n );\n return { passed: true, inconclusive: true, reason: errMsg };\n }\n }\n\n /**\n * Check how many merged PRs the authenticated user has in a repo.\n * Uses GitHub Search API. Returns 0 on error (non-fatal).\n */\n async checkUserMergedPRsInRepo(owner: string, repo: string): Promise<number> {\n try {\n // Use @me to search as the authenticated user\n const { data } = await this.octokit.search.issuesAndPullRequests({\n q: `repo:${owner}/${repo} is:pr is:merged author:@me`,\n per_page: 1, // We only need total_count\n });\n return data.total_count;\n } catch (error) {\n const errMsg = errorMessage(error);\n warn(MODULE, `Could not check merged PRs in ${owner}/${repo}: ${errMsg}. Defaulting to 0.`);\n return 0;\n }\n }\n\n async checkNotClaimed(owner: string, repo: string, issueNumber: number, commentCount: number): Promise<CheckResult> {\n if (commentCount === 0) return { passed: true };\n\n try {\n // Paginate through all comments (up to 100)\n const comments = await this.octokit.paginate(\n this.octokit.issues.listComments,\n {\n owner,\n repo,\n issue_number: issueNumber,\n per_page: 100,\n },\n (response) => response.data,\n );\n\n // Limit to last 100 comments to avoid excessive processing\n const recentComments = comments.slice(-100);\n\n // Look for claiming phrases\n const claimPhrases = [\n \"i'm working on this\",\n 'i am working on this',\n \"i'll take this\",\n 'i will take this',\n 'working on it',\n \"i'd like to work on\",\n 'i would like to work on',\n 'can i work on',\n 'may i work on',\n 'assigned to me',\n \"i'm on it\",\n \"i'll submit a pr\",\n 'i will submit a pr',\n 'working on a fix',\n 'working on a pr',\n ];\n\n for (const comment of recentComments) {\n const body = (comment.body || '').toLowerCase();\n if (claimPhrases.some((phrase) => body.includes(phrase))) {\n return { passed: false };\n }\n }\n\n return { passed: true };\n } catch (error) {\n const errMsg = errorMessage(error);\n warn(MODULE, `Failed to check claim status on ${owner}/${repo}#${issueNumber}: ${errMsg}. Assuming not claimed.`);\n return { passed: true, inconclusive: true, reason: errMsg };\n }\n }\n\n async checkProjectHealth(owner: string, repo: string): Promise<ProjectHealth> {\n const cache = getHttpCache();\n const healthCacheKey = `health:${owner}/${repo}`;\n\n try {\n return await cachedTimeBased(cache, healthCacheKey, HEALTH_CACHE_TTL_MS, async () => {\n // Get repo info (with ETag caching \u2014 repo metadata changes infrequently)\n const url = `/repos/${owner}/${repo}`;\n const repoData = await cachedRequest(\n cache,\n url,\n (headers) =>\n this.octokit.repos.get({ owner, repo, headers }) as Promise<{\n data: { open_issues_count: number; pushed_at: string; stargazers_count: number; forks_count: number };\n headers: Record<string, string>;\n }>,\n );\n\n // Get recent commits\n const { data: commits } = await this.octokit.repos.listCommits({\n owner,\n repo,\n per_page: 1,\n });\n\n const lastCommit = commits[0];\n const lastCommitAt = lastCommit?.commit?.author?.date || repoData.pushed_at;\n const daysSinceLastCommit = daysBetween(new Date(lastCommitAt));\n\n // Check CI status (simplified - just check if workflows exist)\n let ciStatus: 'passing' | 'failing' | 'unknown' = 'unknown';\n try {\n const { data: workflows } = await this.octokit.actions.listRepoWorkflows({\n owner,\n repo,\n per_page: 1,\n });\n if (workflows.total_count > 0) {\n ciStatus = 'passing'; // Assume passing if workflows exist\n }\n } catch (error) {\n const errMsg = errorMessage(error);\n warn(MODULE, `Failed to check CI status for ${owner}/${repo}: ${errMsg}. Defaulting to unknown.`);\n }\n\n return {\n repo: `${owner}/${repo}`,\n lastCommitAt,\n daysSinceLastCommit,\n openIssuesCount: repoData.open_issues_count,\n avgIssueResponseDays: 0, // Would need more API calls to calculate\n ciStatus,\n isActive: daysSinceLastCommit < 30,\n stargazersCount: repoData.stargazers_count,\n forksCount: repoData.forks_count,\n };\n });\n } catch (error) {\n const errMsg = errorMessage(error);\n warn(MODULE, `Error checking project health for ${owner}/${repo}: ${errMsg}`);\n return {\n repo: `${owner}/${repo}`,\n lastCommitAt: '',\n daysSinceLastCommit: 999,\n openIssuesCount: 0,\n avgIssueResponseDays: 0,\n ciStatus: 'unknown',\n isActive: false,\n checkFailed: true,\n failureReason: errMsg,\n };\n }\n }\n\n async fetchContributionGuidelines(owner: string, repo: string): Promise<ContributionGuidelines | undefined> {\n const cacheKey = `${owner}/${repo}`;\n\n // Check cache first\n const cached = guidelinesCache.get(cacheKey);\n if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {\n return cached.guidelines;\n }\n\n const filesToCheck = ['CONTRIBUTING.md', '.github/CONTRIBUTING.md', 'docs/CONTRIBUTING.md', 'contributing.md'];\n\n // Probe all paths in parallel \u2014 take the first success in priority order\n const results = await Promise.allSettled(\n filesToCheck.map((file) =>\n this.octokit.repos.getContent({ owner, repo, path: file }).then(({ data }) => {\n if ('content' in data) {\n return Buffer.from(data.content, 'base64').toString('utf-8');\n }\n return null;\n }),\n ),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status === 'fulfilled' && result.value) {\n const guidelines = this.parseContributionGuidelines(result.value);\n guidelinesCache.set(cacheKey, { guidelines, fetchedAt: Date.now() });\n pruneCache();\n return guidelines;\n }\n if (result.status === 'rejected') {\n const msg = result.reason instanceof Error ? result.reason.message : String(result.reason);\n if (!msg.includes('404') && !msg.includes('Not Found')) {\n warn(MODULE, `Unexpected error fetching ${filesToCheck[i]} from ${owner}/${repo}: ${msg}`);\n }\n }\n }\n\n // Cache the negative result too and prune if needed\n guidelinesCache.set(cacheKey, { guidelines: undefined, fetchedAt: Date.now() });\n pruneCache();\n return undefined;\n }\n\n parseContributionGuidelines(content: string): ContributionGuidelines {\n const guidelines: ContributionGuidelines = {\n rawContent: content,\n };\n\n const lowerContent = content.toLowerCase();\n\n // Detect branch naming conventions\n if (lowerContent.includes('branch')) {\n const branchMatch = content.match(/branch[^\\n]*(?:named?|format|convention)[^\\n]*[`\"]([^`\"]+)[`\"]/i);\n if (branchMatch) {\n guidelines.branchNamingConvention = branchMatch[1];\n }\n }\n\n // Detect commit message format\n if (lowerContent.includes('conventional commit')) {\n guidelines.commitMessageFormat = 'conventional commits';\n } else if (lowerContent.includes('commit message')) {\n const commitMatch = content.match(/commit message[^\\n]*[`\"]([^`\"]+)[`\"]/i);\n if (commitMatch) {\n guidelines.commitMessageFormat = commitMatch[1];\n }\n }\n\n // Detect test framework\n if (lowerContent.includes('jest')) guidelines.testFramework = 'Jest';\n else if (lowerContent.includes('rspec')) guidelines.testFramework = 'RSpec';\n else if (lowerContent.includes('pytest')) guidelines.testFramework = 'pytest';\n else if (lowerContent.includes('mocha')) guidelines.testFramework = 'Mocha';\n\n // Detect linter\n if (lowerContent.includes('eslint')) guidelines.linter = 'ESLint';\n else if (lowerContent.includes('rubocop')) guidelines.linter = 'RuboCop';\n else if (lowerContent.includes('prettier')) guidelines.formatter = 'Prettier';\n\n // Detect CLA requirement\n if (lowerContent.includes('cla') || lowerContent.includes('contributor license agreement')) {\n guidelines.claRequired = true;\n }\n\n return guidelines;\n }\n\n analyzeRequirements(body: string): boolean {\n if (!body || body.length < 50) return false;\n\n // Check for clear structure\n const hasSteps = /\\d\\.|[-*]\\s/.test(body);\n const hasCodeBlock = /```/.test(body);\n const hasExpectedBehavior = /expect|should|must|want/i.test(body);\n\n // Must have at least two indicators of clarity\n const indicators = [hasSteps, hasCodeBlock, hasExpectedBehavior, body.length > 200];\n return indicators.filter(Boolean).length >= 2;\n }\n\n /**\n * Get the repo score from state, or return null if not evaluated\n */\n private getRepoScore(repoFullName: string): number | null {\n const state = this.stateManager.getState();\n const repoScore = state.repoScores?.[repoFullName];\n return repoScore?.score ?? null;\n }\n}\n", "/**\n * Issue Discovery \u2014 orchestrates multi-phase issue search across GitHub.\n *\n * Delegates filtering, scoring, and vetting to focused modules (#356):\n * - issue-filtering.ts \u2014 spam detection, doc-only filtering, per-repo caps\n * - issue-scoring.ts \u2014 viability scores, repo quality bonuses\n * - issue-vetting.ts \u2014 individual issue checks (PRs, claims, health, guidelines)\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { Octokit } from '@octokit/rest';\nimport { getOctokit, checkRateLimit } from './github.js';\nimport { getStateManager } from './state.js';\nimport { daysBetween, getDataDir } from './utils.js';\nimport { DEFAULT_CONFIG, type SearchPriority, type IssueCandidate } from './types.js';\nimport { ValidationError, errorMessage, getHttpStatusCode, isRateLimitError } from './errors.js';\nimport { debug, info, warn } from './logger.js';\nimport { getHttpCache, cachedTimeBased } from './http-cache.js';\nimport { type GitHubSearchItem, isDocOnlyIssue, detectLabelFarmingRepos, applyPerRepoCap } from './issue-filtering.js';\nimport { IssueVetter } from './issue-vetting.js';\nimport { calculateViabilityScore as calcViabilityScore, type ViabilityScoreParams } from './issue-scoring.js';\nimport { getTopicsForCategories } from './category-mapping.js';\n\n// Re-export everything from sub-modules for backward compatibility.\n// Existing consumers (tests, CLI commands) import from './issue-discovery.js'.\nexport {\n isDocOnlyIssue,\n applyPerRepoCap,\n isLabelFarming,\n hasTemplatedTitle,\n detectLabelFarmingRepos,\n DOC_ONLY_LABELS,\n BEGINNER_LABELS,\n type GitHubSearchItem,\n} from './issue-filtering.js';\nexport { calculateRepoQualityBonus, calculateViabilityScore, type ViabilityScoreParams } from './issue-scoring.js';\nexport { type CheckResult } from './issue-vetting.js';\n// Re-export types that were previously defined here\nexport type { SearchPriority, IssueCandidate } from './types.js';\n\nconst MODULE = 'issue-discovery';\n\n/** TTL for cached search API results (15 minutes). */\nconst SEARCH_CACHE_TTL_MS = 15 * 60 * 1000;\n\nexport class IssueDiscovery {\n private octokit: Octokit;\n private stateManager: ReturnType<typeof getStateManager>;\n private githubToken: string;\n private vetter: IssueVetter;\n\n /** Set after searchIssues() runs if rate limits affected the search (low pre-flight quota or mid-search rate limit hits). */\n rateLimitWarning: string | null = null;\n\n constructor(githubToken: string) {\n this.githubToken = githubToken;\n this.octokit = getOctokit(githubToken);\n this.stateManager = getStateManager();\n this.vetter = new IssueVetter(this.octokit, this.stateManager);\n }\n\n /**\n * Wrap octokit.search.issuesAndPullRequests with time-based caching.\n * Repeated identical queries within SEARCH_CACHE_TTL_MS return cached results\n * without consuming GitHub API rate limit points.\n */\n private async cachedSearch(params: {\n q: string;\n sort: 'created' | 'updated' | 'comments' | 'reactions' | 'interactions';\n order: 'asc' | 'desc';\n per_page: number;\n }): Promise<{ total_count: number; items: GitHubSearchItem[] }> {\n const cacheKey = `search:${params.q}:${params.sort}:${params.order}:${params.per_page}`;\n return cachedTimeBased(getHttpCache(), cacheKey, SEARCH_CACHE_TTL_MS, async () => {\n const { data } = await this.octokit.search.issuesAndPullRequests(params);\n return data;\n });\n }\n\n /**\n * Fetch the authenticated user's starred repositories from GitHub.\n * Updates the state manager with the list and timestamp.\n */\n async fetchStarredRepos(): Promise<string[]> {\n info(MODULE, 'Fetching starred repositories...');\n const starredRepos: string[] = [];\n\n try {\n // Paginate through all starred repos (up to 500 to avoid excessive API calls)\n const iterator = this.octokit.paginate.iterator(this.octokit.activity.listReposStarredByAuthenticatedUser, {\n per_page: 100,\n });\n\n let pageCount = 0;\n for await (const { data: repos } of iterator) {\n for (const repo of repos) {\n // Handle both Repository and StarredRepository response types\n // Repository has full_name directly, StarredRepository has { repo: Repository }\n let fullName: string | undefined;\n if ('full_name' in repo && typeof repo.full_name === 'string') {\n // Repository type - full_name is directly on the object\n fullName = repo.full_name;\n } else if ('repo' in repo && repo.repo && typeof repo.repo === 'object' && 'full_name' in repo.repo) {\n // StarredRepository type - full_name is nested in repo property\n fullName = (repo.repo as { full_name: string }).full_name;\n }\n if (fullName) {\n starredRepos.push(fullName);\n }\n }\n pageCount++;\n // Limit to 5 pages (500 repos) to avoid excessive API usage\n if (pageCount >= 5) {\n info(MODULE, 'Reached pagination limit for starred repos (500)');\n break;\n }\n }\n\n info(MODULE, `Fetched ${starredRepos.length} starred repositories`);\n this.stateManager.setStarredRepos(starredRepos);\n return starredRepos;\n } catch (error) {\n const cachedRepos = this.stateManager.getStarredRepos();\n const errMsg = errorMessage(error);\n warn(MODULE, 'Error fetching starred repos:', errMsg);\n\n if (cachedRepos.length === 0) {\n warn(\n MODULE,\n `Failed to fetch starred repositories from GitHub API. ` +\n `No cached repos available. Error: ${errMsg}\\n` +\n `Tip: Ensure your GITHUB_TOKEN has the 'read:user' scope and try again.`,\n );\n } else {\n warn(\n MODULE,\n `Failed to fetch starred repositories from GitHub API. ` +\n `Using ${cachedRepos.length} cached repos instead. Error: ${errMsg}`,\n );\n }\n return cachedRepos;\n }\n }\n\n /**\n * Get starred repos, fetching from GitHub if cache is stale\n */\n async getStarredReposWithRefresh(): Promise<string[]> {\n if (this.stateManager.isStarredReposStale()) {\n return this.fetchStarredRepos();\n }\n return this.stateManager.getStarredRepos();\n }\n\n /**\n * Shared pipeline for Phases 2 and 3: spam-filter, repo-exclusion, vetting, and star-count filter.\n * Extracts the common logic so each phase only needs to supply search results and context.\n */\n private async filterVetAndScore(\n items: GitHubSearchItem[],\n filterIssues: (items: GitHubSearchItem[]) => GitHubSearchItem[],\n excludedRepoSets: Set<string>[],\n remainingNeeded: number,\n minStars: number,\n phaseLabel: string,\n ): Promise<{ candidates: IssueCandidate[]; allVetFailed: boolean; rateLimitHit: boolean }> {\n const spamRepos = detectLabelFarmingRepos(items);\n if (spamRepos.size > 0) {\n const spamCount = items.filter((i) => spamRepos.has(i.repository_url.split('/').slice(-2).join('/'))).length;\n debug(\n MODULE,\n `[SPAM_FILTER] Filtered ${spamCount} issues from ${spamRepos.size} label-farming repos: ${[...spamRepos].join(', ')}`,\n );\n }\n\n const itemsToVet = filterIssues(items)\n .filter((item) => {\n const repoFullName = item.repository_url.split('/').slice(-2).join('/');\n if (spamRepos.has(repoFullName)) return false;\n return excludedRepoSets.every((s) => !s.has(repoFullName));\n })\n .slice(0, remainingNeeded * 2);\n\n if (itemsToVet.length === 0) {\n debug(MODULE, `[${phaseLabel}] All ${items.length} items filtered before vetting`);\n return { candidates: [], allVetFailed: false, rateLimitHit: false };\n }\n\n const {\n candidates: results,\n allFailed: allVetFailed,\n rateLimitHit,\n } = await this.vetter.vetIssuesParallel(\n itemsToVet.map((i) => i.html_url),\n remainingNeeded,\n 'normal',\n );\n\n const starFiltered = results.filter((c) => {\n if (c.projectHealth.checkFailed) return true;\n const stars = c.projectHealth.stargazersCount ?? 0;\n return stars >= minStars;\n });\n const starFilteredCount = results.length - starFiltered.length;\n if (starFilteredCount > 0) {\n debug(MODULE, `[STAR_FILTER] Filtered ${starFilteredCount} ${phaseLabel} candidates below ${minStars} stars`);\n }\n\n return { candidates: starFiltered, allVetFailed, rateLimitHit };\n }\n\n /**\n * Search for issues matching our criteria.\n * Searches in priority order: merged-PR repos first (no label filter), then starred repos,\n * then general search, then actively maintained repos (#349).\n * Filters out issues from low-scoring and excluded repos.\n */\n async searchIssues(\n options: {\n languages?: string[];\n labels?: string[];\n maxResults?: number;\n } = {},\n ): Promise<IssueCandidate[]> {\n const config = this.stateManager.getState().config;\n const languages = options.languages || config.languages;\n const labels = options.labels || config.labels;\n const maxResults = options.maxResults || 10;\n const minStars = config.minStars ?? 50;\n\n const allCandidates: IssueCandidate[] = [];\n let phase0Error: string | null = null;\n let phase1Error: string | null = null;\n let rateLimitHitDuringSearch = false;\n\n // Pre-flight rate limit check (#100)\n this.rateLimitWarning = null;\n try {\n const rateLimit = await checkRateLimit(this.githubToken);\n if (rateLimit.remaining < 5) {\n const resetTime = new Date(rateLimit.resetAt).toLocaleTimeString('en-US', { hour12: false });\n this.rateLimitWarning = `GitHub search API quota low (${rateLimit.remaining}/${rateLimit.limit} remaining, resets at ${resetTime}). Search may be slow.`;\n warn(MODULE, this.rateLimitWarning);\n }\n } catch (error) {\n // Fail fast on auth errors \u2014 no point searching with a bad token\n if (getHttpStatusCode(error) === 401) {\n throw error;\n }\n // Non-fatal: proceed with search for transient/network errors\n warn(MODULE, 'Could not check rate limit:', errorMessage(error));\n }\n\n // Get merged-PR repos (highest merge probability)\n const mergedPRRepos = this.stateManager.getReposWithMergedPRs();\n const mergedPRRepoSet = new Set(mergedPRRepos);\n\n // Get open-PR repos (repos with score data but no merges yet)\n const openPRRepos = this.stateManager.getReposWithOpenPRs();\n\n // Get starred repos (with refresh if stale)\n const starredRepos = await this.getStarredReposWithRefresh();\n const starredRepoSet = new Set(starredRepos);\n\n // Get low-scoring repos from state\n const lowScoringRepos = new Set(this.stateManager.getLowScoringRepos(3)); // Score <= 3 is low\n\n // Common filters\n const trackedUrls = new Set(this.stateManager.getState().activeIssues.map((i) => i.url));\n const excludedRepos = new Set(config.excludeRepos);\n const maxAgeDays = config.maxIssueAgeDays || 90;\n const now = new Date();\n\n // Build query parts\n const labelQuery = labels.map((l) => `label:\"${l}\"`).join(' ');\n // When languages includes 'any', omit the language filter entirely\n const isAnyLanguage = languages.some((l) => l.toLowerCase() === 'any');\n const langQuery = isAnyLanguage ? '' : languages.map((l) => `language:${l}`).join(' ');\n // Phase 0 uses a broader query \u2014 established contributors don't need beginner labels\n const establishedQuery = `is:issue is:open ${langQuery} no:assignee`.replace(/ +/g, ' ').trim();\n // Phases 1+ use label-filtered query for discovery in unfamiliar repos\n const baseQuery = `is:issue is:open ${labelQuery} ${langQuery} no:assignee`.replace(/ +/g, ' ').trim();\n\n // Helper to filter issues\n const includeDocIssues = config.includeDocIssues ?? true;\n const aiBlocklisted = new Set(config.aiPolicyBlocklist ?? DEFAULT_CONFIG.aiPolicyBlocklist ?? []);\n if (aiBlocklisted.size > 0) {\n debug(\n MODULE,\n `[AI_POLICY_FILTER] Filtering issues from ${aiBlocklisted.size} blocklisted repo(s): ${[...aiBlocklisted].join(', ')}`,\n );\n }\n const filterIssues = (items: GitHubSearchItem[]) => {\n return items.filter((item) => {\n if (trackedUrls.has(item.html_url)) return false;\n const repoFullName = item.repository_url.split('/').slice(-2).join('/');\n if (excludedRepos.has(repoFullName)) return false;\n // Filter repos with known anti-AI contribution policies (#108)\n if (aiBlocklisted.has(repoFullName)) return false;\n // Filter OUT low-scoring repos\n if (lowScoringRepos.has(repoFullName)) return false;\n // Filter by issue age based on updated_at\n const updatedAt = new Date(item.updated_at);\n const ageDays = daysBetween(updatedAt, now);\n if (ageDays > maxAgeDays) return false;\n // Filter out doc-only issues unless opted in (#105)\n if (!includeDocIssues && isDocOnlyIssue(item)) return false;\n return true;\n });\n };\n\n // Phase 0: Search repos where user has merged PRs + open-PR repos (highest merge probability)\n // Uses broader query \u2014 established contributors don't need \"good first issue\" labels\n // Merged-PR repos come first, then open-PR repos fill remaining slots (capped at 10 total)\n const phase0Repos = [...mergedPRRepos, ...openPRRepos.filter((r) => !mergedPRRepoSet.has(r))].slice(0, 10);\n const phase0RepoSet = new Set(phase0Repos);\n\n if (phase0Repos.length > 0) {\n const mergedInPhase0 = Math.min(mergedPRRepos.length, phase0Repos.length);\n const openInPhase0 = phase0Repos.length - mergedInPhase0;\n info(\n MODULE,\n `Phase 0: Searching issues in ${phase0Repos.length} repos (${mergedInPhase0} merged-PR, ${openInPhase0} open-PR, no label filter)...`,\n );\n\n // Phase 0a: merged-PR repos (priority: merged_pr)\n const mergedPhase0Repos = phase0Repos.slice(0, mergedInPhase0);\n if (mergedPhase0Repos.length > 0) {\n const remainingNeeded = maxResults - allCandidates.length;\n if (remainingNeeded > 0) {\n const {\n candidates: mergedCandidates,\n allBatchesFailed,\n rateLimitHit,\n } = await this.searchInRepos(mergedPhase0Repos, establishedQuery, remainingNeeded, 'merged_pr', filterIssues);\n allCandidates.push(...mergedCandidates);\n if (allBatchesFailed) {\n phase0Error = 'All merged-PR repo batches failed';\n }\n if (rateLimitHit) {\n rateLimitHitDuringSearch = true;\n }\n info(MODULE, `Found ${mergedCandidates.length} candidates from merged-PR repos`);\n }\n }\n\n // Phase 0b: open-PR repos (priority: starred \u2014 intermediate tier)\n const openPhase0Repos = phase0Repos.slice(mergedInPhase0);\n if (openPhase0Repos.length > 0 && allCandidates.length < maxResults) {\n const remainingNeeded = maxResults - allCandidates.length;\n if (remainingNeeded > 0) {\n const {\n candidates: openCandidates,\n allBatchesFailed,\n rateLimitHit,\n } = await this.searchInRepos(openPhase0Repos, establishedQuery, remainingNeeded, 'starred', filterIssues);\n allCandidates.push(...openCandidates);\n if (allBatchesFailed) {\n const msg = 'All open-PR repo batches failed';\n phase0Error = phase0Error ? `${phase0Error}; ${msg}` : msg;\n }\n if (rateLimitHit) {\n rateLimitHitDuringSearch = true;\n }\n info(MODULE, `Found ${openCandidates.length} candidates from open-PR repos`);\n }\n }\n }\n\n // Phase 0.5: Search preferred organizations (explicit user preference)\n let phase0_5Error: string | null = null;\n const preferredOrgs = config.preferredOrgs ?? [];\n if (allCandidates.length < maxResults && preferredOrgs.length > 0) {\n // Filter out orgs already covered by Phase 0 repos\n const phase0Orgs = new Set(phase0Repos.map((r) => r.split('/')[0]?.toLowerCase()));\n const orgsToSearch = preferredOrgs.filter((org) => !phase0Orgs.has(org.toLowerCase())).slice(0, 5);\n\n if (orgsToSearch.length > 0) {\n info(MODULE, `Phase 0.5: Searching issues in ${orgsToSearch.length} preferred org(s)...`);\n const remainingNeeded = maxResults - allCandidates.length;\n const orgRepoFilter = orgsToSearch.map((org) => `org:${org}`).join(' OR ');\n const orgQuery = `${baseQuery} (${orgRepoFilter})`;\n\n try {\n const data = await this.cachedSearch({\n q: orgQuery,\n sort: 'created',\n order: 'desc',\n per_page: remainingNeeded * 3,\n });\n\n if (data.items.length > 0) {\n const filtered = filterIssues(data.items).filter((item) => {\n const repoFullName = item.repository_url.split('/').slice(-2).join('/');\n return !phase0RepoSet.has(repoFullName);\n });\n const {\n candidates: orgCandidates,\n allFailed: allVetFailed,\n rateLimitHit,\n } = await this.vetter.vetIssuesParallel(\n filtered.slice(0, remainingNeeded * 2).map((i) => i.html_url),\n remainingNeeded,\n 'preferred_org',\n );\n allCandidates.push(...orgCandidates);\n if (allVetFailed) {\n phase0_5Error = 'All preferred org issue vetting failed';\n }\n if (rateLimitHit) {\n rateLimitHitDuringSearch = true;\n }\n info(MODULE, `Found ${orgCandidates.length} candidates from preferred orgs`);\n }\n } catch (error) {\n const errMsg = errorMessage(error);\n phase0_5Error = errMsg;\n if (isRateLimitError(error)) {\n rateLimitHitDuringSearch = true;\n }\n warn(MODULE, `Error searching preferred orgs: ${errMsg}`);\n }\n }\n }\n\n // Phase 1: Search starred repos (filter out already-searched Phase 0 repos)\n if (allCandidates.length < maxResults && starredRepos.length > 0) {\n const reposToSearch = starredRepos.filter((r) => !phase0RepoSet.has(r));\n if (reposToSearch.length > 0) {\n info(MODULE, `Phase 1: Searching issues in ${reposToSearch.length} starred repos...`);\n const remainingNeeded = maxResults - allCandidates.length;\n if (remainingNeeded > 0) {\n const {\n candidates: starredCandidates,\n allBatchesFailed,\n rateLimitHit,\n } = await this.searchInRepos(reposToSearch.slice(0, 10), baseQuery, remainingNeeded, 'starred', filterIssues);\n allCandidates.push(...starredCandidates);\n if (allBatchesFailed) {\n phase1Error = 'All starred repo batches failed';\n }\n if (rateLimitHit) {\n rateLimitHitDuringSearch = true;\n }\n info(MODULE, `Found ${starredCandidates.length} candidates from starred repos`);\n }\n }\n }\n\n // Phase 2: General search (if still need more)\n let phase2Error: string | null = null;\n if (allCandidates.length < maxResults) {\n info(MODULE, 'Phase 2: General issue search...');\n const remainingNeeded = maxResults - allCandidates.length;\n try {\n const data = await this.cachedSearch({\n q: baseQuery,\n sort: 'created',\n order: 'desc',\n per_page: remainingNeeded * 3, // Fetch extra since some will be filtered\n });\n\n info(MODULE, `Found ${data.total_count} issues in general search, processing top ${data.items.length}...`);\n\n const seenRepos = new Set(allCandidates.map((c) => c.issue.repo));\n const {\n candidates: starFiltered,\n allVetFailed,\n rateLimitHit: vetRateLimitHit,\n } = await this.filterVetAndScore(\n data.items,\n filterIssues,\n [phase0RepoSet, starredRepoSet, seenRepos],\n remainingNeeded,\n minStars,\n 'Phase 2',\n );\n\n allCandidates.push(...starFiltered);\n if (allVetFailed) {\n phase2Error = (phase2Error ? phase2Error + '; ' : '') + 'all vetting failed';\n }\n if (vetRateLimitHit) {\n rateLimitHitDuringSearch = true;\n }\n info(MODULE, `Found ${starFiltered.length} candidates from general search`);\n } catch (error) {\n const errMsg = errorMessage(error);\n phase2Error = errMsg;\n if (isRateLimitError(error)) {\n rateLimitHitDuringSearch = true;\n }\n warn(MODULE, `Error in general issue search: ${errMsg}`);\n }\n }\n\n // Phase 3: Actively maintained repos (#349)\n // Searches the \"long tail\" of well-maintained repos (50+ stars, recently pushed,\n // not archived) that Phase 2 may miss because they aren't trending or pre-filtered.\n // Uses label-free query to cast a wider net focused on repo health.\n let phase3Error: string | null = null;\n if (allCandidates.length < maxResults) {\n info(MODULE, 'Phase 3: Searching actively maintained repos...');\n const remainingNeeded = maxResults - allCandidates.length;\n const thirtyDaysAgo = new Date();\n thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);\n const pushedSince = thirtyDaysAgo.toISOString().split('T')[0];\n // When user has category preferences, add a single topic filter to focus on relevant repos.\n // GitHub Search API AND-joins multiple topic: qualifiers, which is overly restrictive,\n // so we pick just the first topic to nudge results without eliminating valid matches.\n const categoryTopics = getTopicsForCategories(config.projectCategories ?? []);\n const topicQuery = categoryTopics.length > 0 ? `topic:${categoryTopics[0]}` : '';\n const phase3Query =\n `is:issue is:open no:assignee ${langQuery} ${topicQuery} stars:>=${minStars} pushed:>=${pushedSince} archived:false`\n .replace(/ +/g, ' ')\n .trim();\n\n try {\n const data = await this.cachedSearch({\n q: phase3Query,\n sort: 'updated',\n order: 'desc',\n per_page: remainingNeeded * 3,\n });\n\n info(\n MODULE,\n `Found ${data.total_count} issues in maintained-repo search, processing top ${data.items.length}...`,\n );\n\n const seenRepos = new Set(allCandidates.map((c) => c.issue.repo));\n const {\n candidates: starFiltered,\n allVetFailed,\n rateLimitHit: vetRateLimitHit,\n } = await this.filterVetAndScore(\n data.items,\n filterIssues,\n [phase0RepoSet, starredRepoSet, seenRepos],\n remainingNeeded,\n minStars,\n 'Phase 3',\n );\n\n allCandidates.push(...starFiltered);\n if (allVetFailed) {\n phase3Error = 'all vetting failed';\n }\n if (vetRateLimitHit) {\n rateLimitHitDuringSearch = true;\n }\n info(MODULE, `Found ${starFiltered.length} candidates from maintained-repo search`);\n } catch (error) {\n const errMsg = errorMessage(error);\n phase3Error = errMsg;\n if (isRateLimitError(error)) {\n rateLimitHitDuringSearch = true;\n }\n warn(MODULE, `Error in maintained-repo search: ${errMsg}`);\n }\n }\n\n if (allCandidates.length === 0) {\n const phaseErrors = [\n phase0Error ? `Phase 0 (merged-PR repos): ${phase0Error}` : null,\n phase0_5Error ? `Phase 0.5 (preferred orgs): ${phase0_5Error}` : null,\n phase1Error ? `Phase 1 (starred repos): ${phase1Error}` : null,\n phase2Error ? `Phase 2 (general): ${phase2Error}` : null,\n phase3Error ? `Phase 3 (maintained repos): ${phase3Error}` : null,\n ].filter(Boolean);\n const details = phaseErrors.length > 0 ? ` ${phaseErrors.join('. ')}.` : '';\n\n // When rate limits caused zero results, return empty array with warning\n // instead of throwing, so callers can handle it gracefully\n if (rateLimitHitDuringSearch) {\n this.rateLimitWarning =\n `Search returned no results due to GitHub API rate limits.${details} ` +\n `Try again after the rate limit resets.`;\n return [];\n }\n\n throw new ValidationError(\n `No issue candidates found across all search phases.${details} ` +\n 'Try adjusting your search criteria (languages, labels) or check your network connection.',\n );\n }\n\n // Surface rate limit warning even with partial results (#100)\n // This overwrites the pre-flight \"quota low\" warning (speculative) with a more\n // informative \"results incomplete\" warning (factual) when rate limits actually hit.\n if (rateLimitHitDuringSearch) {\n this.rateLimitWarning =\n `Search results may be incomplete: GitHub API rate limits were hit during search. ` +\n `Found ${allCandidates.length} candidate${allCandidates.length === 1 ? '' : 's'} but some search phases failed. ` +\n `Try again after the rate limit resets for complete results.`;\n }\n\n // Sort by priority first, then by recommendation, then by viability score\n allCandidates.sort((a, b) => {\n // Priority order: merged_pr > preferred_org > starred > normal\n const priorityOrder: Record<SearchPriority, number> = { merged_pr: 0, preferred_org: 1, starred: 2, normal: 3 };\n const priorityDiff = priorityOrder[a.searchPriority] - priorityOrder[b.searchPriority];\n if (priorityDiff !== 0) return priorityDiff;\n\n // Then by recommendation\n const recommendationOrder = { approve: 0, needs_review: 1, skip: 2 };\n const recDiff = recommendationOrder[a.recommendation] - recommendationOrder[b.recommendation];\n if (recDiff !== 0) return recDiff;\n\n // Then by viability score (highest first)\n return b.viabilityScore - a.viabilityScore;\n });\n\n // Apply per-repo cap: max 2 issues from any single repo (#105)\n const capped = applyPerRepoCap(allCandidates, 2);\n\n return capped.slice(0, maxResults);\n }\n\n /**\n * Search for issues within specific repos using batched queries.\n *\n * To avoid GitHub's secondary rate limit (30 requests/minute), we batch\n * multiple repos into a single search query using OR syntax:\n * repo:owner1/repo1 OR repo:owner2/repo2 OR repo:owner3/repo3\n *\n * This reduces API calls from N (one per repo) to ceil(N/BATCH_SIZE).\n */\n private async searchInRepos(\n repos: string[],\n baseQuery: string,\n maxResults: number,\n priority: SearchPriority,\n filterFn: (items: GitHubSearchItem[]) => GitHubSearchItem[],\n ): Promise<{ candidates: IssueCandidate[]; allBatchesFailed: boolean; rateLimitHit: boolean }> {\n const candidates: IssueCandidate[] = [];\n\n // Batch repos to reduce API calls.\n // GitHub search query has a max length (~256 chars for query part).\n // Each \"repo:owner/repo\" is ~20-40 chars, plus \" OR \" (4 chars).\n // Using 5 repos per batch stays well under the limit.\n const BATCH_SIZE = 5;\n const batches = this.batchRepos(repos, BATCH_SIZE);\n let failedBatches = 0;\n let rateLimitFailures = 0;\n\n for (const batch of batches) {\n if (candidates.length >= maxResults) break;\n\n try {\n // Build repo filter: (repo:a OR repo:b OR repo:c)\n const repoFilter = batch.map((r) => `repo:${r}`).join(' OR ');\n const batchQuery = `${baseQuery} (${repoFilter})`;\n\n const data = await this.cachedSearch({\n q: batchQuery,\n sort: 'created',\n order: 'desc',\n per_page: Math.min(30, (maxResults - candidates.length) * 3),\n });\n\n if (data.items.length > 0) {\n const filtered = filterFn(data.items);\n const remainingNeeded = maxResults - candidates.length;\n const { candidates: vetted } = await this.vetter.vetIssuesParallel(\n filtered.slice(0, remainingNeeded * 2).map((i) => i.html_url),\n remainingNeeded,\n priority,\n );\n candidates.push(...vetted);\n }\n } catch (error) {\n failedBatches++;\n if (isRateLimitError(error)) {\n rateLimitFailures++;\n }\n const batchRepos = batch.join(', ');\n warn(MODULE, `Error searching issues in batch [${batchRepos}]:`, errorMessage(error));\n }\n }\n\n const allBatchesFailed = failedBatches === batches.length && batches.length > 0;\n const rateLimitHit = rateLimitFailures > 0;\n if (allBatchesFailed) {\n warn(\n MODULE,\n `All ${batches.length} batch(es) failed for ${priority} phase. ` +\n `This may indicate a systemic issue (rate limit, auth, network).`,\n );\n }\n\n return { candidates, allBatchesFailed, rateLimitHit };\n }\n\n /**\n * Split repos into batches of the specified size.\n */\n private batchRepos(repos: string[], batchSize: number): string[][] {\n const batches: string[][] = [];\n for (let i = 0; i < repos.length; i += batchSize) {\n batches.push(repos.slice(i, i + batchSize));\n }\n return batches;\n }\n\n /**\n * Vet a specific issue (delegates to IssueVetter).\n */\n async vetIssue(issueUrl: string): Promise<IssueCandidate> {\n return this.vetter.vetIssue(issueUrl);\n }\n\n /**\n * Analyze issue requirements for clarity (delegates to IssueVetter).\n * Kept on class for backward compatibility.\n */\n analyzeRequirements(body: string): boolean {\n return this.vetter.analyzeRequirements(body);\n }\n\n /**\n * Calculate viability score for an issue (delegates to issue-scoring module).\n * Kept on class for backward compatibility with tests that call instance.calculateViabilityScore().\n */\n calculateViabilityScore(params: ViabilityScoreParams): number {\n return calcViabilityScore(params);\n }\n\n /**\n * Save search results to ~/.oss-autopilot/found-issues.md\n * Results are sorted by viability score (highest first)\n */\n saveSearchResults(candidates: IssueCandidate[]): string {\n // Sort by viability score descending\n const sorted = [...candidates].sort((a, b) => b.viabilityScore - a.viabilityScore);\n\n const outputDir = getDataDir();\n const outputFile = path.join(outputDir, 'found-issues.md');\n\n // Directory is created by getDataDir() if needed\n\n // Generate markdown content\n const timestamp = new Date().toISOString();\n let content = `# Found Issues\\n\\n`;\n content += `> Generated at: ${timestamp}\\n\\n`;\n content += `| Score | Repo | Issue | Title | Labels | Updated | Recommendation |\\n`;\n content += `|-------|------|-------|-------|--------|---------|----------------|\\n`;\n\n for (const candidate of sorted) {\n const { issue, viabilityScore, recommendation } = candidate;\n const labels = issue.labels.slice(0, 3).join(', ');\n const truncatedLabels = labels.length > 30 ? labels.substring(0, 27) + '...' : labels;\n const truncatedTitle = issue.title.length > 50 ? issue.title.substring(0, 47) + '...' : issue.title;\n const updatedDate = new Date(issue.updatedAt).toLocaleDateString();\n const recIcon = recommendation === 'approve' ? 'Y' : recommendation === 'skip' ? 'N' : '?';\n\n content += `| ${viabilityScore} | ${issue.repo} | [#${issue.number}](${issue.url}) | ${truncatedTitle} | ${truncatedLabels} | ${updatedDate} | ${recIcon} |\\n`;\n }\n\n content += `\\n## Legend\\n\\n`;\n content += `- **Score**: Viability score (0-100)\\n`;\n content += `- **Recommendation**: Y = approve, N = skip, ? = needs_review\\n`;\n\n fs.writeFileSync(outputFile, content, 'utf-8');\n info(MODULE, `Saved ${sorted.length} issues to ${outputFile}`);\n\n return outputFile;\n }\n\n /**\n * Format issue candidate for display\n */\n formatCandidate(candidate: IssueCandidate): string {\n const { issue, vettingResult, projectHealth, recommendation, reasonsToApprove, reasonsToSkip } = candidate;\n\n const statusIcon = recommendation === 'approve' ? '\u2705' : recommendation === 'skip' ? '\u274C' : '\u26A0\uFE0F';\n\n return `\n## ${statusIcon} Issue Candidate: ${issue.repo}#${issue.number}\n\n**Title:** ${issue.title}\n**Labels:** ${issue.labels.join(', ')}\n**Created:** ${new Date(issue.createdAt).toLocaleDateString()}\n**URL:** ${issue.url}\n\n### Vetting Results\n${Object.entries(vettingResult.checks)\n .map(([key, passed]) => `- ${passed ? '\u2713' : '\u2717'} ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`)\n .join('\\n')}\n\n### Project Health\n- Last commit: ${projectHealth.checkFailed ? 'unknown (API error)' : `${projectHealth.daysSinceLastCommit} days ago`}\n- Open issues: ${projectHealth.openIssuesCount}\n- CI status: ${projectHealth.ciStatus}\n\n### Recommendation: **${recommendation.toUpperCase()}**\n${reasonsToApprove.length > 0 ? `\\n**Reasons to approve:**\\n${reasonsToApprove.map((r) => `- ${r}`).join('\\n')}` : ''}\n${reasonsToSkip.length > 0 ? `\\n**Reasons to skip:**\\n${reasonsToSkip.map((r) => `- ${r}`).join('\\n')}` : ''}\n${vettingResult.notes.length > 0 ? `\\n**Notes:**\\n${vettingResult.notes.map((n) => `- ${n}`).join('\\n')}` : ''}\n`;\n }\n}\n", "/**\n * Issue Conversation Monitor \u2014 tracks issues the user has commented on\n * and detects maintainer responses that need attention.\n *\n * Follows the same pattern as PRMonitor: stateless fetch from GitHub,\n * bounded concurrency via worker pool, bot/acknowledgment filtering.\n */\n\nimport { Octokit } from '@octokit/rest';\nimport { getOctokit } from './github.js';\nimport { isBotAuthor, isAcknowledgmentComment } from './comment-utils.js';\nimport { paginateAll } from './pagination.js';\nimport { getStateManager } from './state.js';\nimport { daysBetween, splitRepo, extractOwnerRepo, isOwnRepo, DEFAULT_CONCURRENCY } from './utils.js';\nimport { runWorkerPool } from './concurrency.js';\nimport type { CommentedIssue, IssueConversationStatus } from './types.js';\nimport { ConfigurationError, errorMessage } from './errors.js';\nimport { debug, warn } from './logger.js';\n\nconst MODULE = 'issue-conversation';\n\nconst MAX_CONCURRENT_REQUESTS = DEFAULT_CONCURRENCY;\n\n/** Associations that indicate someone with repo-level permissions. */\nconst MAINTAINER_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);\n\nexport class IssueConversationMonitor {\n private octokit: Octokit;\n private stateManager: ReturnType<typeof getStateManager>;\n\n constructor(githubToken: string) {\n this.octokit = getOctokit(githubToken);\n this.stateManager = getStateManager();\n }\n\n /**\n * Fetch issues the user has commented on and determine conversation state.\n * Filters out: user-authored issues, user-owned repos, excluded repos/orgs,\n * AI policy blocklisted repos, already-tracked issues, and pull requests.\n */\n async fetchCommentedIssues(\n maxDays: number = 30,\n ): Promise<{ issues: CommentedIssue[]; failures: Array<{ issueUrl: string; error: string }> }> {\n const config = this.stateManager.getState().config;\n\n if (!config.githubUsername) {\n throw new ConfigurationError('No GitHub username configured. Run setup first.');\n }\n\n const username = config.githubUsername;\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - maxDays);\n const since = cutoffDate.toISOString().split('T')[0];\n\n debug(MODULE, `Fetching commented issues for @${username} (last ${maxDays} days)...`);\n\n // Search for open issues the user has commented on, updated within window\n // Single page (100) is sufficient for most users; log if truncated.\n const { data } = await this.octokit.search.issuesAndPullRequests({\n q: `commenter:${username} type:issue state:open updated:>=${since}`,\n sort: 'updated',\n order: 'desc',\n per_page: 100,\n });\n\n if (data.total_count > 100) {\n warn(\n MODULE,\n `Search returned ${data.total_count} results but only first 100 were fetched. Some commented issues may be missing.`,\n );\n }\n\n // Build sets for filtering\n const trackedIssues = this.stateManager.getState().activeIssues || [];\n const trackedIssueKeys = new Set(\n trackedIssues\n .filter((i) => i.status === 'claimed' || i.status === 'in_progress' || i.status === 'pr_submitted')\n .map((i) => `${i.repo}#${i.number}`),\n );\n const blocklist = new Set((config.aiPolicyBlocklist || []).map((r) => r.toLowerCase()));\n\n // Filter out PRs, user-authored issues, excluded repos, blocklisted repos, and already-tracked issues.\n // Also parse repo info for each candidate to avoid re-parsing in analyzeIssueConversation.\n const candidates: Array<{ item: (typeof data.items)[0]; repoFullName: string }> = [];\n for (const item of data.items) {\n // Defensive: skip pull requests in case type:issue qualifier is unreliable\n if (item.pull_request) continue;\n\n const parsed = extractOwnerRepo(item.html_url);\n if (!parsed) {\n warn(MODULE, `Skipping issue with unparseable URL: ${item.html_url}`);\n continue;\n }\n\n const { owner, repo } = parsed;\n const repoFullName = `${owner}/${repo}`;\n\n // Skip issues in user-owned repos (we only care about contributing to others' projects)\n if (isOwnRepo(owner, username)) continue;\n\n // Skip user-authored issues\n if (item.user?.login?.toLowerCase() === username.toLowerCase()) continue;\n\n // Skip excluded repos and orgs\n if (config.excludeRepos.includes(repoFullName)) continue;\n if (config.excludeOrgs?.some((org) => owner.toLowerCase() === org.toLowerCase())) continue;\n\n // Skip blocklisted repos\n if (blocklist.has(repoFullName.toLowerCase())) continue;\n\n // Skip issues already in the tracked pipeline\n if (trackedIssueKeys.has(`${repoFullName}#${item.number}`)) continue;\n\n candidates.push({ item, repoFullName });\n }\n\n debug(MODULE, `Found ${candidates.length} commented issues to check`);\n\n // Fetch comments for each issue using worker pool.\n const results: CommentedIssue[] = [];\n const failures: Array<{ issueUrl: string; error: string }> = [];\n\n await runWorkerPool(\n candidates,\n async ({ item, repoFullName }) => {\n try {\n const issue = await this.analyzeIssueConversation(item, repoFullName, username);\n if (issue) {\n results.push(issue);\n } else {\n failures.push({\n issueUrl: item.html_url,\n error:\n 'No user comment found despite commenter: search match (possible pagination or eventual consistency)',\n });\n }\n } catch (error) {\n const msg = errorMessage(error);\n failures.push({ issueUrl: item.html_url, error: msg });\n warn(MODULE, `Error analyzing issue ${item.html_url}: ${msg}`);\n }\n },\n MAX_CONCURRENT_REQUESTS,\n );\n\n if (failures.length > 0) {\n warn(MODULE, `${failures.length}/${candidates.length} issue analysis call(s) failed`);\n }\n if (failures.length === candidates.length && candidates.length > 0) {\n warn(\n MODULE,\n `All ${candidates.length} issue analysis call(s) failed. Possible systemic issue (rate limit, auth, network).`,\n );\n }\n\n // Sort: new_response first, then waiting, then acknowledged\n const statusOrder: Record<IssueConversationStatus, number> = {\n new_response: 0,\n waiting: 1,\n acknowledged: 2,\n };\n results.sort((a, b) => statusOrder[a.status] - statusOrder[b.status]);\n\n debug(\n MODULE,\n `Analyzed ${results.length} issue conversations (${results.filter((i) => i.status === 'new_response').length} with new responses)`,\n );\n return { issues: results, failures };\n }\n\n /**\n * Analyze a single issue's comment thread to determine conversation status.\n */\n private async analyzeIssueConversation(\n item: { html_url: string; number: number; title: string; labels?: Array<{ name?: string }> },\n repoFullName: string,\n username: string,\n ): Promise<CommentedIssue | null> {\n const { owner, repo } = splitRepo(repoFullName);\n\n const allComments = await paginateAll((page) =>\n this.octokit.issues.listComments({\n owner,\n repo,\n issue_number: item.number,\n per_page: 100,\n page,\n }),\n );\n\n const timeline: Array<{\n author: string;\n body: string;\n createdAt: string;\n isUser: boolean;\n authorAssociation: string;\n }> = [];\n for (const comment of allComments) {\n if (!comment.user?.login) continue; // Skip comments from deleted accounts\n const author = comment.user.login;\n timeline.push({\n author,\n body: comment.body || '',\n createdAt: comment.created_at,\n isUser: author.toLowerCase() === username.toLowerCase(),\n authorAssociation: String((comment as Record<string, unknown>).author_association ?? ''),\n });\n }\n\n timeline.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n\n // Find the user's last comment\n let userLastComment: (typeof timeline)[0] | undefined;\n for (const entry of timeline) {\n if (entry.isUser) userLastComment = entry;\n }\n\n // If user never commented (shouldn't happen with commenter: search, but be safe)\n if (!userLastComment) {\n warn(MODULE, `No user comment found for ${item.html_url} despite commenter: search match`);\n return null;\n }\n\n const userLastCommentTime = new Date(userLastComment.createdAt);\n\n // Only surface comments directed at the user (#343):\n // 1. From a maintainer (OWNER/MEMBER/COLLABORATOR) \u2014 inherently authoritative\n // 2. @mentions the user \u2014 explicitly addressed\n // This filters out community \"+1\" and \"me too\" noise.\n const userMention = `@${username.toLowerCase()}`;\n\n function isDirectedAtUser(entry: { authorAssociation: string; body: string }): boolean {\n return MAINTAINER_ASSOCIATIONS.has(entry.authorAssociation) || entry.body.toLowerCase().includes(userMention);\n }\n\n // Find the last substantive, directed response after the user's last comment\n let lastResponse: { author: string; body: string; createdAt: string; authorAssociation: string } | undefined;\n for (const entry of timeline) {\n if (entry.isUser) continue;\n if (isBotAuthor(entry.author)) continue;\n\n const entryTime = new Date(entry.createdAt);\n if (entryTime > userLastCommentTime) {\n if (isAcknowledgmentComment(entry.body)) continue;\n if (!isDirectedAtUser(entry)) continue;\n\n lastResponse = {\n author: entry.author,\n body: entry.body.slice(0, 200) + (entry.body.length > 200 ? '...' : ''),\n createdAt: entry.createdAt,\n authorAssociation: entry.authorAssociation,\n };\n }\n }\n\n const labels = (item.labels || []).map((l) => l.name || '').filter(Boolean);\n\n const base = {\n repo: repoFullName,\n number: item.number,\n title: item.title,\n url: item.html_url,\n userLastCommentedAt: userLastComment.createdAt,\n labels,\n daysSinceUserComment: daysBetween(userLastCommentTime, new Date()),\n };\n\n if (lastResponse) {\n return {\n ...base,\n status: 'new_response' as const,\n lastResponseAuthor: lastResponse.author,\n lastResponseBody: lastResponse.body,\n lastResponseAt: lastResponse.createdAt,\n isFromMaintainer: MAINTAINER_ASSOCIATIONS.has(lastResponse.authorAssociation),\n };\n }\n\n // No directed response found. Determine whether the user or a relevant\n // commenter (maintainer / @mention) spoke last. Irrelevant community\n // comments are excluded from this check too (#343).\n const lastRelevantComment = [...timeline].reverse().find((e) => {\n if (isBotAuthor(e.author)) return false;\n if (e.isUser) return true;\n return isDirectedAtUser(e);\n });\n const status = lastRelevantComment?.isUser ? ('acknowledged' as const) : ('waiting' as const);\n return { ...base, status };\n }\n}\n", "/**\n * Domain logic extracted from src/commands/daily.ts.\n *\n * Pure or near-pure functions that operate on FetchedPR data:\n * - computeRepoSignals / groupPRsByRepo \u2014 per-repo aggregations\n * - assessCapacity \u2014 capacity assessment against active PRs\n * - collectActionableIssues \u2014 ordered list of issues needing attention\n * - computeActionMenu \u2014 pre-computed action menu for orchestration\n * - toShelvedPRRef \u2014 lightweight projection for digest display\n * - formatActionHint \u2014 human-readable maintainer action hint label\n * - formatBriefSummary / formatSummary / printDigest \u2014 rendering\n */\n\nimport { formatRelativeTime } from './utils.js';\nimport { warn } from './logger.js';\nimport { errorMessage } from './errors.js';\nimport { getStateManager } from './state.js';\nimport type {\n FetchedPR,\n FetchedPRStatus,\n StalenessTier,\n ActionReason,\n DailyDigest,\n AgentState,\n ShelvedPRRef,\n MaintainerActionHint,\n ComputedRepoSignals,\n RepoGroup,\n CommentedIssue,\n CommentedIssueWithResponse,\n} from './types.js';\nimport type {\n CapacityAssessment,\n ActionableIssue,\n ActionableIssueType,\n ActionMenu,\n ActionMenuItem,\n} from '../formatters/json.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Statuses indicating action needed from the contributor.\n * Used for auto-unshelving shelved PRs.\n */\nexport const CRITICAL_STATUSES: ReadonlySet<FetchedPRStatus> = new Set(['needs_addressing']);\n\n/**\n * ActionReason values that indicate high-priority issues blocking capacity.\n * `incomplete_checklist` is excluded \u2014 it's actionable but not blocking.\n * Used in capacity assessment to determine if user can take on new work.\n */\nexport const CRITICAL_ACTION_REASONS: ReadonlySet<ActionReason> = new Set([\n 'needs_response',\n 'needs_changes',\n 'failing_ci',\n 'merge_conflict',\n]);\n\n/** Staleness tiers indicating staleness \u2014 maintainer comments during these tiers don't count as responsive. */\nexport const STALE_STATUSES: ReadonlySet<StalenessTier> = new Set(['dormant', 'approaching_dormant']);\n\n// ---------------------------------------------------------------------------\n// Status overrides\n// ---------------------------------------------------------------------------\n\n/**\n * Apply status overrides from state to the PR list.\n * Overrides are auto-cleared if the PR has new activity since the override was set.\n *\n * When an override changes the status, the contradictory reason field is cleared\n * and an appropriate default is set so downstream logic (assessCapacity, collectActionableIssues)\n * works correctly.\n */\nconst VALID_OVERRIDE_STATUSES: ReadonlySet<FetchedPRStatus> = new Set(['needs_addressing', 'waiting_on_maintainer']);\n\nexport function applyStatusOverrides(prs: FetchedPR[], state: Readonly<AgentState>): FetchedPR[] {\n const overrides = state.config.statusOverrides;\n if (!overrides || Object.keys(overrides).length === 0) return prs;\n\n const stateManager = getStateManager();\n // Snapshot keys before iteration \u2014 clearStatusOverride mutates the same object\n const overrideUrls = new Set(Object.keys(overrides));\n let didAutoClear = false;\n\n const result = prs.map((pr) => {\n try {\n const override = stateManager.getStatusOverride(pr.url, pr.updatedAt);\n if (!override) {\n if (overrideUrls.has(pr.url)) didAutoClear = true;\n return pr;\n }\n if (!VALID_OVERRIDE_STATUSES.has(override.status)) {\n warn('daily-logic', `Invalid override status \"${override.status}\" for ${pr.url} \u2014 ignoring`);\n return pr;\n }\n if (override.status === pr.status) return pr;\n\n // Clear the contradictory reason field and set an appropriate default\n if (override.status === 'waiting_on_maintainer') {\n return { ...pr, status: override.status, actionReason: undefined, waitReason: 'pending_review' as const };\n }\n return { ...pr, status: override.status, waitReason: undefined, actionReason: 'needs_response' as const };\n } catch (err) {\n warn('daily-logic', `Failed to apply status override for ${pr.url}: ${errorMessage(err)}`);\n return pr;\n }\n });\n\n // Persist any auto-cleared overrides so they don't resurrect on restart\n if (didAutoClear) {\n try {\n stateManager.save();\n } catch (err) {\n warn(\n 'daily-logic',\n `Failed to persist auto-cleared overrides \u2014 they may reappear on restart: ${errorMessage(err)}`,\n );\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build a map grouping PRs by repository, skipping PRs with empty repo fields.\n * Shared by groupPRsByRepo and computeRepoSignals.\n */\nfunction buildRepoMap(prs: FetchedPR[], label: string): Map<string, FetchedPR[]> {\n const repoMap = new Map<string, FetchedPR[]>();\n for (const pr of prs) {\n if (!pr.repo) {\n warn(label, `Skipping PR #${pr.number} (${pr.url}) with empty repo field`);\n continue;\n }\n const existing = repoMap.get(pr.repo) || [];\n existing.push(pr);\n repoMap.set(pr.repo, existing);\n }\n return repoMap;\n}\n\n// ---------------------------------------------------------------------------\n// Domain functions\n// ---------------------------------------------------------------------------\n\n/**\n * Map a full FetchedPR to a lightweight ShelvedPRRef for digest output.\n * Only the fields needed for display are retained, reducing JSON payload size.\n */\nexport function toShelvedPRRef(pr: FetchedPR): ShelvedPRRef {\n return {\n number: pr.number,\n url: pr.url,\n title: pr.title,\n repo: pr.repo,\n daysSinceActivity: pr.daysSinceActivity,\n status: pr.status,\n };\n}\n\n/**\n * Group PRs by repository (#80).\n * Ensures one agent per repo during parallel dispatch, preventing branch checkout conflicts.\n */\nexport function groupPRsByRepo(prs: FetchedPR[]): RepoGroup[] {\n const repoMap = buildRepoMap(prs, 'GROUP_BY_REPO');\n const groups: RepoGroup[] = [];\n for (const [repo, repoPRs] of repoMap) {\n groups.push({ repo, prs: repoPRs });\n }\n return groups;\n}\n\n/**\n * Compute per-repo maintainer signals from observed open PR data.\n * - isResponsive: true if any PR in the repo has a maintainer comment and stalenessTier is active\n * - hasActiveMaintainers: true if any non-stale PR exists in the repo (stalenessTier is 'active')\n */\nexport function computeRepoSignals(prs: FetchedPR[]): Map<string, ComputedRepoSignals> {\n const repoMap = buildRepoMap(prs, 'COMPUTE_SIGNALS');\n const result = new Map<string, ComputedRepoSignals>();\n for (const [repo, repoPRs] of repoMap) {\n const isResponsive = repoPRs.some((pr) => pr.lastMaintainerComment && !STALE_STATUSES.has(pr.stalenessTier));\n const hasActiveMaintainers = repoPRs.some((pr) => !STALE_STATUSES.has(pr.stalenessTier));\n result.set(repo, { isResponsive, hasActiveMaintainers });\n }\n return result;\n}\n\n/**\n * Assess whether user has capacity for new issues.\n * Only active (non-shelved) PRs count against the limit.\n */\nexport function assessCapacity(\n activePRs: FetchedPR[],\n maxActivePRs: number,\n shelvedPRCount: number,\n): CapacityAssessment {\n const activePRCount = activePRs.length;\n const criticalIssueCount = activePRs.filter(\n (pr) => pr.status === 'needs_addressing' && pr.actionReason && CRITICAL_ACTION_REASONS.has(pr.actionReason),\n ).length;\n\n // Has capacity if: under PR limit AND no critical issues\n const underPRLimit = activePRCount < maxActivePRs;\n const noCriticalIssues = criticalIssueCount === 0;\n const hasCapacity = underPRLimit && noCriticalIssues;\n\n // Generate reason\n let reason: string;\n const shelvedNote = shelvedPRCount > 0 ? ` + ${shelvedPRCount} shelved` : '';\n if (hasCapacity) {\n reason = `You have capacity: ${activePRCount}/${maxActivePRs} active PRs${shelvedNote}, no critical issues`;\n } else {\n const reasons: string[] = [];\n if (!underPRLimit) {\n reasons.push(`at PR limit (${activePRCount}/${maxActivePRs}${shelvedNote})`);\n }\n if (!noCriticalIssues) {\n reasons.push(`${criticalIssueCount} critical issue${criticalIssueCount === 1 ? '' : 's'} need attention`);\n }\n reason = `No capacity: ${reasons.join(', ')}`;\n }\n\n return {\n hasCapacity,\n activePRCount,\n maxActivePRs,\n shelvedPRCount,\n criticalIssueCount,\n reason,\n };\n}\n\n/**\n * Collect all actionable issues across PRs for the action-first flow.\n * Order: Needs response -> Needs changes -> CI failing -> Merge conflicts -> Incomplete checklist\n *\n * Note: Recently closed PRs are informational only and excluded from this list.\n * They are available separately in digest.recentlyClosedPRs (#156).\n */\nexport function collectActionableIssues(prs: FetchedPR[], lastDigestAt?: string): ActionableIssue[] {\n const issues: ActionableIssue[] = [];\n const actionPRs = prs.filter((pr) => pr.status === 'needs_addressing');\n const lastDigestTime = lastDigestAt ? new Date(lastDigestAt).getTime() : NaN;\n\n const reasonOrder: ActionReason[] = [\n 'needs_response',\n 'needs_changes',\n 'failing_ci',\n 'merge_conflict',\n 'incomplete_checklist',\n ];\n\n for (const reason of reasonOrder) {\n for (const pr of actionPRs) {\n if (pr.actionReason !== reason) continue;\n\n let label: string;\n let type: ActionableIssueType;\n switch (reason) {\n case 'needs_response':\n label = '[Needs Response]';\n type = 'needs_response';\n break;\n case 'needs_changes':\n label = '[Needs Changes]';\n type = 'needs_changes';\n break;\n case 'failing_ci': {\n const checkInfo = pr.failingCheckNames.length > 0 ? ` (${pr.failingCheckNames.join(', ')})` : '';\n label = `[CI Failing${checkInfo}]`;\n type = 'ci_failing';\n break;\n }\n case 'merge_conflict':\n label = '[Merge Conflict]';\n type = 'merge_conflict';\n break;\n case 'incomplete_checklist': {\n const stats = pr.checklistStats ? ` (${pr.checklistStats.checked}/${pr.checklistStats.total})` : '';\n label = `[Incomplete Checklist${stats}]`;\n type = 'incomplete_checklist';\n break;\n }\n default:\n // Defensive fallback for ActionReason values not explicitly handled\n // above (e.g. ci_not_running, needs_rebase, missing_required_files).\n // These aren't in reasonOrder today but this guards future additions.\n warn('daily-logic', `Unhandled ActionReason \"${reason}\" for PR ${pr.url} \u2014 falling back to needs_response`);\n label = `[${reason}]`;\n type = 'needs_response';\n }\n\n // A PR is \"new\" if it was created after the last daily digest (first time seen).\n // If there's no previous digest (first run) or createdAt is invalid, assume new.\n const createdTime = new Date(pr.createdAt).getTime();\n let isNewContribution: boolean;\n if (isNaN(createdTime)) {\n warn('daily-logic', `Invalid createdAt \"${pr.createdAt}\" for PR ${pr.url}, assuming new contribution`);\n isNewContribution = true;\n } else {\n isNewContribution = isNaN(lastDigestTime) || createdTime > lastDigestTime;\n }\n\n issues.push({ type, pr, label, isNewContribution });\n }\n }\n\n return issues;\n}\n\n/**\n * Format a maintainer action hint as a human-readable label\n */\nexport function formatActionHint(hint: MaintainerActionHint): string {\n switch (hint) {\n case 'demo_requested':\n return 'demo/screenshot requested';\n case 'tests_requested':\n return 'tests requested';\n case 'changes_requested':\n return 'code changes requested';\n case 'docs_requested':\n return 'documentation requested';\n case 'rebase_requested':\n return 'rebase requested';\n }\n}\n\n/**\n * Compute the action menu from PR data and capacity.\n * The orchestration layer can insert issue-list options (e.g., \"Pick from list\")\n * using the context flags.\n */\nexport function computeActionMenu(\n actionableIssues: ActionableIssue[],\n capacity: CapacityAssessment,\n commentedIssues: CommentedIssue[] = [],\n): ActionMenu {\n const issueResponses = commentedIssues.filter((i): i is CommentedIssueWithResponse => i.status === 'new_response');\n const items: ActionMenuItem[] = [];\n const hasActionableIssues = actionableIssues.length > 0;\n const hasIssueResponses = issueResponses.length > 0;\n\n if (hasActionableIssues) {\n const isSingle = actionableIssues.length === 1;\n items.push({\n key: 'address_all',\n label: isSingle\n ? 'Address this issue (Recommended)'\n : `Work through all ${actionableIssues.length} issues (Recommended)`,\n description: isSingle\n ? 'Fix the issue blocking your PR'\n : 'Run maintenance in parallel, then address code changes one at a time',\n });\n }\n\n // Issue replies \u2014 positioned after address_all but before search\n if (hasIssueResponses) {\n items.push({\n key: 'issue_replies',\n label: `Review ${issueResponses.length} issue repl${issueResponses.length === 1 ? 'y' : 'ies'}`,\n description: 'Maintainers responded to your comments on issues',\n });\n }\n\n // The orchestration layer (commands/oss.md Action Menu section) may insert issue-list\n // options before the search item when a curated list is available.\n\n items.push({\n key: 'search',\n label: 'Search for new issues',\n description: 'Look for new contribution opportunities',\n });\n\n items.push({\n key: 'done',\n label: 'Done for now',\n description: 'End session with summary',\n });\n\n return {\n items,\n context: {\n hasActionableIssues,\n actionableCount: actionableIssues.length,\n hasCapacity: capacity.hasCapacity,\n hasIssueResponses,\n issueResponseCount: issueResponses.length,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Rendering / formatting\n// ---------------------------------------------------------------------------\n\n/**\n * Format a brief one-liner summary for the action-first flow\n */\nexport function formatBriefSummary(digest: DailyDigest, issueCount: number, issueResponseCount: number = 0): string {\n const attentionText = issueCount > 0 ? `${issueCount} need${issueCount === 1 ? 's' : ''} attention` : 'all on track';\n const issueReplyText =\n issueResponseCount > 0 ? ` | ${issueResponseCount} issue repl${issueResponseCount === 1 ? 'y' : 'ies'}` : '';\n return `\\u{1F4CA} ${digest.summary.totalActivePRs} Active PRs | ${attentionText}${issueReplyText}`;\n}\n\n/**\n * Format summary as markdown (used in JSON output for Claude to display verbatim)\n */\nexport function formatSummary(\n digest: DailyDigest,\n capacity: CapacityAssessment,\n issueResponses: CommentedIssueWithResponse[] = [],\n): string {\n const lines: string[] = [];\n\n // Header\n lines.push('## OSS Dashboard');\n lines.push('');\n lines.push(\n `\\u{1F4CA} **${digest.summary.totalActivePRs} Active PRs** | ${digest.summary.totalMergedAllTime} Merged | ${digest.summary.mergeRate}% Merge Rate`,\n );\n lines.push('\\u2713 Dashboard generated \\u2014 say \"open dashboard\" to view in browser');\n lines.push('');\n\n // Needs Addressing\n if (digest.needsAddressingPRs.length > 0) {\n lines.push('### \\u274C Needs Addressing');\n for (const pr of digest.needsAddressingPRs) {\n lines.push(`- [${pr.repo}#${pr.number}](${pr.url}): ${pr.title}`);\n lines.push(` \\u2514\\u2500 ${pr.displayLabel} ${pr.displayDescription}`);\n }\n lines.push('');\n }\n\n // Waiting on Maintainer\n if (digest.waitingOnMaintainerPRs.length > 0) {\n lines.push('### \\u23F3 Waiting on Maintainer');\n for (const pr of digest.waitingOnMaintainerPRs) {\n lines.push(`- [${pr.repo}#${pr.number}](${pr.url}): ${pr.title}`);\n lines.push(` \\u2514\\u2500 ${pr.displayDescription}`);\n }\n lines.push('');\n }\n\n // Recently Merged (wins!)\n if (digest.recentlyMergedPRs.length > 0) {\n lines.push('### \\u{1F389} Recently Merged');\n for (const pr of digest.recentlyMergedPRs) {\n const mergedDate = pr.mergedAt ? new Date(pr.mergedAt).toLocaleDateString() : '';\n lines.push(`- [${pr.repo}#${pr.number}](${pr.url}): ${pr.title}${mergedDate ? ` (merged ${mergedDate})` : ''}`);\n }\n lines.push('');\n }\n\n // Recently Closed (closed without merge)\n if (digest.recentlyClosedPRs.length > 0) {\n lines.push('### \\u{1F6AB} Recently Closed');\n for (const pr of digest.recentlyClosedPRs) {\n const closedDate = pr.closedAt ? new Date(pr.closedAt).toLocaleDateString() : '';\n lines.push(`- [${pr.repo}#${pr.number}](${pr.url}): ${pr.title}${closedDate ? ` (closed ${closedDate})` : ''}`);\n }\n lines.push('');\n }\n\n // Auto-unshelved (important: maintainer engagement on shelved PRs)\n if (digest.autoUnshelvedPRs.length > 0) {\n lines.push('### \\u{1F514} Auto-Unshelved');\n lines.push('> These PRs were shelved but a maintainer engaged \\u2014 moved back to active.');\n for (const pr of digest.autoUnshelvedPRs) {\n lines.push(`- [${pr.repo}#${pr.number}](${pr.url}): ${pr.title} (${pr.status.replace(/_/g, ' ')})`);\n }\n lines.push('');\n }\n\n // Shelved PRs (dimmed, excluded from capacity)\n if (digest.shelvedPRs.length > 0) {\n lines.push('### \\u{1F4E6} Shelved');\n for (const pr of digest.shelvedPRs) {\n lines.push(`- [${pr.repo}#${pr.number}](${pr.url}): ${pr.title}`);\n }\n lines.push('');\n }\n\n // Issue Replies\n if (issueResponses.length > 0) {\n lines.push('### \\u{1F4AC} Issue Replies');\n for (const issue of issueResponses) {\n lines.push(`- [${issue.repo}#${issue.number}](${issue.url}): ${issue.title}`);\n const timeAgo = formatRelativeTime(issue.lastResponseAt);\n lines.push(\n ` \\u2514\\u2500 @${issue.lastResponseAuthor}: \"${issue.lastResponseBody.slice(0, 80)}${issue.lastResponseBody.length > 80 ? '...' : ''}\"${timeAgo ? ` (${timeAgo})` : ''}`,\n );\n }\n lines.push('');\n }\n\n // Capacity\n const capacityIcon = capacity.hasCapacity ? '\\u2705' : '\\u26A0\\uFE0F';\n const capacityLabel = capacity.hasCapacity ? 'Ready for new work' : 'Focus on existing PRs';\n const shelvedNote = capacity.shelvedPRCount > 0 ? ` + ${capacity.shelvedPRCount} shelved` : '';\n lines.push(\n `**Capacity:** ${capacityIcon} ${capacityLabel} (${capacity.activePRCount}/${capacity.maxActivePRs} PRs${shelvedNote})`,\n );\n\n return lines.join('\\n');\n}\n\n/**\n * Print digest to console (simple text output).\n * Unified renderer: uses the same section ordering as formatSummary\n * but outputs plain text with console.log instead of markdown links.\n */\nexport function printDigest(\n digest: DailyDigest,\n capacity: CapacityAssessment,\n commentedIssues: CommentedIssue[] = [],\n): void {\n console.log('\\n\\u{1F4CA} OSS Daily Check\\n');\n console.log(`Active PRs: ${digest.summary.totalActivePRs}`);\n console.log(`Needing Attention: ${digest.summary.totalNeedingAttention}`);\n console.log(`Merged (all time): ${digest.summary.totalMergedAllTime}`);\n console.log(`Merge Rate: ${digest.summary.mergeRate}%`);\n console.log(\n `\\nCapacity: ${capacity.hasCapacity ? '\\u2705 Ready for new work' : '\\u26A0\\uFE0F Focus on existing work'}`,\n );\n console.log(` ${capacity.reason}\\n`);\n\n if (digest.needsAddressingPRs.length > 0) {\n console.log('\\u274C Needs Addressing:');\n for (const pr of digest.needsAddressingPRs) {\n console.log(` - ${pr.repo}#${pr.number}: ${pr.title}`);\n console.log(` ${pr.displayLabel} ${pr.displayDescription}`);\n }\n console.log('');\n }\n\n if (digest.waitingOnMaintainerPRs.length > 0) {\n console.log('\\u23F3 Waiting on Maintainer:');\n for (const pr of digest.waitingOnMaintainerPRs) {\n console.log(` - ${pr.repo}#${pr.number}: ${pr.title}`);\n console.log(` ${pr.displayDescription}`);\n }\n console.log('');\n }\n\n if (digest.recentlyMergedPRs.length > 0) {\n console.log('\\u{1F389} Recently Merged:');\n for (const pr of digest.recentlyMergedPRs) {\n const mergedDate = pr.mergedAt ? new Date(pr.mergedAt).toLocaleDateString() : '';\n console.log(` - ${pr.repo}#${pr.number}: ${pr.title}${mergedDate ? ` (merged ${mergedDate})` : ''}`);\n }\n console.log('');\n }\n\n if (digest.recentlyClosedPRs.length > 0) {\n console.log('\\u{1F6AB} Recently Closed:');\n for (const pr of digest.recentlyClosedPRs) {\n const closedDate = pr.closedAt ? new Date(pr.closedAt).toLocaleDateString() : '';\n console.log(` - ${pr.repo}#${pr.number}: ${pr.title}${closedDate ? ` (closed ${closedDate})` : ''}`);\n }\n console.log('');\n }\n\n if (digest.autoUnshelvedPRs.length > 0) {\n console.log('\\u{1F514} Auto-Unshelved:');\n for (const pr of digest.autoUnshelvedPRs) {\n console.log(` - ${pr.repo}#${pr.number}: ${pr.title} (${pr.status.replace(/_/g, ' ')})`);\n }\n console.log('');\n }\n\n if (digest.shelvedPRs.length > 0) {\n console.log('\\u{1F4E6} Shelved:');\n for (const pr of digest.shelvedPRs) {\n console.log(` - ${pr.repo}#${pr.number}: ${pr.title}`);\n }\n console.log('');\n }\n\n const issueResponses = commentedIssues.filter((i): i is CommentedIssueWithResponse => i.status === 'new_response');\n if (issueResponses.length > 0) {\n console.log('\\u{1F4AC} Issue Replies:');\n for (const issue of issueResponses) {\n console.log(` - ${issue.repo}#${issue.number}: ${issue.title}`);\n console.log(\n ` @${issue.lastResponseAuthor}: ${issue.lastResponseBody.slice(0, 80)}${issue.lastResponseBody.length > 80 ? '...' : ''}`,\n );\n }\n console.log('');\n }\n\n console.log('Run with --json for structured output');\n console.log('Run \"dashboard serve\" for browser view');\n}\n", "/**\n * Contribution statistics computation.\n * Computes metrics from repo scores and PR data for shareable stats and badges.\n */\n\nimport type { RepoScore } from './types.js';\n\nexport interface ContributionStats {\n totalMerged: number;\n totalClosed: number;\n mergeRate: number;\n activePRs: number;\n reposContributed: number;\n topRepos: Array<{ repo: string; mergedCount: number }>;\n}\n\nconst MAX_TOP_REPOS = 10;\n\nexport interface ComputeStatsInput {\n repoScores: Record<string, Pick<RepoScore, 'mergedPRCount' | 'closedWithoutMergeCount' | 'repo'>>;\n activePRCount: number;\n}\n\n/**\n * Compute contribution statistics from repo score data.\n * Pure function \u2014 no side effects, no API calls.\n */\nexport function computeContributionStats(input: ComputeStatsInput): ContributionStats {\n const { repoScores, activePRCount } = input;\n\n let totalMerged = 0;\n let totalClosed = 0;\n const repoEntries: Array<{ repo: string; mergedCount: number }> = [];\n\n for (const score of Object.values(repoScores)) {\n totalMerged += score.mergedPRCount;\n totalClosed += score.closedWithoutMergeCount;\n if (score.mergedPRCount > 0) {\n repoEntries.push({ repo: score.repo, mergedCount: score.mergedPRCount });\n }\n }\n\n const total = totalMerged + totalClosed;\n const mergeRate = total > 0 ? totalMerged / total : 0;\n\n repoEntries.sort((a, b) => b.mergedCount - a.mergedCount);\n\n return {\n totalMerged,\n totalClosed,\n mergeRate,\n activePRs: activePRCount,\n reposContributed: repoEntries.length,\n topRepos: repoEntries.slice(0, MAX_TOP_REPOS),\n };\n}\n", "/**\n * Fetch a repository's PR description template from GitHub.\n *\n * Checks the standard template locations in GitHub's priority order:\n * 1. .github/PULL_REQUEST_TEMPLATE.md\n * 2. .github/pull_request_template.md\n * 3. docs/pull_request_template.md\n * 4. pull_request_template.md (root)\n *\n * Returns the decoded template content and the path where it was found,\n * or null if no template exists.\n */\n\nimport type { Octokit } from '@octokit/rest';\nimport { debug, warn } from './logger.js';\nimport { errorMessage, getHttpStatusCode, isRateLimitOrAuthError } from './errors.js';\n\nconst MODULE = 'pr-template';\n\n/** Standard paths GitHub checks for PR templates, in priority order. */\nconst TEMPLATE_PATHS = [\n '.github/PULL_REQUEST_TEMPLATE.md',\n '.github/pull_request_template.md',\n 'docs/pull_request_template.md',\n 'pull_request_template.md',\n];\n\nexport interface PRTemplateResult {\n /** The decoded template content, or null if no template was found. */\n template: string | null;\n /** The path where the template was found (e.g., \".github/PULL_REQUEST_TEMPLATE.md\"). */\n source: string | null;\n /** If non-null, an error prevented a complete check of all template paths. */\n error?: string;\n}\n\n/**\n * Fetch a repository's PR template by trying each standard location.\n * Returns on the first successful match. Rate limit and auth errors\n * propagate to the caller (consistent with project error strategy).\n */\nexport async function fetchPRTemplate(octokit: Octokit, owner: string, repo: string): Promise<PRTemplateResult> {\n for (const path of TEMPLATE_PATHS) {\n try {\n debug(MODULE, `Checking ${owner}/${repo} for template at ${path}`);\n const { data } = await octokit.repos.getContent({ owner, repo, path });\n\n // getContent returns an array for directories (e.g., multiple templates); we only want files\n if (Array.isArray(data)) {\n debug(MODULE, `${path} is a directory (multiple templates?), skipping`);\n continue;\n }\n if (data.type !== 'file') {\n debug(MODULE, `${path} is type \"${data.type}\", skipping`);\n continue;\n }\n if (!data.content) {\n debug(MODULE, `${path} has no content, skipping`);\n continue;\n }\n\n const template = Buffer.from(data.content, 'base64').toString('utf-8');\n debug(MODULE, `Found PR template at ${path} (${template.length} chars)`);\n return { template, source: path };\n } catch (err: unknown) {\n // 404 = template doesn't exist at this path, try next\n if (getHttpStatusCode(err) === 404) continue;\n // Rate limit and auth errors must propagate (project error strategy)\n if (isRateLimitOrAuthError(err)) throw err;\n // Other errors (500, network) \u2014 warn and return with error context\n const msg = errorMessage(err);\n warn(MODULE, `Error checking ${owner}/${repo}/${path}: ${msg}`);\n return { template: null, source: null, error: msg };\n }\n }\n\n debug(MODULE, `No PR template found for ${owner}/${repo}`);\n return { template: null, source: null };\n}\n", "/**\n * Core module exports\n * Re-exports all core functionality for convenient imports\n */\n\nexport { StateManager, getStateManager, resetStateManager, type Stats } from './state.js';\nexport {\n PRMonitor,\n type PRCheckFailure,\n type FetchPRsResult,\n computeDisplayLabel,\n classifyCICheck,\n classifyFailingChecks,\n} from './pr-monitor.js';\nexport {\n IssueDiscovery,\n type IssueCandidate,\n type SearchPriority,\n isDocOnlyIssue,\n applyPerRepoCap,\n DOC_ONLY_LABELS,\n} from './issue-discovery.js';\nexport { IssueConversationMonitor } from './issue-conversation.js';\nexport { isBotAuthor, isAcknowledgmentComment } from './comment-utils.js';\nexport { getOctokit, checkRateLimit, type RateLimitInfo } from './github.js';\nexport {\n parseGitHubUrl,\n daysBetween,\n splitRepo,\n isOwnRepo,\n getCLIVersion,\n getDataDir,\n getStatePath,\n getBackupDir,\n getCacheDir,\n formatRelativeTime,\n byDateDescending,\n getGitHubToken,\n getGitHubTokenAsync,\n requireGitHubToken,\n resetGitHubTokenCache,\n detectGitHubUsername,\n DEFAULT_CONCURRENCY,\n} from './utils.js';\nexport {\n OssAutopilotError,\n ConfigurationError,\n ValidationError,\n errorMessage,\n getHttpStatusCode,\n isRateLimitError,\n isRateLimitOrAuthError,\n} from './errors.js';\nexport { enableDebug, isDebugEnabled, debug, info, warn, timed } from './logger.js';\nexport { HttpCache, getHttpCache, cachedRequest, type CacheEntry } from './http-cache.js';\nexport {\n CRITICAL_STATUSES,\n applyStatusOverrides,\n computeRepoSignals,\n groupPRsByRepo,\n assessCapacity,\n collectActionableIssues,\n computeActionMenu,\n toShelvedPRRef,\n formatActionHint,\n formatBriefSummary,\n formatSummary,\n printDigest,\n} from './daily-logic.js';\nexport { computeContributionStats, type ContributionStats, type ComputeStatsInput } from './stats.js';\nexport { fetchPRTemplate, type PRTemplateResult } from './pr-template.js';\nexport * from './types.js';\n", "/**\n * JSON output formatter for CLI --json mode\n * Provides structured output that can be consumed by scripts and plugins\n */\n\nimport type { FetchedPR, DailyDigest, AgentState, RepoGroup, CommentedIssue, ShelvedPRRef } from '../core/types.js';\nimport type { ContributionStats } from '../core/stats.js';\nimport type { PRCheckFailure } from '../core/pr-monitor.js';\nimport type { SearchPriority } from '../core/issue-discovery.js';\n\nexport interface JsonOutput<T = unknown> {\n success: boolean;\n data?: T;\n error?: string;\n timestamp: string;\n}\n\nexport interface CapacityAssessment {\n hasCapacity: boolean;\n activePRCount: number;\n maxActivePRs: number;\n shelvedPRCount: number;\n criticalIssueCount: number;\n reason: string;\n}\n\nexport type ActionableIssueType =\n | 'ci_failing'\n | 'merge_conflict'\n | 'needs_response'\n | 'needs_changes'\n | 'incomplete_checklist';\n\nexport interface ActionableIssue {\n type: ActionableIssueType;\n pr: FetchedPR;\n label: string; // e.g., \"[CI Failing]\"\n /** True if the PR was created after the last daily digest (first time seen). */\n isNewContribution: boolean;\n}\n\n/**\n * Compact version of ActionableIssue for JSON output.\n * References the PR by URL instead of embedding the full object,\n * since the full PR is already available in digest.openPRs.\n * Uses URL (globally unique) instead of number to avoid cross-repo collisions.\n */\nexport interface CompactActionableIssue {\n type: ActionableIssueType;\n prUrl: string;\n label: string;\n /** True if the PR was created after the last daily digest (first time seen). */\n isNewContribution: boolean;\n}\n\n/**\n * A single action menu item pre-computed by the CLI.\n * The orchestration layer can use these directly in AskUserQuestion prompts.\n */\nexport interface ActionMenuItem {\n /** Stable identifier for routing (e.g., \"address_all\", \"search\", \"done\"). */\n key: string;\n /** Display text for the option (e.g., \"Work through all 3 issues (Recommended)\"). */\n label: string;\n /** Explanation shown below the label. */\n description: string;\n}\n\n/**\n * Pre-computed action menu for the orchestration layer.\n * Contains the menu items the CLI can determine from PR data and capacity,\n * plus context flags so the orchestration can insert issue-list options.\n */\nexport interface ActionMenu {\n /** Ordered list of menu items. The orchestration may insert issue-list items after the CLI-generated items (address_all, issue_replies) or at the start when none exist. */\n items: ActionMenuItem[];\n /** Context flags for the orchestration layer to decide on issue-list options. */\n context: {\n hasActionableIssues: boolean;\n actionableCount: number;\n hasCapacity: boolean;\n hasIssueResponses: boolean;\n issueResponseCount: number;\n };\n}\n\n/**\n * Deduplicated daily digest for JSON output (#287).\n *\n * Full PR objects live only in `openPRs`. Category arrays contain PR URLs\n * that reference into `openPRs`, reducing JSON payload size by ~60-70%.\n * Uses URLs (globally unique) instead of numbers to avoid cross-repo collisions.\n * Consumers look up full PR details via: openPRs.find(pr => pr.url === url)\n */\nexport interface DailyDigestCompact {\n generatedAt: string;\n\n /** All open PRs authored by the user \u2014 the single source of truth for full PR objects. */\n openPRs: FetchedPR[];\n\n // Category arrays: PR URLs referencing openPRs (each is a subset filtered by status)\n needsAddressingPRs: string[];\n waitingOnMaintainerPRs: string[];\n\n recentlyClosedPRs: DailyDigest['recentlyClosedPRs'];\n recentlyMergedPRs: DailyDigest['recentlyMergedPRs'];\n shelvedPRs: ShelvedPRRef[];\n autoUnshelvedPRs: ShelvedPRRef[];\n\n summary: DailyDigest['summary'];\n}\n\n/**\n * Compact repo group for JSON output (#287).\n * Uses PR URLs instead of full objects; look up in digest.openPRs.\n * Uses URLs (globally unique) instead of numbers to avoid cross-repo collisions.\n */\nexport interface CompactRepoGroup {\n repo: string;\n prUrls: string[];\n}\n\nexport interface DailyOutput {\n digest: DailyDigestCompact;\n capacity: CapacityAssessment;\n summary: string; // Pre-formatted markdown for Claude to display verbatim\n briefSummary: string; // One-liner for action-first flow\n actionableIssues: CompactActionableIssue[]; // Structured list referencing PRs by URL\n actionMenu: ActionMenu; // Pre-computed action menu for Action Menu section\n commentedIssues: CommentedIssue[]; // Issues user commented on with conversation state\n repoGroups: CompactRepoGroup[]; // PRs grouped by repo for safe parallel dispatch (#80)\n failures: PRCheckFailure[]; // PRs that failed to fetch (e.g., rate limits, network errors)\n}\n\n/**\n * Convert a full DailyDigest to the compact format for JSON output (#287).\n * Category arrays become PR URL arrays; full objects stay only in openPRs.\n * Uses URLs (globally unique) instead of numbers to avoid cross-repo collisions.\n */\nexport function deduplicateDigest(digest: DailyDigest): DailyDigestCompact {\n const toUrls = (prs: FetchedPR[]): string[] => prs.map((pr) => pr.url);\n\n return {\n generatedAt: digest.generatedAt,\n openPRs: digest.openPRs,\n needsAddressingPRs: toUrls(digest.needsAddressingPRs),\n waitingOnMaintainerPRs: toUrls(digest.waitingOnMaintainerPRs),\n recentlyClosedPRs: digest.recentlyClosedPRs,\n recentlyMergedPRs: digest.recentlyMergedPRs,\n shelvedPRs: digest.shelvedPRs,\n autoUnshelvedPRs: digest.autoUnshelvedPRs,\n summary: digest.summary,\n };\n}\n\n/**\n * Convert ActionableIssue[] to CompactActionableIssue[] for JSON output (#287).\n * Replaces the full PR object with just the PR URL (globally unique).\n */\nexport function compactActionableIssues(issues: ActionableIssue[]): CompactActionableIssue[] {\n return issues.map((issue) => ({\n type: issue.type,\n prUrl: issue.pr.url,\n label: issue.label,\n isNewContribution: issue.isNewContribution,\n }));\n}\n\n/**\n * Convert RepoGroup[] to CompactRepoGroup[] for JSON output (#287).\n * Replaces full PR arrays with PR URL arrays.\n */\nexport function compactRepoGroups(groups: RepoGroup[]): CompactRepoGroup[] {\n return groups.map((group) => ({\n repo: group.repo,\n prUrls: group.prs.map((pr) => pr.url),\n }));\n}\n\nexport interface StatusOutput {\n stats: {\n mergedPRs: number;\n closedPRs: number;\n activeIssues: number;\n trustedProjects: number;\n mergeRate: string;\n needsResponse: number;\n };\n lastRunAt: string;\n offline?: boolean;\n lastUpdated?: string;\n}\n\nexport interface SearchOutput {\n candidates: Array<{\n issue: {\n repo: string;\n number: number;\n title: string;\n url: string;\n labels: string[];\n };\n recommendation: 'approve' | 'skip' | 'needs_review';\n reasonsToApprove: string[];\n reasonsToSkip: string[];\n searchPriority: SearchPriority;\n /** 0-100 scale composite viability score */\n viabilityScore: number;\n repoScore?: {\n /** 1-10 scale repository quality score */\n score: number;\n mergedPRCount: number;\n closedWithoutMergeCount: number;\n isResponsive: boolean;\n lastMergedAt?: string;\n };\n }>;\n excludedRepos: string[];\n /** Repos with known anti-AI contribution policies, filtered from search results (#108). */\n aiPolicyBlocklist: string[];\n /** Present when rate limits affected the search \u2014 either low pre-flight quota or mid-search rate limit hits (#100). */\n rateLimitWarning?: string;\n}\n\nexport interface TrackOutput {\n pr: {\n repo: string;\n number: number;\n title: string;\n url: string;\n };\n}\n\nexport interface ConfigOutput {\n config: AgentState['config'];\n}\n\n/** Info about a detected issue list file */\nexport interface IssueListInfo {\n path: string;\n source: 'configured' | 'auto-detected';\n availableCount: number;\n completedCount: number;\n}\n\n/**\n * Output of the startup command (combines auth, setup, daily, dashboard, issue list).\n *\n * Three valid shapes:\n * 1. Setup incomplete: { version, setupComplete: false }\n * 2. Auth failure: { version, setupComplete: true, authError: \"...\" }\n * 3. Success: { version, setupComplete: true, daily, dashboardUrl?, issueList? }\n */\nexport interface StartupOutput {\n version: string;\n setupComplete: boolean;\n /** True when username was auto-detected on first run (zero-config). */\n autoDetected?: boolean;\n authError?: string;\n daily?: DailyOutput;\n /** URL of the interactive SPA dashboard server, when running (e.g., \"http://localhost:3000\") */\n dashboardUrl?: string;\n issueList?: IssueListInfo;\n}\n\n/** A single parsed issue from a markdown list (#82) */\nexport interface ParsedIssueItem {\n repo: string;\n number: number;\n title: string;\n tier: string;\n url: string;\n}\n\n/** Output of the parse-issue-list command (#82) */\nexport interface ParseIssueListOutput {\n available: ParsedIssueItem[];\n completed: ParsedIssueItem[];\n availableCount: number;\n completedCount: number;\n}\n\n/** Info about a new file's integration status (#83) */\nexport interface NewFileInfo {\n path: string;\n referencedBy: string[];\n isIntegrated: boolean;\n suggestedEntryPoints?: string[];\n}\n\n/** Output of the check-integration command (#83) */\nexport interface CheckIntegrationOutput {\n newFiles: NewFileInfo[];\n unreferencedCount: number;\n}\n\n/** Output of the vet command */\nexport interface VetOutput {\n issue: {\n repo: string;\n number: number;\n title: string;\n url: string;\n labels: string[];\n };\n recommendation: 'approve' | 'skip' | 'needs_review';\n reasonsToApprove: string[];\n reasonsToSkip: string[];\n projectHealth: unknown;\n vettingResult: unknown;\n}\n\n/** Output of the comments command */\nexport interface CommentsOutput {\n pr: {\n title: string;\n state: string;\n mergeable: boolean | null;\n head: string;\n base: string;\n url: string;\n };\n reviews: Array<{\n user: string | undefined;\n state: string;\n body: string | null;\n submittedAt: string | null;\n }>;\n reviewComments: Array<{\n user: string | undefined;\n body: string;\n path: string;\n createdAt: string;\n }>;\n issueComments: Array<{\n user: string | undefined;\n body: string | undefined;\n createdAt: string;\n }>;\n summary: {\n reviewCount: number;\n inlineCommentCount: number;\n discussionCommentCount: number;\n };\n}\n\n/** Output of the post command */\nexport interface PostOutput {\n commentUrl: string;\n url: string;\n}\n\n/** Output of the claim command */\nexport interface ClaimOutput {\n commentUrl: string;\n issueUrl: string;\n}\n\n/** Info about a local git clone (#84) */\nexport interface LocalRepoInfo {\n path: string;\n exists: boolean;\n currentBranch: string | null;\n}\n\n/** Output of the local-repos command (#84) */\nexport interface LocalReposOutput {\n repos: Record<string, LocalRepoInfo>;\n scanPaths: string[];\n cachedAt: string;\n fromCache: boolean;\n}\n\n/** Output of the stats command */\nexport interface StatsOutput extends ContributionStats {\n mergeRateFormatted: string;\n username: string;\n}\n\n/**\n * Wrap data in a standard JSON output envelope\n */\nexport function jsonSuccess<T>(data: T): JsonOutput<T> {\n return {\n success: true,\n data,\n timestamp: new Date().toISOString(),\n };\n}\n\n/**\n * Create an error JSON output\n */\nexport function jsonError(message: string): JsonOutput<never> {\n return {\n success: false,\n error: message,\n timestamp: new Date().toISOString(),\n };\n}\n\n/**\n * Output JSON to stdout\n */\nexport function outputJson<T>(data: T): void {\n console.log(JSON.stringify(jsonSuccess(data), null, 2));\n}\n\n/**\n * Output error JSON to stdout (sets success: false)\n */\nexport function outputJsonError(message: string): void {\n console.log(JSON.stringify(jsonError(message), null, 2));\n}\n", "/**\n * Dashboard data fetching and aggregation.\n * Handles GitHub API calls, PR grouping, stats computation, and monthly chart data.\n * Consumed by the dashboard HTTP server (dashboard-server.ts) for the SPA API.\n */\n\nimport { getStateManager, PRMonitor, IssueConversationMonitor, getOctokit } from '../core/index.js';\nimport { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';\nimport { warn } from '../core/logger.js';\nimport { emptyPRCountsResult, fetchMergedPRsSince, fetchClosedPRsSince } from '../core/github-stats.js';\nimport { parseGitHubUrl } from '../core/utils.js';\nimport {\n isBelowMinStars,\n type DailyDigest,\n type AgentState,\n type ClosedPR,\n type MergedPR,\n type StoredMergedPR,\n type StoredClosedPR,\n type CommentedIssue,\n} from '../core/types.js';\nimport { toShelvedPRRef, buildStarFilter } from './daily.js';\n\nconst MODULE = 'dashboard-data';\n\nexport interface DashboardStats {\n activePRs: number;\n shelvedPRs: number;\n mergedPRs: number;\n closedPRs: number;\n mergeRate: string;\n}\n\nexport function buildDashboardStats(\n digest: DailyDigest,\n state: Readonly<AgentState>,\n storedMergedCount?: number,\n storedClosedCount?: number,\n): DashboardStats {\n const summary = digest.summary || {\n totalActivePRs: 0,\n totalMergedAllTime: 0,\n mergeRate: 0,\n totalNeedingAttention: 0,\n };\n const minStars = state.config.minStars ?? 50;\n // Merged: use the higher of stored count vs repoScores aggregate to avoid regressions\n // when the stored list hasn't caught up yet (initial fetch caps at 300 PRs)\n const mergedPRs =\n storedMergedCount !== undefined\n ? Math.max(storedMergedCount, summary.totalMergedAllTime)\n : summary.totalMergedAllTime;\n // Closed: same anti-regression strategy \u2014 use the higher of stored count vs repoScores aggregate\n const aggregateClosedCount = Object.values(state.repoScores || {}).reduce(\n (sum, s) => sum + (isBelowMinStars(s.stargazersCount, minStars) ? 0 : s.closedWithoutMergeCount || 0),\n 0,\n );\n const closedPRs =\n storedClosedCount !== undefined ? Math.max(storedClosedCount, aggregateClosedCount) : aggregateClosedCount;\n return {\n activePRs: summary.totalActivePRs,\n shelvedPRs: (digest.shelvedPRs || []).length,\n mergedPRs,\n closedPRs,\n mergeRate: `${(summary.mergeRate ?? 0).toFixed(1)}%`,\n };\n}\n\n/**\n * Merge fresh API counts into existing stored counts.\n * Months present in the fresh data are updated; months only in the existing data are preserved.\n * This prevents historical data loss when the API returns incomplete results\n * (e.g. due to pagination limits or transient failures).\n */\nexport function mergeMonthlyCounts(\n existing: Record<string, number>,\n fresh: Record<string, number>,\n): Record<string, number> {\n const merged = { ...existing };\n for (const [month, count] of Object.entries(fresh)) {\n merged[month] = count;\n }\n return merged;\n}\n\n/**\n * Persist monthly chart analytics (merged, closed, opened) to state.\n * Each metric is isolated so partial failures don't produce inconsistent state.\n * Fresh API results are merged into existing data so historical months are preserved.\n * Skips updating when fresh data is empty to avoid wiping chart data on transient API failures.\n */\nexport function updateMonthlyAnalytics(\n prs: Array<{ createdAt?: string }>,\n monthlyCounts: Record<string, number>,\n monthlyClosedCounts: Record<string, number>,\n openedFromMerged: Record<string, number>,\n openedFromClosed: Record<string, number>,\n): void {\n const stateManager = getStateManager();\n const state = stateManager.getState();\n\n try {\n if (Object.keys(monthlyCounts).length > 0) {\n stateManager.setMonthlyMergedCounts(mergeMonthlyCounts(state.monthlyMergedCounts || {}, monthlyCounts));\n }\n } catch (error) {\n warn(MODULE, `Failed to store monthly merged counts: ${errorMessage(error)}`);\n }\n try {\n if (Object.keys(monthlyClosedCounts).length > 0) {\n stateManager.setMonthlyClosedCounts(mergeMonthlyCounts(state.monthlyClosedCounts || {}, monthlyClosedCounts));\n }\n } catch (error) {\n warn(MODULE, `Failed to store monthly closed counts: ${errorMessage(error)}`);\n }\n try {\n const combinedOpenedCounts: Record<string, number> = { ...openedFromMerged };\n for (const [month, count] of Object.entries(openedFromClosed)) {\n combinedOpenedCounts[month] = (combinedOpenedCounts[month] || 0) + count;\n }\n for (const pr of prs) {\n if (pr.createdAt) {\n const month = pr.createdAt.slice(0, 7);\n combinedOpenedCounts[month] = (combinedOpenedCounts[month] || 0) + 1;\n }\n }\n if (Object.keys(combinedOpenedCounts).length > 0) {\n stateManager.setMonthlyOpenedCounts(mergeMonthlyCounts(state.monthlyOpenedCounts || {}, combinedOpenedCounts));\n }\n } catch (error) {\n warn(MODULE, `Failed to store monthly opened counts: ${errorMessage(error)}`);\n }\n}\n\nexport interface DashboardFetchResult {\n digest: DailyDigest;\n commentedIssues: CommentedIssue[];\n allMergedPRs: MergedPR[];\n allClosedPRs: ClosedPR[];\n}\n\n/**\n * Fetch fresh dashboard data from GitHub.\n * Returns the digest and commented issues, updating state as a side effect.\n * Throws if the fetch fails entirely (caller should fall back to cached data).\n */\nexport async function fetchDashboardData(token: string): Promise<DashboardFetchResult> {\n const stateManager = getStateManager();\n const prMonitor = new PRMonitor(token);\n const issueMonitor = new IssueConversationMonitor(token);\n const octokit = getOctokit(token);\n const config = stateManager.getState().config;\n\n // Build star filter from cached repoScores (#576)\n const starFilter = buildStarFilter(stateManager.getState());\n\n // Get watermarks for incremental PR fetch\n const watermark = stateManager.getMergedPRWatermark();\n const closedWatermark = stateManager.getClosedPRWatermark();\n\n const [\n { prs, failures },\n recentlyClosedPRs,\n recentlyMergedPRs,\n mergedResult,\n closedResult,\n fetchedIssues,\n newMergedPRs,\n newClosedPRs,\n ] = await Promise.all([\n prMonitor.fetchUserOpenPRs(),\n prMonitor.fetchRecentlyClosedPRs().catch((err): ClosedPR[] => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch recently closed PRs: ${errorMessage(err)}`);\n return [];\n }),\n prMonitor.fetchRecentlyMergedPRs().catch((err): MergedPR[] => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch recently merged PRs: ${errorMessage(err)}`);\n return [];\n }),\n prMonitor.fetchUserMergedPRCounts(starFilter).catch((err) => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch merged PR counts: ${errorMessage(err)}`);\n return emptyPRCountsResult<{ count: number; lastMergedAt: string }>();\n }),\n prMonitor.fetchUserClosedPRCounts(starFilter).catch((err) => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch closed PR counts: ${errorMessage(err)}`);\n return emptyPRCountsResult<number>();\n }),\n issueMonitor.fetchCommentedIssues().catch((error) => {\n if (isRateLimitOrAuthError(error)) throw error;\n const msg = errorMessage(error);\n if (msg.includes('No GitHub username configured')) {\n warn(MODULE, `Issue conversation tracking requires setup: ${msg}`);\n } else {\n warn(MODULE, `Issue conversation fetch failed: ${msg}`);\n }\n return {\n issues: [] as CommentedIssue[],\n failures: [{ issueUrl: 'N/A', error: `Issue conversation fetch failed: ${msg}` }],\n };\n }),\n fetchMergedPRsSince(octokit, config, watermark).catch((err): StoredMergedPR[] => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch merged PRs for storage: ${errorMessage(err)}`);\n return [];\n }),\n fetchClosedPRsSince(octokit, config, closedWatermark).catch((err): StoredClosedPR[] => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch closed PRs for storage: ${errorMessage(err)}`);\n return [];\n }),\n ]);\n\n const commentedIssues = fetchedIssues.issues;\n if (fetchedIssues.failures.length > 0) {\n warn(MODULE, `${fetchedIssues.failures.length} issue conversation check(s) failed`);\n }\n\n if (failures.length > 0) {\n warn(MODULE, `${failures.length} PR fetch(es) failed`);\n }\n\n // Store new merged PRs incrementally (dedupes by URL)\n try {\n stateManager.addMergedPRs(newMergedPRs);\n } catch (error) {\n warn(MODULE, `Failed to store merged PRs: ${errorMessage(error)}`);\n }\n\n // Store new closed PRs incrementally (dedupes by URL)\n try {\n stateManager.addClosedPRs(newClosedPRs);\n } catch (error) {\n warn(MODULE, `Failed to store closed PRs: ${errorMessage(error)}`);\n }\n\n // Convert stored PRs to full types (derive repo/number from URL)\n const allMergedPRs = storedToMergedPRs(stateManager.getMergedPRs());\n const allClosedPRs = storedToClosedPRs(stateManager.getClosedPRs());\n\n // Store monthly chart data (opened/merged/closed) so charts have data\n const { monthlyCounts, monthlyOpenedCounts: openedFromMerged } = mergedResult;\n const { monthlyCounts: monthlyClosedCounts, monthlyOpenedCounts: openedFromClosed } = closedResult;\n updateMonthlyAnalytics(prs, monthlyCounts, monthlyClosedCounts, openedFromMerged, openedFromClosed);\n\n const digest = prMonitor.generateDigest(prs, recentlyClosedPRs, recentlyMergedPRs);\n\n // Apply shelve partitioning for display (auto-unshelve only runs in daily check)\n // Dormant PRs are treated as shelved unless they need addressing\n const shelvedUrls = new Set(stateManager.getState().config.shelvedPRUrls || []);\n const freshShelved = prs.filter(\n (pr) => shelvedUrls.has(pr.url) || (pr.stalenessTier === 'dormant' && pr.status !== 'needs_addressing'),\n );\n digest.shelvedPRs = freshShelved.map(toShelvedPRRef);\n digest.autoUnshelvedPRs = [];\n digest.summary.totalActivePRs = prs.length - freshShelved.length;\n\n stateManager.setLastDigest(digest);\n try {\n stateManager.save();\n } catch (error) {\n warn(MODULE, `Failed to save dashboard digest to state: ${errorMessage(error)}`);\n }\n warn(MODULE, `Refreshed: ${prs.length} PRs fetched`);\n\n return { digest, commentedIssues, allMergedPRs, allClosedPRs };\n}\n\n/**\n * Convert StoredMergedPR[] to MergedPR[] by deriving repo and number from URL.\n * Skips entries with unparseable URLs.\n */\nexport function storedToMergedPRs(stored: StoredMergedPR[]): MergedPR[] {\n const results: MergedPR[] = [];\n let skipped = 0;\n for (const pr of stored) {\n const parsed = parseGitHubUrl(pr.url);\n if (!parsed) {\n skipped++;\n continue;\n }\n results.push({\n url: pr.url,\n repo: `${parsed.owner}/${parsed.repo}`,\n number: parsed.number,\n title: pr.title,\n mergedAt: pr.mergedAt,\n });\n }\n if (skipped > 0) {\n warn(MODULE, `Skipped ${skipped} stored merged PR(s) with unparseable URLs`);\n }\n return results;\n}\n\n/**\n * Convert StoredClosedPR[] to ClosedPR[] by deriving repo and number from URL.\n * Skips entries with unparseable URLs.\n */\nexport function storedToClosedPRs(stored: StoredClosedPR[]): ClosedPR[] {\n const results: ClosedPR[] = [];\n let skipped = 0;\n for (const pr of stored) {\n const parsed = parseGitHubUrl(pr.url);\n if (!parsed) {\n skipped++;\n continue;\n }\n results.push({\n url: pr.url,\n repo: `${parsed.owner}/${parsed.repo}`,\n number: parsed.number,\n title: pr.title,\n closedAt: pr.closedAt,\n });\n }\n if (skipped > 0) {\n warn(MODULE, `Skipped ${skipped} stored closed PR(s) with unparseable URLs`);\n }\n return results;\n}\n\n/**\n * Compute PRs grouped by repository from a digest and state.\n * Used for chart data in the dashboard API.\n */\nexport function computePRsByRepo(\n digest: DailyDigest,\n state: Readonly<AgentState>,\n): Record<string, { active: number; merged: number; closed: number }> {\n const prsByRepo: Record<string, { active: number; merged: number; closed: number }> = {};\n\n // Count active PRs by repo from digest\n for (const pr of digest.openPRs || []) {\n if (!prsByRepo[pr.repo]) prsByRepo[pr.repo] = { active: 0, merged: 0, closed: 0 };\n prsByRepo[pr.repo].active++;\n }\n\n // Add merged/closed counts from repo scores (historical data), filtering by minStars (#576)\n const minStars = state.config.minStars ?? 50;\n for (const [repo, score] of Object.entries(state.repoScores || {})) {\n if (isBelowMinStars(score.stargazersCount, minStars)) continue;\n if (!prsByRepo[repo]) prsByRepo[repo] = { active: 0, merged: 0, closed: 0 };\n prsByRepo[repo].merged = score.mergedPRCount;\n prsByRepo[repo].closed = score.closedWithoutMergeCount;\n }\n\n return prsByRepo;\n}\n\n/**\n * Compute the top repositories sorted by total PR count.\n */\nexport function computeTopRepos(\n prsByRepo: Record<string, { active: number; merged: number; closed: number }>,\n limit: number = 10,\n): Array<[string, { active: number; merged: number; closed: number }]> {\n return Object.entries(prsByRepo)\n .sort((a, b) => b[1].merged + b[1].active + b[1].closed - (a[1].merged + a[1].active + a[1].closed))\n .slice(0, limit);\n}\n\n/**\n * Extract monthly activity data from state.\n */\nexport function getMonthlyData(state: Readonly<AgentState>): {\n monthlyMerged: Record<string, number>;\n monthlyClosed: Record<string, number>;\n monthlyOpened: Record<string, number>;\n} {\n return {\n monthlyMerged: state.monthlyMergedCounts || {},\n monthlyClosed: state.monthlyClosedCounts || {},\n monthlyOpened: state.monthlyOpenedCounts || {},\n };\n}\n", "/**\n * Daily check command\n * Fetches all open PRs fresh from GitHub (v2: no PR-level state tracking),\n * generates a digest, and updates repo scores and analytics in local state.\n *\n * Domain logic lives in src/core/daily-logic.ts; this file is a thin\n * orchestration layer that wires up the phases and handles I/O.\n */\n\nimport {\n getStateManager,\n PRMonitor,\n IssueConversationMonitor,\n requireGitHubToken,\n CRITICAL_STATUSES,\n applyStatusOverrides,\n computeRepoSignals,\n groupPRsByRepo,\n assessCapacity,\n collectActionableIssues,\n computeActionMenu,\n toShelvedPRRef,\n formatBriefSummary,\n formatSummary,\n type DailyDigest,\n type FetchedPR,\n type ShelvedPRRef,\n type MergedPR,\n type ClosedPR,\n type CommentedIssue,\n type CommentedIssueWithResponse,\n type PRCheckFailure,\n type RepoGroup,\n type AgentState,\n type StarFilter,\n} from '../core/index.js';\nimport { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';\nimport { warn } from '../core/logger.js';\nimport { emptyPRCountsResult } from '../core/github-stats.js';\nimport { updateMonthlyAnalytics } from './dashboard-data.js';\nimport {\n deduplicateDigest,\n compactActionableIssues,\n compactRepoGroups,\n type DailyOutput,\n type CapacityAssessment,\n type ActionableIssue,\n type ActionMenu,\n} from '../formatters/json.js';\n\nconst MODULE = 'daily';\n\n// Re-export domain functions so existing consumers (tests, dashboard, startup)\n// can continue importing from './daily.js' without changes.\nexport {\n applyStatusOverrides,\n computeRepoSignals,\n groupPRsByRepo,\n assessCapacity,\n collectActionableIssues,\n computeActionMenu,\n toShelvedPRRef,\n formatBriefSummary,\n formatSummary,\n printDigest,\n CRITICAL_STATUSES,\n} from '../core/index.js';\n\n/**\n * Build a star filter from state for use in fetchUserPRCounts.\n * Returns undefined if no star data is available (first run).\n */\nexport function buildStarFilter(state: Readonly<AgentState>): StarFilter | undefined {\n const minStars = state.config.minStars ?? 50;\n const knownStarCounts = new Map<string, number>();\n for (const [repo, score] of Object.entries(state.repoScores)) {\n if (score.stargazersCount !== undefined) {\n knownStarCounts.set(repo, score.stargazersCount);\n }\n }\n // Only filter if we have some star data to work with\n if (knownStarCounts.size === 0) return undefined;\n return { minStars, knownStarCounts };\n}\n\n/**\n * Internal result of the daily check, using full (non-deduplicated) types.\n * Consumed by printDigest() (text mode) and converted to DailyOutput (JSON mode)\n * via toDailyOutput() which deduplicates PR objects.\n */\nexport interface DailyCheckResult {\n digest: DailyDigest;\n capacity: CapacityAssessment;\n summary: string;\n briefSummary: string;\n actionableIssues: ActionableIssue[];\n actionMenu: ActionMenu;\n commentedIssues: CommentedIssue[];\n repoGroups: RepoGroup[];\n failures: PRCheckFailure[];\n}\n\n// ---------------------------------------------------------------------------\n// Phase result types\n// ---------------------------------------------------------------------------\n\ninterface FetchedPRData {\n prs: FetchedPR[];\n failures: PRCheckFailure[];\n mergedCounts: Map<string, { count: number; lastMergedAt: string | null }>;\n closedCounts: Map<string, number>;\n monthlyCounts: Record<string, number>;\n monthlyClosedCounts: Record<string, number>;\n openedFromMerged: Record<string, number>;\n openedFromClosed: Record<string, number>;\n recentlyClosedPRs: ClosedPR[];\n recentlyMergedPRs: MergedPR[];\n commentedIssues: CommentedIssue[];\n}\n\ninterface PartitionedPRs {\n activePRs: FetchedPR[];\n shelvedPRs: ShelvedPRRef[];\n autoUnshelvedPRs: ShelvedPRRef[];\n digest: DailyDigest;\n}\n\n// ---------------------------------------------------------------------------\n// Phase functions\n// ---------------------------------------------------------------------------\n\n/**\n * Phase 1: Fetch all PR data from GitHub.\n * Retrieves open PRs, merged/closed counts, recently closed/merged PRs, and\n * issue conversation data \u2014 all in parallel where possible.\n */\nasync function fetchPRData(prMonitor: PRMonitor, token: string): Promise<FetchedPRData> {\n // Fetch all open PRs fresh from GitHub\n const { prs, failures } = await prMonitor.fetchUserOpenPRs();\n\n // Log any failures (but continue with successful checks)\n if (failures.length > 0) {\n warn(MODULE, `${failures.length} PR fetch(es) failed`);\n }\n\n // Build star filter from cached repoScores so low-star repos are excluded\n // from merged/closed histograms (#576). Repos with no cached star data pass through.\n const state = getStateManager().getState();\n const starFilter = buildStarFilter(state);\n\n // Fetch merged PR counts, closed PR counts, recently closed PRs, recently merged PRs, and commented issues in parallel\n // All stats fetches are non-critical (cosmetic/scoring), so isolate their failure\n const issueMonitor = new IssueConversationMonitor(token);\n const [mergedResult, closedResult, recentlyClosedPRs, recentlyMergedPRs, issueConversationResult] = await Promise.all(\n [\n prMonitor.fetchUserMergedPRCounts(starFilter).catch((err) => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch merged PR counts: ${errorMessage(err)}`);\n return emptyPRCountsResult<{ count: number; lastMergedAt: string }>();\n }),\n prMonitor.fetchUserClosedPRCounts(starFilter).catch((err) => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch closed PR counts: ${errorMessage(err)}`);\n return emptyPRCountsResult<number>();\n }),\n prMonitor.fetchRecentlyClosedPRs().catch((err): ClosedPR[] => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch recently closed PRs: ${errorMessage(err)}`);\n return [];\n }),\n prMonitor.fetchRecentlyMergedPRs().catch((err): MergedPR[] => {\n if (isRateLimitOrAuthError(err)) throw err;\n warn(MODULE, `Failed to fetch recently merged PRs: ${errorMessage(err)}`);\n return [];\n }),\n issueMonitor.fetchCommentedIssues().catch((error) => {\n if (isRateLimitOrAuthError(error)) throw error;\n const msg = errorMessage(error);\n if (msg.includes('No GitHub username configured')) {\n warn(MODULE, `Issue conversation tracking requires setup: ${msg}`);\n } else {\n warn(MODULE, `Issue conversation fetch failed: ${msg}`);\n }\n return {\n issues: [] as CommentedIssue[],\n failures: [{ issueUrl: 'N/A', error: `Issue conversation fetch failed: ${msg}` }],\n };\n }),\n ],\n );\n\n const commentedIssues = issueConversationResult.issues;\n if (issueConversationResult.failures.length > 0) {\n warn(MODULE, `${issueConversationResult.failures.length} issue conversation check(s) failed`);\n }\n\n const { repos: mergedCounts, monthlyCounts, monthlyOpenedCounts: openedFromMerged } = mergedResult;\n const {\n repos: closedCounts,\n monthlyCounts: monthlyClosedCounts,\n monthlyOpenedCounts: openedFromClosed,\n } = closedResult;\n\n return {\n prs,\n failures,\n mergedCounts,\n closedCounts,\n monthlyCounts,\n monthlyClosedCounts,\n openedFromMerged,\n openedFromClosed,\n recentlyClosedPRs,\n recentlyMergedPRs,\n commentedIssues,\n };\n}\n\n/**\n * Phase 2: Update repo scores in local state.\n * Applies stale repo reset, updates merged/closed counts, computes and stores\n * repo signals from open PR data, refreshes star counts, and syncs trusted projects.\n */\nasync function updateRepoScores(\n prMonitor: PRMonitor,\n prs: FetchedPR[],\n mergedCounts: Map<string, { count: number; lastMergedAt: string | null }>,\n closedCounts: Map<string, number>,\n): Promise<void> {\n const stateManager = getStateManager();\n\n // Reset stale repos first (so excluded/removed repos get zeroed).\n // Guard: if the API returned zero results but we have existing repos with merged PRs,\n // skip the reset to avoid wiping scores due to transient API failures.\n const existingReposWithMerges = Object.values(stateManager.getState().repoScores).filter((s) => s.mergedPRCount > 0);\n if (mergedCounts.size === 0 && existingReposWithMerges.length > 0) {\n warn(\n MODULE,\n `Skipping stale repo reset: API returned 0 merged PR results but state has ${existingReposWithMerges.length} repo(s) with merges. Possible API issue.`,\n );\n } else {\n for (const score of Object.values(stateManager.getState().repoScores)) {\n if (!mergedCounts.has(score.repo)) {\n stateManager.updateRepoScore(score.repo, { mergedPRCount: 0 });\n }\n }\n }\n\n // Update merged/closed counts with per-repo error isolation (matches signal/trust loops below)\n let mergedCountFailures = 0;\n for (const [repo, { count, lastMergedAt }] of mergedCounts) {\n try {\n stateManager.updateRepoScore(repo, { mergedPRCount: count, lastMergedAt: lastMergedAt || undefined });\n } catch (error) {\n mergedCountFailures++;\n warn(MODULE, `Failed to update merged count for ${repo}: ${errorMessage(error)}`);\n }\n }\n if (mergedCountFailures === mergedCounts.size && mergedCounts.size > 0) {\n warn(MODULE, `[ALL_MERGED_COUNT_UPDATES_FAILED] All ${mergedCounts.size} merged count update(s) failed.`);\n }\n\n // Populate closedWithoutMergeCount in repo scores.\n // Diagnostic: warn if API returned empty but we have known closed PRs (possible transient API failure).\n // Unlike merged counts above, there is no stale-reset loop for closed counts, so no skip is needed.\n const existingReposWithClosed = Object.values(stateManager.getState().repoScores).filter(\n (s) => (s.closedWithoutMergeCount || 0) > 0,\n );\n if (closedCounts.size === 0 && existingReposWithClosed.length > 0) {\n warn(\n MODULE,\n `API returned 0 closed PR results but state has ${existingReposWithClosed.length} repo(s) with closed PRs. Possible transient API issue.`,\n );\n }\n let closedCountFailures = 0;\n for (const [repo, count] of closedCounts) {\n try {\n stateManager.updateRepoScore(repo, { closedWithoutMergeCount: count });\n } catch (error) {\n closedCountFailures++;\n warn(MODULE, `Failed to update closed count for ${repo}: ${errorMessage(error)}`);\n }\n }\n if (closedCountFailures === closedCounts.size && closedCounts.size > 0) {\n warn(MODULE, `[ALL_CLOSED_COUNT_UPDATES_FAILED] All ${closedCounts.size} closed count update(s) failed.`);\n }\n\n // Update repo signals from observed open PR data (responsiveness, active maintainers).\n // Only repos with current open PRs get signal updates \u2014 repos with no open PRs\n // preserve their existing signals to avoid degrading scores when PRs are merged.\n // Per-repo try-catch: signal/trust syncing is secondary to the daily digest \u2014\n // a single corrupted repo score should not prevent updates to other repos.\n const repoSignals = computeRepoSignals(prs);\n let signalUpdateFailures = 0;\n for (const [repo, signals] of repoSignals) {\n try {\n stateManager.updateRepoScore(repo, { signals });\n } catch (error) {\n signalUpdateFailures++;\n warn(MODULE, `Failed to update signals for ${repo}: ${errorMessage(error)}`);\n }\n }\n if (signalUpdateFailures === repoSignals.size && repoSignals.size > 0) {\n warn(\n MODULE,\n `[ALL_SIGNAL_UPDATES_FAILED] All ${repoSignals.size} signal update(s) failed. This may indicate corrupted state.`,\n );\n }\n\n // Fetch star counts for all scored repos (used by dashboard minStars filter, #216)\n const allRepos = Object.keys(stateManager.getState().repoScores);\n let starCounts: Map<string, number>;\n try {\n starCounts = await prMonitor.fetchRepoStarCounts(allRepos);\n } catch (error) {\n warn(MODULE, `Failed to fetch repo star counts: ${errorMessage(error)}`);\n warn(\n MODULE,\n 'Repos without cached star data will be excluded from stats until star counts are fetched on the next successful run.',\n );\n starCounts = new Map();\n }\n let starUpdateFailures = 0;\n for (const [repo, stars] of starCounts) {\n try {\n stateManager.updateRepoScore(repo, { stargazersCount: stars });\n } catch (error) {\n starUpdateFailures++;\n warn(MODULE, `Failed to update star count for ${repo}: ${errorMessage(error)}`);\n }\n }\n if (starUpdateFailures === starCounts.size && starCounts.size > 0) {\n warn(MODULE, `[ALL_STAR_COUNT_UPDATES_FAILED] All ${starCounts.size} star count update(s) failed.`);\n }\n\n // Auto-sync trustedProjects from repos with merged PRs\n let trustSyncFailures = 0;\n for (const [repo] of mergedCounts) {\n try {\n stateManager.addTrustedProject(repo);\n } catch (error) {\n trustSyncFailures++;\n warn(MODULE, `Failed to sync trusted project ${repo}: ${errorMessage(error)}`);\n }\n }\n if (trustSyncFailures === mergedCounts.size && mergedCounts.size > 0) {\n warn(\n MODULE,\n `[ALL_TRUST_SYNCS_FAILED] All ${mergedCounts.size} trusted project sync(s) failed. This may indicate corrupted state.`,\n );\n }\n}\n\n/**\n * Phase 4: Partition PRs into active vs shelved buckets.\n * Auto-unshelves PRs where maintainers have engaged, generates the digest,\n * and persists state.\n */\nfunction partitionPRs(\n prMonitor: PRMonitor,\n prs: FetchedPR[],\n recentlyClosedPRs: ClosedPR[],\n recentlyMergedPRs: MergedPR[],\n): PartitionedPRs {\n const stateManager = getStateManager();\n\n // Apply dashboard/CLI status overrides before partitioning.\n // This ensures PRs reclassified in the dashboard (e.g., \"Need Attention\" \u2192 \"Waiting\")\n // are respected by the CLI pipeline.\n const overriddenPRs = applyStatusOverrides(prs, stateManager.getState());\n\n // Partition PRs into active vs shelved, auto-unshelving when maintainers engage\n const shelvedPRs: ShelvedPRRef[] = [];\n const autoUnshelvedPRs: ShelvedPRRef[] = [];\n const activePRs: FetchedPR[] = [];\n\n for (const pr of overriddenPRs) {\n if (stateManager.isPRShelved(pr.url)) {\n if (CRITICAL_STATUSES.has(pr.status)) {\n stateManager.unshelvePR(pr.url);\n autoUnshelvedPRs.push(toShelvedPRRef(pr));\n activePRs.push(pr);\n } else {\n shelvedPRs.push(toShelvedPRRef(pr));\n }\n } else if (pr.stalenessTier === 'dormant' && !CRITICAL_STATUSES.has(pr.status)) {\n // Dormant PRs are auto-shelved unless they need addressing\n // (e.g. maintainer commented on a stale PR \u2014 it should resurface)\n shelvedPRs.push(toShelvedPRRef(pr));\n } else {\n activePRs.push(pr);\n }\n }\n\n // Generate digest from override-applied PRs so status categories are correct.\n // Note: digest.openPRs contains ALL fetched PRs (including shelved).\n // We override summary fields below to reflect active-only counts.\n const digest = prMonitor.generateDigest(overriddenPRs, recentlyClosedPRs, recentlyMergedPRs);\n\n // Attach shelve info to digest\n digest.shelvedPRs = shelvedPRs;\n digest.autoUnshelvedPRs = autoUnshelvedPRs;\n digest.summary.totalActivePRs = activePRs.length;\n\n // Store digest in state so dashboard can render it\n stateManager.setLastDigest(digest);\n\n // Save state (updates lastRunAt, lastDigest, and any auto-unshelve changes)\n stateManager.save();\n\n return { activePRs, shelvedPRs, autoUnshelvedPRs, digest };\n}\n\n/**\n * Phase 5: Build the structured output for the daily command.\n * Assesses capacity, filters dismissed issues, computes actionable items,\n * and assembles the action menu.\n */\nfunction generateDigestOutput(\n digest: DailyDigest,\n activePRs: FetchedPR[],\n shelvedPRs: ShelvedPRRef[],\n commentedIssues: CommentedIssue[],\n failures: PRCheckFailure[],\n previousLastDigestAt?: string,\n): DailyCheckResult {\n const stateManager = getStateManager();\n\n // Assess capacity from active PRs only (shelved PRs excluded)\n const capacity = assessCapacity(activePRs, stateManager.getState().config.maxActivePRs, shelvedPRs.length);\n\n // Filter dismissed issues: suppress if dismissed after last response, resurface + auto-undismiss if new activity\n let hasAutoUndismissed = false;\n const filteredCommentedIssues = commentedIssues.filter((issue) => {\n const dismissedAt = stateManager.getIssueDismissedAt(issue.url);\n if (!dismissedAt) return true; // Not dismissed \u2014 include\n if (issue.status === 'new_response') {\n const responseTime = new Date(issue.lastResponseAt).getTime();\n const dismissTime = new Date(dismissedAt).getTime();\n if (isNaN(responseTime) || isNaN(dismissTime)) {\n // Invalid timestamp \u2014 fail open (include issue to be safe) without\n // permanently removing dismiss record (may be a transient data issue)\n warn(MODULE, `Invalid timestamp in dismiss check for ${issue.url}, including issue`);\n return true;\n }\n if (responseTime > dismissTime) {\n // New activity after dismiss \u2014 auto-undismiss and resurface\n warn(\n MODULE,\n `Auto-undismissing issue ${issue.url}: new response at ${issue.lastResponseAt} after dismiss at ${dismissedAt}`,\n );\n stateManager.undismissIssue(issue.url);\n hasAutoUndismissed = true;\n return true;\n }\n }\n // Still dismissed (last response is at or before dismiss timestamp)\n return false;\n });\n\n const issueResponses = filteredCommentedIssues.filter(\n (i): i is CommentedIssueWithResponse => i.status === 'new_response',\n );\n const summary = formatSummary(digest, capacity, issueResponses);\n\n // Persist auto-undismiss state changes for issues\n if (hasAutoUndismissed) {\n try {\n stateManager.save();\n } catch (error) {\n warn(MODULE, `Failed to persist auto-undismissed state: ${errorMessage(error)}`);\n }\n }\n const actionableIssues = collectActionableIssues(activePRs, previousLastDigestAt);\n digest.summary.totalNeedingAttention = actionableIssues.length;\n const briefSummary = formatBriefSummary(digest, actionableIssues.length, issueResponses.length);\n const actionMenu = computeActionMenu(actionableIssues, capacity, filteredCommentedIssues);\n const repoGroups = groupPRsByRepo(activePRs);\n\n return {\n digest,\n capacity,\n summary,\n briefSummary,\n actionableIssues,\n actionMenu,\n commentedIssues: filteredCommentedIssues,\n repoGroups,\n failures,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a full DailyCheckResult to the compact DailyOutput for JSON serialization (#287).\n * Deduplicates PR objects: category arrays become PR URL references,\n * full objects live only in digest.openPRs. Reduces JSON payload size ~60-70%.\n */\nfunction toDailyOutput(result: DailyCheckResult): DailyOutput {\n return {\n digest: deduplicateDigest(result.digest),\n capacity: result.capacity,\n summary: result.summary,\n briefSummary: result.briefSummary,\n actionableIssues: compactActionableIssues(result.actionableIssues),\n actionMenu: result.actionMenu,\n commentedIssues: result.commentedIssues,\n repoGroups: compactRepoGroups(result.repoGroups),\n failures: result.failures,\n };\n}\n\n/**\n * Core daily check logic, extracted for reuse by the startup command.\n * Fetches all open PRs, updates state, and returns structured output.\n *\n * Returns a deduplicated DailyOutput where category arrays contain PR URLs\n * instead of full objects (#287). Full PR objects are in digest.openPRs only.\n *\n * Orchestrates five named phases:\n * 1. fetchPRData \u2014 fetch open PRs, merged/closed counts, issues\n * 2. updateRepoScores \u2014 update signals, star counts, trust in state\n * 3. updateAnalytics \u2014 store monthly chart data\n * 4. partitionPRs \u2014 shelve/unshelve, generate digest\n * 5. generateDigestOutput \u2014 capacity, dismiss filter, action menu assembly\n */\nexport async function executeDailyCheck(token: string): Promise<DailyOutput> {\n const result = await executeDailyCheckInternal(token);\n return toDailyOutput(result);\n}\n\n/**\n * Internal daily check returning full (non-deduplicated) result.\n * Used by runDaily for text-mode output where full PR objects are needed.\n */\nasync function executeDailyCheckInternal(token: string): Promise<DailyCheckResult> {\n const prMonitor = new PRMonitor(token);\n\n // Phase 1: Fetch all PR data from GitHub\n const {\n prs,\n failures,\n mergedCounts,\n closedCounts,\n monthlyCounts,\n monthlyClosedCounts,\n openedFromMerged,\n openedFromClosed,\n recentlyClosedPRs,\n recentlyMergedPRs,\n commentedIssues,\n } = await fetchPRData(prMonitor, token);\n\n // Phase 2: Update repo scores (signals, star counts, trust sync)\n await updateRepoScores(prMonitor, prs, mergedCounts, closedCounts);\n\n // Phase 3: Persist monthly analytics\n updateMonthlyAnalytics(prs, monthlyCounts, monthlyClosedCounts, openedFromMerged, openedFromClosed);\n\n // Capture lastDigestAt BEFORE Phase 4 overwrites it with the current run's timestamp.\n // Used by collectActionableIssues to determine which PRs are \"new\" (created since last digest).\n const previousLastDigestAt = getStateManager().getState().lastDigestAt;\n\n // Phase 4: Partition PRs, generate and save digest\n const { activePRs, shelvedPRs, digest } = partitionPRs(prMonitor, prs, recentlyClosedPRs, recentlyMergedPRs);\n\n // Phase 5: Build structured output (capacity, dismiss filter, action menu)\n return generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, failures, previousLastDigestAt);\n}\n\n/**\n * Run the daily check and return deduplicated DailyOutput.\n * Errors propagate to the caller.\n */\nexport async function runDaily(): Promise<DailyOutput> {\n // Token is guaranteed by the preAction hook in cli.ts for non-LOCAL_ONLY_COMMANDS.\n const token = requireGitHubToken();\n return executeDailyCheck(token);\n}\n\n/**\n * Run the daily check and return the full (non-deduplicated) result.\n * Used by CLI text mode where printDigest() needs full PR objects.\n */\nexport async function runDailyForDisplay(): Promise<DailyCheckResult> {\n const token = requireGitHubToken();\n return executeDailyCheckInternal(token);\n}\n", "/**\n * Status command\n * Shows current status and stats\n */\n\nimport { getStateManager } from '../core/index.js';\nimport type { StatusOutput } from '../formatters/json.js';\n\ninterface StatusOptions {\n offline?: boolean;\n}\n\nexport type { StatusOutput };\n\nexport async function runStatus(options: StatusOptions): Promise<StatusOutput> {\n const stateManager = getStateManager();\n const stats = stateManager.getStats();\n const state = stateManager.getState();\n\n // Status always reads from local state (no API calls), so offline mode\n // simply adds metadata about cache freshness.\n const lastUpdated = state.lastDigestAt || state.lastRunAt;\n\n // Extract only the stats we want to output (exclude totalTracked)\n const { totalTracked: _totalTracked, ...outputStats } = stats as typeof stats & { totalTracked?: number };\n const output: StatusOutput = {\n stats: outputStats,\n lastRunAt: state.lastRunAt,\n };\n if (options.offline) {\n output.offline = true;\n output.lastUpdated = lastUpdated;\n }\n\n return output;\n}\n", "/**\n * Search command\n * Searches for new issues to work on\n */\n\nimport { IssueDiscovery, requireGitHubToken, getStateManager, DEFAULT_CONFIG } from '../core/index.js';\nimport { type SearchOutput } from '../formatters/json.js';\n\nexport { type SearchOutput } from '../formatters/json.js';\n\ninterface SearchOptions {\n maxResults: number;\n}\n\nexport async function runSearch(options: SearchOptions): Promise<SearchOutput> {\n const token = requireGitHubToken();\n\n const discovery = new IssueDiscovery(token);\n\n const candidates = await discovery.searchIssues({ maxResults: options.maxResults });\n\n const stateManager = getStateManager();\n const { config } = stateManager.getState();\n const excludedRepos = config.excludeRepos || [];\n const aiPolicyBlocklist = config.aiPolicyBlocklist ?? DEFAULT_CONFIG.aiPolicyBlocklist ?? [];\n const searchOutput: SearchOutput = {\n candidates: candidates.map((c) => {\n const repoScoreRecord = stateManager.getRepoScore(c.issue.repo);\n return {\n issue: {\n repo: c.issue.repo,\n number: c.issue.number,\n title: c.issue.title,\n url: c.issue.url,\n labels: c.issue.labels,\n },\n recommendation: c.recommendation,\n reasonsToApprove: c.reasonsToApprove,\n reasonsToSkip: c.reasonsToSkip,\n searchPriority: c.searchPriority,\n viabilityScore: c.viabilityScore,\n repoScore: repoScoreRecord\n ? {\n score: repoScoreRecord.score,\n mergedPRCount: repoScoreRecord.mergedPRCount,\n closedWithoutMergeCount: repoScoreRecord.closedWithoutMergeCount,\n isResponsive: repoScoreRecord.signals?.isResponsive ?? false,\n lastMergedAt: repoScoreRecord.lastMergedAt,\n }\n : undefined,\n };\n }),\n excludedRepos,\n aiPolicyBlocklist,\n };\n if (discovery.rateLimitWarning) {\n searchOutput.rateLimitWarning = discovery.rateLimitWarning;\n }\n return searchOutput;\n}\n", "/**\n * Shared validation patterns and helpers for CLI commands.\n */\n\nimport { ValidationError } from '../core/errors.js';\n\n/** Matches GitHub PR URLs: https://github.com/owner/repo/pull/123 */\nexport const PR_URL_PATTERN = /^https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/pull\\/\\d+$/;\n\n/** Matches GitHub issue URLs: https://github.com/owner/repo/issues/123 */\nexport const ISSUE_URL_PATTERN = /^https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/issues\\/\\d+$/;\n\n/** Matches GitHub issue or PR URLs: /issues/123 or /pull/123 */\nexport const ISSUE_OR_PR_URL_PATTERN = /^https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/(issues|pull)\\/\\d+$/;\n\n/** Maximum allowed URL length */\nconst MAX_URL_LENGTH = 2048;\n/** Maximum allowed PR/issue number */\nconst MAX_PR_NUMBER = 999999;\n/** Maximum allowed message string length */\nconst MAX_MESSAGE_LENGTH = 1000;\n/** Pattern for valid GitHub repository identifiers */\nconst REPO_PATTERN = /^[a-zA-Z0-9._-]+\\/[a-zA-Z0-9._-]+$/;\n\n/**\n * Validate a GitHub URL against a pattern. Throws if invalid.\n */\nexport function validateGitHubUrl(url: string, pattern: RegExp, entityType: 'PR' | 'issue' | 'issue or PR'): void {\n if (pattern.test(url)) return;\n\n const examples: Record<string, string> = {\n PR: 'https://github.com/owner/repo/pull/123',\n issue: 'https://github.com/owner/repo/issues/123',\n 'issue or PR': 'https://github.com/owner/repo/issues/123 or https://github.com/owner/repo/pull/123',\n };\n throw new ValidationError(`Invalid ${entityType} URL: ${url}. Expected format: ${examples[entityType]}`);\n}\n\n/**\n * Validate that a URL does not exceed the maximum allowed length.\n * Returns the URL if valid, throws if too long.\n */\nexport function validateUrl(url: string): string {\n if (url.length > MAX_URL_LENGTH) {\n throw new ValidationError(`URL exceeds maximum length of ${MAX_URL_LENGTH} characters`);\n }\n return url;\n}\n\n/**\n * Validate that a PR/issue number is a positive integer within bounds.\n * Returns the number if valid, throws if invalid.\n */\nexport function validatePRNumber(num: number): number {\n if (!Number.isInteger(num) || num < 1 || num > MAX_PR_NUMBER) {\n throw new ValidationError(`PR number must be a positive integer up to ${MAX_PR_NUMBER}`);\n }\n return num;\n}\n\n/**\n * Validate that a message string does not exceed the maximum allowed length.\n * Returns the message if valid, throws if too long.\n */\nexport function validateMessage(message: string): string {\n if (message.length > MAX_MESSAGE_LENGTH) {\n throw new ValidationError(`Message exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`);\n }\n return message;\n}\n\n/**\n * Validate that a repository identifier matches the \"owner/repo\" format.\n * Returns the identifier if valid, throws if invalid.\n */\nexport function validateRepoIdentifier(repo: string): string {\n if (!REPO_PATTERN.test(repo)) {\n throw new ValidationError(`Invalid repository format: \"${repo}\". Expected \"owner/repo\".`);\n }\n return repo;\n}\n\n/** Maximum allowed GitHub username length */\nconst MAX_USERNAME_LENGTH = 39;\n/** Pattern for valid GitHub username characters (alphanumeric and hyphens) */\nconst USERNAME_CHARS_PATTERN = /^[a-zA-Z0-9-]+$/;\n/** Pattern for consecutive hyphens */\nconst CONSECUTIVE_HYPHENS_PATTERN = /--/;\n\n/**\n * Validate a GitHub username against GitHub's username rules.\n * Throws a ValidationError if the username is invalid.\n *\n * Rules:\n * - Must not be empty\n * - Maximum 39 characters\n * - Only alphanumeric characters and hyphens\n * - Cannot start or end with a hyphen\n * - Cannot contain consecutive hyphens\n */\nexport function validateGitHubUsername(username: string): string {\n if (!username || username.trim().length === 0) {\n throw new ValidationError('GitHub username cannot be empty.');\n }\n\n const trimmed = username.trim();\n\n if (trimmed.length > MAX_USERNAME_LENGTH) {\n throw new ValidationError(\n `GitHub username must be at most ${MAX_USERNAME_LENGTH} characters (got ${trimmed.length}).`,\n );\n }\n\n if (!USERNAME_CHARS_PATTERN.test(trimmed)) {\n throw new ValidationError('GitHub username can only contain alphanumeric characters and hyphens.');\n }\n\n if (trimmed.startsWith('-')) {\n throw new ValidationError('GitHub username cannot start with a hyphen.');\n }\n\n if (trimmed.endsWith('-')) {\n throw new ValidationError('GitHub username cannot end with a hyphen.');\n }\n\n if (CONSECUTIVE_HYPHENS_PATTERN.test(trimmed)) {\n throw new ValidationError('GitHub username cannot contain consecutive hyphens.');\n }\n\n return trimmed;\n}\n", "/**\n * Vet command\n * Vets a specific issue before working on it\n */\n\nimport { IssueDiscovery, requireGitHubToken } from '../core/index.js';\nimport { type VetOutput } from '../formatters/json.js';\nimport { ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';\n\nexport { type VetOutput } from '../formatters/json.js';\n\ninterface VetOptions {\n issueUrl: string;\n}\n\nexport async function runVet(options: VetOptions): Promise<VetOutput> {\n validateUrl(options.issueUrl);\n validateGitHubUrl(options.issueUrl, ISSUE_URL_PATTERN, 'issue');\n\n const token = requireGitHubToken();\n\n const discovery = new IssueDiscovery(token);\n\n const candidate = await discovery.vetIssue(options.issueUrl);\n\n return {\n issue: {\n repo: candidate.issue.repo,\n number: candidate.issue.number,\n title: candidate.issue.title,\n url: candidate.issue.url,\n labels: candidate.issue.labels,\n },\n recommendation: candidate.recommendation,\n reasonsToApprove: candidate.reasonsToApprove,\n reasonsToSkip: candidate.reasonsToSkip,\n projectHealth: candidate.projectHealth,\n vettingResult: candidate.vettingResult,\n };\n}\n", "/**\n * Track/Untrack commands\n * In v2, PRs are fetched fresh from GitHub on each `daily` run.\n * These commands are preserved for backward compatibility.\n */\n\nimport { getOctokit, requireGitHubToken } from '../core/index.js';\nimport type { TrackOutput } from '../formatters/json.js';\nimport { validateUrl, PR_URL_PATTERN, validateGitHubUrl } from './validation.js';\nimport { parseGitHubUrl } from '../core/utils.js';\n\nexport interface UntrackOutput {\n removed: boolean;\n url: string;\n message: string;\n}\n\nexport async function runTrack(options: { prUrl: string }): Promise<TrackOutput> {\n validateUrl(options.prUrl);\n validateGitHubUrl(options.prUrl, PR_URL_PATTERN, 'PR');\n\n const token = requireGitHubToken();\n const octokit = getOctokit(token);\n\n const parsed = parseGitHubUrl(options.prUrl);\n if (!parsed || parsed.type !== 'pull') {\n throw new Error(`Invalid PR URL: ${options.prUrl}`);\n }\n\n const { owner, repo, number } = parsed;\n\n const { data: ghPR } = await octokit.pulls.get({ owner, repo, pull_number: number });\n\n return {\n pr: {\n repo: `${owner}/${repo}`,\n number,\n title: ghPR.title,\n url: options.prUrl,\n },\n };\n}\n\nexport async function runUntrack(options: { prUrl: string }): Promise<UntrackOutput> {\n validateUrl(options.prUrl);\n validateGitHubUrl(options.prUrl, PR_URL_PATTERN, 'PR');\n\n return {\n removed: false,\n url: options.prUrl,\n message: 'In v2, PRs are fetched fresh on each daily run \u2014 there is no local tracking list to remove from.',\n };\n}\n", "/**\n * Read command\n * In v2, PR read/unread state is not tracked locally.\n * This command is a no-op preserved for backward compatibility.\n */\n\nimport { validateUrl } from './validation.js';\n\nexport type ReadOutput =\n | { markedAsRead: number; all: true; message: string }\n | { marked: boolean; url: string | undefined; message: string };\n\nexport async function runRead(options: { prUrl?: string; all?: boolean }): Promise<ReadOutput> {\n if (!options.all && !options.prUrl) {\n throw new Error('PR URL or --all flag required');\n }\n\n if (options.prUrl) {\n validateUrl(options.prUrl);\n }\n\n // In v2, unread state is not tracked locally \u2014 PRs are fetched fresh each run.\n if (options.all) {\n return { markedAsRead: 0, all: true, message: 'In v2, PR read state is not tracked locally.' };\n }\n return { marked: false, url: options.prUrl, message: 'In v2, PR read state is not tracked locally.' };\n}\n", "/**\n * Comments, Post, and Claim commands\n * Handles GitHub comment interactions\n */\n\nimport { getStateManager, getOctokit, parseGitHubUrl, requireGitHubToken } from '../core/index.js';\nimport { paginateAll } from '../core/pagination.js';\nimport { type CommentsOutput, type PostOutput, type ClaimOutput } from '../formatters/json.js';\nimport {\n validateUrl,\n validateMessage,\n validateGitHubUrl,\n PR_URL_PATTERN,\n ISSUE_OR_PR_URL_PATTERN,\n ISSUE_URL_PATTERN,\n} from './validation.js';\n\nexport { type CommentsOutput, type PostOutput, type ClaimOutput } from '../formatters/json.js';\n\ninterface CommentsOptions {\n prUrl: string;\n showBots?: boolean;\n}\n\ninterface PostOptions {\n url: string;\n message: string;\n}\n\ninterface ClaimOptions {\n issueUrl: string;\n message?: string;\n}\n\nexport async function runComments(options: CommentsOptions): Promise<CommentsOutput> {\n validateUrl(options.prUrl);\n validateGitHubUrl(options.prUrl, PR_URL_PATTERN, 'PR');\n\n const token = requireGitHubToken();\n\n const stateManager = getStateManager();\n const octokit = getOctokit(token);\n\n // Parse PR URL\n const parsed = parseGitHubUrl(options.prUrl);\n if (!parsed || parsed.type !== 'pull') {\n throw new Error('Invalid PR URL format');\n }\n\n const { owner, repo, number: pull_number } = parsed;\n\n // Get PR details\n const { data: pr } = await octokit.pulls.get({ owner, repo, pull_number });\n\n // Fetch review comments, issue comments, and reviews in parallel\n const [reviewComments, issueComments, reviews] = await Promise.all([\n paginateAll((page) =>\n octokit.pulls.listReviewComments({\n owner,\n repo,\n pull_number,\n per_page: 100,\n page,\n }),\n ),\n paginateAll((page) =>\n octokit.issues.listComments({\n owner,\n repo,\n issue_number: pull_number,\n per_page: 100,\n page,\n }),\n ),\n paginateAll((page) =>\n octokit.pulls.listReviews({\n owner,\n repo,\n pull_number,\n per_page: 100,\n page,\n }),\n ),\n ]);\n\n // Filter out own comments, optionally show bots\n const username = stateManager.getState().config.githubUsername;\n\n const filterComment = (c: { user?: { login?: string; type?: string } | null }) => {\n if (!c.user) return false;\n if (c.user.login === username) return false;\n if (c.user.type === 'Bot' && !options.showBots) return false;\n return true;\n };\n\n const relevantReviewComments = reviewComments\n .filter(filterComment)\n .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());\n const relevantIssueComments = issueComments\n .filter(filterComment)\n .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());\n const relevantReviews = reviews\n .filter((r) => filterComment(r) && r.body && r.body.trim())\n .sort((a, b) => new Date(b.submitted_at || 0).getTime() - new Date(a.submitted_at || 0).getTime());\n\n return {\n pr: {\n title: pr.title,\n state: pr.state,\n mergeable: pr.mergeable,\n head: pr.head.ref,\n base: pr.base.ref,\n url: pr.html_url,\n },\n reviews: relevantReviews.map((r) => ({\n user: r.user?.login,\n state: r.state,\n body: r.body ?? null,\n submittedAt: r.submitted_at ?? null,\n })),\n reviewComments: relevantReviewComments.map((c) => ({\n user: c.user?.login,\n body: c.body,\n path: c.path,\n createdAt: c.created_at,\n })),\n issueComments: relevantIssueComments.map((c) => ({\n user: c.user?.login,\n body: c.body,\n createdAt: c.created_at,\n })),\n summary: {\n reviewCount: relevantReviews.length,\n inlineCommentCount: relevantReviewComments.length,\n discussionCommentCount: relevantIssueComments.length,\n },\n };\n}\n\nexport async function runPost(options: PostOptions): Promise<PostOutput> {\n validateUrl(options.url);\n validateGitHubUrl(options.url, ISSUE_OR_PR_URL_PATTERN, 'issue or PR');\n\n if (!options.message.trim()) {\n throw new Error('No message provided');\n }\n\n validateMessage(options.message);\n\n const token = requireGitHubToken();\n\n // Parse URL\n const parsed = parseGitHubUrl(options.url);\n if (!parsed) {\n throw new Error('Invalid GitHub URL format');\n }\n\n const { owner, repo, number } = parsed;\n const octokit = getOctokit(token);\n\n const { data: comment } = await octokit.issues.createComment({\n owner,\n repo,\n issue_number: number,\n body: options.message,\n });\n\n return {\n commentUrl: comment.html_url,\n url: options.url,\n };\n}\n\nexport async function runClaim(options: ClaimOptions): Promise<ClaimOutput> {\n validateUrl(options.issueUrl);\n validateGitHubUrl(options.issueUrl, ISSUE_URL_PATTERN, 'issue');\n\n const token = requireGitHubToken();\n\n // Default claim message or custom\n const message = options.message || \"Hi! I'd like to work on this issue. Could you assign it to me?\";\n\n validateMessage(message);\n\n // Parse URL\n const parsed = parseGitHubUrl(options.issueUrl);\n if (!parsed || parsed.type !== 'issues') {\n throw new Error('Invalid issue URL format (must be an issue, not a PR)');\n }\n\n const { owner, repo, number } = parsed;\n\n const octokit = getOctokit(token);\n\n const { data: comment } = await octokit.issues.createComment({\n owner,\n repo,\n issue_number: number,\n body: message,\n });\n\n // Add to tracked issues \u2014 non-fatal if state save fails (comment already posted)\n try {\n const stateManager = getStateManager();\n stateManager.addIssue({\n id: number,\n url: options.issueUrl,\n repo: `${owner}/${repo}`,\n number,\n title: '(claimed)',\n status: 'claimed',\n labels: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n vetted: false,\n });\n stateManager.save();\n } catch (error) {\n console.error(\n `Warning: Comment posted on ${options.issueUrl} but failed to save to local state: ${error instanceof Error ? error.message : error}`,\n );\n }\n\n return {\n commentUrl: comment.html_url,\n issueUrl: options.issueUrl,\n };\n}\n", "/**\n * Config command\n * Shows or updates configuration\n */\n\nimport { getStateManager } from '../core/index.js';\nimport type { ConfigOutput } from '../formatters/json.js';\nimport { validateGitHubUsername } from './validation.js';\n\ninterface ConfigOptions {\n key?: string;\n value?: string;\n}\n\nexport interface ConfigSetOutput {\n success: true;\n key: string;\n value: string;\n}\n\nexport type ConfigCommandOutput = ConfigOutput | ConfigSetOutput;\n\nexport async function runConfig(options: ConfigOptions): Promise<ConfigCommandOutput> {\n const stateManager = getStateManager();\n const currentConfig = stateManager.getState().config;\n\n if (!options.key) {\n // Show current config\n return { config: currentConfig };\n }\n\n if (!options.value) {\n throw new Error('Value required');\n }\n const value = options.value;\n\n // Handle specific config keys\n switch (options.key) {\n case 'username':\n stateManager.updateConfig({ githubUsername: validateGitHubUsername(value) });\n break;\n case 'add-language':\n if (!currentConfig.languages.includes(value)) {\n stateManager.updateConfig({ languages: [...currentConfig.languages, value] });\n }\n break;\n case 'add-label':\n if (!currentConfig.labels.includes(value)) {\n stateManager.updateConfig({ labels: [...currentConfig.labels, value] });\n }\n break;\n case 'exclude-repo': {\n const parts = value.split('/');\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(\n `Invalid repo format \"${value}\". Use \"owner/repo\" format. To exclude an entire org, use: config exclude-org ${value}`,\n );\n }\n const valueLower = value.toLowerCase();\n if (!currentConfig.excludeRepos.some((r) => r.toLowerCase() === valueLower)) {\n stateManager.updateConfig({ excludeRepos: [...currentConfig.excludeRepos, value] });\n stateManager.cleanupExcludedData([value], []);\n }\n break;\n }\n case 'exclude-org': {\n if (value.includes('/')) {\n throw new Error(\n `Invalid org name \"${value}\". Use just the org name (e.g., \"facebook\"), not \"owner/repo\" format. To exclude a specific repo, use: config exclude-repo ${value}`,\n );\n }\n const currentOrgs = currentConfig.excludeOrgs ?? [];\n if (!currentOrgs.some((o) => o.toLowerCase() === value.toLowerCase())) {\n stateManager.updateConfig({ excludeOrgs: [...currentOrgs, value] });\n stateManager.cleanupExcludedData([], [value]);\n }\n break;\n }\n default:\n throw new Error(`Unknown config key: ${options.key}`);\n }\n\n stateManager.save();\n\n return { success: true, key: options.key, value };\n}\n", "/**\n * Init command\n * Initialize with GitHub username. In v2, PRs are fetched fresh on each daily run.\n */\n\nimport { getStateManager } from '../core/index.js';\nimport { validateGitHubUsername } from './validation.js';\n\nexport interface InitOutput {\n username: string;\n message: string;\n}\n\nexport async function runInit(options: { username: string }): Promise<InitOutput> {\n validateGitHubUsername(options.username);\n const stateManager = getStateManager();\n\n // Set username in config\n stateManager.updateConfig({ githubUsername: options.username });\n stateManager.save();\n\n return {\n username: options.username,\n message: 'Username saved. Run `daily` to fetch your open PRs from GitHub.',\n };\n}\n", "/**\n * Setup command\n * Interactive setup / configuration\n */\n\nimport { getStateManager, DEFAULT_CONFIG } from '../core/index.js';\nimport { ValidationError } from '../core/errors.js';\nimport { validateGitHubUsername } from './validation.js';\nimport { PROJECT_CATEGORIES, type ProjectCategory } from '../core/types.js';\n\n/** Parse and validate a positive integer setting value. */\nfunction parsePositiveInt(value: string, settingName: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 1 || !Number.isInteger(parsed)) {\n throw new ValidationError(`Invalid value for ${settingName}: \"${value}\". Must be a positive integer.`);\n }\n return parsed;\n}\n\ninterface SetupOptions {\n reset?: boolean;\n set?: string[];\n}\n\nexport interface SetupSetOutput {\n success: true;\n settings: Record<string, string>;\n warnings?: string[];\n}\n\nexport interface SetupCompleteOutput {\n setupComplete: true;\n config: {\n githubUsername: string;\n maxActivePRs: number;\n dormantThresholdDays: number;\n approachingDormantDays: number;\n languages: string[];\n labels: string[];\n projectCategories: ProjectCategory[];\n preferredOrgs: string[];\n };\n}\n\nexport interface SetupPrompt {\n setting: string;\n prompt: string;\n current: string | number | string[] | null;\n required?: boolean;\n default?: string | number | string[];\n type?: string;\n}\n\nexport interface SetupRequiredOutput {\n setupRequired: true;\n prompts: SetupPrompt[];\n}\n\nexport type SetupOutput = SetupSetOutput | SetupCompleteOutput | SetupRequiredOutput;\n\nexport interface CheckSetupOutput {\n setupComplete: boolean;\n username: string;\n}\n\nexport async function runSetup(options: SetupOptions): Promise<SetupOutput> {\n const stateManager = getStateManager();\n const config = stateManager.getState().config;\n\n // Handle --set mode: apply settings directly\n if (options.set && options.set.length > 0) {\n const results: Record<string, string> = {};\n const warnings: string[] = [];\n\n for (const setting of options.set) {\n const [key, ...valueParts] = setting.split('=');\n const value = valueParts.join('=');\n\n switch (key) {\n case 'username':\n validateGitHubUsername(value);\n stateManager.updateConfig({ githubUsername: value });\n results[key] = value;\n break;\n case 'maxActivePRs': {\n const maxPRs = parsePositiveInt(value, 'maxActivePRs');\n stateManager.updateConfig({ maxActivePRs: maxPRs });\n results[key] = String(maxPRs);\n break;\n }\n case 'dormantDays': {\n const dormant = parsePositiveInt(value, 'dormantDays');\n stateManager.updateConfig({ dormantThresholdDays: dormant });\n results[key] = String(dormant);\n break;\n }\n case 'approachingDays': {\n const approaching = parsePositiveInt(value, 'approachingDays');\n stateManager.updateConfig({ approachingDormantDays: approaching });\n results[key] = String(approaching);\n break;\n }\n case 'languages':\n stateManager.updateConfig({ languages: value.split(',').map((l) => l.trim()) });\n results[key] = value;\n break;\n case 'labels':\n stateManager.updateConfig({ labels: value.split(',').map((l) => l.trim()) });\n results[key] = value;\n break;\n case 'showHealthCheck':\n stateManager.updateConfig({ showHealthCheck: value !== 'false' });\n results[key] = value !== 'false' ? 'true' : 'false';\n break;\n case 'squashByDefault':\n if (value === 'ask') {\n stateManager.updateConfig({ squashByDefault: 'ask' });\n results[key] = 'ask';\n } else {\n stateManager.updateConfig({ squashByDefault: value !== 'false' });\n results[key] = value !== 'false' ? 'true' : 'false';\n }\n break;\n case 'minStars': {\n const stars = Number(value);\n if (!Number.isFinite(stars) || !Number.isInteger(stars) || stars < 0) {\n throw new ValidationError(`Invalid value for minStars: \"${value}\". Must be a non-negative integer.`);\n }\n stateManager.updateConfig({ minStars: stars });\n results[key] = String(stars);\n break;\n }\n case 'includeDocIssues':\n stateManager.updateConfig({ includeDocIssues: value === 'true' });\n results[key] = value === 'true' ? 'true' : 'false';\n break;\n case 'aiPolicyBlocklist': {\n const entries = value\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n const valid: string[] = [];\n const invalid: string[] = [];\n for (const entry of entries) {\n const normalized = entry.replace(/\\s+/g, '');\n if (/^[a-zA-Z0-9._-]+\\/[a-zA-Z0-9._-]+$/.test(normalized)) {\n valid.push(normalized);\n } else {\n invalid.push(entry);\n }\n }\n if (invalid.length > 0) {\n warnings.push(`Warning: Skipping invalid entries (expected \"owner/repo\" format): ${invalid.join(', ')}`);\n results['aiPolicyBlocklist_invalidEntries'] = invalid.join(', ');\n }\n if (valid.length === 0 && entries.length > 0) {\n warnings.push('Warning: All entries were invalid. Blocklist not updated.');\n results[key] = '(all entries invalid)';\n break;\n }\n stateManager.updateConfig({ aiPolicyBlocklist: valid });\n results[key] = valid.length > 0 ? valid.join(', ') : '(empty)';\n break;\n }\n case 'projectCategories': {\n const categories = value\n .split(',')\n .map((c) => c.trim())\n .filter(Boolean);\n const validCategories: ProjectCategory[] = [];\n const invalidCategories: string[] = [];\n for (const cat of categories) {\n if ((PROJECT_CATEGORIES as readonly string[]).includes(cat)) {\n validCategories.push(cat as ProjectCategory);\n } else {\n invalidCategories.push(cat);\n }\n }\n if (invalidCategories.length > 0) {\n warnings.push(\n `Unknown project categories: ${invalidCategories.join(', ')}. Valid: ${PROJECT_CATEGORIES.join(', ')}`,\n );\n }\n const dedupedCategories = [...new Set(validCategories)];\n stateManager.updateConfig({ projectCategories: dedupedCategories });\n results[key] = dedupedCategories.length > 0 ? dedupedCategories.join(', ') : '(empty)';\n break;\n }\n case 'preferredOrgs': {\n const orgs = value\n .split(',')\n .map((o) => o.trim())\n .filter(Boolean);\n const validOrgs: string[] = [];\n for (const org of orgs) {\n if (org.includes('/')) {\n warnings.push(\n `\"${org}\" looks like a repo path. Use org name only (e.g., \"vercel\" not \"vercel/next.js\").`,\n );\n } else if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(org)) {\n warnings.push(`\"${org}\" is not a valid GitHub organization name. Skipping.`);\n } else {\n validOrgs.push(org.toLowerCase());\n }\n }\n const dedupedOrgs = [...new Set(validOrgs)];\n stateManager.updateConfig({ preferredOrgs: dedupedOrgs });\n results[key] = dedupedOrgs.length > 0 ? dedupedOrgs.join(', ') : '(empty)';\n break;\n }\n case 'complete':\n if (value === 'true') {\n stateManager.markSetupComplete();\n results[key] = 'true';\n }\n break;\n default:\n warnings.push(`Unknown setting: ${key}`);\n }\n }\n\n stateManager.save();\n\n return { success: true, settings: results, warnings: warnings.length > 0 ? warnings : undefined };\n }\n\n // Show setup status\n if (config.setupComplete && !options.reset) {\n return {\n setupComplete: true,\n config: {\n githubUsername: config.githubUsername,\n maxActivePRs: config.maxActivePRs,\n dormantThresholdDays: config.dormantThresholdDays,\n approachingDormantDays: config.approachingDormantDays,\n languages: config.languages,\n labels: config.labels,\n projectCategories: config.projectCategories ?? [],\n preferredOrgs: config.preferredOrgs ?? [],\n },\n };\n }\n\n // Output setup prompts\n return {\n setupRequired: true,\n prompts: [\n {\n setting: 'username',\n prompt: 'What is your GitHub username?',\n current: config.githubUsername || null,\n required: true,\n type: 'string',\n },\n {\n setting: 'maxActivePRs',\n prompt: 'How many PRs do you want to work on at once?',\n current: config.maxActivePRs,\n default: 10,\n type: 'number',\n },\n {\n setting: 'dormantDays',\n prompt: 'After how many days of inactivity should a PR be considered dormant?',\n current: config.dormantThresholdDays,\n default: 30,\n type: 'number',\n },\n {\n setting: 'approachingDays',\n prompt: 'At how many days should we warn about approaching dormancy?',\n current: config.approachingDormantDays,\n default: 25,\n type: 'number',\n },\n {\n setting: 'languages',\n prompt: 'What programming languages do you want to contribute to?',\n current: config.languages,\n default: ['typescript', 'javascript'],\n type: 'list',\n },\n {\n setting: 'labels',\n prompt: 'What issue labels should we search for?',\n current: config.labels,\n default: ['good first issue', 'help wanted'],\n type: 'list',\n },\n {\n setting: 'aiPolicyBlocklist',\n prompt: 'Repos with anti-AI contribution policies to block (owner/repo, comma-separated)?',\n current: config.aiPolicyBlocklist ?? DEFAULT_CONFIG.aiPolicyBlocklist ?? null,\n default: ['matplotlib/matplotlib'],\n type: 'list',\n },\n {\n setting: 'projectCategories',\n prompt:\n 'What types of projects interest you? (nonprofit, devtools, infrastructure, web-frameworks, data-ml, education)',\n current: config.projectCategories ?? [],\n default: [],\n type: 'list',\n },\n {\n setting: 'preferredOrgs',\n prompt: 'Any GitHub organizations to prioritize? (org names, comma-separated)',\n current: config.preferredOrgs ?? [],\n default: [],\n type: 'list',\n },\n ],\n };\n}\n\nexport async function runCheckSetup(): Promise<CheckSetupOutput> {\n const stateManager = getStateManager();\n\n return {\n setupComplete: stateManager.isSetupComplete(),\n username: stateManager.getState().config.githubUsername,\n };\n}\n", "/**\n * Dashboard server process management.\n * PID file operations, health probes, and running server detection.\n */\n\nimport * as http from 'http';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getDataDir } from '../core/index.js';\nimport { warn } from '../core/logger.js';\n\nconst MODULE = 'dashboard-server';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface DashboardServerInfo {\n pid: number;\n port: number;\n startedAt: string;\n version?: string;\n}\n\n// \u2500\u2500 PID File Management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function getDashboardPidPath(): string {\n return path.join(getDataDir(), 'dashboard-server.pid');\n}\n\nexport function writeDashboardServerInfo(info: DashboardServerInfo): void {\n fs.writeFileSync(getDashboardPidPath(), JSON.stringify(info), { mode: 0o600 });\n}\n\nexport function readDashboardServerInfo(): DashboardServerInfo | null {\n try {\n const content = fs.readFileSync(getDashboardPidPath(), 'utf-8');\n const parsed = JSON.parse(content);\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof parsed.pid !== 'number' ||\n !Number.isInteger(parsed.pid) ||\n parsed.pid <= 0 ||\n typeof parsed.port !== 'number' ||\n typeof parsed.startedAt !== 'string'\n ) {\n warn(MODULE, 'PID file has invalid structure, ignoring');\n return null;\n }\n return parsed as DashboardServerInfo;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT') {\n warn(MODULE, `Failed to read PID file: ${(err as Error).message}`);\n }\n return null;\n }\n}\n\nexport function removeDashboardServerInfo(): void {\n try {\n fs.unlinkSync(getDashboardPidPath());\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT') {\n warn(MODULE, `Failed to remove PID file: ${(err as Error).message}`);\n }\n }\n}\n\n// \u2500\u2500 Health Probe \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function isDashboardServerRunning(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const req = http.get(`http://127.0.0.1:${port}/api/data`, { timeout: 2000 }, (res) => {\n // Consume response data to free up memory\n res.resume();\n resolve(res.statusCode === 200);\n });\n req.on('error', () => resolve(false));\n req.on('timeout', () => {\n req.destroy();\n resolve(false);\n });\n });\n}\n\nexport async function findRunningDashboardServer(): Promise<{ port: number; url: string } | null> {\n const info = readDashboardServerInfo();\n if (!info) return null;\n\n // Check if process is alive (signal 0 = existence check only)\n try {\n process.kill(info.pid, 0);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ESRCH' && code !== 'EPERM') {\n warn(MODULE, `Unexpected error checking PID ${info.pid}: ${(err as Error).message}`);\n }\n // ESRCH = no process at that PID; EPERM = PID recycled to another user's process\n // Either way, our dashboard server is no longer running \u2014 clean up stale PID file\n removeDashboardServerInfo();\n return null;\n }\n\n // Process exists \u2014 verify it's actually our server via HTTP probe\n if (await isDashboardServerRunning(info.port)) {\n return { port: info.port, url: `http://oss.localhost:${info.port}` };\n }\n\n // Process exists but not responding on expected port \u2014 stale\n removeDashboardServerInfo();\n return null;\n}\n", "/**\n * Dashboard server lifecycle management.\n * Handles launching the interactive SPA dashboard as a background process\n * and detecting whether a server is already running.\n */\n\nimport { spawn } from 'child_process';\nimport {\n findRunningDashboardServer,\n isDashboardServerRunning,\n readDashboardServerInfo,\n removeDashboardServerInfo,\n} from './dashboard-process.js';\nimport { resolveAssetsDir } from './dashboard.js';\nimport { getCLIVersion } from '../core/index.js';\n\nconst DEFAULT_PORT = 3000;\nconst POLL_INTERVAL_MS = 200;\nconst MAX_POLL_ATTEMPTS = 25; // 5 seconds total\n\nexport interface LaunchResult {\n url: string;\n port: number;\n alreadyRunning: boolean;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Launch the interactive dashboard SPA server as a detached background process.\n *\n * Returns the server URL if launched successfully, or null if the SPA assets\n * are not available (dashboard is skipped).\n *\n * If a server is already running (detected via PID file + health probe),\n * returns its URL without launching a new one.\n */\nexport async function launchDashboardServer(options?: { port?: number }): Promise<LaunchResult | null> {\n // 1. Check if SPA assets exist\n const assetsDir = resolveAssetsDir();\n if (!assetsDir) {\n return null;\n }\n\n // 2. Check if a server is already running\n const existing = await findRunningDashboardServer();\n if (existing) {\n // If the running server is from a different CLI version, kill it and relaunch\n // so the dashboard uses the current version's code (#548)\n const info = readDashboardServerInfo();\n const currentVersion = getCLIVersion();\n if (!info) {\n // PID file disappeared between health check and now (race condition).\n // Fall through to launch a new server.\n } else if (info.version && currentVersion !== '0.0.0' && info.version !== currentVersion) {\n console.error(\n `[STARTUP] Dashboard server version mismatch (running: ${info.version}, current: ${currentVersion}). Restarting...`,\n );\n let killed = false;\n try {\n process.kill(info.pid, 'SIGTERM');\n killed = true;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ESRCH') {\n killed = true; // Already exited\n } else {\n console.error(`[STARTUP] Could not kill outdated dashboard (PID ${info.pid}): ${(err as Error).message}`);\n }\n }\n if (killed) {\n removeDashboardServerInfo();\n } else {\n // Could not kill old server (e.g. EPERM); return it rather than\n // attempting a doomed spawn on the same port.\n return { url: existing.url, port: existing.port, alreadyRunning: true };\n }\n // Fall through to launch a new server\n } else {\n return { url: existing.url, port: existing.port, alreadyRunning: true };\n }\n }\n\n // 3. Launch as detached child process\n const port = options?.port ?? DEFAULT_PORT;\n // process.argv[1] is the CLI entry point (cli.bundle.cjs in production, cli.ts in dev)\n const cliPath = process.argv[1];\n\n const child = spawn('node', [cliPath, 'dashboard', 'serve', '--port', String(port), '--no-open'], {\n detached: true,\n stdio: 'ignore',\n });\n\n // Track spawn failures and early exits so the polling loop can bail early\n let spawnFailed = false;\n let childExited = false;\n child.on('error', (err) => {\n spawnFailed = true;\n console.error(`[STARTUP] Failed to spawn dashboard server: ${err.message}`);\n });\n child.on('exit', (code) => {\n childExited = true;\n if (code !== 0 && code !== null) {\n console.error(`[STARTUP] Dashboard server exited prematurely (code ${code})`);\n }\n });\n child.unref();\n\n // 4. Poll for PID file to appear (server writes it after binding)\n for (let i = 0; i < MAX_POLL_ATTEMPTS; i++) {\n await sleep(POLL_INTERVAL_MS);\n\n // Bail early if spawn failed or child crashed before writing PID file\n if (spawnFailed || childExited) {\n return null;\n }\n\n const info = readDashboardServerInfo();\n if (info) {\n // PID file appeared \u2014 verify the server is responding\n if (await isDashboardServerRunning(info.port)) {\n return { url: `http://oss.localhost:${info.port}`, port: info.port, alreadyRunning: false };\n }\n }\n }\n\n // 5. Timeout \u2014 server didn't start in time; kill orphan process\n console.error('[STARTUP] Dashboard server failed to start within 5 seconds');\n if (child.pid) {\n try {\n process.kill(child.pid, 'SIGTERM');\n } catch (err) {\n // ESRCH = process already exited, which is fine\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ESRCH') {\n console.error(\n `[STARTUP] Failed to kill orphan dashboard process (PID ${child.pid}): ${(err as Error).message}`,\n );\n }\n }\n }\n return null;\n}\n", "/**\n * Startup command\n * Combines all pre-flight checks into a single CLI invocation:\n * auth check, setup check, daily fetch, dashboard launch, version detection, issue list detection.\n *\n * Replaces the ~100-line inline bash script in commands/oss.md with a single\n * `node cli.bundle.cjs startup --json` call, reducing UI noise in Claude Code.\n */\n\nimport * as fs from 'fs';\nimport { execFile } from 'child_process';\nimport { getStateManager, getGitHubToken, getCLIVersion, detectGitHubUsername } from '../core/index.js';\nimport { errorMessage } from '../core/errors.js';\nimport { type StartupOutput, type IssueListInfo } from '../formatters/json.js';\nimport { executeDailyCheck } from './daily.js';\nimport { launchDashboardServer } from './dashboard-lifecycle.js';\n\n/**\n * Parse issueListPath from a config file's YAML frontmatter.\n * Returns the path string or undefined if not found.\n */\nexport function parseIssueListPathFromConfig(configContent: string): string | undefined {\n const match = configContent.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!match) return undefined;\n const frontmatter = match[1];\n const pathMatch = frontmatter.match(/issueListPath:\\s*[\"']?([^\"'\\n]+)[\"']?/);\n return pathMatch ? pathMatch[1].trim() : undefined;\n}\n\n/**\n * Count available and completed items in an issue list file.\n * Available: list items (- [) NOT struck through or marked Done.\n * Completed: list items that ARE struck through or marked Done.\n */\nexport function countIssueListItems(content: string): { availableCount: number; completedCount: number } {\n let availableCount = 0;\n let completedCount = 0;\n const lines = content.split('\\n');\n for (const line of lines) {\n // Match list items: \"- [\" or \"- ~~[\" (strikethrough completed items)\n if (/^\\s*- (?:~~)?\\[/.test(line)) {\n if (/~~|\\*\\*Done\\*\\*/.test(line)) {\n completedCount++;\n } else {\n availableCount++;\n }\n }\n }\n return { availableCount, completedCount };\n}\n\n/**\n * Detect an issue list file from config or known paths.\n * Returns IssueListInfo or undefined if no list found.\n */\nexport function detectIssueList(): IssueListInfo | undefined {\n let issueListPath = '';\n let source: IssueListInfo['source'] = 'auto-detected';\n\n // 1. Check config file for configured path\n const configPath = '.claude/oss-autopilot/config.md';\n if (fs.existsSync(configPath)) {\n try {\n const configContent = fs.readFileSync(configPath, 'utf-8');\n const configuredPath = parseIssueListPathFromConfig(configContent);\n if (configuredPath && fs.existsSync(configuredPath)) {\n issueListPath = configuredPath;\n source = 'configured';\n }\n } catch (error) {\n console.error('[STARTUP] Failed to read config:', errorMessage(error));\n }\n }\n\n // 2. Probe known paths\n if (!issueListPath) {\n const probes = ['open-source/potential-issue-list.md', 'oss/issue-list.md', 'issues.md'];\n for (const probe of probes) {\n if (fs.existsSync(probe)) {\n issueListPath = probe;\n source = 'auto-detected';\n break;\n }\n }\n }\n\n if (!issueListPath) return undefined;\n\n // 3. Count available/completed items\n try {\n const content = fs.readFileSync(issueListPath, 'utf-8');\n const { availableCount, completedCount } = countIssueListItems(content);\n return { path: issueListPath, source, availableCount, completedCount };\n } catch (error) {\n console.error(`[STARTUP] Failed to read issue list at ${issueListPath}:`, errorMessage(error));\n return { path: issueListPath, source, availableCount: 0, completedCount: 0 };\n }\n}\n\nexport function openInBrowser(url: string): void {\n let openCmd: string;\n let args: string[];\n switch (process.platform) {\n case 'darwin':\n openCmd = 'open';\n args = [url];\n break;\n case 'win32':\n openCmd = 'cmd';\n args = ['/c', 'start', '', url];\n break;\n default:\n openCmd = 'xdg-open';\n args = [url];\n break;\n }\n execFile(openCmd, args, (error) => {\n if (error) {\n console.error(`[STARTUP] Failed to open dashboard in browser: ${error.message}`);\n }\n });\n}\n\n/**\n * Run startup checks and return structured output.\n * Returns StartupOutput with one of three shapes:\n * 1. Setup incomplete: { version, setupComplete: false }\n * 2. Auth failure: { version, setupComplete: true, authError: \"...\" }\n * 3. Success: { version, setupComplete: true, daily, dashboardUrl?, issueList? }\n *\n * Errors from the daily check propagate to the caller.\n */\nexport async function runStartup(): Promise<StartupOutput> {\n const version = getCLIVersion();\n const stateManager = getStateManager();\n\n // 1. Check setup \u2014 auto-detect if incomplete\n let autoDetected = false;\n if (!stateManager.isSetupComplete()) {\n const detectedUsername = await detectGitHubUsername();\n if (detectedUsername) {\n try {\n stateManager.initializeWithDefaults(detectedUsername);\n autoDetected = true;\n } catch (err) {\n console.error(\n `[STARTUP] Auto-detected username \"${detectedUsername}\" but failed to save config:`,\n errorMessage(err),\n );\n return { version, setupComplete: false };\n }\n } else {\n return { version, setupComplete: false };\n }\n }\n\n // 2. Check auth\n const token = getGitHubToken();\n if (!token) {\n return {\n version,\n setupComplete: true,\n authError:\n 'GitHub authentication required. Install GitHub CLI (https://cli.github.com/) and run \"gh auth login\", or set GITHUB_TOKEN.',\n };\n }\n\n // 3. Run daily check\n const daily = await executeDailyCheck(token);\n\n // 4. Launch interactive SPA dashboard\n // Skip opening on first run (0 PRs) \u2014 the welcome flow handles onboarding\n let dashboardUrl: string | undefined;\n let dashboardOpened = false;\n\n if (daily.digest.summary.totalActivePRs > 0) {\n try {\n const spaResult = await launchDashboardServer();\n if (spaResult) {\n dashboardUrl = spaResult.url;\n openInBrowser(spaResult.url);\n dashboardOpened = true;\n } else {\n console.error('[STARTUP] Dashboard SPA assets not found. Build with: cd packages/dashboard && pnpm run build');\n }\n } catch (error) {\n console.error('[STARTUP] SPA dashboard launch failed:', errorMessage(error));\n }\n }\n\n // Append dashboard status to brief summary (only startup opens the browser, not daily)\n if (dashboardOpened) {\n daily.briefSummary += ' | Dashboard opened in browser';\n }\n\n // 5. Detect issue list\n const issueList = detectIssueList();\n\n return {\n version,\n setupComplete: true,\n autoDetected,\n daily,\n dashboardUrl,\n issueList,\n };\n}\n", "/**\n * Simple in-memory sliding-window rate limiter for the dashboard server.\n *\n * Each endpoint gets its own limiter with a configurable max number of\n * requests per time window. Returns 429 with Retry-After when exceeded.\n */\n\nexport interface RateLimiterConfig {\n /** Maximum requests allowed within the window. */\n maxRequests: number;\n /** Window duration in milliseconds. */\n windowMs: number;\n}\n\nexport class RateLimiter {\n private readonly maxRequests: number;\n private readonly windowMs: number;\n /** Timestamps of accepted requests within the current window. */\n private timestamps: number[] = [];\n\n constructor(config: RateLimiterConfig) {\n this.maxRequests = config.maxRequests;\n this.windowMs = config.windowMs;\n }\n\n /**\n * Check if a request is allowed.\n *\n * @returns `{ allowed: true }` if under the limit, or\n * `{ allowed: false, retryAfterSeconds }` if rate-limited.\n */\n check(): { allowed: true } | { allowed: false; retryAfterSeconds: number } {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n\n // Prune timestamps outside the current window\n this.timestamps = this.timestamps.filter((t) => t > windowStart);\n\n if (this.timestamps.length >= this.maxRequests) {\n // Earliest timestamp in window \u2014 client must wait until it expires\n const oldestInWindow = this.timestamps[0];\n const retryAfterMs = oldestInWindow + this.windowMs - now;\n return { allowed: false, retryAfterSeconds: Math.ceil(retryAfterMs / 1000) };\n }\n\n this.timestamps.push(now);\n return { allowed: true };\n }\n}\n", "/**\n * Move command \u2014 transition a PR between states:\n * attention, waiting, shelved, or auto (reset to computed status).\n */\n\nimport { getStateManager } from '../core/index.js';\nimport { PR_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';\n\nexport const VALID_TARGETS = ['attention', 'waiting', 'shelved', 'auto'] as const;\n\nexport type MoveTarget = (typeof VALID_TARGETS)[number];\n\nexport interface MoveOutput {\n url: string;\n target: MoveTarget;\n /** Human-readable description of what happened. */\n description: string;\n}\n\nexport async function runMove(options: { prUrl: string; target: string }): Promise<MoveOutput> {\n validateUrl(options.prUrl);\n validateGitHubUrl(options.prUrl, PR_URL_PATTERN, 'PR');\n\n const target = options.target as MoveTarget;\n if (!VALID_TARGETS.includes(target)) {\n throw new Error(`Invalid target \"${options.target}\". Must be one of: ${VALID_TARGETS.join(', ')}`);\n }\n\n const stateManager = getStateManager();\n\n switch (target) {\n case 'attention':\n case 'waiting': {\n const status = target === 'attention' ? 'needs_addressing' : 'waiting_on_maintainer';\n const label = target === 'attention' ? 'Need Attention' : 'Waiting on Maintainer';\n // Use current time \u2014 the CLI doesn't have cached PR data. The override\n // will auto-clear on the next daily run if the PR has new activity after this.\n const lastActivityAt = new Date().toISOString();\n stateManager.setStatusOverride(options.prUrl, status, lastActivityAt);\n stateManager.unshelvePR(options.prUrl);\n stateManager.save();\n return { url: options.prUrl, target, description: `Moved to ${label}` };\n }\n case 'shelved': {\n stateManager.shelvePR(options.prUrl);\n stateManager.clearStatusOverride(options.prUrl);\n stateManager.save();\n return {\n url: options.prUrl,\n target,\n description: 'Shelved \u2014 excluded from capacity and actionable items',\n };\n }\n case 'auto': {\n const clearedOverride = stateManager.clearStatusOverride(options.prUrl);\n const unshelved = stateManager.unshelvePR(options.prUrl);\n if (clearedOverride || unshelved) {\n stateManager.save();\n }\n return {\n url: options.prUrl,\n target,\n description: 'Reset to computed status',\n };\n }\n default: {\n const _exhaustive: never = target;\n throw new Error(`Unhandled move target: ${_exhaustive}`);\n }\n }\n}\n", "/**\n * Dashboard HTTP server.\n * Serves the Preact SPA from packages/dashboard/dist/ and provides API endpoints\n * for live data fetching and state mutations (PR state transitions, issue dismiss).\n *\n * Uses Node's built-in http module \u2014 no Express/Fastify.\n */\n\nimport * as http from 'http';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getStateManager, getGitHubToken, getCLIVersion, applyStatusOverrides } from '../core/index.js';\nimport { errorMessage, ValidationError } from '../core/errors.js';\nimport { warn } from '../core/logger.js';\nimport { validateUrl, validateGitHubUrl, PR_URL_PATTERN, ISSUE_URL_PATTERN } from './validation.js';\nimport type { MoveTarget } from './move.js';\nimport {\n fetchDashboardData,\n computePRsByRepo,\n computeTopRepos,\n getMonthlyData,\n buildDashboardStats,\n storedToMergedPRs,\n storedToClosedPRs,\n type DashboardStats,\n} from './dashboard-data.js';\nimport { openInBrowser } from './startup.js';\nimport { writeDashboardServerInfo, removeDashboardServerInfo } from './dashboard-process.js';\nimport { RateLimiter } from './rate-limiter.js';\nimport {\n isBelowMinStars,\n type DailyDigest,\n type AgentState,\n type CommentedIssue,\n type CommentedIssueWithResponse,\n type FetchedPR,\n type MergedPR,\n type ClosedPR,\n type ShelvedPRRef,\n} from '../core/types.js';\n\n// Re-export process management functions for backward compatibility\nexport {\n getDashboardPidPath,\n writeDashboardServerInfo,\n readDashboardServerInfo,\n removeDashboardServerInfo,\n isDashboardServerRunning,\n findRunningDashboardServer,\n type DashboardServerInfo,\n} from './dashboard-process.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface DashboardServerOptions {\n port: number;\n assetsDir: string;\n token: string | null;\n open: boolean;\n}\n\ninterface DashboardJsonData {\n stats: DashboardStats;\n prsByRepo: Record<string, { active: number; merged: number; closed: number }>;\n topRepos: Array<{ repo: string; active: number; merged: number; closed: number }>;\n monthlyMerged: Record<string, number>;\n monthlyOpened: Record<string, number>;\n monthlyClosed: Record<string, number>;\n activePRs: FetchedPR[];\n shelvedPRUrls: string[];\n recentlyMergedPRs: MergedPR[];\n recentlyClosedPRs: ClosedPR[];\n autoUnshelvedPRs: ShelvedPRRef[];\n commentedIssues: CommentedIssue[];\n issueResponses: CommentedIssueWithResponse[];\n allMergedPRs: MergedPR[];\n allClosedPRs: ClosedPR[];\n offline?: boolean;\n lastUpdated?: string;\n}\n\ninterface ActionRequest {\n action: 'move' | 'dismiss_issue_response';\n url: string;\n /** Target state for move action. */\n target?: 'attention' | 'waiting' | 'shelved' | 'auto';\n}\n\n// \u2500\u2500 Constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst VALID_ACTIONS: Set<ActionRequest['action']> = new Set(['move', 'dismiss_issue_response']);\n\nconst MODULE = 'dashboard-server';\n\nconst MAX_BODY_BYTES = 10_240;\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\nconst MIME_TYPES: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.css': 'text/css',\n '.svg': 'image/svg+xml',\n '.json': 'application/json',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n};\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Build the JSON payload that the SPA expects from GET /api/data.\n */\nfunction buildDashboardJson(\n digest: DailyDigest,\n state: Readonly<AgentState>,\n commentedIssues: CommentedIssue[],\n allMergedPRs?: MergedPR[],\n allClosedPRs?: ClosedPR[],\n): DashboardJsonData {\n const prsByRepo = computePRsByRepo(digest, state);\n const topRepos = computeTopRepos(prsByRepo);\n const { monthlyMerged, monthlyOpened, monthlyClosed } = getMonthlyData(state);\n // Derive from state if not provided (e.g. initial load from cached state)\n const mergedPRs = allMergedPRs ?? storedToMergedPRs(getStateManager().getMergedPRs());\n const closedPRs = allClosedPRs ?? storedToClosedPRs(getStateManager().getClosedPRs());\n // Filter out PRs from repos below the minStars threshold\n const minStars = state.config.minStars ?? 50;\n const repoScores = state.repoScores || {};\n const isAboveMinStars = (pr: { repo: string }): boolean =>\n !isBelowMinStars(repoScores[pr.repo]?.stargazersCount, minStars);\n const filteredMergedPRs = mergedPRs.filter(isAboveMinStars);\n const filteredClosedPRs = closedPRs.filter(isAboveMinStars);\n const stats = buildDashboardStats(digest, state, filteredMergedPRs.length, filteredClosedPRs.length);\n const dismissedIssues = state.config.dismissedIssues || {};\n const issueResponses = commentedIssues.filter(\n (i): i is CommentedIssueWithResponse => i.status === 'new_response' && !(i.url in dismissedIssues),\n );\n\n return {\n stats,\n prsByRepo,\n topRepos: topRepos.map(([repo, data]) => ({ repo, ...data })),\n monthlyMerged,\n monthlyOpened,\n monthlyClosed,\n activePRs: applyStatusOverrides(digest.openPRs || [], state),\n shelvedPRUrls: state.config.shelvedPRUrls || [],\n recentlyMergedPRs: digest.recentlyMergedPRs || [],\n recentlyClosedPRs: digest.recentlyClosedPRs || [],\n autoUnshelvedPRs: digest.autoUnshelvedPRs || [],\n commentedIssues,\n issueResponses,\n allMergedPRs: filteredMergedPRs,\n allClosedPRs: filteredClosedPRs,\n };\n}\n\n/**\n * Read the full request body as a UTF-8 string, with a size limit.\n */\nfunction readBody(req: http.IncomingMessage, maxBytes: number = MAX_BODY_BYTES): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let totalLength = 0;\n let aborted = false;\n req.on('data', (chunk: Buffer) => {\n if (aborted) return;\n totalLength += chunk.length;\n if (totalLength > maxBytes) {\n aborted = true;\n req.destroy();\n reject(new Error('Body too large'));\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n if (!aborted) resolve(Buffer.concat(chunks).toString('utf-8'));\n });\n req.on('error', (err) => {\n if (!aborted) reject(err);\n });\n });\n}\n\n/**\n * Set security headers on every response.\n */\nfunction setSecurityHeaders(res: http.ServerResponse): void {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('X-Frame-Options', 'DENY');\n res.setHeader(\n 'Content-Security-Policy',\n \"default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'\",\n );\n res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');\n}\n\n/**\n * Validate that POST requests originate from the local dashboard.\n * Returns true if the Origin is acceptable, false otherwise.\n */\nfunction isValidOrigin(req: http.IncomingMessage, port: number): boolean {\n const origin = req.headers['origin'];\n if (!origin) return true; // No Origin header = same-origin request (non-browser or same-page)\n const allowed = [`http://localhost:${port}`, `http://127.0.0.1:${port}`, `http://oss.localhost:${port}`];\n return allowed.includes(origin);\n}\n\n/**\n * Send a JSON response.\n */\nfunction sendJson(res: http.ServerResponse, statusCode: number, data: unknown): void {\n setSecurityHeaders(res);\n res.setHeader('Cache-Control', 'no-store');\n const body = JSON.stringify(data);\n res.writeHead(statusCode, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(body),\n });\n res.end(body);\n}\n\n/**\n * Send an error JSON response.\n */\nfunction sendError(res: http.ServerResponse, statusCode: number, message: string): void {\n sendJson(res, statusCode, { error: message });\n}\n\n// \u2500\u2500 Server \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function startDashboardServer(options: DashboardServerOptions): Promise<void> {\n const { port: requestedPort, assetsDir, token, open } = options;\n\n const stateManager = getStateManager();\n const resolvedAssetsDir = path.resolve(assetsDir);\n\n // \u2500\u2500 Cached data \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Start immediately with state.json data (written by the daily check that\n // precedes this server launch). A background GitHub fetch refreshes the\n // cache after the port is bound, so the startup poller sees us in time.\n let cachedDigest: DailyDigest = stateManager.getState().lastDigest!;\n let cachedCommentedIssues: CommentedIssue[] = [];\n\n if (!cachedDigest) {\n throw new Error(\n 'No dashboard data available. Run the daily check first: GITHUB_TOKEN=$(gh auth token) npm start -- daily',\n );\n }\n\n // \u2500\u2500 Build cached JSON response \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let cachedJsonData: DashboardJsonData;\n try {\n cachedJsonData = buildDashboardJson(cachedDigest, stateManager.getState(), cachedCommentedIssues);\n } catch (error) {\n throw new Error(\n `Failed to build dashboard data: ${errorMessage(error)}. State data may be corrupted \u2014 try running: daily --json`,\n { cause: error },\n );\n }\n\n // \u2500\u2500 Rate limiters \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const dataLimiter = new RateLimiter({ maxRequests: 30, windowMs: 60_000 }); // 30/min\n const actionLimiter = new RateLimiter({ maxRequests: 10, windowMs: 60_000 }); // 10/min\n const refreshLimiter = new RateLimiter({ maxRequests: 6, windowMs: 60_000 }); // 6/min\n\n // \u2500\u2500 Request handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const server = http.createServer(async (req, res) => {\n const method = req.method || 'GET';\n const url = req.url || '/';\n\n try {\n // \u2500\u2500 API routes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (url === '/api/data' && method === 'GET') {\n const check = dataLimiter.check();\n if (!check.allowed) {\n res.setHeader('Retry-After', String(check.retryAfterSeconds));\n sendError(res, 429, 'Too many requests');\n return;\n }\n // Re-read state.json if CLI commands modified it externally\n if (stateManager.reloadIfChanged()) {\n try {\n cachedJsonData = buildDashboardJson(cachedDigest, stateManager.getState(), cachedCommentedIssues);\n } catch (error) {\n warn(MODULE, `Failed to rebuild dashboard data after state reload: ${errorMessage(error)}`);\n // Intentional: serve previous cachedJsonData rather than returning 500\n }\n }\n sendJson(res, 200, cachedJsonData);\n return;\n }\n\n if (url === '/api/action' && method === 'POST') {\n if (!isValidOrigin(req, actualPort)) {\n sendError(res, 403, 'Invalid origin');\n return;\n }\n const check = actionLimiter.check();\n if (!check.allowed) {\n res.setHeader('Retry-After', String(check.retryAfterSeconds));\n sendError(res, 429, 'Too many requests');\n return;\n }\n await handleAction(req, res);\n return;\n }\n\n if (url === '/api/refresh' && method === 'POST') {\n if (!isValidOrigin(req, actualPort)) {\n sendError(res, 403, 'Invalid origin');\n return;\n }\n const check = refreshLimiter.check();\n if (!check.allowed) {\n res.setHeader('Retry-After', String(check.retryAfterSeconds));\n sendError(res, 429, 'Too many requests');\n return;\n }\n await handleRefresh(req, res);\n return;\n }\n\n // \u2500\u2500 Static file serving \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (method === 'GET') {\n serveStaticFile(url, res);\n return;\n }\n\n sendError(res, 405, 'Method not allowed');\n } catch (error) {\n warn(MODULE, `Unhandled request error: ${method} ${url} ${errorMessage(error)}`);\n if (!res.headersSent) {\n sendError(res, 500, 'Internal server error');\n }\n }\n });\n\n server.requestTimeout = REQUEST_TIMEOUT_MS;\n\n // \u2500\u2500 POST /api/action handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n async function handleAction(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {\n // Reload state before mutating to avoid overwriting external CLI changes\n stateManager.reloadIfChanged();\n\n let body: ActionRequest;\n try {\n const raw = await readBody(req);\n body = JSON.parse(raw) as ActionRequest;\n } catch (e) {\n const isBodyTooLarge = e instanceof Error && e.message === 'Body too large';\n sendError(res, isBodyTooLarge ? 413 : 400, isBodyTooLarge ? 'Request body too large' : 'Invalid JSON body');\n return;\n }\n\n if (!body.action || !VALID_ACTIONS.has(body.action)) {\n sendError(res, 400, `Invalid action. Must be one of: ${[...VALID_ACTIONS].join(', ')}`);\n return;\n }\n\n if (!body.url || typeof body.url !== 'string') {\n sendError(res, 400, 'Missing or invalid \"url\" field');\n return;\n }\n\n // Validate URL format \u2014 move is PR-only, dismiss_issue_response is issue-only.\n const isDismiss = body.action === 'dismiss_issue_response';\n try {\n validateUrl(body.url);\n validateGitHubUrl(body.url, isDismiss ? ISSUE_URL_PATTERN : PR_URL_PATTERN, isDismiss ? 'issue' : 'PR');\n } catch (err) {\n if (err instanceof ValidationError) {\n sendError(res, 400, err.message);\n } else {\n warn(MODULE, `Unexpected error during URL validation: ${errorMessage(err)}`);\n sendError(res, 400, 'Invalid URL');\n }\n return;\n }\n\n try {\n if (body.action === 'move') {\n const { VALID_TARGETS, runMove } = await import('./move.js');\n if (!body.target || !VALID_TARGETS.includes(body.target as MoveTarget)) {\n sendError(res, 400, `move requires a valid \"target\" field (${VALID_TARGETS.join(', ')})`);\n return;\n }\n await runMove({ prUrl: body.url, target: body.target });\n } else {\n // dismiss_issue_response\n stateManager.dismissIssue(body.url, new Date().toISOString());\n stateManager.save();\n }\n } catch (error) {\n warn(MODULE, `Action failed: ${body.action} ${body.url} ${errorMessage(error)}`);\n sendError(res, 500, 'Action failed');\n return;\n }\n\n // Rebuild dashboard data from cached digest + updated state\n cachedJsonData = buildDashboardJson(cachedDigest, stateManager.getState(), cachedCommentedIssues);\n\n sendJson(res, 200, cachedJsonData);\n }\n\n // \u2500\u2500 POST /api/refresh handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n async function handleRefresh(_req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {\n const currentToken = token || getGitHubToken();\n if (!currentToken) {\n sendError(res, 401, 'No GitHub token available. Cannot refresh data.');\n return;\n }\n\n try {\n stateManager.reloadIfChanged();\n warn(MODULE, 'Refreshing dashboard data from GitHub...');\n const result = await fetchDashboardData(currentToken);\n cachedDigest = result.digest;\n cachedCommentedIssues = result.commentedIssues;\n cachedJsonData = buildDashboardJson(\n cachedDigest,\n stateManager.getState(),\n cachedCommentedIssues,\n result.allMergedPRs,\n result.allClosedPRs,\n );\n sendJson(res, 200, cachedJsonData);\n } catch (error) {\n warn(MODULE, `Dashboard refresh failed: ${errorMessage(error)}`);\n sendError(res, 500, 'Refresh failed');\n }\n }\n\n // \u2500\u2500 Static file serving \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n function serveStaticFile(requestUrl: string, res: http.ServerResponse): void {\n // Decode URL, handling malformed percent-encoding\n let urlPath: string;\n try {\n urlPath = decodeURIComponent(requestUrl.split('?')[0]);\n } catch (_err) {\n warn(MODULE, `Malformed URL received: ${requestUrl}`);\n sendError(res, 400, 'Malformed URL');\n return;\n }\n\n // Security: reject paths with parent directory references\n if (urlPath.includes('..')) {\n sendError(res, 403, 'Forbidden');\n return;\n }\n\n // Resolve the file path from sanitized URL\n const relativePath = urlPath === '/' ? 'index.html' : urlPath.replace(/^\\/+/, '');\n let filePath = path.join(resolvedAssetsDir, relativePath);\n\n // Belt-and-suspenders: ensure resolved path is within assets directory\n if (!filePath.startsWith(resolvedAssetsDir + path.sep) && filePath !== resolvedAssetsDir) {\n sendError(res, 403, 'Forbidden');\n return;\n }\n\n // If file doesn't exist or is a directory, serve index.html for SPA routing\n try {\n const stat = fs.statSync(filePath);\n if (stat.isDirectory()) {\n filePath = path.join(resolvedAssetsDir, 'index.html');\n }\n } catch (err) {\n const nodeErr = err as NodeJS.ErrnoException;\n if (nodeErr.code === 'ENOENT') {\n filePath = path.join(resolvedAssetsDir, 'index.html');\n } else {\n warn(MODULE, `Failed to stat file: ${filePath}`);\n sendError(res, 500, 'Internal server error');\n return;\n }\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n\n try {\n const content = fs.readFileSync(filePath);\n setSecurityHeaders(res);\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': content.length,\n 'Cache-Control': 'public, max-age=3600',\n });\n res.end(content);\n } catch (error) {\n const nodeErr = error as NodeJS.ErrnoException;\n if (nodeErr.code === 'ENOENT') {\n sendError(res, 404, 'Not found');\n } else {\n warn(MODULE, `Failed to serve static file: ${filePath}`);\n sendError(res, 500, 'Failed to read file');\n }\n }\n }\n\n // \u2500\u2500 Start server with port retry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const MAX_PORT_ATTEMPTS = 10;\n let actualPort = requestedPort;\n\n for (let attempt = 0; attempt < MAX_PORT_ATTEMPTS; attempt++) {\n try {\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(actualPort, '127.0.0.1', () => resolve());\n });\n // Success \u2014 break out of retry loop\n break;\n } catch (err) {\n const nodeErr = err as NodeJS.ErrnoException;\n if (nodeErr.code === 'EADDRINUSE' && attempt < MAX_PORT_ATTEMPTS - 1) {\n warn(MODULE, `Port ${actualPort} is in use, trying ${actualPort + 1}...`);\n actualPort++;\n continue;\n }\n throw new Error(`Failed to start server: ${nodeErr.message}`, { cause: err });\n }\n }\n\n // Write PID file so other processes can detect this running server\n writeDashboardServerInfo({\n pid: process.pid,\n port: actualPort,\n startedAt: new Date().toISOString(),\n version: getCLIVersion(),\n });\n\n const serverUrl = `http://oss.localhost:${actualPort}`;\n warn(MODULE, `Dashboard server running at ${serverUrl} (also: http://localhost:${actualPort})`);\n\n // \u2500\u2500 Background refresh \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Port is bound and PID file written \u2014 now fetch fresh data from GitHub\n // so subsequent /api/data requests get live data instead of cached state.\n if (token) {\n fetchDashboardData(token)\n .then((result) => {\n stateManager.reloadIfChanged();\n cachedDigest = result.digest;\n cachedCommentedIssues = result.commentedIssues;\n cachedJsonData = buildDashboardJson(\n cachedDigest,\n stateManager.getState(),\n cachedCommentedIssues,\n result.allMergedPRs,\n result.allClosedPRs,\n );\n warn(MODULE, 'Background data refresh complete');\n })\n .catch((error) => {\n warn(MODULE, `Background data refresh failed (serving cached data): ${errorMessage(error)}`);\n });\n }\n\n // \u2500\u2500 Open browser \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (open) {\n openInBrowser(serverUrl);\n }\n\n // \u2500\u2500 Clean shutdown \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const shutdown = () => {\n warn(MODULE, 'Shutting down dashboard server...');\n removeDashboardServerInfo();\n server.close(() => {\n process.exit(0);\n });\n // Force exit after 3 seconds if server doesn't close cleanly\n setTimeout(() => process.exit(0), 3000).unref();\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n}\n", "/**\n * Dashboard command \u2014 serves the interactive Preact SPA dashboard.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getGitHubToken } from '../core/index.js';\n\n// \u2500\u2500 Serve (interactive dashboard) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface ServeOptions {\n port: number;\n open: boolean;\n}\n\n/**\n * Resolve the SPA assets directory from packages/dashboard/dist/.\n * Tries multiple strategies to locate it across dev (tsx) and bundled (cjs) modes.\n */\nexport function resolveAssetsDir(): string | null {\n // Strategy 1: relative to this source file (works in dev with tsx)\n const devPath = path.resolve(__dirname, '../../dashboard/dist');\n if (fs.existsSync(path.join(devPath, 'index.html'))) {\n return devPath;\n }\n\n // Strategy 2: relative to the CLI bundle location (packages/core/dist/cli.bundle.cjs)\n const bundlePath = path.resolve(path.dirname(process.argv[1]), '../../dashboard/dist');\n if (fs.existsSync(path.join(bundlePath, 'index.html'))) {\n return bundlePath;\n }\n\n // Strategy 3: resolve the dashboard package via require.resolve\n try {\n const dashboardPkgPath = require.resolve('@oss-autopilot/dashboard/package.json');\n const dashboardDist = path.join(path.dirname(dashboardPkgPath), 'dist');\n if (fs.existsSync(path.join(dashboardDist, 'index.html'))) {\n return dashboardDist;\n }\n } catch (error) {\n const code = (error as NodeJS.ErrnoException & { code?: string }).code;\n if (code !== 'MODULE_NOT_FOUND') {\n console.error('Error resolving dashboard package:', error);\n }\n }\n\n return null;\n}\n\nexport async function serveDashboard(options: ServeOptions): Promise<void> {\n const assetsDir = resolveAssetsDir();\n if (!assetsDir) {\n console.error('Could not find dashboard SPA assets.');\n console.error('Make sure packages/dashboard has been built:');\n console.error(' cd packages/dashboard && pnpm run build');\n process.exit(1);\n }\n\n const token = getGitHubToken();\n\n const { startDashboardServer } = await import('./dashboard-server.js');\n await startDashboardServer({\n port: options.port,\n assetsDir,\n token,\n open: options.open,\n });\n}\n", "/**\n * Parse issue list command (#82)\n * Parses markdown issue lists into structured JSON with tier classification\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { ParseIssueListOutput, ParsedIssueItem } from '../formatters/json.js';\nimport { errorMessage } from '../core/errors.js';\n\ninterface ParseListOptions {\n filePath: string;\n}\n\nexport type { ParseIssueListOutput, ParsedIssueItem };\n\n/** Extract GitHub issue/PR URLs from a markdown line */\nfunction extractGitHubUrl(line: string): { repo: string; number: number; url: string } | null {\n const match = line.match(/https:\\/\\/github\\.com\\/([^/]+\\/[^/]+)\\/issues\\/(\\d+)/);\n if (match) {\n return { repo: match[1], number: parseInt(match[2], 10), url: match[0] };\n }\n const prMatch = line.match(/https:\\/\\/github\\.com\\/([^/]+\\/[^/]+)\\/pull\\/(\\d+)/);\n if (prMatch) {\n return { repo: prMatch[1], number: parseInt(prMatch[2], 10), url: prMatch[0] };\n }\n return null;\n}\n\n/** Extract issue title from a markdown line (text after URL or checkbox) */\nfunction extractTitle(line: string): string {\n // Remove markdown link syntax: [title](url) -> title\n let cleaned = line.replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1');\n // Remove bare URLs\n cleaned = cleaned.replace(/https?:\\/\\/\\S+/g, '');\n // Remove list markers (-, *, +, numbered)\n cleaned = cleaned.replace(/^\\s*[-*+]\\s*/, '').replace(/^\\s*\\d+\\.\\s*/, '');\n // Remove checkboxes\n cleaned = cleaned.replace(/\\[[ xX]\\]\\s*/, '');\n // Remove strikethrough markers\n cleaned = cleaned.replace(/~~/g, '');\n // Remove \"Done\" markers\n cleaned = cleaned.replace(/\\b(Done|DONE|done)\\b/g, '');\n // Remove leading/trailing punctuation and whitespace\n cleaned = cleaned.replace(/^[\\s\\-\\u2013\\u2014:]+/, '').replace(/[\\s\\-\\u2013\\u2014:]+$/, '');\n return cleaned.trim();\n}\n\n/** Determine if a line represents a completed item */\nfunction isCompleted(line: string): boolean {\n // Strikethrough: ~~text~~\n if (/~~.+~~/.test(line)) return true;\n // Checked checkbox: [x] or [X]\n if (/\\[[xX]\\]/.test(line)) return true;\n // \"Done\" marker (standalone word, case insensitive)\n if (/\\bdone\\b/i.test(line)) return true;\n return false;\n}\n\n/** Parse a markdown string into structured issue items */\nexport function parseIssueList(content: string): ParseIssueListOutput {\n const lines = content.split('\\n');\n const available: ParsedIssueItem[] = [];\n const completed: ParsedIssueItem[] = [];\n let currentTier = 'Uncategorized';\n\n for (const line of lines) {\n // Check for section headings (# or ##)\n const headingMatch = line.match(/^#{1,3}\\s+(.+)/);\n if (headingMatch) {\n currentTier = headingMatch[1].trim();\n continue;\n }\n\n // Skip empty lines and non-list items\n if (!line.trim() || !/^\\s*[-*+]|\\s*\\d+\\.|\\s*\\[[ xX]\\]/.test(line)) {\n continue;\n }\n\n // Extract GitHub URL -- skip lines without one\n const ghUrl = extractGitHubUrl(line);\n if (!ghUrl) continue;\n\n const title = extractTitle(line);\n const item: ParsedIssueItem = {\n repo: ghUrl.repo,\n number: ghUrl.number,\n title: title || `#${ghUrl.number}`,\n tier: currentTier,\n url: ghUrl.url,\n };\n\n if (isCompleted(line)) {\n completed.push(item);\n } else {\n available.push(item);\n }\n }\n\n return {\n available,\n completed,\n availableCount: available.length,\n completedCount: completed.length,\n };\n}\n\nexport async function runParseList(options: ParseListOptions): Promise<ParseIssueListOutput> {\n const filePath = path.resolve(options.filePath);\n\n if (!fs.existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n\n let content: string;\n try {\n content = fs.readFileSync(filePath, 'utf-8');\n } catch (error) {\n const msg = errorMessage(error);\n throw new Error(`Failed to read file: ${msg}`, { cause: error });\n }\n\n return parseIssueList(content);\n}\n", "/**\n * Check integration command (#83)\n * Detects new files in the current branch that aren't referenced elsewhere\n */\n\nimport * as path from 'path';\nimport { execFileSync } from 'child_process';\nimport type { CheckIntegrationOutput, NewFileInfo } from '../formatters/json.js';\nimport { debug } from '../core/index.js';\nimport { errorMessage } from '../core/errors.js';\n\ninterface CheckIntegrationOptions {\n base: string;\n}\n\nexport type { CheckIntegrationOutput, NewFileInfo };\n\n/** File extensions we consider \"code\" that should be imported/referenced */\nconst CODE_EXTENSIONS = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n '.py',\n '.rb',\n '.go',\n '.rs',\n '.java',\n '.kt',\n '.vue',\n '.svelte',\n]);\n\n/** Files that are typically entry points or config, not expected to be imported */\nconst IGNORED_PATTERNS = [\n /^\\./, // dotfiles\n /\\.(test|spec|e2e)\\.[^.]+$/, // test files\n /\\.(config|rc)\\.[^.]+$/, // config files\n /__tests__\\//, // test directories\n /\\.d\\.ts$/, // type declarations\n /\\.md$/, // documentation\n /\\.json$/, // json files\n /\\.ya?ml$/, // yaml files\n];\n\n/** Get the basename without extension for import matching (TS/JS) */\nfunction getImportName(filePath: string): string {\n const ext = path.extname(filePath);\n const base = path.basename(filePath, ext);\n // index files are imported by their directory name\n if (base === 'index') {\n return path.basename(path.dirname(filePath));\n }\n return base;\n}\n\n/** Suggest likely entry points for a new file based on its location */\nfunction suggestEntryPoints(newFile: string, existingFiles: string[]): string[] {\n const dir = path.dirname(newFile);\n const suggestions: string[] = [];\n\n // Look for index files in the same directory\n for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {\n const indexFile = path.join(dir, `index${ext}`);\n if (existingFiles.includes(indexFile)) {\n suggestions.push(indexFile);\n }\n }\n\n // Look for barrel/index in parent directory\n const parentDir = path.dirname(dir);\n for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {\n const parentIndex = path.join(parentDir, `index${ext}`);\n if (existingFiles.includes(parentIndex)) {\n suggestions.push(parentIndex);\n }\n }\n\n return [...new Set(suggestions)];\n}\n\nexport async function runCheckIntegration(options: CheckIntegrationOptions): Promise<CheckIntegrationOutput> {\n const base = options.base;\n\n // Get new files added in this branch vs base\n let newFiles: string[];\n try {\n const output = execFileSync('git', ['diff', '--name-only', '--diff-filter=A', `${base}...HEAD`], {\n encoding: 'utf-8',\n timeout: 10000,\n }).trim();\n newFiles = output ? output.split('\\n').filter(Boolean) : [];\n } catch (error) {\n const msg = errorMessage(error);\n throw new Error(`Failed to run git diff: ${msg}`, { cause: error });\n }\n\n // Filter to code files, excluding tests, configs, etc.\n const codeFiles = newFiles.filter((f) => {\n const ext = path.extname(f);\n if (!CODE_EXTENSIONS.has(ext)) return false;\n return !IGNORED_PATTERNS.some((p) => p.test(f));\n });\n\n if (codeFiles.length === 0) {\n return { newFiles: [], unreferencedCount: 0 };\n }\n\n // Get all tracked files in the repo for reference checking\n let allFiles: string[];\n try {\n allFiles = execFileSync('git', ['ls-files'], {\n encoding: 'utf-8',\n timeout: 10000,\n })\n .trim()\n .split('\\n')\n .filter(Boolean);\n } catch (err) {\n // git ls-files failed (e.g. not a git repo) -- proceed without reference list\n debug('check-integration', 'git ls-files failed, reference checking will be skipped', err);\n allFiles = [];\n }\n\n // For each new file, search for references in the repo\n const results: NewFileInfo[] = [];\n\n for (const newFile of codeFiles) {\n const importName = getImportName(newFile);\n const fileWithoutExt = newFile.replace(/\\.[^.]+$/, '');\n\n // Search for references using git grep (fast, respects .gitignore)\n let referencedBy: string[] = [];\n // Search for: import from './filename', require('./filename'), or just the filename stem\n const patterns = [\n importName, // bare name (covers most import patterns)\n ];\n\n // Also search for path-based imports (relative path without extension)\n if (fileWithoutExt.includes('/')) {\n patterns.push(fileWithoutExt);\n }\n\n for (const pattern of patterns) {\n try {\n const grepOutput = execFileSync('git', ['grep', '-l', '--', pattern], {\n encoding: 'utf-8',\n timeout: 10000,\n }).trim();\n if (grepOutput) {\n const matches = grepOutput.split('\\n').filter((f) => f !== newFile);\n referencedBy.push(...matches);\n }\n } catch (error: unknown) {\n // git grep exit code 1 = no matches (expected), exit code 2+ = real error\n const exitCode =\n error && typeof error === 'object' && 'status' in error ? (error as { status: unknown }).status : undefined;\n if (exitCode !== undefined && exitCode !== 1) {\n const msg = errorMessage(error);\n debug('check-integration', `git grep failed for \"${pattern}\": ${msg}`);\n }\n }\n }\n\n // Deduplicate\n referencedBy = [...new Set(referencedBy)];\n\n const isIntegrated = referencedBy.length > 0;\n const info: NewFileInfo = {\n path: newFile,\n referencedBy,\n isIntegrated,\n };\n\n if (!isIntegrated) {\n info.suggestedEntryPoints = suggestEntryPoints(newFile, allFiles);\n }\n\n results.push(info);\n }\n\n const unreferencedCount = results.filter((r) => !r.isIntegrated).length;\n return { newFiles: results, unreferencedCount };\n}\n", "/**\n * Local repos command (#84)\n * Scans configurable directories for local git clones and caches results\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { execFileSync } from 'child_process';\nimport { getStateManager, debug } from '../core/index.js';\nimport { errorMessage } from '../core/errors.js';\nimport type { LocalReposOutput, LocalRepoInfo } from '../formatters/json.js';\n\ninterface LocalReposOptions {\n scan?: boolean;\n paths?: string[];\n}\n\nexport type { LocalReposOutput, LocalRepoInfo };\n\n/** Default directories to scan for local clones */\nconst DEFAULT_SCAN_PATHS = [\n path.join(os.homedir(), 'Documents', 'oss'),\n path.join(os.homedir(), 'dev'),\n path.join(os.homedir(), 'projects'),\n path.join(os.homedir(), 'src'),\n path.join(os.homedir(), 'code'),\n path.join(os.homedir(), 'repos'),\n];\n\n/** Extract the GitHub \"owner/repo\" remote from a git directory */\nfunction getGitHubRemote(repoPath: string): string | null {\n try {\n const remoteUrl = execFileSync('git', ['-C', repoPath, 'remote', 'get-url', 'origin'], {\n encoding: 'utf-8',\n timeout: 5000,\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n\n // Match HTTPS: https://github.com/owner/repo.git or https://github.com/owner/repo\n const httpsMatch = remoteUrl.match(/github\\.com\\/([^/]+\\/[^/]+?)(?:\\.git)?$/);\n if (httpsMatch) return httpsMatch[1];\n\n // Match SSH: git@github.com:owner/repo.git\n const sshMatch = remoteUrl.match(/github\\.com[:/]([^/]+\\/[^/]+?)(?:\\.git)?$/);\n if (sshMatch) return sshMatch[1];\n\n return null;\n } catch (err) {\n // git remote get-url failed (no remote, not a git repo, or timeout) \u2014 skip this repo\n debug('local-repos', `Failed to get GitHub remote for ${repoPath}`, err);\n return null;\n }\n}\n\n/** Get the current branch of a git repo */\nfunction getCurrentBranch(repoPath: string): string | null {\n try {\n return (\n execFileSync('git', ['-C', repoPath, 'branch', '--show-current'], {\n encoding: 'utf-8',\n timeout: 5000,\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim() || null\n );\n } catch (err) {\n // git branch --show-current failed \u2014 repo may be in detached HEAD state or inaccessible\n debug('local-repos', `Failed to get current branch for ${repoPath}`, err);\n return null;\n }\n}\n\n/** Scan directories for git repos, returning a map of owner/repo -> local path */\nexport function scanForRepos(scanPaths: string[]): Record<string, LocalRepoInfo> {\n const repos: Record<string, LocalRepoInfo> = {};\n\n for (const scanPath of scanPaths) {\n if (!fs.existsSync(scanPath)) continue;\n\n // Find git repos up to 3 levels deep\n let gitDirs: string[];\n try {\n const output = execFileSync('find', [scanPath, '-maxdepth', '4', '-name', '.git', '-type', 'd'], {\n encoding: 'utf-8',\n timeout: 30000,\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n gitDirs = output ? output.split('\\n').filter(Boolean) : [];\n } catch (err) {\n // find command failed for this scan path (permission denied, path gone, etc.) \u2014 skip it\n debug('local-repos', `find failed for scan path ${scanPath}`, err);\n continue;\n }\n\n for (const gitDir of gitDirs) {\n const repoPath = path.dirname(gitDir);\n const remote = getGitHubRemote(repoPath);\n if (!remote) continue;\n\n const currentBranch = getCurrentBranch(repoPath);\n repos[remote] = {\n path: repoPath,\n exists: true,\n currentBranch,\n };\n }\n }\n\n return repos;\n}\n\nexport async function runLocalRepos(options: LocalReposOptions): Promise<LocalReposOutput> {\n const stateManager = getStateManager();\n const state = stateManager.getState();\n const scanPaths =\n options.paths?.map((p) => path.resolve(p)) ??\n state.config.localRepoScanPaths ??\n DEFAULT_SCAN_PATHS.filter((p) => fs.existsSync(p));\n\n // Use cached data unless --scan is specified\n if (!options.scan && state.localRepoCache) {\n const cache = state.localRepoCache;\n return {\n repos: cache.repos,\n scanPaths: cache.scanPaths,\n cachedAt: cache.cachedAt,\n fromCache: true,\n };\n }\n\n const repos = scanForRepos(scanPaths);\n\n // Cache the results in state\n const cachedAt = new Date().toISOString();\n try {\n stateManager.setLocalRepoCache({ repos, scanPaths, cachedAt });\n stateManager.save();\n } catch (error) {\n const msg = errorMessage(error);\n console.error(`Warning: Failed to cache scan results: ${msg}`);\n }\n\n return {\n repos,\n scanPaths,\n cachedAt,\n fromCache: false,\n };\n}\n", "/**\n * Dismiss/Undismiss commands\n * Manages dismissing issue notifications without posting a comment.\n * Dismissed URLs resurface automatically when new responses arrive after the dismiss timestamp.\n */\n\nimport { getStateManager } from '../core/index.js';\nimport { ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';\n\nexport interface DismissOutput {\n dismissed: boolean;\n url: string;\n}\n\nexport interface UndismissOutput {\n undismissed: boolean;\n url: string;\n}\n\nexport async function runDismiss(options: { url: string }): Promise<DismissOutput> {\n validateUrl(options.url);\n validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');\n\n const stateManager = getStateManager();\n const added = stateManager.dismissIssue(options.url, new Date().toISOString());\n\n if (added) {\n stateManager.save();\n }\n\n return { dismissed: added, url: options.url };\n}\n\nexport async function runUndismiss(options: { url: string }): Promise<UndismissOutput> {\n validateUrl(options.url);\n validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');\n\n const stateManager = getStateManager();\n const removed = stateManager.undismissIssue(options.url);\n\n if (removed) {\n stateManager.save();\n }\n\n return { undismissed: removed, url: options.url };\n}\n", "/**\n * pr-template command \u2014 Fetch a repository's PR description template.\n *\n * Usage: oss-autopilot pr-template owner/repo --json\n */\n\nimport { getOctokit } from '../core/github.js';\nimport { requireGitHubToken, splitRepo } from '../core/utils.js';\nimport { fetchPRTemplate, type PRTemplateResult } from '../core/pr-template.js';\n\nexport async function runPRTemplate(opts: { repo: string }): Promise<PRTemplateResult> {\n const { owner, repo } = splitRepo(opts.repo);\n const token = requireGitHubToken();\n const octokit = getOctokit(token);\n return fetchPRTemplate(octokit, owner, repo);\n}\n", "/**\n * Stats command\n * Compute and display contribution statistics.\n */\n\nimport { getStateManager } from '../core/index.js';\nimport { computeContributionStats } from '../core/stats.js';\nimport type { StatsOutput } from '../formatters/json.js';\n\nexport async function runStats(): Promise<StatsOutput> {\n const stateManager = getStateManager();\n const state = stateManager.getState();\n const activePRCount = state.lastDigest?.summary?.totalActivePRs ?? 0;\n\n const stats = computeContributionStats({\n repoScores: state.repoScores ?? {},\n activePRCount,\n });\n\n return {\n ...stats,\n mergeRateFormatted: `${(stats.mergeRate * 100).toFixed(1)}%`,\n username: state.config.githubUsername,\n };\n}\n\nexport function formatStatsMarkdown(stats: StatsOutput): string {\n const lines: string[] = [\n `# OSS Contribution Stats for @${stats.username}`,\n '',\n '| Metric | Value |',\n '|--------|-------|',\n `| Merged PRs | ${stats.totalMerged} |`,\n `| Merge Rate | ${stats.mergeRateFormatted} |`,\n `| Active PRs | ${stats.activePRs} |`,\n `| Repos Contributed | ${stats.reposContributed} |`,\n '',\n ];\n\n if (stats.topRepos.length > 0) {\n lines.push('## Top Repos', '', '| Repo | Merged PRs |', '|------|-----------|');\n for (const repo of stats.topRepos) {\n lines.push(`| ${repo.repo} | ${repo.mergedCount} |`);\n }\n lines.push('');\n }\n\n lines.push('---', '*Generated by [OSS Autopilot](https://github.com/costajohnt/oss-autopilot)*');\n return lines.join('\\n');\n}\n\ninterface BadgeData {\n schemaVersion: number;\n label: string;\n message: string;\n color: string;\n}\n\nfunction pickBadgeColor(stats: StatsOutput): string {\n if (stats.totalMerged === 0) return 'blue';\n if (stats.mergeRate >= 0.8) return 'brightgreen';\n if (stats.mergeRate >= 0.6) return 'green';\n if (stats.mergeRate >= 0.4) return 'yellow';\n return 'orange';\n}\n\nexport function formatStatsBadge(stats: StatsOutput): BadgeData {\n const message =\n stats.totalMerged > 0 ? `${stats.mergeRateFormatted} merge rate | ${stats.totalMerged} merged` : 'Getting Started';\n\n return { schemaVersion: 1, label: 'OSS Contributions', message, color: pickBadgeColor(stats) };\n}\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", "#!/usr/bin/env node\n/**\n * OSS Autopilot CLI\n * Entry point with commander for argument parsing.\n *\n * Command definitions live in cli-registry.ts \u2014 each declares its name,\n * localOnly flag (skip GitHub token check), and a register function.\n * Heavy command modules are lazy-loaded via dynamic import() in action\n * handlers so only the invoked command's dependencies are evaluated.\n */\n\nimport { Command } from 'commander';\nimport { getGitHubTokenAsync, enableDebug, debug, getCLIVersion } from './core/index.js';\nimport { commands } from './cli-registry.js';\n\nconst VERSION = getCLIVersion();\n\nconst program = new Command();\n\nprogram\n .name('oss-autopilot')\n .description('AI-powered autopilot for managing open source contributions')\n .version(VERSION)\n .option('--debug', 'Enable debug logging');\n\n// Build the local-only set from registry metadata (replaces hardcoded LOCAL_ONLY_COMMANDS).\nconst localOnlySet = new Set(commands.filter((c) => c.localOnly).map((c) => c.name));\n\n// Register all commands from the registry.\nfor (const cmd of commands) {\n cmd.register(program);\n}\n\n// Validate GitHub token before running commands that need it\nprogram.hook('preAction', async (thisCommand, actionCommand) => {\n // Enable debug logging if --debug flag is set\n const globalOpts = thisCommand.opts();\n if (globalOpts.debug) {\n enableDebug();\n debug('cli', `Running command: ${actionCommand.name()}`);\n }\n\n // actionCommand is the command being executed (e.g., 'status', 'daily')\n const commandName = actionCommand.name();\n\n if (!localOnlySet.has(commandName)) {\n const token = await getGitHubTokenAsync();\n if (!token) {\n console.error('Error: GitHub authentication required.');\n console.error('');\n console.error('Option 1 (Recommended): Install and authenticate GitHub CLI');\n console.error(' Install: https://cli.github.com/');\n console.error(' Then run: gh auth login');\n console.error('');\n console.error('Option 2: Set GITHUB_TOKEN environment variable');\n console.error(' export GITHUB_TOKEN=\"your-github-token-here\"');\n console.error('');\n console.error('Then run your command again.');\n process.exit(1);\n }\n }\n});\n\n// Parse and execute\nprogram.parse();\n", "/**\n * CLI Command Registry\n *\n * All CLI command definitions live here as a flat array of CLICommandDef objects.\n * Each command declares its name, localOnly flag (skip GitHub token check), and\n * a register function that wires up the Commander command with display logic.\n *\n * Heavy command modules are lazy-loaded via dynamic import() in action handlers\n * so that only the invoked command's dependencies are evaluated.\n */\n\nimport type { Command } from 'commander';\nimport { errorMessage } from './core/errors.js';\nimport { outputJson, outputJsonError } from './formatters/json.js';\n\ninterface CLICommandDef {\n /** Command name (used to build the local-only set for the preAction hook). */\n name: string;\n /** If true, skip the preAction GitHub token check. */\n localOnly?: boolean;\n /** Register this command on the given Commander program. */\n register(program: Command): void;\n}\n\n/** Shared error handler for CLI action catch blocks. */\nfunction handleCommandError(err: unknown, json?: boolean): never {\n const msg = errorMessage(err);\n if (json) {\n outputJsonError(msg);\n } else {\n console.error(`Error: ${msg}`);\n }\n process.exit(1);\n}\n\n/** Print local repos in human-readable format (used by local-repos command). */\nfunction printRepos(repos: Record<string, { path: string; currentBranch: string | null }>): void {\n const entries = Object.entries(repos).sort(([a], [b]) => a.localeCompare(b));\n for (const [remote, info] of entries) {\n const branch = info.currentBranch ? ` (${info.currentBranch})` : '';\n console.log(` ${remote}${branch}`);\n console.log(` ${info.path}`);\n }\n}\n\nexport const commands: CLICommandDef[] = [\n // \u2500\u2500 Daily \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'daily',\n register(program) {\n program\n .command('daily')\n .description('Run daily check on all tracked PRs')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n try {\n if (options.json) {\n const { runDaily } = await import('./commands/daily.js');\n const data = await runDaily();\n outputJson(data);\n } else {\n const { runDailyForDisplay, printDigest } = await import('./commands/daily.js');\n const result = await runDailyForDisplay();\n printDigest(result.digest, result.capacity, result.commentedIssues);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'status',\n localOnly: true,\n register(program) {\n program\n .command('status')\n .description('Show current status and stats')\n .option('--json', 'Output as JSON')\n .option('--offline', 'Use cached data only (no GitHub API calls)')\n .action(async (options) => {\n try {\n const { runStatus } = await import('./commands/status.js');\n const data = await runStatus({ offline: options.offline });\n if (options.json) {\n outputJson(data);\n } else {\n console.log('\\n\\ud83d\\udcca OSS Status\\n');\n console.log(`Merged PRs: ${data.stats.mergedPRs}`);\n console.log(`Closed PRs: ${data.stats.closedPRs}`);\n console.log(`Merge Rate: ${data.stats.mergeRate}`);\n console.log(`Needs Response: ${data.stats.needsResponse}`);\n if (data.offline) {\n console.log(`\\nLast Updated: ${data.lastUpdated || 'Never'}`);\n console.log('(Offline mode: showing cached data)');\n } else {\n console.log(`\\nLast Run: ${data.lastRunAt || 'Never'}`);\n }\n console.log('\\nRun with --json for structured output');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Search \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'search',\n register(program) {\n program\n .command('search [count]')\n .description('Search for new issues to work on')\n .option('--json', 'Output as JSON')\n .action(async (count, options) => {\n try {\n const { runSearch } = await import('./commands/search.js');\n let maxResults = 5;\n if (count !== undefined) {\n const parsed = Number(count);\n if (!Number.isFinite(parsed) || parsed < 1 || !Number.isInteger(parsed)) {\n throw new Error(`Invalid count \"${count}\". Must be a positive integer.`);\n }\n maxResults = parsed;\n }\n const MAX_SEARCH_RESULTS = 100;\n if (maxResults > MAX_SEARCH_RESULTS) {\n console.warn(`Capping search to ${MAX_SEARCH_RESULTS} results (requested: ${maxResults})`);\n maxResults = MAX_SEARCH_RESULTS;\n }\n if (!options.json) {\n console.log(`\\nSearching for issues (max ${maxResults})...\\n`);\n }\n const data = await runSearch({ maxResults });\n if (options.json) {\n outputJson(data);\n } else {\n if (data.candidates.length === 0) {\n if (data.rateLimitWarning) {\n console.warn(`\\n${data.rateLimitWarning}\\n`);\n } else {\n console.log('No matching issues found.');\n }\n return;\n }\n\n if (data.rateLimitWarning) {\n console.warn(`\\n${data.rateLimitWarning}\\n`);\n }\n\n console.log(`Found ${data.candidates.length} candidates:\\n`);\n\n for (const candidate of data.candidates) {\n const { issue, recommendation, reasonsToApprove, reasonsToSkip, viabilityScore } = candidate;\n console.log(`[${recommendation.toUpperCase()}] ${issue.repo}#${issue.number}: ${issue.title}`);\n console.log(` URL: ${issue.url}`);\n console.log(` Viability: ${viabilityScore}/100`);\n if (reasonsToApprove.length > 0) console.log(` Approve: ${reasonsToApprove.join(', ')}`);\n if (reasonsToSkip.length > 0) console.log(` Skip: ${reasonsToSkip.join(', ')}`);\n console.log('---');\n }\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Vet \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'vet',\n register(program) {\n program\n .command('vet <issue-url>')\n .description('Vet a specific issue before working on it')\n .option('--json', 'Output as JSON')\n .action(async (issueUrl, options) => {\n try {\n const { runVet } = await import('./commands/vet.js');\n const data = await runVet({ issueUrl });\n if (options.json) {\n outputJson(data);\n } else {\n const { issue, recommendation, reasonsToApprove, reasonsToSkip } = data;\n console.log(`\\nVetting issue: ${issueUrl}\\n`);\n console.log(`[${recommendation.toUpperCase()}] ${issue.repo}#${issue.number}: ${issue.title}`);\n console.log(` URL: ${issue.url}`);\n if (reasonsToApprove.length > 0) console.log(` Approve: ${reasonsToApprove.join(', ')}`);\n if (reasonsToSkip.length > 0) console.log(` Skip: ${reasonsToSkip.join(', ')}`);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Track \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'track',\n register(program) {\n program\n .command('track <pr-url>')\n .description('Add a PR to track')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, options) => {\n try {\n const { runTrack } = await import('./commands/track.js');\n const data = await runTrack({ prUrl });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(`\\nPR: ${data.pr.repo}#${data.pr.number} - ${data.pr.title}`);\n console.log('Note: In v2, PRs are tracked automatically via the daily run.');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Untrack \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'untrack',\n localOnly: true,\n register(program) {\n program\n .command('untrack <pr-url>')\n .description('Stop tracking a PR')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, options) => {\n try {\n const { runUntrack } = await import('./commands/track.js');\n const data = await runUntrack({ prUrl });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(\n 'Note: In v2, PRs are fetched fresh on each daily run \\u2014 there is no local tracking list to remove from.',\n );\n console.log('Use `shelve` to temporarily hide a PR from the daily summary.');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Read \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'read',\n localOnly: true,\n register(program) {\n program\n .command('read [pr-url]')\n .description('Mark PR comments as read')\n .option('--all', 'Mark all PRs as read')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, options) => {\n try {\n const { runRead } = await import('./commands/read.js');\n const data = await runRead({ prUrl, all: options.all });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(\n 'Note: In v2, PR read state is not tracked locally. PRs are fetched fresh on each daily run.',\n );\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Comments \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'comments',\n register(program) {\n program\n .command('comments <pr-url>')\n .description('Show all comments on a PR')\n .option('--bots', 'Include bot comments')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, options) => {\n try {\n const { runComments } = await import('./commands/comments.js');\n const data = await runComments({ prUrl, showBots: options.bots });\n if (options.json) {\n outputJson(data);\n } else {\n const { formatRelativeTime } = await import('./core/utils.js');\n console.log(`\\nFetching comments for: ${prUrl}\\n`);\n console.log(`## ${data.pr.title}\\n`);\n console.log(`**Status:** ${data.pr.state} | **Mergeable:** ${data.pr.mergeable ?? 'checking...'}`);\n console.log(`**Branch:** ${data.pr.head} -> ${data.pr.base}`);\n console.log(`**URL:** ${data.pr.url}\\n`);\n\n const REVIEW_STATE_LABELS: Record<string, string> = {\n APPROVED: '[Approved]',\n CHANGES_REQUESTED: '[Changes]',\n };\n if (data.reviews.length > 0) {\n console.log('### Reviews (newest first)\\n');\n for (const review of data.reviews) {\n const state = REVIEW_STATE_LABELS[review.state] ?? '[Comment]';\n const time = review.submittedAt ? formatRelativeTime(review.submittedAt) : '';\n console.log(`${state} **@${review.user}** (${review.state}) - ${time}`);\n if (review.body) {\n console.log(`> ${review.body.split('\\n').join('\\n> ')}\\n`);\n }\n }\n }\n\n if (data.reviewComments.length > 0) {\n console.log('### Inline Comments (newest first)\\n');\n for (const comment of data.reviewComments) {\n const time = formatRelativeTime(comment.createdAt);\n console.log(`**@${comment.user}** on \\`${comment.path}\\` - ${time}`);\n console.log(`> ${comment.body.split('\\n').join('\\n> ')}`);\n console.log('');\n }\n }\n\n if (data.issueComments.length > 0) {\n console.log('### Discussion (newest first)\\n');\n for (const comment of data.issueComments) {\n const time = formatRelativeTime(comment.createdAt);\n console.log(`**@${comment.user}** - ${time}`);\n console.log(`> ${comment.body?.split('\\n').join('\\n> ')}\\n`);\n }\n }\n\n if (data.reviewComments.length === 0 && data.issueComments.length === 0 && data.reviews.length === 0) {\n console.log('No comments from other users.\\n');\n }\n\n console.log('---');\n console.log(\n `**Summary:** ${data.summary.reviewCount} reviews, ${data.summary.inlineCommentCount} inline comments, ${data.summary.discussionCommentCount} discussion comments`,\n );\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Post \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'post',\n register(program) {\n program\n .command('post <url> [message...]')\n .description('Post a comment to a PR or issue')\n .option('--stdin', 'Read message from stdin')\n .option('--json', 'Output as JSON')\n .action(async (url, messageParts, options) => {\n try {\n let message: string;\n if (options.stdin) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n message = Buffer.concat(chunks).toString('utf-8').trim();\n } else {\n message = messageParts.join(' ');\n }\n const { runPost } = await import('./commands/comments.js');\n const data = await runPost({ url, message });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(`Comment posted: ${data.commentUrl}`);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Claim \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'claim',\n register(program) {\n program\n .command('claim <issue-url> [message...]')\n .description('Claim an issue by posting a comment')\n .option('--json', 'Output as JSON')\n .action(async (issueUrl, messageParts, options) => {\n try {\n const { runClaim } = await import('./commands/comments.js');\n const message = messageParts.length > 0 ? messageParts.join(' ') : undefined;\n const data = await runClaim({ issueUrl, message });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(`Issue claimed: ${data.commentUrl}`);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'config',\n localOnly: true,\n register(program) {\n program\n .command('config [key] [value]')\n .description('Show or update configuration')\n .option('--json', 'Output as JSON')\n .action(async (key, value, options) => {\n try {\n const { runConfig } = await import('./commands/config.js');\n const data = await runConfig({ key, value });\n if (options.json) {\n outputJson(data);\n } else if ('config' in data) {\n console.log('\\n\\u2699\\ufe0f Current Configuration:\\n');\n console.log(JSON.stringify(data.config, null, 2));\n } else {\n console.log(`Set ${data.key} to: ${data.value}`);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Init \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'init',\n register(program) {\n program\n .command('init <username>')\n .description('Initialize with your GitHub username and import open PRs')\n .option('--json', 'Output as JSON')\n .action(async (username, options) => {\n try {\n const { runInit } = await import('./commands/init.js');\n const data = await runInit({ username });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(`\\nUsername set to @${data.username}.`);\n console.log('Run `oss-autopilot daily` to fetch your open PRs from GitHub.');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'setup',\n localOnly: true,\n register(program) {\n program\n .command('setup')\n .description('Interactive setup / configuration')\n .option('--reset', 'Re-run setup even if already complete')\n .option('--set <settings...>', 'Set specific values (key=value)')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n try {\n const { runSetup } = await import('./commands/setup.js');\n const data = await runSetup({ reset: options.reset, set: options.set });\n if (options.json) {\n outputJson(data);\n } else if ('success' in data) {\n // --set mode\n for (const [key, value] of Object.entries(data.settings)) {\n console.log(`\\u2713 ${key}: ${value}`);\n }\n if (data.warnings) {\n for (const w of data.warnings) {\n console.warn(w);\n }\n }\n } else if ('setupComplete' in data && data.setupComplete) {\n // Already complete\n console.log('\\n\\u2699\\ufe0f OSS Autopilot Setup\\n');\n console.log('\\u2713 Setup already complete!\\n');\n console.log('Current settings:');\n console.log(` GitHub username: ${data.config.githubUsername || '(not set)'}`);\n console.log(` Max active PRs: ${data.config.maxActivePRs}`);\n console.log(` Dormant threshold: ${data.config.dormantThresholdDays} days`);\n console.log(` Approaching dormant: ${data.config.approachingDormantDays} days`);\n console.log(` Languages: ${data.config.languages.join(', ')}`);\n console.log(` Labels: ${data.config.labels.join(', ')}`);\n console.log(`\\nRun 'setup --reset' to reconfigure.`);\n } else if ('setupRequired' in data) {\n // Needs setup\n console.log('\\n\\u2699\\ufe0f OSS Autopilot Setup\\n');\n console.log('SETUP_REQUIRED');\n console.log('---');\n console.log('Please configure the following settings:\\n');\n for (const prompt of data.prompts) {\n console.log(`SETTING: ${prompt.setting}`);\n console.log(`PROMPT: ${prompt.prompt}`);\n const currentVal = Array.isArray(prompt.current) ? prompt.current.join(', ') : prompt.current;\n console.log(`CURRENT: ${currentVal ?? '(not set)'}`);\n if (prompt.required) console.log('REQUIRED: true');\n if (prompt.default !== undefined) {\n const defaultVal = Array.isArray(prompt.default) ? prompt.default.join(', ') : prompt.default;\n console.log(`DEFAULT: ${defaultVal}`);\n }\n if (prompt.type) console.log(`TYPE: ${prompt.type}`);\n console.log('');\n }\n console.log('---');\n console.log('END_SETUP_PROMPTS');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Check Setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'checkSetup',\n localOnly: true,\n register(program) {\n program\n .command('checkSetup')\n .description('Check if setup is complete')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n try {\n const { runCheckSetup } = await import('./commands/setup.js');\n const data = await runCheckSetup();\n if (options.json) {\n outputJson(data);\n } else if (data.setupComplete) {\n console.log('SETUP_COMPLETE');\n console.log(`username=${data.username}`);\n } else {\n console.log('SETUP_INCOMPLETE');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Dashboard Serve \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'serve',\n localOnly: true,\n register(program) {\n const dashboardCmd = program.command('dashboard').description('Dashboard commands');\n dashboardCmd\n .command('serve')\n .description('Start interactive dashboard server')\n .option('--port <port>', 'Port to listen on', '3000')\n .option('--no-open', 'Do not open browser automatically')\n .action(async (options) => {\n try {\n const port = parseInt(options.port, 10);\n if (isNaN(port) || port < 1 || port > 65535) {\n console.error(`Invalid port number: \"${options.port}\". Must be an integer between 1 and 65535.`);\n process.exit(1);\n }\n const { serveDashboard } = await import('./commands/dashboard.js');\n await serveDashboard({ port, open: options.open });\n } catch (err) {\n handleCommandError(err);\n }\n });\n },\n },\n\n // \u2500\u2500 Parse Issue List \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'parse-issue-list',\n localOnly: true,\n register(program) {\n program\n .command('parse-issue-list <path>')\n .description('Parse a markdown issue list into structured JSON')\n .option('--json', 'Output as JSON')\n .action(async (filePath, options) => {\n try {\n const { runParseList } = await import('./commands/parse-list.js');\n const data = await runParseList({ filePath });\n if (options.json) {\n outputJson(data);\n } else {\n const path = await import('path');\n const resolvedPath = path.resolve(filePath);\n console.log(`\\n\\ud83d\\udccb Issue List: ${resolvedPath}\\n`);\n console.log(`Available: ${data.availableCount} | Completed: ${data.completedCount}\\n`);\n if (data.available.length > 0) {\n console.log('--- Available ---');\n for (const item of data.available) {\n console.log(` [${item.tier}] ${item.repo}#${item.number}: ${item.title}`);\n }\n }\n if (data.completed.length > 0) {\n console.log('\\n--- Completed ---');\n for (const item of data.completed) {\n console.log(` [${item.tier}] ${item.repo}#${item.number}: ${item.title}`);\n }\n }\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Check Integration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'check-integration',\n localOnly: true,\n register(program) {\n program\n .command('check-integration')\n .description('Detect new files not referenced by the codebase')\n .option('--base <branch>', 'Base branch to compare against', 'main')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n try {\n const { runCheckIntegration } = await import('./commands/check-integration.js');\n const data = await runCheckIntegration({ base: options.base });\n if (options.json) {\n outputJson(data);\n } else if (data.newFiles.length === 0) {\n console.log('\\nNo new code files to check.');\n } else {\n console.log(`\\n\\ud83d\\udd0d Integration Check (base: ${options.base})\\n`);\n console.log(`New files: ${data.newFiles.length} | Unreferenced: ${data.unreferencedCount}\\n`);\n for (const file of data.newFiles) {\n const status = file.isIntegrated ? '\\u2705' : '\\u26a0\\ufe0f';\n console.log(`${status} ${file.path}`);\n if (file.isIntegrated) {\n console.log(` Referenced by: ${file.referencedBy.join(', ')}`);\n } else {\n console.log(' Not referenced by any file');\n if (file.suggestedEntryPoints && file.suggestedEntryPoints.length > 0) {\n console.log(` Suggested entry points: ${file.suggestedEntryPoints.join(', ')}`);\n }\n }\n }\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Local Repos \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'local-repos',\n localOnly: true,\n register(program) {\n program\n .command('local-repos')\n .description('Scan filesystem for local git clones')\n .option('--scan', 'Force re-scan (ignores cache)')\n .option('--paths <dirs...>', 'Directories to scan')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n try {\n const { runLocalRepos } = await import('./commands/local-repos.js');\n const data = await runLocalRepos({ scan: options.scan, paths: options.paths });\n if (options.json) {\n outputJson(data);\n } else if (data.fromCache) {\n console.log(`\\n\\ud83d\\udcc1 Local Repos (cached ${data.cachedAt})\\n`);\n printRepos(data.repos);\n } else {\n console.log(`Found ${Object.keys(data.repos).length} repos:\\n`);\n printRepos(data.repos);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Startup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'startup',\n localOnly: true,\n register(program) {\n program\n .command('startup')\n .description('Run all pre-flight checks and daily fetch in one call')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n try {\n const { runStartup } = await import('./commands/startup.js');\n const data = await runStartup();\n if (options.json) {\n outputJson(data);\n } else {\n if (!data.setupComplete) {\n console.log('Setup incomplete. Run /setup-oss first.');\n } else if (data.authError) {\n console.error(`Error: ${data.authError}`);\n } else {\n console.log(`OSS Autopilot v${data.version}`);\n console.log(data.daily?.briefSummary ?? '');\n }\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Shelve \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'shelve',\n localOnly: true,\n register(program) {\n program\n .command('shelve <pr-url>')\n .description('Shelve a PR (exclude from capacity and actionable issues)')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, options) => {\n try {\n const { runMove } = await import('./commands/move.js');\n const data = await runMove({ prUrl, target: 'shelved' });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(data.description);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Unshelve \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'unshelve',\n localOnly: true,\n register(program) {\n program\n .command('unshelve <pr-url>')\n .description('Unshelve a PR (include in capacity and actionable issues again)')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, options) => {\n try {\n const { runMove } = await import('./commands/move.js');\n const data = await runMove({ prUrl, target: 'auto' });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(data.description);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Move \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'move',\n localOnly: true,\n register(program) {\n program\n .command('move <pr-url> <target>')\n .description('Move a PR between states: attention, waiting, shelved, or auto (reset to computed)')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, target, options) => {\n try {\n const { runMove } = await import('./commands/move.js');\n const data = await runMove({ prUrl, target });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(data.description);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Dismiss \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'dismiss',\n localOnly: true,\n register(program) {\n program\n .command('dismiss <url>')\n .description('Dismiss notifications for an issue (resurfaces on new activity)')\n .option('--json', 'Output as JSON')\n .action(async (url, options) => {\n try {\n const { runDismiss } = await import('./commands/dismiss.js');\n const data = await runDismiss({ url });\n if (options.json) {\n outputJson(data);\n } else if (data.dismissed) {\n console.log(`Dismissed: ${url}`);\n console.log('Notifications are now muted.');\n console.log('New responses after this point will resurface automatically.');\n } else {\n console.log('Already dismissed.');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Undismiss \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'undismiss',\n localOnly: true,\n register(program) {\n program\n .command('undismiss <url>')\n .description('Undismiss an issue (re-enable notifications)')\n .option('--json', 'Output as JSON')\n .action(async (url, options) => {\n try {\n const { runUndismiss } = await import('./commands/dismiss.js');\n const data = await runUndismiss({ url });\n if (options.json) {\n outputJson(data);\n } else if (data.undismissed) {\n console.log(`Undismissed: ${url}`);\n console.log('Notifications are active again.');\n } else {\n console.log('Was not dismissed.');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Override Status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'override',\n localOnly: true,\n register(program) {\n program\n .command('override <pr-url> <status>')\n .description('Manually override PR status (needs_addressing or waiting_on_maintainer)')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, status, options) => {\n try {\n const { runMove } = await import('./commands/move.js');\n const validStatuses = ['needs_addressing', 'waiting_on_maintainer'];\n if (!validStatuses.includes(status)) {\n throw new Error(`Invalid status \"${status}\". Must be one of: ${validStatuses.join(', ')}`);\n }\n const target = status === 'needs_addressing' ? 'attention' : 'waiting';\n const data = await runMove({ prUrl, target });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(data.description);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Clear Override \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'clear-override',\n localOnly: true,\n register(program) {\n program\n .command('clear-override <pr-url>')\n .description('Clear a manual status override for a PR')\n .option('--json', 'Output as JSON')\n .action(async (prUrl, options) => {\n try {\n const { runMove } = await import('./commands/move.js');\n const data = await runMove({ prUrl, target: 'auto' });\n if (options.json) {\n outputJson(data);\n } else {\n console.log(data.description);\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 PR Template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'pr-template',\n register(program) {\n program\n .command('pr-template <repo>')\n .description(\"Fetch a repository's PR description template\")\n .option('--json', 'Output as JSON')\n .action(async (repo, options) => {\n try {\n const { runPRTemplate } = await import('./commands/pr-template.js');\n const data = await runPRTemplate({ repo });\n if (options.json) {\n outputJson(data);\n } else if (data.template) {\n console.log(`\\nPR template found at: ${data.source}\\n`);\n console.log(data.template);\n } else if (data.error) {\n console.error(`\\nWarning: Could not check for PR template: ${data.error}`);\n } else {\n console.log('\\nNo PR template found for this repository.');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n\n // \u2500\u2500 Stats \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n name: 'stats',\n localOnly: true,\n register(program) {\n program\n .command('stats')\n .description('Show contribution statistics')\n .option('--json', 'Output as JSON')\n .option('--markdown', 'Output as shareable markdown report')\n .option('--badge', 'Output as shields.io endpoint JSON')\n .action(async (options) => {\n try {\n const { runStats, formatStatsMarkdown, formatStatsBadge } = await import('./commands/stats.js');\n const data = await runStats();\n if (options.badge) {\n console.log(JSON.stringify(formatStatsBadge(data), null, 2));\n } else if (options.markdown) {\n console.log(formatStatsMarkdown(data));\n } else if (options.json) {\n outputJson(data);\n } else {\n console.log(`\\nOSS Contribution Stats (@${data.username})\\n`);\n console.log(` Merged PRs: ${data.totalMerged}`);\n console.log(` Closed PRs: ${data.totalClosed}`);\n console.log(` Merge Rate: ${data.mergeRateFormatted}`);\n console.log(` Active PRs: ${data.activePRs}`);\n console.log(` Repos Contributed: ${data.reposContributed}`);\n if (data.topRepos.length > 0) {\n console.log('\\n Top Repos:');\n for (const repo of data.topRepos.slice(0, 5)) {\n console.log(` ${repo.repo}: ${repo.mergedCount} merged`);\n }\n }\n console.log('\\n Use --markdown for a shareable report or --badge for shields.io');\n }\n } catch (err) {\n handleCommandError(err, options.json);\n }\n });\n },\n },\n];\n"],
|
|
5
|
-
"mappings": ";ioBAAA,IAAAA,GAAAC,GAAAC,IAAA,CAGA,IAAMC,GAAN,cAA6B,KAAM,CAOjC,YAAYC,EAAUC,EAAMC,EAAS,CACnC,MAAMA,CAAO,EAEb,MAAM,kBAAkB,KAAM,KAAK,WAAW,EAC9C,KAAK,KAAO,KAAK,YAAY,KAC7B,KAAK,KAAOD,EACZ,KAAK,SAAWD,EAChB,KAAK,YAAc,MACrB,CACF,EAKMG,GAAN,cAAmCJ,EAAe,CAKhD,YAAYG,EAAS,CACnB,MAAM,EAAG,4BAA6BA,CAAO,EAE7C,MAAM,kBAAkB,KAAM,KAAK,WAAW,EAC9C,KAAK,KAAO,KAAK,YAAY,IAC/B,CACF,EAEAJ,GAAQ,eAAiBC,GACzBD,GAAQ,qBAAuBK,KCtC/B,IAAAC,GAAAC,GAAAC,IAAA,IAAM,CAAE,qBAAAC,EAAqB,EAAI,KAE3BC,GAAN,KA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AC7B,qDACF,EACA,+BAAgC,CAC9B,+DACF,EACA,wBAAyB,CAAC,+CAA+C,EACzE,yBAA0B,CACxB,yDACF,EACA,mBAAoB,CAAC,8CAA8C,EACnE,uBAAwB,CACtB,uEACF,EACA,uBAAwB,CACtB,wDACF,EACA,wBAAyB,CACvB,uDACF,EACA,eAAgB,CACd,8DACF,EACA,yBAA0B,CACxB,+EACF,EACA,gCAAiC,CAC/B,kGACF,EACA,wBAAyB,CACvB,oFACF,EACA,0BAA2B,CACzB,+EACF,EACA,yBAA0B,CACxB,8DACF,EACA,gBAAiB,CAAC,kDAAkD,EACpE,kBAAmB,CAAC,6CAA6C,EACjE,iBAAkB,CAChB,4DACF,EACA,mBAAoB,CAClB,uDACF,EACA,8BAA+B,CAC7B,gDACF,EACA,+BAAgC,CAC9B,0DACF,EACA,kBAAmB,CAAC,oDAAoD,EACxE,sBAAuB,CACrB,yDACF,EACA,mDAAoD,CAClD,qEACF,EACA,gBAAiB,CACf,mEACF,EACA,iBAAkB,CAChB,4EACF,EACA,8BAA+B,CAC7B,sDACF,EACA,+BAAgC,CAC9B,gFACF,EACA,wBAAyB,CACvB,sDACF,EACA,kDAAmD,CACjD,kEACF,EACA,eAAgB,CACd,kEACF,EACA,uBAAwB,CACtB,+DACF,EACA,8BAA+B,CAC7B,qDACF,EACA,+BAAgC,CAC9B,+DACF,EACA,oBAAqB,CAAC,0CAA0C,EAChE,qBAAsB,CAAC,+CAA+C,EACtE,iCAAkC,CAChC,mDACF,EACA,2BAA4B,CAAC,qCAAqC,EAClE,8BAA+B,CAC7B,sDACF,EACA,4BAA6B,CAC3B,gEACF,EACA,YAAa,CAAC,2DAA2D,EACzE,qBAAsB,CACpB,4EACF,EACA,4BAA6B,CAC3B,+FACF,EACA,6BAA8B,CAC5B,0DACF,EACA,wBAAyB,CACvB,8EACF,EACA,qBAAsB,CACpB,iFACF,EACA,uBAAwB,CACtB,4EACF,EACA,uDAAwD,CACtD,8CACF,EACA,qDAAsD,CACpD,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SAAU,CAAC,yDAAyD,EACpE,gBAAiB,CACf,iEACF,EACA,WAAY,CAAC,oDAAoD,EACjE,aAAc,CACZ,oEACF,EACA,iBAAkB,CAAC,sDAAsD,EACzE,aAAc,CACZ,gEACF,EACA,eAAgB,CACd,oEACF,EACA,qBAAsB,CACpB,sDACF,EACA,OAAQ,CAAC,uDAAuD,CAClE,EACA,aAAc,CACZ,cAAe,CACb,gFACF,EACA,cAAe,CACb,wEACF,EACA,sBAAuB,CACrB,kEACF,EACA,eAAgB,CACd,oFACF,EACA,qBAAsB,CACpB,wEACF,EACA,SAAU,CACR,gEACA,CAAC,EACD,CAAE,kBAAmB,CAAE,SAAU,cAAe,CAAE,CACpD,EACA,YAAa,CACX,gEACF,EACA,WAAY,CACV,uEACF,EACA,kBAAmB,CACjB,qEACF,EACA,gBAAiB,CAAC,uDAAuD,EACzE,SAAU,CAAC,2DAA2D,EACtE,mBAAoB,CAClB,8FACF,EACA,2BAA4B,CAC1B,6HACF,EACA,mBAAoB,CAClB,yEACF,EACA,iBAAkB,CAAC,sCAAsC,EACzD,kBAAmB,CAAC,gDAAgD,EACpE,oBAAqB,CACnB,0EACA,CAAC,EACD,CAAE,QAAS,CAAC,eAAgB,oBAAoB,CAAE,CACpD,EACA,oBAAqB,CACnB,0DACF,EACA,mBAAoB,CAAC,kDAAkD,EACvE,YAAa,CACX,iEACF,EACA,mBAAoB,CAClB,yDACF,EACA,YAAa,CAAC,iDAAiD,CACjE,EACA,aAAc,CACZ,oBAAqB,CACnB,yEACF,EACA,8BAA+B,CAC7B,uFACF,EACA,oBAAqB,CAAC,+CAA+C,EACrE,iCAAkC,CAChC,6DACF,EACA,oBAAqB,CACnB,oEACF,EACA,iCAAkC,CAChC,kFACF,EACA,oBAAqB,CACnB,wDACF,EACA,iBAAkB,CAChB,iEACF,EACA,8BAA+B,CAC7B,uDACF,EACA,+BAAgC,CAC9B,4DACF,EACA,wBAAyB,CAAC,8CAA8C,EACxE,yBAA0B,CACxB,uDACF,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AC3D,4DACA,CAAC,EACD,CACE,QAAS,CACP,WACA,yDACF,CACF,CACF,EACA,wDAAyD,CACvD,2DACF,EACA,0CAA2C,CACzC,iEACF,EACA,2CAA4C,CAC1C,uEACF,EACA,+BAAgC,CAC9B,kDACF,EACA,0BAA2B,CACzB,wDACF,EACA,kBAAmB,CACjB,8DACF,EACA,sCAAuC,CACrC,gFACF,EACA,iCAAkC,CAChC,sFACF,EACA,yBAA0B,CACxB,4FACF,EACA,2DAA4D,CAC1D,4BACF,EACA,sDAAuD,CACrD,kCACF,EACA,8CAA+C,CAC7C,wCACF,EACA,iCAAkC,CAAC,oBAAoB,EACvD,4BAA6B,CAAC,0BAA0B,EACxD,oBAAqB,CAAC,gCAAgC,EACtD,mCAAoC,CAClC,mEACF,EACA,qBAAsB,CACpB,yEACF,EACA,sBAAuB,CACrB,+EACF,EACA,0CAA2C,CACzC,yFACF,EACA,4BAA6B,CAC3B,+FACF,EACA,6BAA8B,CAC5B,qGACF,CACF,EACA,kBAAmB,CACjB,yBAA0B,CAAC,qCAAqC,EAChE,yBAA0B,CACxB,qDACF,EACA,sBAAuB,CAAC,kDAAkD,EAC1E,gBAAiB,CAAC,+CAA+C,EACjE,yBAA0B,CAAC,oCAAoC,EAC/D,yBAA0B,CACxB,oDACF,CACF,EACA,SAAU,CACR,cAAe,CAAC,oDAAoD,EACpE,eAAgB,CACd,0DACF,EACA,iBAAkB,CAChB,gEACF,EACA,kBAAmB,CACjB,sEACF,EACA,eAAgB,CACd,+DACF,EACA,gBAAiB,CACf,qEACF,EACA,UAAW,CAAC,6CAA6C,EACzD,WAAY,CAAC,mDAAmD,EAChE,WAAY,CAAC,6DAA6D,EAC1E,YAAa,CACX,mEACF,EACA,iBAAkB,CAAC,oDAAoD,EACvE,kBAAmB,CACjB,0DACF,EACA,WAAY,CAAC,4BAA4B,EACzC,YAAa,CAAC,kCAAkC,EAChD,gBAAiB,CAAC,mDAAmD,EACrE,iBAAkB,CAChB,yDACF,EACA,iBAAk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,GACjB,MAAMC,GAAoB,IAEtC,QAAQ,MAAM,wCAAwC,EACtD,QAAQ,MAAM,EAAE,EAChB,QAAQ,MAAM,6DAA6D,EAC3E,QAAQ,MAAM,oCAAoC,EAClD,QAAQ,MAAM,2BAA2B,EACzC,QAAQ,MAAM,EAAE,EAChB,QAAQ,MAAM,iDAAiD,EAC/D,QAAQ,MAAM,gDAAgD,EAC9D,QAAQ,MAAM,EAAE,EAChB,QAAQ,MAAM,8BAA8B,EAC5C,QAAQ,KAAK,CAAC,EAGpB,CAAC,EAGDX,GAAQ,MAAM",
|
|
6
|
-
"names": ["require_error", "__commonJSMin", "exports", "CommanderError", "exitCode", "code", "message", "InvalidArgumentError", "require_argument", "__commonJSMin", "exports", "InvalidArgumentError", "Argument", "name", "description", "value", "previous", "fn", "values", "arg", "humanReadableArgName", "nameOutput", "require_help", "__commonJSMin", "exports", "humanReadableArgName", "Help", "contextOptions", "cmd", "visibleCommands", "helpCommand", "a", "b", "getSortKey", "option", "visibleOptions", "helpOption", "removeShort", "removeLong", "globalOptions", "ancestorCmd", "argument", "args", "arg", "helper", "max", "command", "cmdName", "ancestorCmdNames", "extraInfo", "choice", "extraDescription", "heading", "items", "unsortedItems", "visibleItems", "getGroup", "result", "item", "group", "termWidth", "helpWidth", "callFormatItem", "term", "description", "output", "commandDescription", "argumentList", "options", "optionList", "globalOptionList", "sub", "commands", "commandList", "str", "stripColor", "word", "itemIndentStr", "paddedTerm", "spacerWidth", "remainingWidth", "formattedDescription", "width", "rawLines", "chunkPattern", "wrappedLines", "line", "chunks", "sumChunks", "sumWidth", "chunk", "visibleWidth", "nextChunk", "sgrPattern", "require_option", "__commonJSMin", "exports", "InvalidArgumentError", "Option", "flags", "description", "optionFlags", "splitOptionFlags", "value", "arg", "names", "impliedOptionValues", "newImplied", "name", "fn", "mandatory", "hide", "previous", "values", "camelcase", "heading", "DualOptions", "options", "option", "key", "optionKey", "preset", "negativeValue", "str", "word", "shortFlag", "longFlag", "shortFlagExp", "longFlagExp", "flagParts", "unsupportedFlag", "baseError", "require_suggestSimilar", "__commonJSMin", "exports", "editDistance", "a", "b", "d", "i", "j", "cost", "suggestSimilar", "word", "candidates", "searchingOptions", "candidate", "similar", "bestDistance", "minSimilarity", "distance", "length", "require_command", "__commonJSMin", "exports", "EventEmitter", "childProcess", "path", "fs", "process", "Argument", "humanReadableArgName", "CommanderError", "Help", "stripColor", "Option", "DualOptions", "suggestSimilar", "Command", "_Command", "name", "str", "write", "useColor", "sourceCommand", "result", "command", "nameAndArgs", "actionOptsOrExecDesc", "execOpts", "desc", "opts", "args", "cmd", "configuration", "displayHelp", "displaySuggestion", "description", "parseArg", "defaultValue", "argument", "names", "detail", "previousArgument", "enableOrNameAndArgs", "helpName", "helpArgs", "helpDescription", "helpCommand", "deprecatedDescription", "event", "listener", "allowedValues", "fn", "err", "exitCode", "code", "message", "expectedArgsCount", "actionArgs", "flags", "target", "value", "previous", "invalidArgumentMessage", "option", "matchingOption", "matchingFlag", "knownBy", "alreadyUsed", "existingCmd", "newCmd", "oname", "positiveLongFlag", "handleOptionValue", "val", "invalidValueMessage", "valueSource", "oldValue", "config", "regex", "def", "m", "combine", "allowUnknown", "allowExcess", "positional", "passThrough", "storeAsProperties", "key", "source", "argv", "parseOptions", "execArgv", "userArgs", "executableFile", "executableDir", "subcommandName", "executableDirMessage", "executableMissing", "subcommand", "launchWithNode", "sourceExt", "findFile", "baseDir", "baseName", "localBin", "foundExt", "ext", "resolvedScriptPath", "localFile", "legacyName", "proc", "incrementNodeInspectorPort", "signal", "exitCallback", "wrappedError", "commandName", "operands", "unknown", "subCommand", "promiseChain", "arg", "i", "myParseArg", "parsedValue", "processedArgs", "declaredArg", "index", "processed", "v", "promise", "hooks", "hookedCommand", "callback", "hookDetail", "hook", "parsed", "checkForUnknownOptions", "commandEvent", "anOption", "definedNonDefaultOptions", "optionKey", "conflictingAndDefined", "defined", "dest", "maybeOption", "negativeNumberArg", "opt", "short", "activeVariadicOption", "activeGroup", "len", "combinedOptions", "errorOptions", "dualHelper", "hasCustomOptionValue", "impliedKey", "conflictingOption", "findBestOptionFromValue", "optionValue", "negativeOption", "positiveOption", "getErrorMessage", "bestOption", "flag", "suggestion", "candidateFlags", "moreFlags", "receivedArgs", "expected", "unknownName", "candidateNames", "versionOption", "argsDescription", "alias", "matchingCommand", "aliases", "heading", "filename", "contextOptions", "helper", "context", "text", "error", "baseWrite", "hasColors", "helpWidth", "deprecatedCallback", "outputContext", "eventContext", "helpInformation", "position", "helpEvent", "helpStr", "helpOption", "debugOption", "debugHost", "debugPort", "match", "require_commander", "__commonJSMin", "exports", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "name", "flags", "description", "isBelowMinStars", "stargazersCount", "minStars", "DEFAULT_CONFIG", "INITIAL_STATE", "PROJECT_CATEGORIES", "init_types", "__esmMin", "errorMessage", "e", "getHttpStatusCode", "error", "status", "isRateLimitError", "isRateLimitOrAuthError", "err", "msg", "OssAutopilotError", "ConfigurationError", "ValidationError", "init_errors", "__esmMin", "message", "code", "enableDebug", "debugEnabled", "debug", "module", "message", "args", "timestamp", "info", "warn", "timed", "label", "fn", "start", "result", "duration", "err", "init_logger", "__esmMin", "utils_exports", "__export", "DEFAULT_CONCURRENCY", "byDateDescending", "daysBetween", "detectGitHubUsername", "extractOwnerRepo", "formatRelativeTime", "getBackupDir", "getCLIVersion", "getCacheDir", "getDataDir", "getGitHubToken", "getGitHubTokenAsync", "getStatePath", "isOwnRepo", "parseGitHubUrl", "requireGitHubToken", "resetGitHubTokenCache", "splitRepo", "dir", "isValidOwnerRepo", "owner", "repo", "OWNER_PATTERN", "REPO_PATTERN", "url", "prMatch", "issueMatch", "match", "from", "to", "repoFullName", "username", "pkgPath", "dateStr", "date", "diffMs", "diffMins", "diffHours", "diffDays", "getDate", "a", "b", "dateA", "cachedGitHubToken", "tokenFetchAttempted", "token", "debug", "MODULE", "err", "ConfigurationError", "resolve", "reject", "error", "stdout", "login", "GITHUB_USERNAME_RE", "fs", "path", "os", "import_child_process", "init_utils", "__esmMin", "init_errors", "init_logger", "isLockStale", "lockPath", "existing", "LOCK_TIMEOUT_MS", "err", "debug", "MODULE", "acquireLock", "lockData", "releaseLock", "atomicWriteFileSync", "filePath", "data", "mode", "tmpPath", "migrateV1ToV2", "rawState", "mergedPRs", "closedPRs", "repoScores", "pr", "migratedState", "isValidState", "state", "s", "createFreshState", "CURRENT_STATE_VERSION", "INITIAL_STATE", "migrateFromLegacyLocation", "newStatePath", "getStatePath", "LEGACY_STATE_FILE", "getDataDir", "LEGACY_BACKUP_DIR", "newBackupDir", "getBackupDir", "backupFiles", "f", "backupFile", "srcPath", "destPath", "file", "legacyDataDir", "error", "warn", "errorMessage", "cleanupErr", "tryRestoreFromBackup", "backupDir", "backupPath", "repoCount", "statePath", "backupErr", "loadState", "restoredState", "mtimeMs", "safeGetMtimeMs", "needsCleanupSave", "rawConfig", "PR_URL_RE", "url", "cleanupError", "cleanupBackups", "files", "saveState", "timestamp", "randomSuffix", "reloadStateIfChanged", "lastLoadedMtimeMs", "result", "fs", "path", "init_state_persistence", "__esmMin", "init_types", "init_utils", "init_errors", "init_logger", "createDefaultRepoScore", "repo", "calculateScore", "repoScore", "score", "mergedBonus", "closedPenalty", "lastMergedDate", "warn", "MODULE", "getRepoScore", "state", "updateRepoScore", "updates", "debug", "incrementMergedCount", "newCount", "incrementClosedCount", "markRepoHostile", "getReposWithMergedPRs", "rs", "a", "b", "getReposWithOpenPRs", "getHighScoringRepos", "minScore", "threshold", "getLowScoringRepos", "maxScore", "now", "age", "SCORE_TTL_MS", "getStats", "totalMerged", "totalClosed", "totalTracked", "isBelowMinStars", "completed", "mergeRate", "init_repo_score_manager", "__esmMin", "init_types", "init_logger", "getStateManager", "stateManager", "StateManager", "MODULE", "MAX_EVENTS", "init_state", "__esmMin", "init_state_persistence", "init_repo_score_manager", "init_logger", "_StateManager", "inMemoryOnly", "createFreshState", "result", "loadState", "username", "debug", "saveState", "reloadStateIfChanged", "digest", "counts", "cache", "prs", "existingUrls", "pr", "newPRs", "a", "b", "config", "type", "data", "event", "e", "since", "until", "eventTime", "issue", "i", "repo", "repos", "orgs", "repoLower", "r", "o", "matches", "beforeTrusted", "p", "removedTrusted", "lastFetched", "staleThresholdMs", "lastFetchedDate", "url", "index", "timestamp", "status", "lastActivityAt", "currentUpdatedAt", "override", "getRepoScore", "updates", "updateRepoScore", "incrementMergedCount", "incrementClosedCount", "markRepoHostile", "getReposWithMergedPRs", "getReposWithOpenPRs", "minScore", "getHighScoringRepos", "maxScore", "getLowScoringRepos", "getStats", "getUserAgent", "init_universal_user_agent", "__esmMin", "register", "state", "name", "method", "options", "callback", "registered", "init_register", "__esmMin", "addHook", "state", "kind", "name", "hook", "orig", "method", "options", "result", "result_", "error", "init_add", "__esmMin", "removeHook", "state", "name", "method", "index", "registered", "init_remove", "__esmMin", "bindApi", "hook", "state", "name", "removeHookRef", "bindable", "removeHook", "kind", "args", "addHook", "Singular", "singularHookName", "singularHookState", "singularHook", "register", "Collection", "bind", "before_after_hook_default", "init_before_after_hook", "__esmMin", "init_register", "init_add", "init_remove", "lowercaseKeys", "object", "newObj", "key", "isPlainObject", "value", "proto", "Ctor", "mergeDeep", "defaults", "options", "result", "removeUndefinedProperties", "obj", "merge", "route", "method", "url", "mergedOptions", "preview", "addQueryParameters", "parameters", "separator", "names", "name", "removeNonChars", "variableName", "extractUrlVariableNames", "matches", "urlVariableRegex", "a", "b", "omit", "keysToOmit", "encodeReserved", "str", "part", "encodeUnreserved", "c", "encodeValue", "operator", "isDefined", "isKeyOperator", "getValues", "context", "modifier", "value2", "k", "tmp", "parseUrl", "template", "expand", "operators", "_", "expression", "literal", "values", "variable", "parse", "headers", "body", "urlVariableNames", "omittedParameters", "option", "remainingParameters", "format", "previewsFromAcceptHeader", "endpointWithDefaults", "withDefaults", "oldDefaults", "newDefaults", "DEFAULTS2", "endpoint2", "VERSION", "userAgent", "DEFAULTS", "endpoint", "init_dist_bundle", "__esmMin", "init_universal_user_agent", "getUserAgent", "require_fast_content_type_parse", "__commonJSMin", "exports", "module", "NullObject", "paramRE", "quotedPairRE", "mediaTypeRE", "defaultContentType", "parse", "header", "index", "type", "result", "key", "match", "value", "safeParse", "intRegex", "noiseValue", "originalStringify", "originalParse", "customFormat", "bigIntsStringify", "noiseStringify", "JSONStringify", "isContextSourceSupported", "convertMarkedBigIntsReviver", "JSONParseV2", "MAX_INT", "MAX_DIGITS", "stringsOrLargeNumbers", "noiseValueWithQuotes", "JSONParse", "init_json_with_bigint", "__esmMin", "value", "replacer", "space", "key", "_", "__", "context", "userReviver", "text", "reviver", "isBigNumber", "isInt", "serializedData", "digits", "fractional", "exponential", "isString", "isFractionalOrExponential", "isLessThanMaxSafeInt", "RequestError", "init_dist_src", "__esmMin", "message", "statusCode", "options", "requestCopy", "isPlainObject", "value", "proto", "Ctor", "fetchWrapper", "requestOptions", "fetch", "log", "parseSuccessResponseBody", "body", "JSONStringify", "requestHeaders", "name", "fetchResponse", "error", "message", "requestError", "RequestError", "status", "url", "responseHeaders", "key", "octokitResponse", "matches", "deprecationLink", "getResponseData", "toErrorMessage", "response", "contentType", "noop", "mimetype", "isJSONResponse", "text", "JSONParse", "data", "suffix", "v", "withDefaults", "oldEndpoint", "newDefaults", "endpoint2", "route", "parameters", "endpointOptions", "request2", "route2", "parameters2", "import_fast_content_type_parse", "VERSION", "defaults_default", "request", "init_dist_bundle", "__esmMin", "init_universal_user_agent", "init_json_with_bigint", "init_dist_src", "getUserAgent", "endpoint", "_buildMessageForResponseErrors", "data", "graphql", "request2", "query", "options", "key", "FORBIDDEN_VARIABLE_OPTIONS", "parsedOptions", "requestOptions", "result", "NON_VARIABLE_OPTIONS", "baseUrl", "GHES_V3_SUFFIX_REGEX", "response", "headers", "GraphqlResponseError", "withDefaults", "newDefaults", "newRequest", "withCustomRequest", "customRequest", "VERSION", "graphql2", "init_dist_bundle", "__esmMin", "init_universal_user_agent", "request", "getUserAgent", "auth", "token", "isApp", "isJWT", "isInstallation", "isUserToServer", "withAuthorizationPrefix", "hook", "request", "route", "parameters", "endpoint", "b64url", "sep", "jwtRE", "createTokenAuth", "init_dist_bundle", "__esmMin", "VERSION", "init_version", "__esmMin", "createLogger", "logger", "noop", "consoleWarn", "consoleError", "userAgentTrail", "Octokit", "init_dist_src", "__esmMin", "init_universal_user_agent", "init_before_after_hook", "init_dist_bundle", "init_version", "VERSION", "getUserAgent", "defaults", "args", "options", "newPlugins", "currentPlugins", "plugin", "hook", "before_after_hook_default", "requestDefaults", "request", "withCustomRequest", "authStrategy", "otherOptions", "auth", "createTokenAuth", "classConstructor", "i", "VERSION", "init_version", "__esmMin", "requestLog", "octokit", "request", "options", "start", "requestOptions", "path", "response", "requestId", "error", "init_dist_src", "__esmMin", "init_version", "VERSION", "normalizePaginatedListResponse", "response", "incompleteResults", "repositorySelection", "totalCount", "totalCommits", "namespaceKey", "data", "iterator", "octokit", "route", "parameters", "options", "requestMethod", "method", "headers", "url", "normalizedResponse", "parsedUrl", "params", "page", "per_page", "error", "paginate", "mapFn", "gather", "results", "iterator2", "result", "earlyExit", "done", "paginateRest", "VERSION", "composePaginateRest", "init_dist_bundle", "__esmMin", "VERSION", "init_version", "__esmMin", "Endpoints", "endpoints_default", "init_endpoints", "__esmMin", "endpointsToMethods", "octokit", "newMethods", "scope", "endpointMethodsMap", "handler", "decorate", "methodName", "defaults", "decorations", "requestWithDefaults", "withDecorations", "args", "options", "newScope", "newMethodName", "name", "alias", "init_endpoints_to_methods", "__esmMin", "init_endpoints", "endpoints", "endpoints_default", "endpoint", "route", "method", "url", "endpointDefaults", "target", "descriptor", "value", "cache", "restEndpointMethods", "octokit", "endpointsToMethods", "legacyRestEndpointMethods", "api", "init_dist_src", "__esmMin", "init_version", "init_endpoints_to_methods", "VERSION", "VERSION", "init_version", "__esmMin", "Octokit", "init_dist_src", "__esmMin", "init_dist_bundle", "init_version", "requestLog", "legacyRestEndpointMethods", "paginateRest", "VERSION", "require_light", "__commonJSMin", "exports", "module", "global", "factory", "commonjsGlobal", "getCjsExportFromNamespace", "n", "load", "received", "defaults", "onto", "k", "ref", "v", "overwrite", "parser", "DLList", "incr", "decr", "value", "node", "results", "cb", "ref1", "ref2", "DLList_1", "Events", "instance", "name", "status", "base", "args", "e", "promises", "listener", "returned", "error", "x", "Events_1", "DLList$1", "Events$1", "Queues", "num_priorities", "i", "j", "job", "priority", "fn", "list", "arr", "len", "Queues_1", "BottleneckError", "BottleneckError_1", "BottleneckError$1", "DEFAULT_PRIORITY", "Job", "NUM_PRIORITIES", "parser$1", "task", "options", "jobDefaults", "rejectOnDrop", "_states", "Promise", "_resolve", "_reject", "sProperty", "message", "expected", "reachedHWM", "blocked", "chained", "clearGlobalState", "run", "free", "eventInfo", "passed", "error1", "retry", "retryAfter", "Job_1", "BottleneckError$2", "LocalDatastore", "parser$2", "storeOptions", "storeInstanceOptions", "amount", "maximum", "now", "reservoir", "flush", "t", "resolve", "reject", "time", "maxConcurrent", "weight", "capacity", "index", "expiration", "wait", "queueLength", "LocalDatastore_1", "BottleneckError$3", "States", "status1", "id", "current", "next", "initial", "pos", "acc", "States_1", "DLList$2", "Sync", "promise", "Sync_1", "version", "version$1", "version$2", "require$$2", "require$$3", "require$$4", "Events$2", "Group", "IORedisConnection$1", "RedisConnection$1", "Scripts$1", "parser$3", "limiterOptions", "Bottleneck_1", "key", "limiter", "deleted", "cursor", "end", "found", "keys", "start", "Group_1", "Batcher", "Events$3", "parser$4", "res", "rej", "data", "ret", "Batcher_1", "require$$4$1", "require$$8", "Bottleneck", "DEFAULT_PRIORITY$1", "Events$4", "Job$1", "LocalDatastore$1", "NUM_PRIORITIES$1", "Queues$1", "RedisDatastore$1", "States$1", "Sync$1", "parser$5", "splice", "invalid", "_limiter", "running", "queue", "success", "empty", "total", "drained", "newCapacity", "done", "waitForExecuting", "at", "finished", "counts", "shifted", "strategy", "schedule", "wrapped", "lib", "wrapRequest", "state", "request", "options", "doRequest", "pathname", "isAuth", "isAuthRequest", "isWrite", "isSearch", "isGraphQL", "jobOptions", "noop", "req", "res", "error", "method", "routeMatcher", "paths", "regex2", "path", "c", "r", "throttling", "octokit", "octokitOptions", "enabled", "Bottleneck", "BottleneckLight", "id", "timeout", "connection", "common", "groups", "createGroups", "triggersNotification", "events", "emitter", "e", "info", "state2", "retryCount", "wantRetry", "retryAfter", "retryAfter2", "error2", "rateLimitReset", "import_light", "VERSION", "triggers_notification_paths_default", "regex", "init_dist_bundle", "__esmMin", "formatResetTime", "date", "getOctokit", "token", "_octokit", "_currentToken", "ThrottledOctokit", "retryAfter", "options", "retryCount", "opts", "resetAt", "warn", "MODULE", "checkRateLimit", "octokit", "data", "search", "init_github", "__esmMin", "init_dist_src", "init_dist_bundle", "init_logger", "Octokit", "throttling", "isContributorCommit", "commitAuthor", "contributorUsername", "author", "CI_FIX_BOTS", "isCommitAfterComment", "commitDate", "commentDate", "commitMs", "commentMs", "MIN_RESPONSE_GAP_MS", "determineStatus", "input", "ciStatus", "hasMergeConflict", "hasUnrespondedComment", "hasIncompleteChecklist", "reviewDecision", "daysSinceActivity", "dormantThreshold", "approachingThreshold", "rawCommitDate", "latestCommitAuthor", "lastMaintainerCommentDate", "latestChangesRequestedDate", "hasActionableCIFailure", "stalenessTier", "latestCommitDate", "init_status_determination", "__esmMin", "runWorkerPool", "items", "worker", "concurrency", "index", "aborted", "poolWorker", "item", "err", "workerCount", "init_concurrency", "__esmMin", "paginateAll", "fetchPage", "perPage", "maxPages", "allItems", "page", "data", "init_pagination", "__esmMin", "getHttpCache", "_httpCache", "HttpCache", "cachedRequest", "cache", "url", "fetcher", "existing", "debug", "MODULE", "promise", "extraHeaders", "cached", "response", "etag", "err", "isNotModifiedError", "freshCached", "cleanup", "cachedTimeBased", "key", "maxAgeMs", "result", "getHttpStatusCode", "fs", "path", "crypto", "DEFAULT_MAX_AGE_MS", "init_http_cache", "__esmMin", "init_utils", "init_logger", "init_errors", "cacheDir", "getCacheDir", "entry", "age", "filePath", "raw", "body", "evicted", "files", "now", "file", "f", "classifyCICheck", "name", "description", "conclusion", "nameLower", "AUTH_GATE_PATTERNS", "p", "FORK_LIMITATION_PATTERNS", "INFRASTRUCTURE_PATTERNS", "descLower", "classifyFailingChecks", "failingCheckNames", "conclusions", "analyzeCheckRuns", "checkRuns", "hasFailingChecks", "hasPendingChecks", "hasSuccessfulChecks", "failingCheckConclusions", "check", "analyzeCombinedStatus", "combinedStatus", "realStatuses", "s", "desc", "hasRealFailure", "hasRealPending", "hasRealSuccess", "effectiveCombinedState", "hasStatuses", "failingStatusNames", "mergeStatuses", "checkRunAnalysis", "combinedAnalysis", "checkRunCount", "allFailingNames", "init_ci_analysis", "__esmMin", "isBotAuthor", "author", "KNOWN_BOT_USERNAMES", "isAcknowledgmentComment", "body", "lower", "kw", "init_comment_utils", "__esmMin", "determineReviewDecision", "reviews", "latestByUser", "review", "login", "state", "states", "getLatestChangesRequestedDate", "latest", "isAllSelfReplies", "reviewId", "reviewComments", "commentsForReview", "c", "authorMap", "comment", "parentAuthor", "commentAuthor", "getInlineCommentBody", "checkUnrespondedComments", "comments", "username", "timeline", "usernameLower", "author", "body", "resolvedBody", "a", "b", "lastUserCommentTime", "item", "lastMaintainerComment", "isBotAuthor", "itemTime", "isAcknowledgmentComment", "init_review_analysis", "__esmMin", "init_comment_utils", "isConditionalChecklistItem", "line", "CONDITIONAL_CHECKLIST_PATTERN", "analyzeChecklist", "body", "checkedPattern", "uncheckedLinePattern", "checkedMatches", "uncheckedLines", "checked", "nonConditionalUnchecked", "effectiveTotal", "init_checklist_analysis", "__esmMin", "extractMaintainerActionHints", "commentBody", "reviewDecision", "hints", "lower", "kw", "init_maintainer_analysis", "__esmMin", "computeDisplayLabel", "pr", "entry", "ACTION_DISPLAY", "WAIT_DISPLAY", "warn", "init_display_utils", "__esmMin", "init_logger", "checks", "actionable", "c", "infrastructure", "failingNames", "emptyPRCountsResult", "isCachedPRCounts", "v", "obj", "fetchUserPRCounts", "octokit", "githubUsername", "query", "label", "accumulateRepo", "starFilter", "cache", "getHttpCache", "minStarsSuffix", "cacheKey", "cached", "PR_COUNTS_CACHE_TTL_MS", "debug", "MODULE", "repos", "monthlyCounts", "monthlyOpenedCounts", "dailyActivityCounts", "page", "fetched", "totalCount", "data", "item", "parsed", "extractOwnerRepo", "warn", "owner", "repo", "isOwnRepo", "isBelowMinStars", "primaryDate", "month", "day", "openedMonth", "openedDay", "MAX_PAGINATION_PAGES", "fetchUserMergedPRCounts", "mergedAt", "existing", "fetchUserClosedPRCounts", "fetchRecentPRs", "config", "days", "mapItem", "sinceDate", "since", "results", "parseGitHubUrl", "fetchRecentlyClosedPRs", "number", "fetchRecentlyMergedPRs", "fetchMergedPRsSince", "dateFilter", "q", "fetchClosedPRsSince", "closedAt", "init_github_stats", "__esmMin", "init_utils", "init_types", "init_logger", "init_http_cache", "MODULE", "MAX_CONCURRENT_REQUESTS", "PRMonitor", "init_pr_monitor", "__esmMin", "init_github", "init_state", "init_utils", "init_status_determination", "init_concurrency", "init_errors", "init_pagination", "init_logger", "init_http_cache", "init_ci_analysis", "init_review_analysis", "init_checklist_analysis", "init_maintainer_analysis", "init_display_utils", "init_github_stats", "DEFAULT_CONCURRENCY", "githubToken", "getOctokit", "getStateManager", "config", "ConfigurationError", "debug", "allItems", "page", "perPage", "firstPage", "totalCount", "totalPages", "nextPage", "prs", "failures", "filteredItems", "item", "parsed", "extractOwnerRepo", "isOwnRepo", "warn", "timed", "runWorkerPool", "pr", "error", "errMsg", "errorMessage", "a", "b", "prUrl", "parseGitHubUrl", "ValidationError", "owner", "repo", "number", "prResponse", "comments", "reviewsResponse", "reviewComments", "paginateAll", "err", "status", "getHttpStatusCode", "msg", "ghPR", "reviews", "reviewDecision", "determineReviewDecision", "hasMergeConflict", "hasUnrespondedComment", "lastMaintainerComment", "checkUnrespondedComments", "ciPromise", "commitInfoPromise", "res", "ciStatus", "failingCheckNames", "failingCheckConclusions", "commitInfo", "latestCommitDate", "latestCommitAuthor", "hasIncompleteChecklist", "checklistStats", "analyzeChecklist", "maintainerActionHints", "extractMaintainerActionHints", "daysSinceActivity", "daysBetween", "latestChangesRequestedDate", "getLatestChangesRequestedDate", "classifiedChecks", "classifyFailingChecks", "hasActionableCIFailure", "c", "actionReason", "waitReason", "stalenessTier", "determineStatus", "fields", "displayLabel", "displayDescription", "computeDisplayLabel", "mergeable", "mergeableState", "sha", "statusResponse", "checksResponse", "combinedStatus", "allCheckRuns", "latestCheckRunsByName", "check", "existing", "checkRuns", "checkRunAnalysis", "analyzeCheckRuns", "combinedAnalysis", "analyzeCombinedStatus", "mergeStatuses", "statusCode", "starFilter", "fetchUserMergedPRCounts", "fetchUserClosedPRCounts", "repos", "results", "cache", "getHttpCache", "uniqueRepos", "chunkSize", "chunk", "settled", "parts", "name", "url", "data", "cachedRequest", "headers", "chunkFailures", "j", "result", "remaining", "days", "fetchRecentlyClosedPRs", "fetchRecentlyMergedPRs", "recentlyClosedPRs", "recentlyMergedPRs", "now", "needsAddressingPRs", "waitingOnMaintainerPRs", "stats", "wasMerged", "isDocOnlyIssue", "item", "nonEmptyLabels", "l", "n", "DOC_ONLY_LABELS", "isLabelFarming", "BEGINNER_LABELS", "hasTemplatedTitle", "title", "detectLabelFarmingRepos", "items", "spamRepos", "repoSpamCounts", "repoFullName", "repo", "count", "applyPerRepoCap", "candidates", "maxPerRepo", "repoCounts", "kept", "c", "init_issue_filtering", "__esmMin", "calculateRepoQualityBonus", "stargazersCount", "forksCount", "bonus", "calculateViabilityScore", "params", "score", "updatedAt", "daysSinceUpdate", "daysBetween", "init_issue_scoring", "__esmMin", "init_utils", "repoBelongsToCategory", "repoFullName", "categories", "owner", "category", "orgs", "CATEGORY_ORGS", "org", "getTopicsForCategories", "topics", "categoryTopics", "CATEGORY_TOPICS", "topic", "init_category_mapping", "__esmMin", "pruneCache", "now", "key", "value", "guidelinesCache", "CACHE_TTL_MS", "CACHE_MAX_SIZE", "toRemove", "a", "b", "MODULE", "MAX_CONCURRENT_REQUESTS", "HEALTH_CACHE_TTL_MS", "IssueVetter", "init_issue_vetting", "__esmMin", "init_pagination", "init_utils", "init_errors", "init_logger", "init_http_cache", "init_issue_scoring", "init_category_mapping", "DEFAULT_CONCURRENCY", "octokit", "stateManager", "issueUrl", "parsed", "parseGitHubUrl", "ValidationError", "owner", "repo", "number", "repoFullName", "ghIssue", "existingPRCheck", "claimCheck", "projectHealth", "contributionGuidelines", "userMergedPRCount", "noExistingPR", "notClaimed", "clearRequirements", "projectActive", "vettingResult", "trackedIssue", "l", "reasonsToSkip", "reasonsToApprove", "config", "repoScoreRecord", "effectiveMergedCount", "orgName", "orgHasMergedPRs", "rs", "projectCategories", "matchesCategory", "repoBelongsToCategory", "recommendation", "hasInconclusiveChecks", "repoQualityBonus", "calculateRepoQualityBonus", "repoScore", "viabilityScore", "calculateViabilityScore", "starredRepos", "preferredOrgs", "searchPriority", "o", "urls", "maxResults", "priority", "candidates", "pending", "failedVettingCount", "rateLimitFailures", "attemptedCount", "url", "task", "candidate", "error", "isRateLimitError", "warn", "errorMessage", "allFailed", "issueNumber", "data", "linkedPRs", "paginateAll", "page", "event", "e", "errMsg", "commentCount", "recentComments", "response", "claimPhrases", "comment", "body", "phrase", "cache", "getHttpCache", "healthCacheKey", "cachedTimeBased", "repoData", "cachedRequest", "headers", "commits", "lastCommitAt", "daysSinceLastCommit", "daysBetween", "ciStatus", "workflows", "cacheKey", "cached", "filesToCheck", "results", "file", "i", "result", "guidelines", "msg", "content", "lowerContent", "branchMatch", "commitMatch", "hasSteps", "hasCodeBlock", "hasExpectedBehavior", "fs", "path", "MODULE", "SEARCH_CACHE_TTL_MS", "IssueDiscovery", "init_issue_discovery", "__esmMin", "init_github", "init_state", "init_utils", "init_types", "init_errors", "init_logger", "init_http_cache", "init_issue_filtering", "init_issue_vetting", "init_issue_scoring", "init_category_mapping", "githubToken", "getOctokit", "getStateManager", "IssueVetter", "params", "cacheKey", "cachedTimeBased", "getHttpCache", "data", "info", "starredRepos", "iterator", "pageCount", "repos", "repo", "fullName", "error", "cachedRepos", "errMsg", "errorMessage", "warn", "items", "filterIssues", "excludedRepoSets", "remainingNeeded", "minStars", "phaseLabel", "spamRepos", "detectLabelFarmingRepos", "spamCount", "i", "debug", "itemsToVet", "item", "repoFullName", "s", "results", "allVetFailed", "rateLimitHit", "starFiltered", "c", "starFilteredCount", "options", "config", "languages", "labels", "maxResults", "allCandidates", "phase0Error", "phase1Error", "rateLimitHitDuringSearch", "rateLimit", "checkRateLimit", "resetTime", "getHttpStatusCode", "mergedPRRepos", "mergedPRRepoSet", "openPRRepos", "starredRepoSet", "lowScoringRepos", "trackedUrls", "excludedRepos", "maxAgeDays", "now", "labelQuery", "l", "langQuery", "establishedQuery", "baseQuery", "includeDocIssues", "aiBlocklisted", "DEFAULT_CONFIG", "updatedAt", "daysBetween", "isDocOnlyIssue", "phase0Repos", "r", "phase0RepoSet", "mergedInPhase0", "openInPhase0", "mergedPhase0Repos", "mergedCandidates", "allBatchesFailed", "openPhase0Repos", "openCandidates", "msg", "phase0_5Error", "preferredOrgs", "phase0Orgs", "orgsToSearch", "org", "orgRepoFilter", "orgQuery", "filtered", "orgCandidates", "isRateLimitError", "reposToSearch", "starredCandidates", "phase2Error", "seenRepos", "vetRateLimitHit", "phase3Error", "thirtyDaysAgo", "pushedSince", "categoryTopics", "getTopicsForCategories", "topicQuery", "phase3Query", "phaseErrors", "details", "ValidationError", "a", "b", "priorityOrder", "priorityDiff", "recommendationOrder", "recDiff", "applyPerRepoCap", "priority", "filterFn", "candidates", "batches", "failedBatches", "rateLimitFailures", "batch", "repoFilter", "batchQuery", "vetted", "batchRepos", "batchSize", "issueUrl", "body", "calculateViabilityScore", "sorted", "outputDir", "getDataDir", "outputFile", "timestamp", "content", "candidate", "issue", "viabilityScore", "recommendation", "truncatedLabels", "truncatedTitle", "updatedDate", "recIcon", "vettingResult", "projectHealth", "reasonsToApprove", "reasonsToSkip", "key", "passed", "n", "MODULE", "MAX_CONCURRENT_REQUESTS", "MAINTAINER_ASSOCIATIONS", "IssueConversationMonitor", "init_issue_conversation", "__esmMin", "init_github", "init_comment_utils", "init_pagination", "init_state", "init_utils", "init_concurrency", "init_errors", "init_logger", "DEFAULT_CONCURRENCY", "githubToken", "getOctokit", "getStateManager", "maxDays", "config", "ConfigurationError", "username", "cutoffDate", "since", "debug", "data", "warn", "trackedIssues", "trackedIssueKeys", "i", "blocklist", "r", "candidates", "item", "parsed", "extractOwnerRepo", "owner", "repo", "repoFullName", "isOwnRepo", "org", "results", "failures", "runWorkerPool", "issue", "error", "msg", "errorMessage", "statusOrder", "a", "b", "splitRepo", "allComments", "paginateAll", "page", "timeline", "comment", "author", "userLastComment", "entry", "userLastCommentTime", "userMention", "isDirectedAtUser", "lastResponse", "isBotAuthor", "isAcknowledgmentComment", "labels", "l", "base", "daysBetween", "status", "e", "applyStatusOverrides", "prs", "state", "overrides", "stateManager", "getStateManager", "overrideUrls", "didAutoClear", "result", "pr", "override", "VALID_OVERRIDE_STATUSES", "warn", "err", "errorMessage", "buildRepoMap", "label", "repoMap", "existing", "toShelvedPRRef", "groupPRsByRepo", "groups", "repo", "repoPRs", "computeRepoSignals", "isResponsive", "STALE_STATUSES", "hasActiveMaintainers", "assessCapacity", "activePRs", "maxActivePRs", "shelvedPRCount", "activePRCount", "criticalIssueCount", "CRITICAL_ACTION_REASONS", "underPRLimit", "noCriticalIssues", "hasCapacity", "reason", "shelvedNote", "reasons", "collectActionableIssues", "lastDigestAt", "issues", "actionPRs", "lastDigestTime", "reasonOrder", "type", "createdTime", "isNewContribution", "computeActionMenu", "actionableIssues", "capacity", "commentedIssues", "issueResponses", "i", "items", "hasActionableIssues", "hasIssueResponses", "isSingle", "formatBriefSummary", "digest", "issueCount", "issueResponseCount", "attentionText", "issueReplyText", "formatSummary", "lines", "mergedDate", "closedDate", "issue", "timeAgo", "formatRelativeTime", "capacityIcon", "capacityLabel", "printDigest", "CRITICAL_STATUSES", "init_daily_logic", "__esmMin", "init_utils", "init_logger", "init_errors", "init_state", "computeContributionStats", "input", "repoScores", "activePRCount", "totalMerged", "totalClosed", "repoEntries", "score", "total", "mergeRate", "a", "b", "init_stats", "__esmMin", "fetchPRTemplate", "octokit", "owner", "repo", "path", "TEMPLATE_PATHS", "debug", "MODULE", "data", "template", "err", "getHttpStatusCode", "isRateLimitOrAuthError", "msg", "errorMessage", "warn", "init_pr_template", "__esmMin", "init_logger", "init_errors", "init_core", "__esmMin", "init_state", "init_pr_monitor", "init_issue_discovery", "init_issue_conversation", "init_comment_utils", "init_github", "init_utils", "init_errors", "init_logger", "init_http_cache", "init_daily_logic", "init_stats", "init_pr_template", "init_types", "deduplicateDigest", "digest", "toUrls", "prs", "pr", "compactActionableIssues", "issues", "issue", "compactRepoGroups", "groups", "group", "jsonSuccess", "data", "jsonError", "message", "outputJson", "outputJsonError", "init_json", "__esmMin", "buildDashboardStats", "digest", "state", "storedMergedCount", "storedClosedCount", "summary", "minStars", "mergedPRs", "aggregateClosedCount", "sum", "s", "isBelowMinStars", "closedPRs", "mergeMonthlyCounts", "existing", "fresh", "merged", "month", "count", "updateMonthlyAnalytics", "prs", "monthlyCounts", "monthlyClosedCounts", "openedFromMerged", "openedFromClosed", "stateManager", "getStateManager", "error", "warn", "MODULE", "errorMessage", "combinedOpenedCounts", "pr", "fetchDashboardData", "token", "prMonitor", "PRMonitor", "issueMonitor", "IssueConversationMonitor", "octokit", "getOctokit", "config", "starFilter", "buildStarFilter", "watermark", "closedWatermark", "failures", "recentlyClosedPRs", "recentlyMergedPRs", "mergedResult", "closedResult", "fetchedIssues", "newMergedPRs", "newClosedPRs", "err", "isRateLimitOrAuthError", "emptyPRCountsResult", "msg", "fetchMergedPRsSince", "fetchClosedPRsSince", "commentedIssues", "allMergedPRs", "storedToMergedPRs", "allClosedPRs", "storedToClosedPRs", "shelvedUrls", "freshShelved", "toShelvedPRRef", "stored", "results", "skipped", "parsed", "parseGitHubUrl", "computePRsByRepo", "prsByRepo", "repo", "score", "computeTopRepos", "limit", "a", "b", "getMonthlyData", "init_dashboard_data", "__esmMin", "init_core", "init_errors", "init_logger", "init_github_stats", "init_utils", "init_types", "init_daily", "daily_exports", "__export", "CRITICAL_STATUSES", "applyStatusOverrides", "assessCapacity", "buildStarFilter", "collectActionableIssues", "computeActionMenu", "computeRepoSignals", "executeDailyCheck", "formatBriefSummary", "formatSummary", "groupPRsByRepo", "printDigest", "runDaily", "runDailyForDisplay", "toShelvedPRRef", "state", "minStars", "knownStarCounts", "repo", "score", "fetchPRData", "prMonitor", "token", "prs", "failures", "warn", "MODULE", "getStateManager", "starFilter", "issueMonitor", "IssueConversationMonitor", "mergedResult", "closedResult", "recentlyClosedPRs", "recentlyMergedPRs", "issueConversationResult", "err", "isRateLimitOrAuthError", "errorMessage", "emptyPRCountsResult", "error", "msg", "commentedIssues", "mergedCounts", "monthlyCounts", "openedFromMerged", "closedCounts", "monthlyClosedCounts", "openedFromClosed", "updateRepoScores", "stateManager", "existingReposWithMerges", "s", "mergedCountFailures", "count", "lastMergedAt", "existingReposWithClosed", "closedCountFailures", "repoSignals", "signalUpdateFailures", "signals", "allRepos", "starCounts", "starUpdateFailures", "stars", "trustSyncFailures", "partitionPRs", "overriddenPRs", "shelvedPRs", "autoUnshelvedPRs", "activePRs", "pr", "digest", "generateDigestOutput", "previousLastDigestAt", "capacity", "hasAutoUndismissed", "filteredCommentedIssues", "issue", "dismissedAt", "responseTime", "dismissTime", "issueResponses", "i", "summary", "actionableIssues", "briefSummary", "actionMenu", "repoGroups", "toDailyOutput", "result", "deduplicateDigest", "compactActionableIssues", "compactRepoGroups", "executeDailyCheckInternal", "PRMonitor", "updateMonthlyAnalytics", "requireGitHubToken", "init_daily", "__esmMin", "init_core", "init_errors", "init_logger", "init_github_stats", "init_dashboard_data", "init_json", "status_exports", "__export", "runStatus", "options", "stateManager", "getStateManager", "stats", "state", "lastUpdated", "_totalTracked", "outputStats", "output", "init_status", "__esmMin", "init_core", "search_exports", "__export", "runSearch", "options", "token", "requireGitHubToken", "discovery", "IssueDiscovery", "candidates", "stateManager", "getStateManager", "config", "excludedRepos", "aiPolicyBlocklist", "DEFAULT_CONFIG", "searchOutput", "c", "repoScoreRecord", "init_search", "__esmMin", "init_core", "validateGitHubUrl", "url", "pattern", "entityType", "examples", "ValidationError", "validateUrl", "MAX_URL_LENGTH", "validateMessage", "message", "MAX_MESSAGE_LENGTH", "validateGitHubUsername", "username", "trimmed", "MAX_USERNAME_LENGTH", "USERNAME_CHARS_PATTERN", "CONSECUTIVE_HYPHENS_PATTERN", "PR_URL_PATTERN", "ISSUE_URL_PATTERN", "ISSUE_OR_PR_URL_PATTERN", "init_validation", "__esmMin", "init_errors", "vet_exports", "__export", "runVet", "options", "validateUrl", "validateGitHubUrl", "ISSUE_URL_PATTERN", "token", "requireGitHubToken", "candidate", "IssueDiscovery", "init_vet", "__esmMin", "init_core", "init_validation", "track_exports", "__export", "runTrack", "runUntrack", "options", "validateUrl", "validateGitHubUrl", "PR_URL_PATTERN", "token", "requireGitHubToken", "octokit", "getOctokit", "parsed", "parseGitHubUrl", "owner", "repo", "number", "ghPR", "init_track", "__esmMin", "init_core", "init_validation", "init_utils", "read_exports", "__export", "runRead", "options", "validateUrl", "init_read", "__esmMin", "init_validation", "comments_exports", "__export", "runClaim", "runComments", "runPost", "options", "validateUrl", "validateGitHubUrl", "PR_URL_PATTERN", "token", "requireGitHubToken", "stateManager", "getStateManager", "octokit", "getOctokit", "parsed", "parseGitHubUrl", "owner", "repo", "pull_number", "pr", "reviewComments", "issueComments", "reviews", "paginateAll", "page", "username", "filterComment", "c", "relevantReviewComments", "a", "b", "relevantIssueComments", "relevantReviews", "r", "ISSUE_OR_PR_URL_PATTERN", "validateMessage", "number", "comment", "ISSUE_URL_PATTERN", "message", "error", "init_comments", "__esmMin", "init_core", "init_pagination", "init_validation", "config_exports", "__export", "runConfig", "options", "stateManager", "getStateManager", "currentConfig", "value", "validateGitHubUsername", "parts", "valueLower", "r", "currentOrgs", "o", "init_config", "__esmMin", "init_core", "init_validation", "init_exports", "__export", "runInit", "options", "validateGitHubUsername", "stateManager", "getStateManager", "init_init", "__esmMin", "init_core", "init_validation", "setup_exports", "__export", "runCheckSetup", "runSetup", "parsePositiveInt", "value", "settingName", "parsed", "ValidationError", "options", "stateManager", "getStateManager", "config", "results", "warnings", "setting", "key", "valueParts", "validateGitHubUsername", "maxPRs", "dormant", "approaching", "l", "stars", "entries", "r", "valid", "invalid", "entry", "normalized", "categories", "c", "validCategories", "invalidCategories", "cat", "PROJECT_CATEGORIES", "dedupedCategories", "orgs", "o", "validOrgs", "org", "dedupedOrgs", "DEFAULT_CONFIG", "init_setup", "__esmMin", "init_core", "init_errors", "init_validation", "init_types", "getDashboardPidPath", "getDataDir", "writeDashboardServerInfo", "info", "readDashboardServerInfo", "content", "parsed", "warn", "MODULE", "err", "removeDashboardServerInfo", "isDashboardServerRunning", "port", "resolve", "req", "res", "findRunningDashboardServer", "code", "http", "fs", "path", "init_dashboard_process", "__esmMin", "init_core", "init_logger", "sleep", "ms", "resolve", "launchDashboardServer", "options", "resolveAssetsDir", "existing", "findRunningDashboardServer", "info", "readDashboardServerInfo", "currentVersion", "getCLIVersion", "killed", "err", "removeDashboardServerInfo", "port", "DEFAULT_PORT", "cliPath", "child", "spawnFailed", "childExited", "code", "i", "MAX_POLL_ATTEMPTS", "POLL_INTERVAL_MS", "isDashboardServerRunning", "import_child_process", "init_dashboard_lifecycle", "__esmMin", "init_dashboard_process", "init_dashboard", "init_core", "startup_exports", "__export", "countIssueListItems", "detectIssueList", "openInBrowser", "parseIssueListPathFromConfig", "runStartup", "configContent", "match", "pathMatch", "content", "availableCount", "completedCount", "lines", "line", "issueListPath", "source", "configPath", "configuredPath", "error", "errorMessage", "probes", "probe", "url", "openCmd", "args", "version", "getCLIVersion", "stateManager", "getStateManager", "autoDetected", "detectedUsername", "detectGitHubUsername", "err", "token", "getGitHubToken", "daily", "executeDailyCheck", "dashboardUrl", "dashboardOpened", "spaResult", "launchDashboardServer", "issueList", "fs", "import_child_process", "init_startup", "__esmMin", "init_core", "init_errors", "init_daily", "init_dashboard_lifecycle", "RateLimiter", "init_rate_limiter", "__esmMin", "config", "now", "windowStart", "t", "retryAfterMs", "move_exports", "__export", "VALID_TARGETS", "runMove", "options", "validateUrl", "validateGitHubUrl", "PR_URL_PATTERN", "target", "stateManager", "getStateManager", "status", "label", "lastActivityAt", "clearedOverride", "unshelved", "_exhaustive", "init_move", "__esmMin", "init_core", "init_validation", "dashboard_server_exports", "__export", "findRunningDashboardServer", "getDashboardPidPath", "isDashboardServerRunning", "readDashboardServerInfo", "removeDashboardServerInfo", "startDashboardServer", "writeDashboardServerInfo", "buildDashboardJson", "digest", "state", "commentedIssues", "allMergedPRs", "allClosedPRs", "prsByRepo", "computePRsByRepo", "topRepos", "computeTopRepos", "monthlyMerged", "monthlyOpened", "monthlyClosed", "getMonthlyData", "mergedPRs", "storedToMergedPRs", "getStateManager", "closedPRs", "storedToClosedPRs", "minStars", "repoScores", "isAboveMinStars", "pr", "isBelowMinStars", "filteredMergedPRs", "filteredClosedPRs", "stats", "buildDashboardStats", "dismissedIssues", "issueResponses", "i", "repo", "data", "applyStatusOverrides", "readBody", "req", "maxBytes", "MAX_BODY_BYTES", "resolve", "reject", "chunks", "totalLength", "aborted", "chunk", "err", "setSecurityHeaders", "res", "isValidOrigin", "port", "origin", "sendJson", "statusCode", "body", "sendError", "message", "options", "requestedPort", "assetsDir", "token", "open", "stateManager", "resolvedAssetsDir", "cachedDigest", "cachedCommentedIssues", "cachedJsonData", "error", "errorMessage", "dataLimiter", "RateLimiter", "actionLimiter", "refreshLimiter", "server", "method", "url", "check", "warn", "MODULE", "actualPort", "handleAction", "handleRefresh", "serveStaticFile", "REQUEST_TIMEOUT_MS", "raw", "e", "isBodyTooLarge", "VALID_ACTIONS", "isDismiss", "validateUrl", "validateGitHubUrl", "ISSUE_URL_PATTERN", "PR_URL_PATTERN", "ValidationError", "VALID_TARGETS", "runMove", "_req", "currentToken", "getGitHubToken", "result", "fetchDashboardData", "requestUrl", "urlPath", "relativePath", "filePath", "ext", "contentType", "MIME_TYPES", "content", "MAX_PORT_ATTEMPTS", "attempt", "nodeErr", "getCLIVersion", "serverUrl", "openInBrowser", "shutdown", "http", "fs", "path", "init_dashboard_server", "__esmMin", "init_core", "init_errors", "init_logger", "init_validation", "init_dashboard_data", "init_startup", "init_dashboard_process", "init_rate_limiter", "init_types", "dashboard_exports", "__export", "resolveAssetsDir", "serveDashboard", "devPath", "bundlePath", "dashboardPkgPath", "dashboardDist", "error", "options", "assetsDir", "token", "getGitHubToken", "startDashboardServer", "fs", "path", "init_dashboard", "__esmMin", "init_core", "parse_list_exports", "__export", "parseIssueList", "runParseList", "extractGitHubUrl", "line", "match", "prMatch", "extractTitle", "cleaned", "isCompleted", "content", "lines", "available", "completed", "currentTier", "headingMatch", "ghUrl", "title", "item", "options", "filePath", "error", "msg", "errorMessage", "fs", "path", "init_parse_list", "__esmMin", "init_errors", "check_integration_exports", "__export", "runCheckIntegration", "getImportName", "filePath", "ext", "base", "suggestEntryPoints", "newFile", "existingFiles", "dir", "suggestions", "indexFile", "parentDir", "parentIndex", "options", "newFiles", "output", "error", "msg", "errorMessage", "codeFiles", "f", "CODE_EXTENSIONS", "IGNORED_PATTERNS", "p", "allFiles", "err", "debug", "results", "importName", "fileWithoutExt", "referencedBy", "patterns", "pattern", "grepOutput", "matches", "exitCode", "isIntegrated", "info", "unreferencedCount", "r", "path", "import_child_process", "init_check_integration", "__esmMin", "init_core", "init_errors", "local_repos_exports", "__export", "runLocalRepos", "scanForRepos", "getGitHubRemote", "repoPath", "remoteUrl", "httpsMatch", "sshMatch", "err", "debug", "getCurrentBranch", "scanPaths", "repos", "scanPath", "gitDirs", "output", "gitDir", "remote", "currentBranch", "options", "stateManager", "getStateManager", "state", "p", "DEFAULT_SCAN_PATHS", "cache", "cachedAt", "error", "msg", "errorMessage", "fs", "path", "os", "import_child_process", "init_local_repos", "__esmMin", "init_core", "init_errors", "dismiss_exports", "__export", "runDismiss", "runUndismiss", "options", "validateUrl", "validateGitHubUrl", "ISSUE_URL_PATTERN", "stateManager", "getStateManager", "added", "removed", "init_dismiss", "__esmMin", "init_core", "init_validation", "pr_template_exports", "__export", "runPRTemplate", "opts", "owner", "repo", "splitRepo", "token", "requireGitHubToken", "octokit", "getOctokit", "fetchPRTemplate", "init_pr_template", "__esmMin", "init_github", "init_utils", "stats_exports", "__export", "formatStatsBadge", "formatStatsMarkdown", "runStats", "state", "getStateManager", "activePRCount", "stats", "computeContributionStats", "lines", "repo", "pickBadgeColor", "init_stats", "__esmMin", "init_core", "import_index", "program", "createCommand", "createArgument", "createOption", "CommanderError", "InvalidArgumentError", "InvalidOptionArgumentError", "Command", "Argument", "Option", "Help", "commander", "init_core", "init_errors", "init_json", "handleCommandError", "err", "json", "msg", "errorMessage", "outputJsonError", "printRepos", "repos", "entries", "a", "b", "remote", "info", "branch", "commands", "program", "options", "runDaily", "data", "outputJson", "runDailyForDisplay", "printDigest", "result", "runStatus", "count", "runSearch", "maxResults", "parsed", "MAX_SEARCH_RESULTS", "candidate", "issue", "recommendation", "reasonsToApprove", "reasonsToSkip", "viabilityScore", "issueUrl", "runVet", "prUrl", "runTrack", "runUntrack", "runRead", "runComments", "formatRelativeTime", "REVIEW_STATE_LABELS", "review", "state", "time", "comment", "url", "messageParts", "message", "chunks", "chunk", "runPost", "runClaim", "key", "value", "runConfig", "username", "runInit", "runSetup", "w", "prompt", "currentVal", "defaultVal", "runCheckSetup", "port", "serveDashboard", "filePath", "runParseList", "resolvedPath", "item", "runCheckIntegration", "file", "status", "runLocalRepos", "runStartup", "runMove", "target", "runDismiss", "runUndismiss", "validStatuses", "repo", "runPRTemplate", "runStats", "formatStatsMarkdown", "formatStatsBadge", "VERSION", "getCLIVersion", "program", "Command", "localOnlySet", "commands", "c", "cmd", "thisCommand", "actionCommand", "enableDebug", "debug", "commandName", "getGitHubTokenAsync"]
|
|
7
|
-
}
|