infra-kit 0.3.11 → 0.3.13
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/{chunk-KPQTJQ42.js → chunk-DPCWCXJD.js} +2 -2
- package/dist/{chunk-KPQTJQ42.js.map → chunk-DPCWCXJD.js.map} +2 -2
- package/dist/chunk-LMAO6FEM.js +238 -0
- package/dist/chunk-LMAO6FEM.js.map +7 -0
- package/dist/{chunk-PZ2AWWGK.js → chunk-QLAQ7F4M.js} +2 -2
- package/dist/{chunk-PZ2AWWGK.js.map → chunk-QLAQ7F4M.js.map} +2 -2
- package/dist/chunk-SHFPI4QA.js +2 -0
- package/dist/{chunk-JXLXSX7Q.js.map → chunk-SHFPI4QA.js.map} +2 -2
- package/dist/{chunk-M46KGMQ6.js → chunk-SSBYKOHY.js} +4 -4
- package/dist/{chunk-M46KGMQ6.js.map → chunk-SSBYKOHY.js.map} +3 -3
- package/dist/cli.js +10 -10
- package/dist/cli.js.map +3 -3
- package/dist/dev-server.js +30 -30
- package/dist/dev-server.js.map +4 -4
- package/dist/{dev-wizard-run-S5HEFLYE.js → dev-wizard-run-XM5L23UP.js} +2 -2
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +4 -4
- package/dist/update-check.js +1 -1
- package/package.json +9 -9
- package/readme.md +1 -1
- package/dist/chunk-JXLXSX7Q.js +0 -2
- package/dist/chunk-VNHAMXNA.js +0 -218
- package/dist/chunk-VNHAMXNA.js.map +0 -7
- /package/dist/{dev-wizard-run-S5HEFLYE.js.map → dev-wizard-run-XM5L23UP.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/commands/audit/audit.ts", "../src/lib/package-config/package-config.ts", "../src/lib/package-validator/fs-utils.ts", "../src/lib/package-validator/package-validator.ts", "../src/lib/package-validator/loader/config-loader.ts", "../src/lib/package-validator/loader/package-discovery.ts", "../src/lib/package-validator/checks/config-check.ts", "../src/lib/package-validator/checks/files-check.ts", "../src/lib/package-validator/checks/scripts-check.ts", "../src/lib/package-validator/checks/turbo-check.ts", "../src/types.ts", "../src/commands/audit/preset-proxy-check.ts", "../src/commands/config-get/config-get.ts", "../src/commands/dev-status/dev-context-reader.ts", "../src/commands/dev-status/dev-status.ts", "../src/commands/doctor/doctor.ts", "../src/commands/doctor/prune-routes.ts", "../src/commands/env-load/env-load.ts", "../src/integrations/doppler/doppler-errors.ts", "../src/integrations/doppler/doppler-project.ts", "../src/integrations/doppler/token-resolver.ts", "../src/lib/workflow-envs/workflow-envs.ts", "../src/lib/project-envs/project-envs.ts", "../src/lib/warm-cache/purge-repo.ts", "../src/lib/warm-cache/warm-cache.ts", "../src/commands/init/agent-files.ts", "../src/lib/managed-block/managed-block.ts", "../src/commands/init/init.ts", "../src/lib/config-bootstrap/config-bootstrap.ts", "../src/lib/config-templates/config-templates.ts", "../src/commands/init/migrate-config.ts", "../src/lib/vendor/factory-config.ts", "../src/lib/vendor/factory-config-schema.ts", "../src/lib/config-overrides/config-overrides.ts", "../src/commands/doctor/report.ts", "../src/commands/env-clear/env-clear.ts", "../src/commands/env-list/env-list.ts", "../src/commands/env-status/env-status.ts", "../src/commands/env-token-list/env-token-list.ts", "../src/lib/redact/redact.ts", "../src/commands/gh-merge-dev/gh-merge-dev.ts", "../src/integrations/gh/gh-cli-auth/gh-cli-auth.ts", "../src/integrations/gh/gh-release-prs/gh-release-prs.ts", "../src/lib/release-utils/release-utils.ts", "../src/integrations/jira/api.ts", "../src/lib/git-guard/git-guard.ts", "../src/lib/prompts/release-picker.ts", "../src/lib/errors/prompt-cancelled-error.ts", "../src/lib/json-output/json-output.ts", "../src/commands/gh-release-deliver/gh-release-deliver.ts", "../src/lib/errors/format-zx-error.ts", "../src/lib/worktrees/remove-worktrees.ts", "../src/commands/gh-release-deploy-all/gh-release-deploy-all.ts", "../src/lib/prompts/env-picker.ts", "../src/lib/workflow-envs/protected-envs.ts", "../src/commands/gh-release-deploy-selected/gh-release-deploy-selected.ts", "../src/commands/gh-release-list/gh-release-list.ts", "../src/commands/release-create/release-create.ts", "../src/lib/version-utils/load-existing-versions.ts", "../src/lib/version-utils/version-utils.ts", "../src/lib/version-utils/next-version.ts", "../src/commands/release-desc-edit/release-desc-edit.ts", "../src/commands/reopen/reopen.ts", "../src/integrations/cursor/add-folders-to-workspace.ts", "../src/integrations/cursor/launch-cursor.ts", "../src/integrations/cursor/reconcile-workspace-folders.ts", "../src/integrations/cursor/remove-folders-from-workspace.ts", "../src/integrations/cursor/resolve-workspace-path.ts", "../src/integrations/cursor/open-cursor-workspace.ts", "../src/integrations/zed/add-folders-to-zed-workspace.ts", "../src/integrations/zed/open-zed-workspace.ts", "../src/integrations/zed/reuse-zed-workspace.ts", "../src/lib/assert-never/assert-never.ts", "../src/integrations/ide/add-ide-worktree-folders.ts", "../src/integrations/ide/open-ide-workspace.ts", "../src/integrations/ide/provider-label.ts", "../src/integrations/ide/remove-ide-worktree-folders.ts", "../src/integrations/ide/types.ts", "../src/lib/project-discovery/project-discovery.ts", "../src/commands/vendor-check/vendor-check.ts", "../src/lib/vendor/hash.ts", "../src/lib/vendor/manifest.ts", "../src/lib/vendor/walk.ts", "../src/lib/vendor/skip-sets.ts", "../src/commands/version/version.ts", "../src/commands/worktrees-add/worktrees-add.ts", "../src/commands/worktrees-list/worktrees-list.ts", "../src/commands/worktrees-remove/worktrees-remove.ts", "../src/commands/worktrees-sync/worktrees-sync.ts", "../src/lib/command-catalog/command-catalog.ts", "../src/lib/node-warnings/node-warnings.ts"],
|
|
4
|
-
"sourcesContent": ["import path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport { getProjectRoot } from 'src/lib/git-utils'\nimport { logger } from 'src/lib/logger'\nimport { ROOT_DEFAULT_RULES } from 'src/lib/package-config'\nimport type { ResolvedPackageRules } from 'src/lib/package-config'\nimport { discoverPackages, pathExists, validatePackage } from 'src/lib/package-validator'\nimport type { PackageValidationResult } from 'src/lib/package-validator'\nimport { defineMcpTool, textContent } from 'src/types'\n\nimport { checkDevPresets } from './preset-proxy-check'\n\n// TODO [DO]: extract `audit` into its own standalone CLI tool, decoupled from infra-kit.\n\ninterface AuditOptions {\n /** Audit every non-vendor workspace package instead of just the current one. */\n all?: boolean\n /** Audit the monorepo root (turbo pipeline + root commands) instead of a package. */\n root?: boolean\n /** Directory to resolve the current package from. Defaults to `process.cwd()`. */\n cwd?: string\n}\n\n/** A directory to audit plus the under-the-hood defaults that apply to it. */\ninterface AuditTarget {\n dir: string\n baseline?: Readonly<ResolvedPackageRules>\n}\n\n/**\n * Walk upward from `start` to the nearest directory containing a package.json.\n * Used so `infra-kit audit` (no `--all`) targets the package whose package.json\n * script invoked it, regardless of the exact working directory.\n *\n * @example\n * await findPackageRoot('/repo/packages/serverless-config/src')\n * // => '/repo/packages/serverless-config'\n */\nconst findPackageRoot = async (start: string): Promise<string> => {\n let current = path.resolve(start)\n\n while (current !== path.dirname(current)) {\n if (await pathExists(path.join(current, 'package.json'))) {\n return current\n }\n\n current = path.dirname(current)\n }\n\n if (await pathExists(path.join(current, 'package.json'))) {\n return current\n }\n\n throw new Error(\n `No package.json found in or above ${start} \u2014 cd into a package directory, or pass --root to audit a monorepo root`,\n )\n}\n\n/**\n * Resolve which directories to audit, and the baseline defaults each uses:\n * `root` \u2192 the monorepo root with {@link ROOT_DEFAULT_RULES}; `all` \u2192 every\n * discovered non-vendor package; otherwise the package walked up from cwd.\n */\nconst resolveTargets = async (options: AuditOptions): Promise<AuditTarget[]> => {\n if (options.root) {\n return [{ dir: await getProjectRoot(), baseline: ROOT_DEFAULT_RULES }]\n }\n\n if (options.all) {\n const dirs = await discoverPackages(await getProjectRoot())\n\n return dirs.map((dir) => {\n return { dir }\n })\n }\n\n return [{ dir: await findPackageRoot(options.cwd ?? process.cwd()) }]\n}\n\n/**\n * Print a package's audit result as doctor-style `[PASS]`/`[FAIL]` lines.\n */\nconst logResult = (result: PackageValidationResult): void => {\n const header = result.passed ? 'PASS' : 'FAIL'\n\n logger.info(`\\n${result.packageName} \u2014 ${header}`)\n\n for (const check of result.checks) {\n const icon = check.status === 'pass' ? '[PASS]' : '[FAIL]'\n\n logger.info(` ${icon} ${check.name}: ${check.message}`)\n }\n}\n\n/**\n * Audit the monorepo root (`root`), every non-vendor workspace package (`all`),\n * or the package resolved by walking up from the working directory (default \u2014\n * the shape used by a package's `\"infra-kit-check\": \"pnpm exec infra-kit audit\"` script). The\n * returned `structuredContent.allPassed` lets the CLI set a non-zero exit code so\n * the audit fails CI; this function never calls `process.exit` so the MCP tool\n * can reuse it.\n *\n * @example\n * // CLI inside packages/serverless-config: `infra-kit audit`\n * await audit() // audits the current package\n * await audit({ all: true }) // audits every non-vendor workspace package\n * await audit({ root: true }) // audits the monorepo root (turbo + root commands)\n */\nexport const audit = async (options: AuditOptions = {}) => {\n const targets = await resolveTargets(options)\n\n const results: PackageValidationResult[] = []\n\n for (const target of targets) {\n results.push(await validatePackage(target.dir, target.baseline))\n }\n\n // Root audit also validates project-level devServersPresets proxy locality (a `local`\n // route override must have its backend launched by the preset). Skipped when the\n // project declares no presets. Only meaningful at the root \u2014 presets live in the\n // project infra-kit.json, not in any single package.\n if (options.root) {\n const presetResult = await checkDevPresets(targets[0]!.dir)\n\n if (presetResult) {\n results.push(presetResult)\n }\n }\n\n for (const result of results) {\n logResult(result)\n }\n\n const allPassed = results.every((result) => {\n return result.passed\n })\n\n logger.info(`\\n${allPassed ? '\u2705 All valid' : '\u274C Audit failed'} (${results.length} checked)`)\n\n const structuredContent = {\n allPassed,\n packages: results.map((result) => {\n return {\n name: result.packageName,\n passed: result.passed,\n checks: result.checks,\n }\n }),\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\nconst auditInputSchema = {\n all: z.boolean().optional().describe('Audit every non-vendor workspace package'),\n root: z.boolean().optional().describe('Audit the monorepo root (turbo pipeline + root commands)'),\n}\n\nconst auditOutputSchema = {\n allPassed: z.boolean().describe('Whether every audited package passed all checks'),\n packages: z\n .array(\n z.object({\n name: z.string(),\n passed: z.boolean(),\n checks: z.array(\n z.object({\n name: z.string(),\n status: z.enum(['pass', 'fail']),\n message: z.string(),\n }),\n ),\n }),\n )\n .describe('Per-package check results'),\n}\n\n// MCP Tool Registration\nexport const auditMcpTool = defineMcpTool({\n name: 'audit',\n description:\n 'Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.',\n inputSchema: auditInputSchema,\n outputSchema: auditOutputSchema,\n handler: (params) => {\n return audit({ all: params.all, root: params.root })\n },\n})\n", "import type { InfraKitPackageConfig } from '@slip-stream-kit/config'\n\n/**\n * Audit POLICY: the baselines a package's `infra-kit.config.ts` is resolved against, and the merge\n * that resolves it.\n *\n * The config-authoring surface (`defineConfig`, the `InfraKit*` types, `packageConfigSchema`) lives in\n * `@slip-stream-kit/config` \u2014 a separate npm package a consumer installs locally. The baselines\n * deliberately did NOT move with it: they are decisions this CLI enforces, not a contract a consumer\n * authors against. Shipping them to consumers would freeze audit policy into their lockfiles and make\n * every rule change a coordinated release.\n */\n\n/** Fully-resolved rules with every defaultable field present. */\nexport interface ResolvedPackageRules {\n requiredScripts: string[]\n requiredFiles: string[]\n turboTasks: string[]\n}\n\n/**\n * Baseline rules for a standard TypeScript workspace package, applied to any key\n * a package leaves unset. These are the \"under the hood\" defaults so a conforming\n * package's config can stay empty; non-standard packages override the relevant key.\n */\nexport const DEFAULT_RULES: Readonly<ResolvedPackageRules> = {\n requiredScripts: ['build', 'ts-check', 'eslint-check', 'prettier-check', 'test'],\n requiredFiles: ['tsconfig.json', 'eslint.config.js', 'readme.md'],\n turboTasks: [],\n}\n\n/**\n * Baseline rules for the monorepo root (`infra-kit audit --root`). Checks the\n * root commands, the workspace/turbo files, and that the turbo pipeline defines\n * the expected tasks \u2014 so the root's own config can also stay empty.\n */\nexport const ROOT_DEFAULT_RULES: Readonly<ResolvedPackageRules> = {\n requiredScripts: ['build', 'dev', 'test', 'qa', 'infra-kit-check', 'fix'],\n requiredFiles: ['turbo.json', 'pnpm-workspace.yaml'],\n turboTasks: ['build', 'test', 'ts-check', 'eslint-check', 'prettier-check', 'infra-kit-check'],\n}\n\n/**\n * Merge a parsed package config over a baseline. Each key is replaced wholesale\n * when the package provides it, otherwise the baseline value is used.\n *\n * @example\n * resolvePackageConfig({ requiredScripts: [] })\n * // => { requiredScripts: [], requiredFiles: [...DEFAULT_RULES.requiredFiles], turboTasks: [] }\n */\nexport const resolvePackageConfig = (\n config: InfraKitPackageConfig,\n baseline: Readonly<ResolvedPackageRules> = DEFAULT_RULES,\n): ResolvedPackageRules => {\n return {\n requiredScripts: config.requiredScripts ?? [...baseline.requiredScripts],\n requiredFiles: config.requiredFiles ?? [...baseline.requiredFiles],\n turboTasks: config.turbo?.requiredTasks ?? [...baseline.turboTasks],\n }\n}\n", "import fs from 'node:fs/promises'\n\n/**\n * Resolve whether a path is reachable, suppressing ENOENT into a boolean.\n *\n * @example\n * await pathExists('/etc/hosts') // => true\n * await pathExists('/nope') // => false\n */\nexport const pathExists = async (target: string): Promise<boolean> => {\n try {\n await fs.access(target)\n\n return true\n } catch {\n return false\n }\n}\n", "import path from 'node:path'\n\nimport { DEFAULT_RULES } from 'src/lib/package-config'\nimport type { ResolvedPackageRules } from 'src/lib/package-config'\n\nimport { checkConfig, checkFiles, checkScripts, checkTurbo } from './checks'\nimport { readPackageJson } from './loader'\nimport type { PackageCheck, PackageValidationResult } from './types'\n\n// Re-exported on the historical import path so consumers and tests that reach\n// for the loader through `package-validator` keep resolving after the split.\nexport { discoverPackages, loadPackageConfig } from './loader'\nexport type { PackageCheck, PackageValidationResult } from './types'\n\n/**\n * Validate a single directory against its `infra-kit.config.ts` rules: the config\n * must be present and valid, every required script must be declared, every\n * required file must exist, and (root only) every required turbo task must be\n * defined. When the config fails to load, only that check is reported (the rules\n * are unknown, so the rule-based checks are skipped). `baseline` selects which\n * under-the-hood defaults apply \u2014 package defaults or {@link ROOT_DEFAULT_RULES}.\n *\n * @example\n * const result = await validatePackage('/repo/packages/serverless-config')\n * // result.passed reflects the package's conformance; result.checks lists each check\n */\nexport const validatePackage = async (\n packageDir: string,\n baseline: Readonly<ResolvedPackageRules> = DEFAULT_RULES,\n): Promise<PackageValidationResult> => {\n const pkgJson = await readPackageJson(packageDir)\n const packageName = pkgJson.name ?? path.basename(packageDir)\n\n const { check: configCheck, rules } = await checkConfig(packageDir, baseline)\n const checks: PackageCheck[] = [configCheck]\n\n if (rules) {\n checks.push(...checkScripts(pkgJson.scripts ?? {}, rules.requiredScripts))\n checks.push(...(await checkFiles(packageDir, rules.requiredFiles)))\n checks.push(...(await checkTurbo(packageDir, rules.turboTasks)))\n }\n\n const passed = checks.every((check) => {\n return check.status === 'pass'\n })\n\n return { packageDir, packageName, checks, passed }\n}\n", "import { packageConfigSchema } from '@slip-stream-kit/config/internal'\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { z } from 'zod'\n\nimport { DEFAULT_RULES, resolvePackageConfig } from 'src/lib/package-config'\nimport type { ResolvedPackageRules } from 'src/lib/package-config'\n\nimport { pathExists } from '../fs-utils'\n\n/** Per-package config filename every validated package must provide. */\nexport const PACKAGE_CONFIG_FILE = 'infra-kit.config.ts'\n\ninterface PackageJsonShape {\n name?: string\n scripts?: Record<string, string>\n}\n\n/**\n * Read and JSON-parse a package.json, returning an empty object when it is\n * missing or unreadable so callers can degrade into a clear \"missing\" check.\n */\nexport const readPackageJson = async (packageDir: string): Promise<PackageJsonShape> => {\n try {\n const raw = await fs.readFile(path.join(packageDir, 'package.json'), 'utf-8')\n\n return JSON.parse(raw) as PackageJsonShape\n } catch {\n return {}\n }\n}\n\n/**\n * Load, resolve, and validate a package's `infra-kit.config.ts`.\n *\n * Dynamic-imports the file (ESM), resolves the Vite-style factory or object\n * default export, validates the result against {@link packageConfigSchema}, and\n * merges it over the defaults. Throws a descriptive error when the file is\n * absent or the resolved config violates the schema.\n *\n * @example\n * await loadPackageConfig('/repo/packages/serverless-config')\n * // => { requiredScripts: [], requiredFiles: ['serverless.common.yml'], turboTasks: [] }\n */\nexport const loadPackageConfig = async (\n packageDir: string,\n baseline: Readonly<ResolvedPackageRules> = DEFAULT_RULES,\n): Promise<ResolvedPackageRules> => {\n const configPath = path.join(packageDir, PACKAGE_CONFIG_FILE)\n\n if (!(await pathExists(configPath))) {\n throw new Error(`${PACKAGE_CONFIG_FILE} not found at ${configPath}`)\n }\n\n // Cache-bust with the file mtime so repeated loads (long-running MCP server)\n // pick up edits without a process restart. `.ts` configs load via Node's\n // native type stripping (the repo requires Node >= 24).\n const stat = await fs.stat(configPath)\n const moduleUrl = `${pathToFileURL(configPath).href}?mtime=${Number(stat.mtimeMs)}`\n\n const imported = (await import(moduleUrl)) as { default?: unknown }\n const rawExport = imported.default\n\n if (rawExport === undefined) {\n throw new Error(`${PACKAGE_CONFIG_FILE} at ${configPath} has no default export`)\n }\n\n const resolvedExport = typeof rawExport === 'function' ? await (rawExport as () => unknown)() : rawExport\n\n const parsed = packageConfigSchema.safeParse(resolvedExport)\n\n if (!parsed.success) {\n throw new Error(`Invalid ${PACKAGE_CONFIG_FILE} at ${configPath}: ${z.prettifyError(parsed.error)}`)\n }\n\n return resolvePackageConfig(parsed.data, baseline)\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\nimport yaml from 'yaml'\n\nimport { pathExists } from '../fs-utils'\n\nconst WORKSPACE_FILE = 'pnpm-workspace.yaml'\n\n/**\n * List the immediate child directories of `dir`, returning `[]` when the path\n * can't be read (e.g. the parent glob segment matched a non-existent dir).\n */\nconst listChildDirs = async (dir: string): Promise<string[]> => {\n const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => {\n return []\n })\n\n return entries\n .filter((entry) => {\n return entry.isDirectory()\n })\n .map((entry) => {\n return path.join(dir, entry.name)\n })\n}\n\n/**\n * Apply one glob segment to a set of directories: `*` fans out to every child\n * directory, a literal segment keeps the dirs where that child path exists.\n */\nconst expandSegment = async (dirs: string[], segment: string): Promise<string[]> => {\n const next: string[] = []\n\n for (const dir of dirs) {\n if (segment === '*') {\n next.push(...(await listChildDirs(dir)))\n\n continue\n }\n\n const candidate = path.join(dir, segment)\n\n if (await pathExists(candidate)) {\n next.push(candidate)\n }\n }\n\n return next\n}\n\n/**\n * Expand a single pnpm-workspace glob (only the `*` segment wildcard is\n * supported, which covers every pattern this monorepo uses) into directories.\n */\nconst expandGlob = async (projectRoot: string, pattern: string): Promise<string[]> => {\n let dirs = [projectRoot]\n\n for (const segment of pattern.split('/')) {\n dirs = await expandSegment(dirs, segment)\n }\n\n return dirs\n}\n\n/**\n * Discover validatable workspace packages from `pnpm-workspace.yaml`.\n *\n * Negation patterns (`!\u2026`) and everything under `vendor/` are excluded \u2014\n * vendor is mirrored from `starter-workspace` and is checksum-enforced by\n * `pnpm vendor:check`, so its configs are owned upstream, not here. Only\n * directories that actually contain a package.json are returned.\n *\n * @example\n * await discoverPackages('/repo')\n * // => ['/repo/apps/infra-kit/cli', '/repo/packages/serverless-config']\n */\nexport const discoverPackages = async (projectRoot: string): Promise<string[]> => {\n const raw = await fs.readFile(path.join(projectRoot, WORKSPACE_FILE), 'utf-8')\n const parsed = (yaml.parse(raw) ?? {}) as { packages?: string[] }\n\n const patterns = (parsed.packages ?? []).filter((pattern) => {\n return !pattern.startsWith('!') && !pattern.startsWith('vendor')\n })\n\n const found = new Set<string>()\n\n for (const pattern of patterns) {\n const dirs = await expandGlob(projectRoot, pattern)\n\n for (const dir of dirs) {\n if (await pathExists(path.join(dir, 'package.json'))) {\n found.add(dir)\n }\n }\n }\n\n return [...found].sort()\n}\n", "import { DEFAULT_RULES } from 'src/lib/package-config'\nimport type { ResolvedPackageRules } from 'src/lib/package-config'\n\nimport { PACKAGE_CONFIG_FILE, loadPackageConfig } from '../loader'\nimport type { PackageCheck } from '../types'\n\n/**\n * Build the \"config present and valid\" check, returning the resolved rules when\n * the load succeeds so the caller can run the rule-based checks against them.\n * When the config fails to load the rules are `null` and the caller skips the\n * rule-based checks (the expectations are unknown).\n */\nexport const checkConfig = async (\n packageDir: string,\n baseline: Readonly<ResolvedPackageRules> = DEFAULT_RULES,\n): Promise<{ check: PackageCheck; rules: ResolvedPackageRules | null }> => {\n try {\n const rules = await loadPackageConfig(packageDir, baseline)\n\n return {\n check: { name: PACKAGE_CONFIG_FILE, status: 'pass', message: 'present and valid' },\n rules,\n }\n } catch (err) {\n return {\n check: { name: PACKAGE_CONFIG_FILE, status: 'fail', message: (err as Error).message },\n rules: null,\n }\n }\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport type { PackageCheck } from '../types'\n\n/**\n * Check that every required file exists relative to the package root AND is a\n * regular file. A directory that happens to share the required name fails \u2014 a\n * required `readme.md` must be the file, not a folder.\n */\nexport const checkFiles = async (packageDir: string, requiredFiles: string[]): Promise<PackageCheck[]> => {\n return Promise.all(\n requiredFiles.map(async (file) => {\n const stat = await fs.stat(path.join(packageDir, file)).catch(() => {\n return null\n })\n\n if (!stat) {\n return { name: `file:${file}`, status: 'fail' as const, message: `missing file: ${file}` }\n }\n\n if (!stat.isFile()) {\n return { name: `file:${file}`, status: 'fail' as const, message: `not a file: ${file} (found a directory)` }\n }\n\n return { name: `file:${file}`, status: 'pass' as const, message: 'exists' }\n }),\n )\n}\n", "import type { PackageCheck } from '../types'\n\n/**\n * Check that every required script is present in the package.json `scripts` map\n * and carries a runnable command. A key declared with an empty or whitespace-only\n * value fails as well \u2014 an empty script silently no-ops in CI, so presence alone\n * is not enough.\n */\nexport const checkScripts = (scripts: Record<string, string>, requiredScripts: string[]): PackageCheck[] => {\n return requiredScripts.map((script) => {\n const value = scripts[script]\n\n if (typeof value !== 'string') {\n return { name: `script:${script}`, status: 'fail', message: `missing \"${script}\" in package.json scripts` }\n }\n\n if (value.trim().length === 0) {\n return { name: `script:${script}`, status: 'fail', message: `\"${script}\" is empty in package.json scripts` }\n }\n\n return { name: `script:${script}`, status: 'pass', message: 'defined' }\n })\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport type { PackageCheck } from '../types'\n\nconst TURBO_FILE = 'turbo.json'\n\n/**\n * Check that every required turbo task is defined in turbo.json `tasks`. A root\n * task may be keyed as either `name` or `//#name`, so both forms count as present.\n * Runs only when the resolved rules ask for turbo tasks (the monorepo root).\n *\n * Reports a single clear diagnostic when turbo.json is unreadable or carries no\n * `tasks` object, rather than emitting one identical \"missing task\" line per\n * required task.\n */\nexport const checkTurbo = async (packageDir: string, requiredTasks: string[]): Promise<PackageCheck[]> => {\n if (requiredTasks.length === 0) {\n return []\n }\n\n let parsed: { tasks?: Record<string, unknown> }\n\n try {\n const raw = await fs.readFile(path.join(packageDir, TURBO_FILE), 'utf-8')\n\n parsed = JSON.parse(raw) as { tasks?: Record<string, unknown> }\n } catch (err) {\n return [{ name: TURBO_FILE, status: 'fail', message: `cannot read/parse ${TURBO_FILE}: ${(err as Error).message}` }]\n }\n\n const tasks = parsed.tasks\n\n if (tasks === null || typeof tasks !== 'object') {\n return [{ name: TURBO_FILE, status: 'fail', message: `no \"tasks\" object defined in ${TURBO_FILE}` }]\n }\n\n return requiredTasks.map((task) => {\n const defined = task in tasks || `//#${task}` in tasks\n\n return {\n name: `turbo:${task}`,\n status: defined ? 'pass' : 'fail',\n message: defined ? 'defined' : `missing turbo task \"${task}\" in ${TURBO_FILE}`,\n }\n })\n}\n", "import type { z } from 'zod'\n\nexport interface ToolsExecutionResult<TStructured = Record<string, unknown>> {\n [x: string]: unknown\n content: {\n type: 'text'\n text: string\n }[]\n structuredContent?: TStructured\n}\n\nexport interface RequiredConfirmedOptionArg {\n confirmedCommand: boolean\n}\n\nexport interface McpTool<TIn extends z.ZodRawShape = z.ZodRawShape, TOut extends z.ZodRawShape = z.ZodRawShape> {\n name: string\n description: string\n inputSchema: TIn\n outputSchema: TOut\n /**\n * When true, this tool is gated by the MCP destructive-op confirm gate (see `lib/tool-handler`):\n * a first call WITHOUT `confirm:true` returns a resolved-args gate response instead of running,\n * and only a second call carrying `confirm:true` executes. This is ORTHOGONAL to the\n * `confirmedCommand:true` the boundary always injects (a prompt-skip discriminator, not a gate).\n * Set only on genuinely destructive tools; the default-deny catalog test enforces coverage.\n */\n requiresHumanConfirm?: boolean\n handler: (\n params: z.infer<z.ZodObject<TIn>> & RequiredConfirmedOptionArg,\n ) => Promise<ToolsExecutionResult<z.infer<z.ZodObject<TOut>>>>\n}\n\n/**\n * Build the dual-channel content array shared by every MCP tool. Narrows the\n * literal `type: 'text'` so handlers can use inferred return types without TS\n * widening `type` to `string` \u2014 which would otherwise break assignability\n * against the MCP SDK's content union.\n *\n * @example\n * return {\n * content: textContent(JSON.stringify(structuredContent, null, 2)),\n * structuredContent,\n * }\n */\nexport const textContent = (text: string): ToolsExecutionResult['content'] => {\n return [{ type: 'text', text }]\n}\n\n/**\n * Factory that ties the handler's return type to the declared `outputSchema`\n * so `structuredContent` is checked against the schema at compile time. If a\n * handler accidentally drops or renames a field, TS errors at the registration\n * site rather than at runtime in an MCP client.\n *\n * @example\n * export const envLoadMcpTool = defineMcpTool({\n * name: 'env-load',\n * description: '...',\n * inputSchema: { config: z.string() },\n * outputSchema: {\n * filePath: z.string(),\n * variableCount: z.number(),\n * project: z.string(),\n * config: z.string(),\n * },\n * handler: envLoad,\n * })\n */\nexport const defineMcpTool = <TIn extends z.ZodRawShape, TOut extends z.ZodRawShape>(\n tool: McpTool<TIn, TOut>,\n): McpTool<TIn, TOut> => {\n return tool\n}\n", "/**\n * Root-audit checks for `devServersPresets`: target-key grammar, then proxy locality.\n *\n * Bridges the impure world (project config + discovery + each frontend's loaded\n * `infra-kit.config.ts`) to the pure {@link validatePresetKeys} / {@link validatePresetProxy}\n * rules, then shapes the result as a {@link PackageValidationResult} so it slots into the\n * existing `infra-kit audit --root` output. Skipped (returns null) when the project declares\n * no `devServersPresets`.\n */\nimport { discoverApiApps, discoverUiApps } from 'src/dev/discovery'\nimport { buildPresetProxyContext } from 'src/dev/preset-proxy-context'\nimport type { LoadError } from 'src/dev/preset-proxy-context'\nimport { validatePresetKeys, validatePresetProxy } from 'src/dev/presets'\nimport type { DiscoveredParts } from 'src/dev/presets'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport type { PackageCheck, PackageValidationResult } from 'src/lib/package-validator'\n\n/** Shape validator issues + config load errors into audit check lines (fail-only; caller adds the pass line). */\nconst toFailChecks = (issues: ReturnType<typeof validatePresetProxy>, loadErrors: LoadError[]): PackageCheck[] => {\n return [\n ...loadErrors.map((error): PackageCheck => {\n return {\n name: `devServersPresets:config:${error.app}`,\n status: 'fail',\n message: `could not load apps/${error.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${error.message}`,\n }\n }),\n ...issues.map((issue): PackageCheck => {\n return { name: `devServersPresets:${issue.preset}`, status: 'fail', message: issue.message }\n }),\n ]\n}\n\n/**\n * Run the `devServersPresets` audit for the monorepo root: first the target-key grammar\n * (every key must name an `<app>/api` or `<app>/ui` package), then proxy locality. Returns\n * a synthetic `devServersPresets` validation result (one pass line, or one fail line per\n * bad key / violation / unloadable referenced config), or null when there are no presets\n * to check.\n *\n * @example\n * const result = await checkDevPresets('/repo')\n * // result?.checks[0] => { name: 'devServersPresets:proxy-locality', status: 'pass', message: '\u2026' }\n */\nexport const checkDevPresets = async (root: string): Promise<PackageValidationResult | null> => {\n const presets = (await getInfraKitConfig()).devServersPresets\n\n if (!presets || Object.keys(presets).length === 0) {\n return null\n }\n\n // Grammar first: an unparseable target key makes `resolvePreset` throw, so it has to\n // surface as an audit line here rather than crash every check below it.\n const keyIssues = validatePresetKeys(presets)\n\n if (keyIssues.length > 0) {\n const checks = keyIssues.map((issue): PackageCheck => {\n return { name: `devServersPresets:${issue.preset}`, status: 'fail', message: issue.message }\n })\n\n return { packageDir: root, packageName: 'devServersPresets', checks, passed: false }\n }\n\n const apiApps = discoverApiApps(root)\n const uiApps = discoverUiApps(root)\n const discovered: DiscoveredParts = {\n api: apiApps.map((a) => {\n return a.name\n }),\n ui: uiApps.map((a) => {\n return a.name\n }),\n }\n\n const { ctx, loadErrors } = await buildPresetProxyContext(root, presets, discovered, apiApps)\n\n const failChecks = toFailChecks(validatePresetProxy(presets, ctx), loadErrors)\n\n const checks: PackageCheck[] =\n failChecks.length === 0\n ? [\n {\n name: 'devServersPresets:proxy-locality',\n status: 'pass',\n message: 'every local proxy override resolves to a backend the preset launches',\n },\n ]\n : failChecks\n\n return { packageDir: root, packageName: 'devServersPresets', checks, passed: failChecks.length === 0 }\n}\n", "import { z } from 'zod'\n\nimport { getInfraKitConfig, getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/**\n * Return the fully MERGED infra-kit config \u2014 the exact object every other command sees at runtime, after\n * the three override layers (project `infra-kit.json` \u2192 `~/.infra-kit/infra-kit.json` \u2192\n * `~/.infra-kit/projects/<repo>/infra-kit.json`) are shallow-merged. Read-only introspection: it REUSES\n * {@link getInfraKitConfig} (never re-implements the loader), so an agent sees precisely the resolved\n * config, not a re-derived approximation, and can reason about dev presets / env management / proxy routes\n * without shelling out.\n *\n * Throws the same \"infra-kit.json not found\" error the loader throws when run outside a configured repo \u2014\n * that is an honest failure, not an empty success.\n */\nexport const configGet = async () => {\n const [config, paths] = await Promise.all([getInfraKitConfig(), getInfraKitConfigPaths()])\n\n const topLevelKeys = Object.keys(config).sort()\n\n logger.info(`Merged config for ${paths.projectName} \u2014 ${topLevelKeys.length} section(s): ${topLevelKeys.join(', ')}`)\n logger.info(` source: ${paths.main}`)\n\n const structuredContent = {\n // `config` is the merged object. A typed InfraKitConfig is assignable to Record<string, unknown>.\n config: config as Record<string, unknown>,\n configPath: paths.main,\n projectName: paths.projectName,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\nconst configGetOutputSchema = {\n config: z\n .record(z.string(), z.unknown())\n .describe(\n 'The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, ide, worktrees, envAutoLoad, dev, devServersPresets, and devProxy.',\n ),\n configPath: z\n .string()\n .describe('Absolute path to the project-level infra-kit.json (the base layer / committed source of truth).'),\n projectName: z\n .string()\n .describe(\n 'Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).',\n ),\n}\n\n// MCP Tool Registration\nexport const configGetMcpTool = defineMcpTool({\n name: 'config-get',\n description:\n 'Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the override file. Fails with the loader error when run outside a configured infra-kit repo.',\n inputSchema: {},\n outputSchema: configGetOutputSchema,\n handler: () => {\n return configGet()\n },\n})\n", "import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\n/**\n * The dev-context fragment directory the running dev server writes to. This MIRRORS\n * `DevServerRunner.devContextDir` (see `src/dev/dev-server.ts` \u2014 `path.join(process.cwd(), '.infra-kit',\n * 'dev-context')`): the runner writes ONE `<app>.json` fragment per app it starts, and this reader reads\n * exactly those. Kept as a tiny standalone helper (not imported from the dev-server module) so `dev-status`\n * stays a light, side-effect-free read that never pulls the fastify/chokidar dev stack into its graph.\n */\nexport const getDevContextDir = (cwd: string = process.cwd()): string => {\n return path.join(cwd, '.infra-kit', 'dev-context')\n}\n\n/**\n * Reader-side view of one `<app>.json` fragment (the writer's `DevContextFragment`), plus the fragment\n * file's on-disk mtime \u2014 the AUTHORITATIVE freshness signal. Every field is defensively coerced: a\n * fragment can be half-written (the runner writes tmp-then-rename, but a foreign process or an old wire\n * version could still leave a partial or oddly-typed file), and a status read must never throw on one.\n */\nexport interface DevContextRecord {\n /** App folder name \u2014 the fragment filename without its `.json` suffix. */\n app: string\n /** The app package name the vite helper reads to decide a `local` route. */\n package: string\n /** The ACTUAL bound port the dev server is listening on (the writer is the binder). */\n port: number\n /** PID of the dev-server process that wrote the fragment (ownership / staleness metadata). */\n pid: number\n /** Registered portless hostname for the app. */\n alias: string\n /** Authoritative local origin the vite helper proxies to. */\n origin: string\n /** Release slug the runner recorded for this worktree. */\n release: string\n /** Epoch ms the runner self-reported writing the fragment (writer clock \u2014 may lie; prefer mtime). */\n writtenAt: number\n /** Filesystem mtime of the fragment (epoch ms) \u2014 the authoritative freshness signal. */\n fragmentMtimeMs: number\n}\n\nconst asString = (value: unknown): string => {\n return typeof value === 'string' ? value : ''\n}\n\nconst asNumber = (value: unknown): number => {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\n/**\n * Read every dev-context fragment currently on disk, sorted by app name. Returns `[]` \u2014 never throws \u2014\n * when there is no dev session: a missing directory, an empty directory, an unreadable or corrupt fragment\n * all resolve to \"not present\", which the caller reports as a clean empty status, not an error.\n *\n * Purely reads: it does a `readdirSync` + `statSync` + `readFileSync` per fragment and nothing else. It\n * starts no process and opens no socket, so it cannot bring a dev server up.\n */\nexport const readDevContextFragments = (cwd?: string): DevContextRecord[] => {\n const dir = getDevContextDir(cwd)\n\n let entries: string[]\n\n try {\n entries = fs.readdirSync(dir)\n } catch {\n // No dev-context dir at all \u2192 no active dev session.\n return []\n }\n\n const records: DevContextRecord[] = []\n\n for (const name of entries) {\n // Only committed fragments. The runner writes `<app>.json.<pid>.tmp` before renaming, so a `.json`\n // suffix excludes the in-flight temp files by construction.\n if (!name.endsWith('.json')) continue\n\n const full = path.join(dir, name)\n\n let mtimeMs: number\n let raw: string\n\n try {\n const stat = fs.statSync(full)\n\n if (!stat.isFile()) continue\n\n mtimeMs = stat.mtimeMs\n raw = fs.readFileSync(full, 'utf-8')\n } catch {\n continue\n }\n\n let parsed: unknown\n\n try {\n parsed = JSON.parse(raw)\n } catch {\n // Half-written or non-JSON fragment \u2014 skip it rather than fail the whole read.\n continue\n }\n\n if (parsed === null || typeof parsed !== 'object') continue\n\n const fragment = parsed as Record<string, unknown>\n\n records.push({\n app: name.replace(/\\.json$/, ''),\n package: asString(fragment.package),\n port: asNumber(fragment.port),\n pid: asNumber(fragment.pid),\n alias: asString(fragment.alias),\n origin: asString(fragment.origin),\n release: asString(fragment.release),\n writtenAt: asNumber(fragment.writtenAt),\n fragmentMtimeMs: mtimeMs,\n })\n }\n\n return records.sort((a, b) => {\n return a.app.localeCompare(b.app)\n })\n}\n", "import { z } from 'zod'\n\nimport { defaultIsListening } from 'src/dev/proxy/portless-driver'\nimport { logger } from 'src/lib/logger'\nimport { defineMcpTool, textContent } from 'src/types'\n\nimport { readDevContextFragments } from './dev-context-reader'\n\n/**\n * Injection seams for the handler. All three default to the real world; tests override them so the read is\n * hermetic (a seeded fragment dir, a fixed clock, a stub probe) and NO server is ever spawned.\n */\nexport interface DevStatusDeps {\n /** Clock for the freshness computation. Defaults to `Date.now`. */\n now?: () => number\n /** Root to read `.infra-kit/dev-context` under. Defaults to `process.cwd()`. */\n cwd?: string\n /**\n * TCP liveness probe. Defaults to the engine's OWN probe ({@link defaultIsListening}, a bounded\n * `net.connect`) \u2014 the same one `doctor` uses. `dev-status` NEVER asserts liveness it did not probe:\n * every `live` value below is a real connect result, not an inference from fragment presence.\n */\n isListening?: (port: number) => Promise<boolean>\n}\n\n/**\n * Report what `infra-kit dev` currently has running, by READING the dev-context fragments the dev server\n * writes to `<cwd>/.infra-kit/dev-context/`. Strictly advisory and strictly read-only: it starts no server\n * and only inspects on-disk state plus a bounded TCP probe.\n *\n * Two facts an agent must not conflate are surfaced separately:\n * - PRESENCE + FRESHNESS: a fragment exists and how long ago it was written (`fragmentMtime` /\n * `ageSeconds`, from the file's mtime \u2014 the authoritative signal). A stale fragment is a strong hint a\n * server died without cleaning up.\n * - LIVENESS: whether the app's port answers a TCP connect RIGHT NOW. A fresh fragment with `live:false`\n * is a crashed/killed dev server whose fragment was never removed.\n *\n * When no fragments exist (no dev session, or `dev` cleaned up on exit) it returns `{ active: false,\n * apps: [] }` \u2014 a clean empty result, not an error.\n */\nexport const devStatus = async (deps: DevStatusDeps = {}) => {\n const now = deps.now ?? Date.now\n const isListening = deps.isListening ?? defaultIsListening\n\n const records = readDevContextFragments(deps.cwd)\n const at = now()\n\n const apps = await Promise.all(\n records.map(async (record) => {\n const ageSeconds = Math.max(0, Math.round((at - record.fragmentMtimeMs) / 1000))\n const live = await isListening(record.port)\n\n return {\n app: record.app,\n package: record.package,\n port: record.port,\n pid: record.pid,\n alias: record.alias,\n origin: record.origin,\n release: record.release,\n writtenAt: record.writtenAt > 0 ? new Date(record.writtenAt).toISOString() : null,\n fragmentMtime: new Date(record.fragmentMtimeMs).toISOString(),\n ageSeconds,\n live,\n }\n }),\n )\n\n const active = apps.length > 0\n\n if (!active) {\n logger.info('No active infra-kit dev session (no dev-context fragments found).')\n } else {\n logger.info(`infra-kit dev: ${apps.length} app(s) with a dev-context fragment on disk:`)\n\n for (const app of apps) {\n const liveness = app.live ? 'live' : 'NOT responding'\n const freshness = `written ${app.ageSeconds}s ago`\n\n logger.info(` ${app.app} (${app.package}) \u2192 ${app.origin} on :${app.port} \u2014 ${liveness}, ${freshness}`)\n }\n }\n\n const structuredContent = { active, apps }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\nconst devStatusOutputSchema = {\n active: z\n .boolean()\n .describe(\n 'True when at least one dev-context fragment exists on disk (an infra-kit dev session has apps registered). False means no active dev session was found \u2014 this is a clean result, NOT an error.',\n ),\n apps: z\n .array(\n z.object({\n app: z.string().describe('App folder name (the fragment filename without .json).'),\n package: z.string().describe('The app package name the vite helper reads to decide a local route.'),\n port: z.number().describe('The actual bound port the dev server is listening on.'),\n pid: z\n .number()\n .describe('PID of the dev-server process that wrote the fragment (ownership / staleness metadata).'),\n alias: z.string().describe('Registered portless hostname for the app.'),\n origin: z.string().describe('Authoritative local origin the vite helper proxies to for this app.'),\n release: z.string().describe('Release slug the runner recorded for this worktree.'),\n writtenAt: z\n .string()\n .nullable()\n .describe(\n 'ISO 8601 time the runner self-reported writing the fragment (writer clock \u2014 may be wrong; prefer fragmentMtime). Null when the fragment did not record it.',\n ),\n fragmentMtime: z\n .string()\n .describe('ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal.'),\n ageSeconds: z\n .number()\n .describe(\n 'Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment.',\n ),\n live: z\n .boolean()\n .describe(\n 'Whether a TCP connection to the app port succeeds RIGHT NOW (a real engine liveness probe, not an inference). A fresh fragment with live:false is a crashed or killed dev server whose fragment was not cleaned up.',\n ),\n }),\n )\n .describe('One entry per dev-context fragment on disk, sorted by app name. Empty when no dev session is active.'),\n}\n\n// MCP Tool Registration\nexport const devStatusMcpTool = defineMcpTool({\n name: 'dev-status',\n description:\n 'Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. Returns { active: false, apps: [] } when no dev session is active.',\n inputSchema: {},\n outputSchema: devStatusOutputSchema,\n handler: () => {\n return devStatus()\n },\n})\n", "import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { z } from 'zod'\nimport { $ } from 'zx'\n\nimport { decidePrune, isDevSessionRunning } from 'src/commands/doctor/prune-routes'\nimport { buildDopplerChildEnv } from 'src/commands/env-load/env-load'\nimport { AGENTS_MARKER_END, AGENTS_MARKER_START } from 'src/commands/init/agent-files'\nimport { MARKER_END, MARKER_START, buildShellBlock } from 'src/commands/init/init'\nimport {\n caFingerprintMatches,\n createPortlessDriver,\n defaultIsListening,\n defaultIsProxyServing,\n formatPortlessCommand,\n handshakeChainsToCa,\n listRoutes,\n readCaPath,\n resolvePortlessBin,\n} from 'src/dev/proxy/portless-driver'\nimport type { HandshakeResult, PortlessRoute } from 'src/dev/proxy/portless-driver'\nimport { probeEnvToken, resolveEnvToken } from 'src/integrations/doppler'\nimport type { EnvTokenProbe, EnvTokenSource, ResolvedEnvToken } from 'src/integrations/doppler'\nimport { describeOverrides, readOverrideSummary } from 'src/lib/config-overrides'\nimport { DEFAULT_WARM_TTL_SECONDS, ENV_LOAD_FILE, getProjectWarmCacheDir } from 'src/lib/constants'\nimport { getTokenStorePath, readTokenStore } from 'src/lib/env-tokens'\nimport type { TokenStore } from 'src/lib/env-tokens'\nimport { getProjectRoot } from 'src/lib/git-utils/git-utils'\nimport {\n DEFAULT_DEV_PROXY_PORT,\n getInfraKitConfig,\n getInfraKitConfigPaths,\n resetInfraKitConfigCache,\n resolveConfiguredIdes,\n} from 'src/lib/infra-kit-config'\nimport type { InfraKitConfig } from 'src/lib/infra-kit-config'\nimport { hasManagedBlock } from 'src/lib/managed-block'\nimport { tildify } from 'src/lib/path-display'\nimport { listProjectEnvNames } from 'src/lib/project-envs'\nimport { canonicalizeProjectRoot } from 'src/lib/warm-cache'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/**\n * One diagnosis. `name` is a stable public identifier \u2014 it is returned over MCP, keyed by the report's\n * section map (`report.ts`), and pasted into bug reports \u2014 so renaming one is a breaking change.\n */\nexport interface CheckResult {\n name: string\n status: 'pass' | 'fail'\n message: string\n}\n\nconst checkCommand = async (\n name: string,\n command: string[],\n successMsg: string,\n failMsg: string,\n): Promise<CheckResult> => {\n try {\n await $`${command}`\n\n return { name, status: 'pass', message: successMsg }\n } catch {\n return { name, status: 'fail', message: failMsg }\n }\n}\n\nexport const checkZshrcInitialized = (): CheckResult => {\n const name = 'zshrc init block'\n const zshrcPath = path.join(os.homedir(), '.zshrc')\n\n if (!fs.existsSync(zshrcPath)) {\n return { name, status: 'fail', message: '~/.zshrc not found. Run: infra-kit init' }\n }\n\n const content = fs.readFileSync(zshrcPath, 'utf-8')\n const startIdx = content.indexOf(MARKER_START)\n const endIdx = content.indexOf(MARKER_END)\n\n if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) {\n return {\n name,\n status: 'fail',\n message: 'infra-kit shell block missing from ~/.zshrc. Run: infra-kit init',\n }\n }\n\n const installedBlock = content.slice(startIdx, endIdx + MARKER_END.length).trim()\n const expectedBlock = buildShellBlock().trim()\n\n if (installedBlock !== expectedBlock) {\n return {\n name,\n status: 'fail',\n message: 'infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit init',\n }\n }\n\n return { name, status: 'pass', message: 'infra-kit shell block in ~/.zshrc is up to date' }\n}\n\n/**\n * Surface the state of the project-scoped warm env cache (populated by an\n * auto-loaded shell startup). Informational only \u2014 always passes \u2014 since a\n * missing or stale warm file just means the next auto-load will (re)populate\n * it rather than indicating a problem.\n */\nconst checkWarmCache = async (): Promise<CheckResult> => {\n const name = 'warm cache'\n\n let root: string\n\n try {\n root = await getProjectRoot()\n } catch {\n return { name, status: 'pass', message: 'warm cache: not a git project' }\n }\n\n const canon = canonicalizeProjectRoot(root)\n\n if (!canon) {\n return { name, status: 'pass', message: 'warm cache: unavailable' }\n }\n\n const warmFile = path.join(getProjectWarmCacheDir(canon), ENV_LOAD_FILE)\n\n if (!fs.existsSync(warmFile)) {\n return { name, status: 'pass', message: 'warm cache: none yet (populated on next auto-load)' }\n }\n\n const ageSeconds = Math.floor((Date.now() - fs.statSync(warmFile).mtimeMs) / 1000)\n const ageMinutes = Math.floor(ageSeconds / 60)\n const ttlMinutes = Math.floor(DEFAULT_WARM_TTL_SECONDS / 60)\n\n if (ageSeconds >= DEFAULT_WARM_TTL_SECONDS) {\n return {\n name,\n status: 'pass',\n message: `warm cache: present but stale (${ageMinutes}m old, TTL ${ttlMinutes}m) \u2014 will refresh`,\n }\n }\n\n return { name, status: 'pass', message: `warm cache: present, ${ageMinutes}m old` }\n}\n\nconst checkPnpmWorkspaceVirtualStore = async (): Promise<CheckResult> => {\n const name = 'pnpm enableGlobalVirtualStore'\n\n try {\n const root = await getProjectRoot()\n const yamlPath = path.join(root, 'pnpm-workspace.yaml')\n\n if (!fs.existsSync(yamlPath)) {\n return { name, status: 'fail', message: `pnpm-workspace.yaml not found at ${yamlPath}` }\n }\n\n const content = fs.readFileSync(yamlPath, 'utf-8')\n // eslint-disable-next-line sonarjs/super-linear-regex\n const enabled = /^\\s*enableGlobalVirtualStore\\s*:\\s*true\\s*$/m.test(content)\n\n if (!enabled) {\n return {\n name,\n status: 'fail',\n message: 'enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml',\n }\n }\n\n return { name, status: 'pass', message: 'enableGlobalVirtualStore: true is set' }\n } catch (err) {\n return {\n name,\n status: 'fail',\n message: `Failed to read pnpm-workspace.yaml: ${(err as Error).message}`,\n }\n }\n}\n\n/**\n * The merged infra-kit config, read ONCE per `doctor()` run and threaded into every check that needs\n * it. Either half is populated, never both.\n *\n * Reading it once is not an optimization, it is the fix for a real race: `checkInfraKitConfigValid`\n * and `checkIdeInstalled` each called `resetInfraKitConfigCache()` and were dispatched together\n * inside one `Promise.all`, so they clobbered the same module-level cache slot \u2014 whichever reset\n * landed second could blow away a config the other had just populated. One read, no shared slot.\n */\nexport interface DoctorConfig {\n config: InfraKitConfig | null\n error: Error | null\n}\n\n/**\n * Read the merged config once for the whole run, resetting the module cache exactly once so `doctor`\n * always reports what is on disk NOW (it is the command a user runs right after editing the file).\n * Never throws: a broken config is the thing `doctor` exists to explain, so it is captured and\n * threaded rather than allowed to abort the run.\n *\n * @example\n * await readDoctorConfig() // => { config: { environments: ['dev'], \u2026 }, error: null }\n * // // broken file => { config: null, error: Error('\u2026unrecognized key\u2026') }\n */\nexport const readDoctorConfig = async (): Promise<DoctorConfig> => {\n try {\n resetInfraKitConfigCache()\n\n return { config: await getInfraKitConfig(), error: null }\n } catch (err) {\n return { config: null, error: err as Error }\n }\n}\n\nconst checkInfraKitConfigValid = (read: DoctorConfig): CheckResult => {\n const name = 'infra-kit config valid'\n\n if (read.error) return { name, status: 'fail', message: read.error.message }\n\n return {\n name,\n status: 'pass',\n message: 'infra-kit.json is valid (user overrides applied if present)',\n }\n}\n\n/** Every seam the three token checks touch \u2014 the store, the resolver, Doppler, and the file modes. */\nexport interface EnvTokenCheckDeps {\n /** Reads `tokens.json`. THROWS on a corrupt store (bad JSON / bad shape) \u2014 that throw is the diagnosis. */\n readStore?: () => Promise<TokenStore | null>\n /** Resolves one env's token (`INFRA_KIT_ENV_TOKEN` \u2192 store \u2192 throw). */\n resolveToken?: (env: string) => Promise<ResolvedEnvToken>\n /** Asks Doppler what a token actually is. Never throws; see {@link probeEnvToken}. */\n probe?: (args: { childEnv: NodeJS.ProcessEnv; project: string; config: string }) => Promise<EnvTokenProbe>\n storePath?: () => Promise<string>\n /** `null` = the path does not exist. */\n statPath?: (target: string) => fs.Stats | null\n chmodPath?: (target: string, mode: number) => void\n}\n\n/** `tokens.json` holds live credentials: owner-only, and owner-only traversal to reach it. */\nconst TOKEN_FILE_MODE = 0o600\nconst TOKEN_DIR_MODE = 0o700\n\n/** One env's token as doctor sees it: WHERE it came from, never WHAT it is. */\ninterface EnvTokenEntry {\n env: string\n /** `null` = no token resolves for this env. */\n source: EnvTokenSource | null\n}\n\n/**\n * `env <name>: token (store)` / `env <name>: no token`, for every configured environment. The source\n * ONLY \u2014 a doctor line is printed to a terminal, pasted into a bug report, and returned over MCP, so\n * the one thing it can never carry is the token itself.\n *\n * @example\n * describeEntries([{ env: 'dev', source: 'store' }, { env: 'prod', source: null }])\n * // => 'dev: token (store), prod: no token'\n */\nconst describeEntries = (entries: EnvTokenEntry[]): string => {\n return entries\n .map((entry) => {\n const held = entry.source === null ? 'no token' : `token (${entry.source})`\n\n return `${entry.env}: ${held}`\n })\n .join(', ')\n}\n\n/** Resolve each env's token to a SOURCE, collapsing \"no token\" (a throw) into `source: null`. */\nconst resolveEntries = async (\n environments: string[],\n resolveToken: NonNullable<EnvTokenCheckDeps['resolveToken']>,\n): Promise<EnvTokenEntry[]> => {\n return Promise.all(\n environments.map(async (env): Promise<EnvTokenEntry> => {\n try {\n const { source } = await resolveToken(env)\n\n return { env, source }\n } catch {\n return { env, source: null }\n }\n }),\n )\n}\n\n/**\n * Which envs have a service token, and is the one that MATTERS among them?\n *\n * Under token-only auth the `envAutoLoad.config` env is load-bearing: no token there means the\n * developer's shell silently stops getting its environment, so that one is a FAIL. Every other env is\n * a listing line, not a verdict \u2014 a developer legitimately holds a `dev` token and no `prod` one, and\n * a doctor that failed on that would train everyone to ignore it.\n *\n * @example\n * await checkEnvTokensConfigured({ config, error: null })\n * // => { name: 'env tokens configured', status: 'pass', message: 'auto-load env \"dev\": token (store). dev: token (store), prod: no token' }\n */\nexport const checkEnvTokensConfigured = async (\n read: DoctorConfig,\n deps: EnvTokenCheckDeps = {},\n): Promise<CheckResult> => {\n const name = 'env tokens configured'\n const readStore = deps.readStore ?? readTokenStore\n const resolveToken = deps.resolveToken ?? resolveEnvToken\n\n if (!read.config) {\n return { name, status: 'pass', message: 'Skipped \u2014 infra-kit config could not be read (see config check)' }\n }\n\n // A corrupt store throws for EVERY env, which would otherwise render as \"no token anywhere\" \u2014 the\n // same symptom as a fresh machine, with a completely different fix. Surface the store's own\n // (actionable) error instead, and let the remaining checks still run.\n //\n // There is no longer a \"store belongs to another repo\" case to report here: the store carries no\n // `repoRoot` (see `lib/env-tokens`), so a hand-written store loads and a basename collision between\n // two checkouts is an accepted risk, not a diagnosis. Do not add a branch back for it.\n try {\n await readStore()\n } catch (err) {\n return { name, status: 'fail', message: `Token store unreadable \u2014 ${(err as Error).message}` }\n }\n\n // The env universe is the union of what the workflows declare and what we hold tokens for \u2014 see\n // `lib/project-envs`. It replaces `config.environments`, which was a hand-maintained third copy.\n const envs = await listProjectEnvNames()\n const autoLoadEnv = read.config.envAutoLoad?.config\n\n // The auto-load env is load-bearing whether or not anything declares it: it is what the shell tries\n // to load. Probe it even when no workflow names it, so \"no token for it\" beats \"we never looked\".\n const universe = autoLoadEnv && !envs.includes(autoLoadEnv) ? [...envs, autoLoadEnv] : envs\n\n const entries = await resolveEntries(universe, resolveToken)\n const listing = describeEntries(entries)\n\n if (autoLoadEnv === undefined) {\n return { name, status: 'pass', message: `No envAutoLoad configured \u2014 no env is load-bearing. ${listing}` }\n }\n\n const autoLoadEntry = entries.find((entry) => {\n return entry.env === autoLoadEnv\n })\n\n if (!autoLoadEntry || autoLoadEntry.source === null) {\n return {\n name,\n status: 'fail',\n message:\n `No Doppler service token for the auto-load env \"${autoLoadEnv}\" \u2014 your shell env will not load. ` +\n `Fix: run \\`infra-kit env-token-set ${autoLoadEnv}\\`. ${listing}`,\n }\n }\n\n return {\n name,\n status: 'pass',\n message: `auto-load env \"${autoLoadEnv}\": token (${autoLoadEntry.source}). ${listing}`,\n }\n}\n\n/** The verdict for each probe outcome. `unreachable` is a PASS \u2014 see {@link checkEnvTokenValid}. */\nconst PROBE_VERDICT: Record<EnvTokenProbe['outcome'], { status: CheckResult['status']; describe: string }> = {\n valid: { status: 'pass', describe: 'live and correctly scoped' },\n revoked: { status: 'fail', describe: 'REJECTED by Doppler (revoked or invalid)' },\n 'mis-scoped': { status: 'fail', describe: 'live but scoped to a DIFFERENT config' },\n unreachable: { status: 'pass', describe: 'could not be checked (Doppler unreachable)' },\n}\n\n/**\n * Is the auto-load env's token actually LIVE and correctly SCOPED? The only check here that leaves the\n * machine, and the only one that can tell a developer why their shell went quiet.\n *\n * An UNREACHABLE probe passes, deliberately: a network failure proves nothing about a token, and a\n * doctor that reported \"your token is revoked\" to a developer on a plane would be worse than one that\n * said nothing. The same `null`-means-couldn't-tell contract the Doppler listings always carried.\n *\n * @example\n * await checkEnvTokenValid({ config, error: null })\n * // => { name: 'env token valid', status: 'fail', message: 'The token for env \"dev\" is live but scoped to a DIFFERENT config \u2026' }\n */\nexport const checkEnvTokenValid = async (read: DoctorConfig, deps: EnvTokenCheckDeps = {}): Promise<CheckResult> => {\n const name = 'env token valid'\n const resolveToken = deps.resolveToken ?? resolveEnvToken\n const probe = deps.probe ?? probeEnvToken\n\n if (!read.config) {\n return { name, status: 'pass', message: 'Skipped \u2014 infra-kit config could not be read (see config check)' }\n }\n\n const env = read.config.envAutoLoad?.config\n\n if (env === undefined) {\n return { name, status: 'pass', message: 'Skipped \u2014 no envAutoLoad env to probe' }\n }\n\n let token: string\n\n try {\n token = (await resolveToken(env)).token\n } catch {\n // Already the FAIL of `env tokens configured`; repeating it here would double-count one problem.\n return { name, status: 'pass', message: `Skipped \u2014 no token for env \"${env}\" (see env tokens configured)` }\n }\n\n const project = read.config.envManagement.config.name\n const result = await probe({ childEnv: buildDopplerChildEnv(token), project, config: env })\n const verdict = PROBE_VERDICT[result.outcome]\n const suffix =\n result.outcome === 'revoked' || result.outcome === 'mis-scoped'\n ? ` Fix: run \\`infra-kit env-token-set ${env}\\` with a token scoped to \"${env}\".`\n : ''\n\n return {\n name,\n status: verdict.status,\n message: `The token for env \"${env}\" (project \"${project}\") is ${verdict.describe}.${suffix}`,\n }\n}\n\n/** `-rw-------` / `drwx------` \u2014 the permission bits of a path, or `null` when it does not exist. */\nconst modeOf = (target: string, statPath: NonNullable<EnvTokenCheckDeps['statPath']>): number | null => {\n const stats = statPath(target)\n\n return stats === null ? null : stats.mode & 0o777\n}\n\n/**\n * The token store is a credential file, so it must be 0600, reachable only through 0700 directories.\n * `writeTokenStore` sets all four every time it writes \u2014 so a violation here means something ELSE\n * touched them (an editor's save-and-rename, a `cp -r`, a synced dotfiles dir), which is exactly the\n * case a self-healing writer cannot fix on its own.\n *\n * Skipped when the store does not exist: a machine with no tokens has nothing to protect, and CI\n * (`INFRA_KIT_ENV_TOKEN`) never writes one.\n *\n * @example\n * await checkTokenStorePerms(false)\n * // => { name: 'tokens.json perms', status: 'fail', message: '~/.infra-kit/projects/api/tokens.json is 0644, expected 0600 \u2026' }\n */\nexport const checkTokenStorePerms = async (fix: boolean, deps: EnvTokenCheckDeps = {}): Promise<CheckResult> => {\n const name = 'tokens.json perms'\n const storePath = deps.storePath ?? getTokenStorePath\n const statPath = deps.statPath ?? defaultStatPath\n const chmodPath = deps.chmodPath ?? fs.chmodSync\n\n let target: string\n\n try {\n target = await storePath()\n } catch {\n return { name, status: 'pass', message: 'Skipped \u2014 the token store path could not be resolved' }\n }\n\n if (modeOf(target, statPath) === null) {\n return { name, status: 'pass', message: `No token store yet at ${tildify(target)}` }\n }\n\n // Every directory on the way to the file, plus the file: a 0600 file inside a world-readable\n // directory chain is still a credential a `find` away.\n const projectDir = path.dirname(target)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n const audited: Array<{ target: string; expected: number; actual: number | null }> = [\n { target: userConfigDir, expected: TOKEN_DIR_MODE, actual: modeOf(userConfigDir, statPath) },\n { target: projectsDir, expected: TOKEN_DIR_MODE, actual: modeOf(projectsDir, statPath) },\n { target: projectDir, expected: TOKEN_DIR_MODE, actual: modeOf(projectDir, statPath) },\n { target, expected: TOKEN_FILE_MODE, actual: modeOf(target, statPath) },\n ]\n const loose = audited.filter((entry) => {\n return entry.actual !== null && entry.actual !== entry.expected\n })\n\n if (loose.length === 0) {\n return { name, status: 'pass', message: `${tildify(target)} is 0600 (0700 dirs)` }\n }\n\n const describe = loose\n .map((entry) => {\n return `${tildify(entry.target)} is ${formatMode(entry.actual!)}, expected ${formatMode(entry.expected)}`\n })\n .join('; ')\n\n if (!fix) {\n return {\n name,\n status: 'fail',\n message: `${describe}. Fix: run \\`infra-kit doctor --fix\\`, or chmod them by hand.`,\n }\n }\n\n for (const entry of loose) {\n chmodPath(entry.target, entry.expected)\n }\n\n return { name, status: 'pass', message: `Tightened ${loose.length} path(s): ${describe}` }\n}\n\n/** `0600`, `0755` \u2014 a mode's permission bits in the form a user types at `chmod`. */\nconst formatMode = (mode: number): string => {\n return `0${mode.toString(8).padStart(3, '0')}`\n}\n\n/** `fs.statSync` with \"does not exist\" as a value rather than a throw. */\nconst defaultStatPath = (target: string): fs.Stats | null => {\n try {\n return fs.statSync(target)\n } catch {\n return null\n }\n}\n\n/**\n * Surface where this developer's user-scope override file lives and what it CONTAINS. Always passes\n * (informational) inside a git repo; fails only when the config paths can't be resolved at all.\n *\n * Three-way on purpose. Every non-excluded command now seeds layer 3 in its preAction hook \u2014 and\n * `doctor` is one of them, so by the time this check runs the file should already exist. An ABSENT\n * file therefore no longer means \"not yet created\", it means the seed FAILED (read-only `$HOME`, a\n * sandbox, a locked-down CI image). That failure path is `logger.debug` only, so this line is the\n * ONLY place a permanently-failing seed becomes visible \u2014 it must not be confusable with a healthy\n * empty file. Content reporting is shared with `config path` via `readOverrideSummary` /\n * `describeOverrides` (one JSON-tolerance policy: raw keys, malformed degrades, never throws).\n *\n * @example\n * await checkUserOverridePath()\n * // {\n * // name: 'user override path',\n * // status: 'pass',\n * // message: '~/.infra-kit/projects/api/infra-kit.json (2 override(s): ide, dev) \u2014 project: api',\n * // }\n * // absent -> '\u2026 (not created \u2014 seed failed?) \u2014 project: api'\n * // empty -> '\u2026 (empty \u2014 no overrides) \u2014 project: api'\n * // corrupt -> '\u2026 (unreadable \u2014 invalid JSON) \u2014 project: api'\n */\nexport const checkUserOverridePath = async (): Promise<CheckResult> => {\n const name = 'user override path'\n\n try {\n const paths = await getInfraKitConfigPaths()\n const exists = fs.existsSync(paths.userProject)\n const summary = await readOverrideSummary(paths.userProject, exists)\n const suffix = exists ? describeOverrides(summary) : '(not created \u2014 seed failed?)'\n\n return {\n name,\n status: 'pass',\n message: `${tildify(paths.userProject)} ${suffix} \u2014 project: ${paths.projectName}`,\n }\n } catch (err) {\n return { name, status: 'fail', message: (err as Error).message }\n }\n}\n\n/**\n * Surface a lingering legacy `~/.infra-kit/config.json` left behind after the\n * user-global config was renamed to `infra-kit.json`. The on-`init` auto-rename\n * is the migration path, but a user who edits the file and never re-runs `init`\n * would silently have their overrides stop applying \u2014 this makes that visible.\n *\n * Branches on whether the canonical `infra-kit.json` already exists so the\n * message is accurate: only the \"no infra-kit.json yet\" case means overrides are\n * not being applied; when both exist the legacy file is merely stale.\n * Informational pass (no warning) when the paths can't resolve \u2014 mirrors\n * {@link checkIdeInstalled}: nothing to surface if there's no resolvable target.\n *\n * @example\n * await checkLegacyUserGlobalConfig()\n * // { name: 'legacy user-global config', status: 'fail', message: 'Legacy user-global config.json found \u2026' }\n */\nexport const checkLegacyUserGlobalConfig = async (): Promise<CheckResult> => {\n const name = 'legacy user-global config'\n\n let paths: Awaited<ReturnType<typeof getInfraKitConfigPaths>>\n\n try {\n paths = await getInfraKitConfigPaths()\n } catch {\n return { name, status: 'pass', message: 'Skipped \u2014 infra-kit config paths could not be resolved' }\n }\n\n const legacyPath = path.join(path.dirname(paths.userGlobal), 'config.json')\n\n if (!fs.existsSync(legacyPath)) {\n return { name, status: 'pass', message: 'No legacy user-global config.json' }\n }\n\n if (!fs.existsSync(paths.userGlobal)) {\n return {\n name,\n status: 'fail',\n message: `Legacy user-global config.json found at ${tildify(legacyPath)} \u2014 run \\`infra-kit init\\` to migrate it (your overrides are not being applied).`,\n }\n }\n\n return {\n name,\n status: 'fail',\n message: `Stale legacy config.json found at ${tildify(legacyPath)} \u2014 ${tildify(paths.userGlobal)} is active; remove the old file.`,\n }\n}\n\ninterface IdeProbe {\n ok: boolean\n label: string\n failMsg: string\n}\n\nconst IDE_PROBE_META: Record<'cursor' | 'zed', { command: string[]; label: string; failMsg: string }> = {\n cursor: {\n command: ['cursor', '--version'],\n label: 'Cursor',\n failMsg: 'Cursor is not installed. Install from: https://cursor.com/',\n },\n zed: {\n command: ['zed', '--version'],\n label: 'Zed',\n failMsg: 'Zed is not installed. Install from: https://zed.dev/',\n },\n}\n\nconst probeIde = async (provider: 'cursor' | 'zed'): Promise<IdeProbe> => {\n const meta = IDE_PROBE_META[provider]\n\n try {\n await $`${meta.command}`\n\n return { ok: true, label: meta.label, failMsg: meta.failMsg }\n } catch {\n return { ok: false, label: meta.label, failMsg: meta.failMsg }\n }\n}\n\n/**\n * Check that every editor configured under `ide` is installed. Probes each binary (`cursor`/`zed`)\n * named by the ALREADY-READ config ({@link readDoctorConfig}). Passes only if all configured editors\n * are present; fails listing any that are missing. Informational pass when no IDE is configured or\n * the config can't be read \u2014 an unconfigured editor is a valid setup, and config validity is\n * reported separately by `checkInfraKitConfigValid`.\n *\n * @example\n * await checkIdeInstalled({ config: { ide: [{ provider: 'cursor' }] }, error: null })\n * // => { name: 'ide installed', status: 'pass', message: 'Installed: Cursor' }\n */\nexport const checkIdeInstalled = async (read: DoctorConfig): Promise<CheckResult> => {\n const name = 'ide installed'\n\n if (!read.config) {\n return { name, status: 'pass', message: 'Skipped \u2014 infra-kit config could not be read (see config check)' }\n }\n\n const providers = resolveConfiguredIdes(read.config).map((ide) => {\n return ide.provider\n })\n\n if (providers.length === 0) {\n return { name, status: 'pass', message: 'No IDE configured (ide unset)' }\n }\n\n const probes = await Promise.all(\n providers.map((provider) => {\n return probeIde(provider)\n }),\n )\n const missing = probes.filter((probe) => {\n return !probe.ok\n })\n\n if (missing.length === 0) {\n return {\n name,\n status: 'pass',\n message: `Installed: ${probes\n .map((probe) => {\n return probe.label\n })\n .join(', ')}`,\n }\n }\n\n return {\n name,\n status: 'fail',\n message: missing\n .map((probe) => {\n return probe.failMsg\n })\n .join('; '),\n }\n}\n\nconst RTK_REQUIRED_INDEXES = [1, 2, 3, 5, 7] as const\n\nconst checkRtkConfigured = async (): Promise<CheckResult> => {\n const name = 'rtk configured'\n\n try {\n const result = await $`rtk init --show`\n const statusLines = result.stdout\n .split('\\n')\n .map((l) => {\n return l.trim()\n })\n .filter((l) => {\n return l.startsWith('[ok]') || l.startsWith('[--]')\n })\n\n const failed: number[] = []\n\n for (const idx of RTK_REQUIRED_INDEXES) {\n const line = statusLines[idx - 1]\n\n if (!line || !line.startsWith('[ok]')) {\n failed.push(idx)\n }\n }\n\n if (failed.length > 0) {\n return {\n name,\n status: 'fail',\n message: `rtk setup incomplete (items ${failed.join(', ')} not [ok]). Run: rtk init -g --auto-patch`,\n }\n }\n\n return {\n name,\n status: 'pass',\n message: 'rtk hook, RTK.md, global CLAUDE.md, settings.json, and Cursor hook are configured',\n }\n } catch (err) {\n return {\n name,\n status: 'fail',\n message: `Failed to run 'rtk init --show': ${(err as Error).message}`,\n }\n }\n}\n\n/**\n * Check that the repo agent-instruction guidance managed by `infra-kit init` exists:\n * the guidance block in `CLAUDE.md`. Presence only. Repo-gated: returns no checks\n * when run outside an infra-kit repo so doctor never crashes there. A repo that\n * predates the AGENTS.md\u2192CLAUDE.md migration will report this check as failing until\n * `infra-kit init` is re-run.\n */\nexport const checkAgentFiles = async (): Promise<CheckResult[]> => {\n let mainConfigPath: string\n\n try {\n mainConfigPath = (await getInfraKitConfigPaths()).main\n } catch {\n return []\n }\n\n if (!fs.existsSync(mainConfigPath)) return []\n\n const claudePath = path.join(path.dirname(mainConfigPath), 'CLAUDE.md')\n const content = fs.existsSync(claudePath) ? fs.readFileSync(claudePath, 'utf-8') : ''\n const present = hasManagedBlock(content, AGENTS_MARKER_START, AGENTS_MARKER_END)\n\n return [\n {\n name: 'CLAUDE.md block',\n status: present ? 'pass' : 'fail',\n message: present ? 'CLAUDE.md block present' : 'infra-kit block missing from CLAUDE.md. Run: infra-kit init',\n },\n ]\n}\n\n/**\n * The one-time, out-of-band, ROOT command that installs the `:443` daemon. infra-kit never runs it \u2014 it\n * only ever prints it (principle 3: infra-kit probes and prints, it never elevates).\n *\n * Rendered from the resolved `dist/cli.js`, never as a bare `portless`: portless is an npm dependency in\n * `node_modules`, not a global bin, and `sudo` swaps `PATH` for `secure_path` \u2014 so the bare form cannot\n * resolve under sudo even in a shell where it otherwise would. See {@link formatPortlessCommand}.\n */\nconst installDaemonCmd = (bin: string): string => {\n return formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n}\n\n/** The sudo-free \"trust the local CA\" command, rendered from the same resolved bin. */\nconst trustCmd = (bin: string): string => {\n return formatPortlessCommand(['trust'], { bin })\n}\n\n/** TLS chain failures that mean \"the daemon's cert does not chain to the `ca.pem` we hold\". */\nconst CA_MISMATCH_CODES = new Set(['SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'])\n\n/**\n * A validating probe of an IP literal sends no SNI and lands on portless's default cert, which has no IP\n * SAN \u2014 so this code means OUR probe forgot a `servername`, never that the user's CA went bad. It must\n * never reach a `portless trust` remediation: doing so would tell every correctly-configured user to\n * repair a trust store that is fine.\n */\nconst PROBE_BUG_CODE = 'ERR_TLS_CERT_ALTNAME_INVALID'\n\n/** Every process/fs seam the portless checks touch, injected so tests never reach the real daemon. */\nexport interface PortlessCheckDeps {\n resolveBin?: () => string | null\n isProxyServing?: (port: number, tls: boolean) => Promise<boolean>\n handshake?: (port: number, servername: string) => Promise<HandshakeResult>\n caTrusted?: () => boolean\n routes?: () => PortlessRoute[]\n isListening?: (port: number) => Promise<boolean>\n caPath?: () => string\n}\n\n/** Is the daemon serving portless-over-TLS on the dev proxy port? Proven on the wire; reads no state file. */\nconst checkPortlessServing = async (\n isProxyServing: NonNullable<PortlessCheckDeps['isProxyServing']>,\n bin: string,\n): Promise<CheckResult> => {\n const name = `portless serving TLS on :${DEFAULT_DEV_PROXY_PORT}`\n const serving = await isProxyServing(DEFAULT_DEV_PROXY_PORT, true)\n\n if (!serving) {\n return {\n name,\n status: 'fail',\n message: `No portless daemon is serving HTTPS on :${DEFAULT_DEV_PROXY_PORT}. Install it once (needs root): \\`${installDaemonCmd(bin)}\\`.`,\n }\n }\n\n return { name, status: 'pass', message: `portless is serving HTTPS on :${DEFAULT_DEV_PROXY_PORT}` }\n}\n\n/**\n * Does the daemon serve a certificate that chains to the `ca.pem` on disk? The only check that VALIDATES\n * the chain \u2014 the serving probe above deliberately does not, so that a down daemon and an untrusted CA stay\n * two distinguishable failures with two different fixes.\n *\n * Probes `localhost` (always in the default cert's SANs, so it works on a fresh machine with zero aliases)\n * and, when one is registered, a real alias \u2014 which validates the exact path the browser takes.\n */\nconst checkPortlessCaChain = async (\n handshake: NonNullable<PortlessCheckDeps['handshake']>,\n routes: PortlessRoute[],\n caPath: string,\n bin: string,\n): Promise<CheckResult> => {\n const name = 'portless CA chain valid'\n const servernames = [\n 'localhost',\n ...routes.slice(0, 1).map((route) => {\n return route.name\n }),\n ]\n const results = await Promise.all(\n servernames.map(async (servername) => {\n return { servername, result: await handshake(DEFAULT_DEV_PROXY_PORT, servername) }\n }),\n )\n const failed = results.filter((entry) => {\n return !entry.result.ok\n })\n\n if (failed.length === 0) {\n return {\n name,\n status: 'pass',\n message: `Served certificate chains to ${tildify(caPath)} (${servernames.join(', ')})`,\n }\n }\n\n const codes = failed.map((entry) => {\n return entry.result.ok ? '' : entry.result.code\n })\n\n if (codes.includes(PROBE_BUG_CODE)) {\n return {\n name,\n status: 'fail',\n message: `Internal check error: the TLS probe got ${PROBE_BUG_CODE} for servername(s) ${failed\n .map((entry) => {\n return entry.servername\n })\n .join(', ')} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`,\n }\n }\n\n if (\n codes.some((code) => {\n return CA_MISMATCH_CODES.has(code)\n })\n ) {\n return {\n name,\n status: 'fail',\n message: `The daemon is serving a certificate that does not chain to ${tildify(caPath)}. Its CA was regenerated \u2014 run \\`${trustCmd(bin)}\\`, or reinstall: \\`${installDaemonCmd(bin)}\\`.`,\n }\n }\n\n return { name, status: 'fail', message: `TLS handshake failed (${codes.join(', ')})` }\n}\n\n/**\n * Was `portless trust` run for the CA now on disk? Fingerprint marker only \u2014 it proves the marker was\n * written for THIS `ca.pem` and the CA has not been regenerated since. It does NOT prove the keychain still\n * trusts it: a user who deletes the certificate by hand in Keychain Access leaves the marker behind and\n * passes here. Accepted residual (see `caFingerprintMatches`); the chain check above is what proves what the\n * daemon actually serves.\n */\nconst checkPortlessCaTrusted = (trusted: boolean, caPath: string, bin: string): CheckResult => {\n const name = 'portless CA trusted'\n\n if (!trusted) {\n return {\n name,\n status: 'fail',\n message: `The portless CA is not trusted (or was regenerated). Run: \\`${trustCmd(bin)}\\` (no sudo needed).`,\n }\n }\n\n return { name, status: 'pass', message: `${tildify(caPath)} matches the recorded ca.trusted fingerprint` }\n}\n\n/**\n * Routes whose target port has nothing listening \u2014 a worktree whose runner was SIGKILLed. Newly worth\n * surfacing under HTTPS: a dead target is now an opaque 502 from the proxy rather than a connection refusal.\n */\nconst checkPortlessStaleRoutes = async (\n routes: PortlessRoute[],\n isListening: NonNullable<PortlessCheckDeps['isListening']>,\n bin: string,\n): Promise<CheckResult> => {\n const name = 'portless routes'\n\n if (routes.length === 0) return { name, status: 'pass', message: 'No portless routes registered' }\n\n const probed = await Promise.all(\n routes.map(async (route) => {\n return { route, live: await isListening(route.port) }\n }),\n )\n const stale = probed\n .filter((entry) => {\n return !entry.live\n })\n .map((entry) => {\n return entry.route.name\n })\n\n if (stale.length === 0) {\n return { name, status: 'pass', message: `${routes.length} portless route(s), all live` }\n }\n\n return {\n name,\n status: 'fail',\n message: `${stale.length} stale portless route(s): ${stale.join(', ')}. Remove with \\`${formatPortlessCommand(['alias', '--remove', '<name>'], { bin })}\\`.`,\n }\n}\n\n/**\n * The portless block of doctor: is the HTTPS dev proxy installed, serving, trusted, and free of dead routes?\n * This is the diagnostic surface for the port-free HTTPS dev URLs \u2014 it is what tells a developer to run\n * `trust` (sudo-free) or the one-time `service install` (root), and it never conflates the two. Both are\n * printed via {@link formatPortlessCommand} \u2014 as `<node> <cli.js> \u2026`, the only form that runs.\n *\n * Every check observes the daemon **on the wire or on our own disk** \u2014 never through portless's `proxy.port`\n * / `proxy.pid` / `proxy.tls` markers, which are process-global singletons that ANY daemon start rewrites and\n * ANY daemon stop deletes. Gating on them made doctor report a perfectly healthy `:443` daemon as dead.\n *\n * Reports only: nothing here is auto-run, and nothing requiring sudo ever could be.\n *\n * @example\n * await checkPortless()\n * // [{ name: 'portless installed', status: 'pass', message: '\u2026' }, \u2026 5 checks]\n */\nexport const checkPortless = async (deps: PortlessCheckDeps = {}): Promise<CheckResult[]> => {\n const resolveBin = deps.resolveBin ?? resolvePortlessBin\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const handshake = deps.handshake ?? handshakeChainsToCa\n const caTrusted = deps.caTrusted ?? caFingerprintMatches\n const readRoutes = deps.routes ?? listRoutes\n const isListening = deps.isListening ?? defaultIsListening\n const caPath = (deps.caPath ?? readCaPath)()\n // Resolved ONCE, then threaded into every remediation below: each one is rendered as `<node> <bin> \u2026`, so a\n // check that could not name the binary could not print a runnable fix either.\n const bin = resolveBin()\n\n if (bin === null) {\n return [\n {\n name: 'portless installed',\n status: 'fail',\n message: 'portless is not resolvable from node_modules \u2014 run `pnpm install`.',\n },\n ]\n }\n\n const installed: CheckResult = {\n name: 'portless installed',\n status: 'pass',\n message: 'portless is resolvable from node_modules',\n }\n const routes = readRoutes()\n const serving = await checkPortlessServing(isProxyServing, bin)\n // Nothing is answering on :443 \u2014 there is no certificate to validate, so the chain check would only add a\n // second, derivative failure to the one the user must fix first.\n const chain: CheckResult =\n serving.status === 'fail'\n ? { name: 'portless CA chain valid', status: 'pass', message: 'Skipped \u2014 no daemon to handshake with' }\n : await checkPortlessCaChain(handshake, routes, caPath, bin)\n\n return [\n installed,\n serving,\n chain,\n checkPortlessCaTrusted(caTrusted(), caPath, bin),\n await checkPortlessStaleRoutes(routes, isListening, bin),\n ]\n}\n\n/** Seams for {@link pruneStalePortlessRoutes}: the daemon, the wire and the process table, all injectable. */\nexport interface PruneRoutesDeps {\n routes?: () => PortlessRoute[]\n isListening?: (port: number) => Promise<boolean>\n /** Is a dev session alive? Defaults to a `ps` scan \u2014 see {@link isDevSessionRunning}. */\n devSessionRunning?: () => boolean\n removeAlias?: (name: string) => Promise<void>\n}\n\n/**\n * `doctor --fix`: remove the portless routes a dead dev-server left behind.\n *\n * The counterpart to {@link checkPortlessStaleRoutes}, which only ever REPORTS. Acting on the same\n * evidence needs one more guard, and it is not optional: \"nothing is listening\" cannot distinguish a dead\n * route from a UI whose vite has not bound its port yet (`assignUiPort` registers the alias, then\n * `getFreePort` RELEASES the port until vite boots \u2014 and a UI alias has no dev-context fragment to\n * corroborate it with). Every such false positive requires a dev session to be running, so a live dev\n * session withholds the prune entirely. See `prune-routes.ts` for the full argument.\n */\nexport const pruneStalePortlessRoutes = async (deps: PruneRoutesDeps = {}): Promise<CheckResult> => {\n const name = 'portless routes'\n const readRoutes = deps.routes ?? listRoutes\n const isListening = deps.isListening ?? defaultIsListening\n const devRunning = deps.devSessionRunning ?? isDevSessionRunning\n const routes = readRoutes()\n\n if (routes.length === 0) return { name, status: 'pass', message: 'No portless routes registered' }\n\n const probed = await Promise.all(\n routes.map(async (route) => {\n return { name: route.name, port: route.port, live: await isListening(route.port) }\n }),\n )\n const { prunable, withheld } = decidePrune(probed, devRunning())\n\n if (withheld.length > 0) {\n return {\n name,\n status: 'fail',\n message:\n `${withheld.length} route(s) look stale (${withheld.join(', ')}), but a dev session is running \u2014 ` +\n 'a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. ' +\n 'Stop dev and re-run `infra-kit doctor --fix`.',\n }\n }\n\n if (prunable.length === 0) {\n return { name, status: 'pass', message: `${routes.length} portless route(s), all live` }\n }\n\n const removeAlias = deps.removeAlias ?? createPortlessDriver().removeAlias\n\n // Serial, not `Promise.all`: each removal shells out to portless, which takes its own route lock.\n for (const alias of prunable) {\n await removeAlias(alias)\n }\n\n return {\n name,\n status: 'pass',\n message: `Removed ${prunable.length} stale portless route(s): ${prunable.join(', ')}`,\n }\n}\n\n/**\n * Check installation and authentication status of gh, doppler, aws, and rtk CLIs\n */\nexport const doctor = async (options: { fix?: boolean } = {}) => {\n // ONE read, before anything is dispatched: the checks below used to reset the shared config cache\n // concurrently from inside the `Promise.all`. See {@link readDoctorConfig}.\n const read = await readDoctorConfig()\n\n const baseChecks: CheckResult[] = await Promise.all([\n checkCommand(\n 'gh installed',\n ['gh', '--version'],\n 'GitHub CLI is installed',\n 'GitHub CLI is not installed. Install from: https://cli.github.com/',\n ),\n checkCommand(\n 'gh authenticated',\n ['gh', 'auth', 'status'],\n 'GitHub CLI is authenticated',\n 'GitHub CLI is not authenticated. Run: gh auth login',\n ),\n checkCommand(\n 'doppler installed',\n ['doppler', '--version'],\n 'Doppler CLI is installed',\n 'Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli',\n ),\n checkCommand(\n 'aws installed',\n ['aws', '--version'],\n 'AWS CLI is installed',\n 'AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html',\n ),\n checkCommand(\n 'rtk installed',\n ['rtk', '--version'],\n 'RTK is installed',\n 'RTK is not installed. Install from: https://github.com/rtk-ai/rtk',\n ),\n checkCommand(\n 'typescript-language-server installed',\n ['typescript-language-server', '--version'],\n 'typescript-language-server is installed',\n 'typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing',\n ),\n checkCommand(\n 'cmux installed',\n ['cmux', '--version'],\n 'cmux is installed',\n 'cmux is not installed. Install from: https://cmux.com/',\n ),\n checkRtkConfigured(),\n Promise.resolve(checkZshrcInitialized()),\n checkWarmCache(),\n checkPnpmWorkspaceVirtualStore(),\n Promise.resolve(checkInfraKitConfigValid(read)),\n checkEnvTokensConfigured(read),\n checkEnvTokenValid(read),\n checkTokenStorePerms(options.fix ?? false),\n checkUserOverridePath(),\n checkLegacyUserGlobalConfig(),\n checkIdeInstalled(read),\n ])\n\n const portlessChecks = await checkPortless()\n\n // `--fix` SWAPS the read-only stale-route check for the one that actually removes them, so the report\n // never prints a \"stale route\" failure beside the line that just cleaned it up.\n if (options.fix) {\n const pruned = await pruneStalePortlessRoutes()\n const index = portlessChecks.findIndex((check) => {\n return check.name === pruned.name\n })\n\n if (index >= 0) portlessChecks[index] = pruned\n else portlessChecks.push(pruned)\n }\n\n const checks: CheckResult[] = [...baseChecks, ...portlessChecks, ...(await checkAgentFiles())]\n\n // NO rendering here, deliberately. `doctor()` has two callers \u2014 the CLI action and the MCP tool \u2014\n // and only one of them has a terminal. Printing from inside would emit a human report into an MCP\n // server's stderr on every agent call; the CLI action owns presentation instead (see `report.ts`).\n const structuredContent = {\n checks: checks.map((c) => {\n return { name: c.name, status: c.status, message: c.message }\n }),\n allPassed: checks.every((c) => {\n return c.status === 'pass'\n }),\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const doctorMcpTool = defineMcpTool({\n name: 'doctor',\n description: 'Check installation and authentication status of gh, doppler, aws, and rtk CLIs',\n inputSchema: {},\n outputSchema: {\n checks: z\n .array(\n z.object({\n name: z.string().describe('Name of the check'),\n status: z.enum(['pass', 'fail']).describe('Check result'),\n message: z.string().describe('Details about the check result'),\n }),\n )\n .describe('List of all check results'),\n allPassed: z.boolean().describe('Whether all checks passed'),\n },\n // Read-only on purpose: `--fix` is NOT reachable here. The MCP boundary auto-confirms every tool call,\n // so a state-mutating flag must never be one `handler: doctor` away from an agent invoking it.\n handler: () => {\n return doctor()\n },\n})\n", "/**\n * `infra-kit doctor --fix`: remove the portless routes a DEAD dev-server left behind.\n *\n * A runner deregisters its aliases in `shutdown()` \u2014 but `shutdown()` only runs when a signal handler\n * gets to run. `kill -9`, an OOM kill, a force-quit or a power loss all skip it, and alias removal is an\n * async subprocess, so neither the synchronous force-quit path nor a `process.on('exit')` hook could ever\n * do it either. The route then outlives its server: a name in portless's table pointing at a port nothing\n * serves. Hit that URL and you get an opaque 502. This command is the ONLY thing that can clean that up.\n *\n * \u2500\u2500\u2500 Why \"nothing is listening\" is NOT, on its own, a safe test \u2500\u2500\u2500\n *\n * It is the test {@link checkPortlessStaleRoutes} already uses, and it is unsound. It is only harmless\n * there because that check merely PRINTS. Making it ACT on the same evidence would delete live routes:\n *\n * - `assignUiPort` picks a UI port with `getFreePort()`, which binds a probe socket and RELEASES it.\n * The alias is registered immediately; `vite` only binds the port seconds later, when it boots. For\n * that entire window a perfectly healthy UI route has nothing listening on its port.\n * - A UI alias has no dev-context fragment either (only `startOneApp` writes those, and only for\n * backends), so there is no second source of evidence to fall back on.\n * - A watch-restart re-closes and re-binds a backend port, so even an API route has brief dead windows.\n *\n * \u2500\u2500\u2500 The invariant that makes it safe \u2500\u2500\u2500\n *\n * Every one of those false-positives requires a dev session to be RUNNING. So:\n *\n * prune only when no dev session is alive anywhere on this machine.\n *\n * With nothing running, nothing can be mid-boot or mid-restart, and a port with no listener is genuinely\n * dead. The check is deliberately OVER-eager (see {@link DEV_ACTIVITY_PATTERNS}): a false \"dev is running\"\n * costs the user one retry, while a false \"dev is stopped\" deletes a live route. The costs are not\n * symmetric, so neither is the default.\n *\n * Removal is also the mildest possible action: it kills no process, and the next `infra-kit dev` simply\n * re-registers the alias. This module never signals anything.\n */\nimport { execFileSync } from 'node:child_process'\n\n/** A portless route after its port has been probed on the wire. */\nexport interface ProbedRoute {\n name: string\n port: number\n /** Is something listening on `port` right now? */\n live: boolean\n}\n\n/** What {@link decidePrune} concluded, split by what may actually be touched. */\nexport interface PruneDecision {\n /** Dead on the wire AND no dev session is running: safe to remove. */\n prunable: string[]\n /**\n * Dead on the wire, but a dev session IS running \u2014 so \"dead\" is unprovable: this is exactly the shape\n * of a UI route whose vite has not bound its port yet. Reported, never removed.\n */\n withheld: string[]\n}\n\n/**\n * Decide which routes may be removed. Pure \u2014 the whole safety property lives here, so it is testable\n * without a daemon, a process table, or a network.\n *\n * @example\n * decidePrune([{ name: 'x.api', port: 1, live: false }], false) // => { prunable: ['x.api'], withheld: [] }\n * decidePrune([{ name: 'x.api', port: 1, live: false }], true) // => { prunable: [], withheld: ['x.api'] }\n */\nexport const decidePrune = (probed: readonly ProbedRoute[], devSessionRunning: boolean): PruneDecision => {\n const dead = probed\n .filter((route) => {\n return !route.live\n })\n .map((route) => {\n return route.name\n })\n\n // A live dev session makes \"nothing is listening\" meaningless \u2014 it is indistinguishable from a UI that\n // is still booting. Withhold ALL of them rather than guess which are which.\n if (devSessionRunning) return { prunable: [], withheld: dead }\n\n return { prunable: dead, withheld: [] }\n}\n\n/**\n * Command lines of a live `infra-kit dev` RUNNER. Matched against `ps -eo command=`.\n *\n * Deliberately the runner and NOTHING ELSE \u2014 not `turbo`, not `vite`. That looks too narrow, and the first\n * draft of this file did include them, reasoning that \"over-matching only withholds a prune\". Running it\n * disproved that: a crashed session leaves `turbo run dev` orphans alive (exactly the orphan class\n * `managed-child` exists to prevent), so matching turbo means the leftovers of a dead session permanently\n * block the cleanup of that same session's routes \u2014 `--fix` would be inert on precisely the machine that\n * needs it. Observed: three orphaned `turbo run dev` processes withholding six dead routes.\n *\n * The runner is also the CORRECT thing to gate on, not merely the workable one. It is the only process that\n * registers a portless alias, so only its presence can mean \"a route may be about to become live\":\n * - a route can only appear at all while a runner is alive;\n * - the booting-UI window (alias registered, vite has not bound the port yet) is bounded by the runner;\n * - an orphaned turbo/vite registers no new routes, and if one still HOLDS a route's port then the wire\n * probe already sees it as live and it is never a prune candidate in the first place.\n */\nconst DEV_RUNNER_PATTERNS: readonly RegExp[] = [/\\binfra-kit\\s+dev\\b/, /cli\\.js\\s+dev\\b/, /dev-server\\.(?:js|ts)\\b/]\n\n/**\n * Does this `ps` command line belong to a live `infra-kit dev` runner?\n *\n * @example\n * looksLikeDevRunner('node /x/dist/cli.js dev --watch') // => true\n * looksLikeDevRunner('node /x/node_modules/.bin/turbo run dev') // => false \u2014 an orphan, not a runner\n */\nexport const looksLikeDevRunner = (command: string): boolean => {\n return DEV_RUNNER_PATTERNS.some((pattern) => {\n return pattern.test(command)\n })\n}\n\n/** Absolute path to `ps` \u2014 never resolved through `PATH`, which a writable entry could substitute. */\nconst PS_BIN = '/bin/ps'\n\n/** Every running process's command line, one per entry. */\nconst defaultReadCommands = (): string[] => {\n return execFileSync(PS_BIN, ['-eo', 'command='], { encoding: 'utf8', maxBuffer: 8 << 20 }).split('\\n')\n}\n\n/**\n * Is an `infra-kit dev` runner alive anywhere on this machine?\n *\n * Machine-wide, not repo-wide: portless routes are machine-global, and a runner in another worktree can be\n * mid-boot against a route this repo can see.\n *\n * Fails CLOSED: if `ps` cannot be read we report `true` \u2014 \"a runner might be up\" \u2014 so an unreadable process\n * table withholds the prune instead of authorising it.\n */\nexport const isDevSessionRunning = (readCommands: () => string[] = defaultReadCommands): boolean => {\n try {\n return readCommands().some(looksLikeDevRunner)\n } catch {\n // No process table, no proof of safety.\n return true\n }\n}\n", "import select from '@inquirer/select'\nimport { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\nimport { $ } from 'zx'\n\nimport {\n DopplerAuthError,\n INFRA_KIT_ENV_TOKEN_VAR,\n buildDopplerNotFoundMessage,\n classifyDopplerAuthFailure,\n classifyDopplerFailure,\n getDopplerProject,\n resolveEnvToken,\n} from 'src/integrations/doppler'\nimport { commandEcho } from 'src/lib/command-echo'\nimport {\n ENV_LOAD_FILE,\n INFRA_KIT_ENV_AUTOLOADED_VAR,\n INFRA_KIT_ENV_CLEARED_VAR,\n INFRA_KIT_ENV_CONFIG_VAR,\n INFRA_KIT_ENV_LOADED_AT_VAR,\n INFRA_KIT_ENV_PROJECT_ROOT_VAR,\n INFRA_KIT_ENV_PROJECT_VAR,\n INFRA_KIT_ENV_VAR,\n atomicWriteFileSync,\n getSessionCacheDir,\n} from 'src/lib/constants'\nimport { extractStderr } from 'src/lib/errors/operation-error'\nimport { getProjectRoot } from 'src/lib/git-utils'\nimport { logger } from 'src/lib/logger'\nimport { listProjectEnvNames } from 'src/lib/project-envs'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { canonicalizeProjectRoot, evictStaleWarmCaches, shouldWriteWarm, writeWarmCache } from 'src/lib/warm-cache'\nimport { defineMcpTool, textContent } from 'src/types'\n\ninterface EnvLoadArgs {\n config?: string\n}\n\ninterface WriteEnvLoadFileArgs {\n /** Resolved Doppler config / environment name (no interactive picker here). */\n config: string\n /**\n * Marks the produced file as auto-loaded. `true` writes the\n * INFRA_KIT_ENV_AUTOLOADED marker; `false` (a manual load) instead unsets the\n * marker and lifts any clear suppression so a deliberate load wins.\n */\n autoLoaded?: boolean\n /**\n * Auto-load only: re-checked AFTER the Doppler download, immediately before the\n * atomic write. Return false to abort (a clear or a manual load landed during the\n * slow download). Manual loads omit it and always write.\n */\n beforeWrite?: () => boolean\n /**\n * Canonical (realpath'd) project dir the SHELL passed via `--project-dir` on the\n * shell-startup auto-load spawn. Its presence (with `autoLoaded`) is what enables\n * the project-scoped WARM cache write; see {@link shouldWriteWarm}. Undefined for\n * manual loads and the cli-invocation trigger \u2014 those write no warm copy.\n */\n projectDir?: string\n}\n\nexport interface EnvLoadFileResult {\n filePath: string\n variableCount: number\n project: string\n config: string\n}\n\ninterface EnvLoadFileLinesArgs {\n pairs: Array<[string, string]>\n config: string\n project: string\n projectRoot: string\n loadedAt: string\n autoLoaded: boolean\n}\n\n/**\n * The auto-load marker lines appended to env-load.sh. Pure so the marker policy\n * is unit-testable without touching Doppler or the filesystem.\n *\n * @example\n * buildAutoLoadMarkerLines(true) // => [\"INFRA_KIT_ENV_AUTOLOADED='1'\"]\n * buildAutoLoadMarkerLines(false) // => ['unset INFRA_KIT_ENV_AUTOLOADED', 'unset INFRA_KIT_ENV_CLEARED']\n */\nconst buildAutoLoadMarkerLines = (autoLoaded: boolean): string[] => {\n if (autoLoaded) {\n return [`${INFRA_KIT_ENV_AUTOLOADED_VAR}=${shellSingleQuote('1')}`]\n }\n\n // Manual load: drop any auto marker so auto-load never re-clobbers a deliberate\n // choice, and lift a prior clear suppression so the manual load takes effect.\n return [`unset ${INFRA_KIT_ENV_AUTOLOADED_VAR}`, `unset ${INFRA_KIT_ENV_CLEARED_VAR}`]\n}\n\n/** The payload key that carries the token's scope \u2014 the one {@link assertTokenScope} compares. */\nconst DOPPLER_CONFIG_KEY = 'DOPPLER_CONFIG'\n\n/**\n * Secret names that must NEVER be written into the sourced file. A Doppler project can hold a secret\n * called `DOPPLER_TOKEN` (or `INFRA_KIT_ENV_TOKEN`), and `env-load.sh` is sourced into EVERY shell \u2014\n * exporting one would hand a live credential to every child process forever, and (per SPIKE-0 Q5) an\n * exported `DOPPLER_TOKEN` would then hijack the next download's auth.\n *\n * `DOPPLER_CONFIG` / `DOPPLER_PROJECT` are deliberately NOT filtered: they are not credentials, they\n * are the scope evidence {@link assertTokenScope} and `doctor` read back.\n */\nconst CREDENTIAL_SECRET_KEYS = new Set<string>(['DOPPLER_TOKEN', INFRA_KIT_ENV_TOKEN_VAR])\n\n/** Warn at most once per process: a project carrying a token secret would otherwise warn on every load. */\nlet credentialFilterWarned = false\n\n/**\n * Tell the user we dropped a credential-bearing secret from their shell env \u2014 silently swallowing a\n * key they can see in the Doppler dashboard would read as a bug. Names the KEY only, never the value.\n */\nconst warnFilteredCredentialKeys = (keys: string[]): void => {\n if (keys.length === 0 || credentialFilterWarned) return\n\n credentialFilterWarned = true\n\n logger.warn(\n `infra-kit: not exporting ${keys.join(', ')} from Doppler into your shell \u2014 ` +\n 'a service token must not be sourced into every process.',\n )\n}\n\n/**\n * Build the dotenv-format shell lines for env-load.sh. Pure apart from the one-shot credential\n * warning, so callers can assert the exact marker behavior. `set -a`/`set +a` auto-export every\n * assignment when the file is sourced.\n */\nexport const buildEnvLoadFileLines = ({\n pairs,\n config,\n project,\n projectRoot,\n loadedAt,\n autoLoaded,\n}: EnvLoadFileLinesArgs): string[] => {\n const emitted = pairs.filter(([key]) => {\n return !CREDENTIAL_SECRET_KEYS.has(key)\n })\n\n warnFilteredCredentialKeys(\n pairs\n .filter(([key]) => {\n return CREDENTIAL_SECRET_KEYS.has(key)\n })\n .map(([key]) => {\n return key\n }),\n )\n\n return [\n 'set -a',\n ...emitted.map(([key, value]) => {\n return `${key}=${shellSingleQuote(value)}`\n }),\n // Purpose-named env-name handle for non-shell tooling (e.g. infra-kit/vite's\n // `<env>` proxy interpolation). Single-quoted like every sourced value.\n `${INFRA_KIT_ENV_VAR}=${shellSingleQuote(config)}`,\n `${INFRA_KIT_ENV_CONFIG_VAR}=${shellSingleQuote(config)}`,\n `${INFRA_KIT_ENV_PROJECT_VAR}=${shellSingleQuote(project)}`,\n `${INFRA_KIT_ENV_PROJECT_ROOT_VAR}=${shellSingleQuote(projectRoot)}`,\n `${INFRA_KIT_ENV_LOADED_AT_VAR}=${shellSingleQuote(loadedAt)}`,\n ...buildAutoLoadMarkerLines(autoLoaded),\n 'set +a',\n ]\n}\n\n/**\n * Project root (git top-level) the loaded env belongs to, for the cross-project\n * shell gate. Returns '' when this isn't a git checkout so a non-git infra-kit\n * project still loads \u2014 the shell gate then fails open (spawns rather than skips)\n * instead of breaking the whole load on `git rev-parse` throwing.\n */\nconst resolveProjectRootSafe = async (): Promise<string> => {\n try {\n return await getProjectRoot()\n } catch {\n return ''\n }\n}\n\n/**\n * Download Doppler secrets for a resolved config and atomically write env-load.sh\n * to the session cache dir. Does NOT print to stdout \u2014 shared by the CLI/MCP\n * `envLoad` entry (which prints the path) and the auto-load path (which lets the\n * shell precmd hook source the file).\n */\nexport const writeEnvLoadFile = async ({\n config,\n autoLoaded = false,\n beforeWrite,\n projectDir,\n}: WriteEnvLoadFileArgs): Promise<EnvLoadFileResult | null> => {\n const project = await getDopplerProject()\n const projectRoot = await resolveProjectRootSafe()\n\n const pairs = await downloadDopplerSecrets(project, config)\n\n const loadedAt = new Date().toISOString()\n const envFileLines = buildEnvLoadFileLines({ pairs, config, project, projectRoot, loadedAt, autoLoaded })\n const fileContents = `${envFileLines.join('\\n')}\\n`\n\n const cacheDir = getSessionCacheDir()\n const envFilePath = path.resolve(cacheDir, ENV_LOAD_FILE)\n\n // Re-check suppression immediately before the atomic write: a clear or a manual\n // load may have landed during the slow Doppler download (auto-load path only).\n if (beforeWrite && !beforeWrite()) return null\n\n fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 })\n atomicWriteFileSync(envFilePath, fileContents, 0o600)\n\n // Project-scoped WARM copy: lets the NEXT shell source these vars instantly at\n // startup (pure zsh, no Doppler) before this session's fresh file lands. Gated so\n // it only fires for a shell-startup auto-load whose realpath'd git root matches the\n // dir the shell keyed on (see shouldWriteWarm). Each warm write also sweeps stale\n // warm dirs \u2014 we own the only cache reaper in the codebase.\n const canonicalProjectRoot = canonicalizeProjectRoot(projectRoot)\n\n if (shouldWriteWarm({ autoLoaded, projectDir, canonicalProjectRoot })) {\n writeWarmCache(projectDir!, fileContents)\n evictStaleWarmCaches()\n }\n\n return {\n filePath: envFilePath,\n variableCount: pairs.length,\n project,\n config,\n }\n}\n\n/**\n * Load environment variables from Doppler for the given config\n */\nexport const envLoad = async (args: EnvLoadArgs) => {\n const { config } = args\n\n let selectedConfig = ''\n\n if (config) {\n selectedConfig = config\n } else {\n // No auth pre-probe before the picker: under token-only auth there is no account\n // to validate, and the per-env token is only knowable AFTER a config is chosen.\n // A missing/rejected token surfaces from the download with an actionable message.\n //\n // The choices are every env this project has \u2014 workflow-declared and token-only alike (see\n // `lib/project-envs`). Deliberately NOT filtered to the envs we hold a token for: an env you cannot\n // yet load is exactly the one you need to SEE, so that picking it tells you to run\n // `infra-kit env-token-set <env>` rather than leaving you to wonder where it went.\n const envs = await listProjectEnvNames()\n\n commandEcho.setInteractive()\n selectedConfig = await withEscape(\n (context) => {\n return select(\n {\n message: 'Select environment config',\n choices: envs.map((env) => {\n return { name: env, value: env }\n }),\n },\n context,\n )\n },\n // Render to stderr so the prompt is visible when stdout is captured via $() in the shell function.\n // Only env-load and env-clear use the $() stdout-capture shell pattern.\n { output: process.stderr },\n )\n }\n\n commandEcho.addOption('--config', selectedConfig)\n\n // A manual load is authoritative: autoLoaded=false drops the auto marker.\n const result = await writeEnvLoadFile({ config: selectedConfig, autoLoaded: false })\n\n // A manual load passes no beforeWrite, so it always writes \u2014 this guards the\n // invariant (and narrows the nullable result) rather than handling a real path.\n if (!result) throw new Error('env-load: write was unexpectedly aborted')\n\n // REQUIRED\n process.stdout.write(`${result.filePath}\\n`)\n\n // Logs to stderr (pino \u2192 pretty-print), so it doesn't pollute the captured\n // file path that the shell wrapper reads from stdout.\n commandEcho.print()\n\n const structuredContent = {\n filePath: result.filePath,\n variableCount: result.variableCount,\n project: result.project,\n config: result.config,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n/**\n * Cap the Doppler stdout we're willing to accept. A well-formed env bundle is\n * O(10 KB); megabytes would indicate a service regression or the wrong stream\n * being captured, and we don't want to write that to disk or source it.\n */\nexport const DOPPLER_MAX_OUTPUT_BYTES = 1024 * 1024\n\n/**\n * Hard upper bound for the Doppler subprocess. Well under zx's default so a\n * hung call surfaces quickly instead of blocking an interactive shell or an\n * MCP tool handler.\n */\nconst DOPPLER_DOWNLOAD_TIMEOUT_MS = 30_000\n\n/**\n * Doppler env vars we refuse to inherit into the download child. SPIKE-0 Q5: an inherited\n * `DOPPLER_TOKEN` OVERRIDES everything else the CLI would use \u2014 and `env-load` itself exports a whole\n * Doppler project into the shell, so a project that happens to hold a secret named `DOPPLER_TOKEN`\n * would silently hijack the NEXT download. `DOPPLER_PROJECT` / `DOPPLER_CONFIG` are scrubbed for the\n * same reason: they are the payload's own scope evidence, and an inherited copy could shadow the\n * `--project` / `--config` we pass in argv.\n */\nconst INHERITED_DOPPLER_VARS = ['DOPPLER_TOKEN', 'DOPPLER_PROJECT', 'DOPPLER_CONFIG'] as const\n\n/**\n * The child environment for `doppler secrets download`: the caller's env with the inherited Doppler\n * vars scrubbed and OUR resolved token set explicitly.\n *\n * The token travels by ENV, never by argv: `ps` shows argv to every user on the box, and\n * `commandEcho` prints option values back to the terminal. Pure (takes the base env) so the scrub is\n * unit-testable without touching `process.env`.\n *\n * @example\n * buildDopplerChildEnv('dp.st.x', { PATH: '/bin', DOPPLER_CONFIG: 'prod' })\n * // => { PATH: '/bin', DOPPLER_TOKEN: 'dp.st.x' } (DOPPLER_CONFIG dropped)\n */\nexport const buildDopplerChildEnv = (token: string, baseEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv => {\n const childEnv: NodeJS.ProcessEnv = { ...baseEnv }\n\n for (const name of INHERITED_DOPPLER_VARS) {\n delete childEnv[name]\n }\n\n childEnv.DOPPLER_TOKEN = token\n\n return childEnv\n}\n\nconst downloadDopplerSecrets = async (project: string, config: string): Promise<Array<[string, string]>> => {\n const { token } = await resolveEnvToken(config)\n\n const childEnv = buildDopplerChildEnv(token)\n\n const prevQuiet = $.quiet\n\n $.quiet = true\n try {\n let result\n\n try {\n result = await $({\n env: childEnv,\n })`doppler secrets download --no-file --format json --project ${project} --config ${config}`.timeout(\n DOPPLER_DOWNLOAD_TIMEOUT_MS,\n )\n } catch (error: unknown) {\n throw translateDopplerDownloadError(error, project, config)\n }\n\n assertDopplerOutputSize(result.stdout)\n\n const pairs = parseDopplerSecretsJson(result.stdout)\n\n assertTokenScope(pairs, config)\n\n return pairs\n } finally {\n $.quiet = prevQuiet\n }\n}\n\n/**\n * Defense in depth against a MIS-SCOPED token: the payload always carries `DOPPLER_CONFIG` as an\n * ordinary secret, and it echoes the `--config` we asked for (SPIKE-0 Q2 \u2014 it is the CONFIG, not\n * `DOPPLER_ENVIRONMENT`, which can differ: config `dev_personal` lives in environment `dev`).\n *\n * ABSENT \u21D2 PROCEED, deliberately. The Doppler CLI already refuses a real mismatch on the wire\n * (SPIKE-0 Q1: exit 1, \"does not have access to requested config\"), so it \u2014 not this \u2014 is the\n * load-bearing guard. An absent `DOPPLER_CONFIG` therefore means Doppler changed what it injects,\n * and failing closed here would blank every developer's shell at once on the SILENT autoload path.\n *\n * @example\n * assertTokenScope([['DOPPLER_CONFIG', 'dev']], 'dev') // ok\n * assertTokenScope([['FOO', 'bar']], 'dev') // ok (absent \u21D2 proceed)\n * assertTokenScope([['DOPPLER_CONFIG', 'prod']], 'dev') // throws: token is scoped to \"prod\"\n */\nexport const assertTokenScope = (pairs: Array<[string, string]>, config: string): void => {\n const actual = pairs.find(([key]) => {\n return key === DOPPLER_CONFIG_KEY\n })?.[1]\n\n if (actual === undefined || actual === config) return\n\n // A DopplerAuthError, not a plain Error: this IS an auth failure, and only the auth CLASS reaches the\n // sticky marker that a shell-startup user ever sees. A plain Error here would be classified transient,\n // expire in 30s, and leave them silently loading another environment's secrets \u2014 the exact failure this\n // assert exists to catch. The message stays richer than the generic one: we know the token's real config.\n throw new DopplerAuthError(\n config,\n null,\n `Doppler returned secrets for config \"${actual}\" but \"${config}\" was requested \u2014 the service token for ` +\n `env \"${config}\" is scoped to the wrong config. Refusing to load another environment's secrets.\\n` +\n `Fix: run \\`infra-kit env-token-set ${config}\\` with a token scoped to \"${config}\".`,\n )\n}\n\n/**\n * Turn a raw `doppler secrets download` failure into an actionable error. An AUTH-class failure (the\n * token is invalid, revoked, or mis-scoped) becomes a {@link DopplerAuthError} carrying the\n * env-token-set message; a recognized project/config not-found points at the exact infra-kit.json\n * field. Anything else \u2014 network, timeout \u2014 is rethrown untouched so it degrades to the existing\n * behavior, never worse.\n *\n * This is THE boundary where Doppler's raw stderr is read: the markers exist only here, and the\n * classification leaves this function as a TYPE (`DopplerAuthError`), never as prose for a downstream\n * module to re-parse. `lib/env-autoload` used to text-match the raw markers on the error this\n * function had already rewritten \u2014 they were long gone, so the sticky auth marker was never written\n * and a revoked token went silent. Exported so a seam test can drive the REAL error a caller sees.\n *\n * The not-found message no longer lists the AVAILABLE names: `listDopplerProjects` /\n * `listDopplerConfigs` require an ACCOUNT login, which token-only auth deleted, so that probe could\n * only ever return `null` now. `buildDopplerNotFoundMessage` already treats `null` as \"couldn't\n * tell\" and omits the suggestion line rather than misreporting \"none exist\".\n *\n * @example\n * translateDopplerDownloadError({ stderr: 'Doppler Error: Invalid Auth token' }, 'p', 'dev')\n * // => DopplerAuthError { authKind: 'revoked', message: '\u2026 `infra-kit env-token-set <env>` \u2026' }\n * translateDopplerDownloadError(new Error('connect ETIMEDOUT'), 'p', 'dev')\n * // => the same Error, untouched\n */\nexport const translateDopplerDownloadError = (error: unknown, project: string, config: string): Error => {\n const stderr = extractStderr(error) ?? (error instanceof Error ? error.message : String(error))\n const kind = classifyDopplerFailure(stderr)\n\n if (kind === 'auth') return new DopplerAuthError(config, classifyDopplerAuthFailure(stderr))\n\n if (kind === 'unknown') return error instanceof Error ? error : new Error(String(error))\n\n return new Error(buildDopplerNotFoundMessage({ kind, project, config, available: null }))\n}\n\nexport const assertDopplerOutputSize = (stdout: string): void => {\n const bytes = Buffer.byteLength(stdout, 'utf-8')\n\n if (bytes > DOPPLER_MAX_OUTPUT_BYTES) {\n throw new Error(\n `doppler returned unexpectedly large output (${bytes} bytes > ${DOPPLER_MAX_OUTPUT_BYTES}) \u2014 refusing to write to disk`,\n )\n }\n}\n\nexport const shellSingleQuote = (value: string): string => {\n const escaped = value.replaceAll(\"'\", \"'\\\\''\")\n\n return `'${escaped}'`\n}\n\n/** A valid POSIX env-var name: a letter or underscore, then word characters. */\nconst ENV_VAR_NAME_PATTERN = /^[A-Z_]\\w*$/i\n\n/**\n * Parse the `doppler secrets download --format json` output (a flat\n * `{\"KEY\":\"value\"}` map) into ordered `[key, value]` pairs, validating the shape\n * and every name/value. Values are returned RAW \u2014 callers must single-quote them\n * before emitting shell (an unquoted `a$(cmd)b` would execute on `source`).\n *\n * @example\n * parseDopplerSecretsJson('{\"FOO\":\"bar\",\"BAZ\":\"a$(x)\"}')\n * // => [['FOO', 'bar'], ['BAZ', 'a$(x)']]\n */\nexport const parseDopplerSecretsJson = (stdout: string): Array<[string, string]> => {\n let parsed: unknown\n\n try {\n parsed = JSON.parse(stdout)\n } catch {\n throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(stdout.slice(0, 80))})`)\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)')\n }\n\n const pairs: Array<[string, string]> = []\n\n for (const [key, value] of Object.entries(parsed)) {\n if (!ENV_VAR_NAME_PATTERN.test(key)) {\n throw new Error(\n `doppler returned an invalid env var name for env-load (got: ${JSON.stringify(key.slice(0, 80))})`,\n )\n }\n\n if (typeof value !== 'string') {\n throw new TypeError(`doppler returned a non-string value for \"${key}\" (got ${typeof value})`)\n }\n\n pairs.push([key, value])\n }\n\n if (pairs.length === 0) {\n throw new Error('doppler returned empty output for env-load')\n }\n\n return pairs\n}\n\n// MCP Tool Registration\nexport const envLoadMcpTool = defineMcpTool({\n name: 'env-load',\n description:\n 'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced (\"source <filePath>\") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. \"config\" is required when invoked via MCP (the CLI interactive picker is unreachable without a TTY).',\n inputSchema: {\n config: z\n .string()\n .describe('Doppler config / environment name to load (e.g. \"dev\", \"arthur\", \"renana\"). Required for MCP calls.'),\n },\n outputSchema: {\n filePath: z.string().describe('Path to the file that must be sourced to apply variables'),\n variableCount: z.number().describe('Number of variables loaded'),\n project: z.string().describe('Doppler project name'),\n config: z.string().describe('Doppler config name'),\n },\n handler: envLoad,\n})\n", "/**\n * Translate Doppler `secrets download` not-found failures into actionable,\n * point-at-the-fix guidance. Pure (no I/O) so the classification + message policy\n * is unit-testable without spawning the Doppler CLI \u2014 mirroring the pure-helper\n * pattern in `commands/env-load/env-load.ts`.\n *\n * Observed Doppler output on a not-found download (verified 2026-06-27, doppler\n * v3.76.0), exit 1, written to STDERR (stdout empty):\n * Unable to download secrets\n * Doppler Error: Could not find requested project 'name'\n * Doppler Error: Could not find requested config 'name'\n * Only the \"Doppler Error:\" prefix is ANSI-colored; the \"Could not find requested\n * ...\" text is plain, so substring matching is color-safe. zx's\n * `ProcessOutput.message` also concatenates stdout+stderr, so the same markers are\n * matchable off `.message` when `.stderr` is unavailable.\n */\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\n\n/** Which kind of Doppler not-found a download failure represents (`unknown` = not a not-found error). */\nexport type DopplerNotFoundKind = 'project' | 'config' | 'unknown'\n\n/**\n * Every class of `secrets download` failure we act on. `'auth'` is the token-only addition: the\n * service token is absent, revoked, garbage, or scoped to a DIFFERENT config. It is deliberately\n * distinct from the not-found kinds (the name is wrong) and from `'unknown'` (network, timeout,\n * Doppler down) \u2014 only `'auth'` is a durable, user-fixable state, and only `'auth'` earns the sticky\n * shell-startup marker (see `lib/env-autoload/auth-failure.ts`).\n */\nexport type DopplerFailureKind = 'auth' | DopplerNotFoundKind\n\nconst PROJECT_NOT_FOUND_MARKER = 'Could not find requested project'\nconst CONFIG_NOT_FOUND_MARKER = 'Could not find requested config'\n\n/**\n * The REAL auth-class stderr markers, captured from a live Doppler CLI v3.76.0 (SPIKE-0 Q1/Q4):\n * - `Invalid Auth token` \u2014 revoked / garbage token\n * - `This token does not have access to requested config 'x'` \u2014 mis-scoped token\n * Both are plain (uncolored) text, so substring matching is ANSI-safe. The second one is the CLI\n * ENFORCING the token's scope for us \u2014 it is the primary mis-scope guard, not our payload assert.\n */\nconst INVALID_TOKEN_MARKER = 'Invalid Auth token'\nconst TOKEN_SCOPE_MARKER = 'does not have access to requested config'\n\n/**\n * Classify a Doppler `secrets download` failure from its stderr/message text. The full lattice:\n * auth-class first (a mis-scoped token's message names a config but is NOT a not-found), then the\n * two not-found kinds, then `'unknown'` for everything else so the caller can rethrow the original\n * untouched (degrades to status quo, never worse).\n *\n * @example\n * classifyDopplerFailure('Doppler Error: Invalid Auth token') // => 'auth'\n * classifyDopplerFailure(\"This token does not have access to requested config 'dev'\") // => 'auth'\n * classifyDopplerFailure(\"Doppler Error: Could not find requested project 'x'\") // => 'project'\n * classifyDopplerFailure('connect ETIMEDOUT') // => 'unknown'\n */\nexport const classifyDopplerFailure = (stderr: string): DopplerFailureKind => {\n if (stderr.includes(INVALID_TOKEN_MARKER) || stderr.includes(TOKEN_SCOPE_MARKER)) return 'auth'\n\n if (stderr.includes(PROJECT_NOT_FOUND_MARKER)) return 'project'\n\n if (stderr.includes(CONFIG_NOT_FOUND_MARKER)) return 'config'\n\n return 'unknown'\n}\n\n/**\n * The two auth-class failures, told apart. Both are `'auth'` to\n * {@link classifyDopplerFailure} \u2014 they share one fix (a new token) \u2014 but they are DIFFERENT\n * diagnoses, and `doctor` must not conflate them: \"your token was revoked\" sends a user to the\n * Doppler dashboard, \"your token is scoped to the wrong config\" sends them to re-issue it against\n * the right one.\n */\nexport type DopplerAuthKind = 'revoked' | 'mis-scoped'\n\n/**\n * Split an auth-class failure into its two diagnoses, or `null` when the text is not auth-class at\n * all (network, timeout, not-found) \u2014 the caller must not read `null` as \"the token is fine\", only\n * as \"this failure says nothing about the token\".\n *\n * @example\n * classifyDopplerAuthFailure(\"This token does not have access to requested config 'dev'\") // => 'mis-scoped'\n * classifyDopplerAuthFailure('Doppler Error: Invalid Auth token') // => 'revoked'\n * classifyDopplerAuthFailure('connect ETIMEDOUT') // => null\n */\nexport const classifyDopplerAuthFailure = (stderr: string): DopplerAuthKind | null => {\n if (stderr.includes(TOKEN_SCOPE_MARKER)) return 'mis-scoped'\n\n if (stderr.includes(INVALID_TOKEN_MARKER)) return 'revoked'\n\n return null\n}\n\n/**\n * Is this failure text an auth-class Doppler failure (bad / absent / mis-scoped service token)\n * rather than a transient one (network, timeout, Doppler down)? The single source of truth for that\n * question \u2014 `lib/env-autoload/auth-failure.ts` delegates its `isAuthFailure` default here.\n *\n * @example\n * isDopplerAuthFailure('Doppler Error: Invalid Auth token') // => true\n * isDopplerAuthFailure('network unreachable') // => false\n */\nexport const isDopplerAuthFailure = (stderr: string): boolean => {\n return classifyDopplerFailure(stderr) === 'auth'\n}\n\n/**\n * Classify a Doppler download failure into the NOT-FOUND lattice only. Auth-class failures collapse\n * to `'unknown'` here on purpose: this predicate's whole contract is \"is this a wrong-NAME error\",\n * and its callers enrich with project/config listings that an auth failure must never trigger. Use\n * {@link classifyDopplerFailure} when you need the full lattice.\n *\n * @example\n * classifyDopplerDownloadError(\"Doppler Error: Could not find requested project 'x'\") // => 'project'\n * classifyDopplerDownloadError(\"Doppler Error: Could not find requested config 'dev'\") // => 'config'\n * classifyDopplerDownloadError('Doppler Error: Invalid Auth token') // => 'unknown'\n */\nexport const classifyDopplerDownloadError = (stderr: string): DopplerNotFoundKind => {\n const kind = classifyDopplerFailure(stderr)\n\n return kind === 'auth' ? 'unknown' : kind\n}\n\n/**\n * The actionable body for an auth-class download failure: Doppler REFUSED the token we sent, so the\n * fix is always a new token for this env \u2014 never `doppler login` (account auth no longer exists).\n *\n * Deliberately does not interpolate the raw stderr: this message is user-facing, and the one rule a\n * credential path cannot bend is that nothing token-adjacent gets rendered by accident.\n *\n * @example\n * buildDopplerAuthFailureMessage('dev')\n * // => 'Doppler rejected the service token for env \"dev\" \u2026 run `infra-kit env-token-set <env>` \u2026'\n */\nexport const buildDopplerAuthFailureMessage = (env: string): string => {\n return [\n `Doppler rejected the service token for env \"${env}\" \u2014 it is invalid, revoked, or scoped to a different config.`,\n `Fix: run \\`infra-kit env-token-set ${env}\\` with a token scoped to that config.`,\n 'CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config.',\n ].join('\\n')\n}\n\n/**\n * An auth-class `secrets download` failure, as a TYPE rather than a string. This is the error\n * `env-load`'s `translateDopplerDownloadError` throws for the auth class, and it is what every\n * DOWNSTREAM consumer classifies on.\n *\n * WHY a class and not \"match the message\": the moment the raw Doppler stderr is translated into a\n * human-facing message the markers it was classified by are GONE. A consumer that re-derives the\n * class by re-parsing that message is coupled to prose owned by another module \u2014 and the coupling is\n * SILENT: reword the message and the auth channel simply stops firing, with every unit test on both\n * sides still green (exactly the defect this type exists to make impossible). The classification now\n * travels WITH the error.\n *\n * It is the DOPPLER-REFUSED-US subset of {@link EnvAuthError}, the durable/user-fixable env-auth class:\n * a missing token never reaches Doppler, and a corrupt token store never reaches the resolver, yet all\n * three are equally durable and equally the user's to fix. Downstream policy (the sticky auth marker)\n * therefore classifies on `isEnvAuthFailure`; `isDopplerAuthError` remains for the callers who\n * genuinely mean \"the token was SENT and Doppler rejected it\".\n *\n * The message is unchanged \u2014 {@link buildDopplerAuthFailureMessage} still renders it \u2014 so a human who\n * only ever sees `error.message` sees precisely what they saw before.\n *\n * (The @example names the command as `infra-kit env-token-set <env>` rather than with a literal arg\n * for `program.test.ts`'s benefit: to that scan an `<env>` placeholder ENDS the command, but a literal\n * `dev` is indistinguishable from a subcommand and would be reported as a dead one.)\n *\n * @example\n * throw new DopplerAuthError('dev', 'revoked')\n * // message: 'Doppler rejected the service token for env \"dev\" \u2026 `infra-kit env-token-set <env>` \u2026'\n */\nexport class DopplerAuthError extends EnvAuthError {\n /**\n * The env (= Doppler config) whose service token Doppler refused. Names the fix, carries no token.\n *\n * `declare` NARROWS the base's `string | null` (a Doppler refusal always names one env) without\n * re-declaring the field: under `useDefineForClassFields` a real re-declaration would `defineProperty`\n * it back to `undefined` AFTER `super()` had set it.\n */\n declare readonly env: string\n /**\n * Which of the two auth diagnoses the raw stderr indicated, or `null` when it was not stated\n * (e.g. the payload-scope assert, which never sees Doppler's stderr). Diagnostic only \u2014 every\n * auth kind shares one fix.\n */\n readonly authKind: DopplerAuthKind | null\n\n /**\n * `message` overrides the rendered text for a caller that knows MORE than the generic diagnosis \u2014\n * the payload-scope assert can name the config the token actually belongs to, which Doppler's own\n * refusal cannot. It never changes the CLASS: every auth failure must remain type-detectable, or it\n * degrades to the transient 30s marker and the user is never told (the defect this type exists to\n * make impossible).\n */\n constructor(env: string, authKind: DopplerAuthKind | null = null, message?: string) {\n super(message ?? buildDopplerAuthFailureMessage(env), env)\n this.name = 'DopplerAuthError'\n this.authKind = authKind\n }\n}\n\n/**\n * The NARROW type guard: \"we sent Doppler a token and Doppler refused it\". Not text-matching \u2014 that\n * is how a caller asks \"was this the token?\" without re-parsing a rendered message.\n *\n * Use {@link isEnvAuthFailure} instead when the question is the POLICY one \u2014 \"is this durable and the\n * user's to fix?\" \u2014 because a missing token and a corrupt token store are both of those and neither is\n * a Doppler refusal. Classifying auto-load policy on THIS guard is precisely how the missing-token\n * (migration) case shipped silent.\n *\n * @example\n * isDopplerAuthError(new DopplerAuthError('dev')) // => true\n * isDopplerAuthError(new Error('Doppler Error: Invalid Auth token')) // => false (untranslated: not ours to claim)\n */\nexport const isDopplerAuthError = (error: unknown): error is DopplerAuthError => {\n return error instanceof DopplerAuthError\n}\n\ninterface DopplerNotFoundMessageArgs {\n /** Whether the missing entity is the project or the config within it. */\n kind: 'project' | 'config'\n project: string\n config: string\n /**\n * Names to suggest. `null` = lookup failed/unavailable, `[]` = none exist; both\n * omit the suggestion line so a failed enrichment probe is never misreported as\n * a definitive \"none available\".\n */\n available?: string[] | null\n}\n\n/**\n * Build the actionable, multi-line error body for a Doppler not-found failure:\n * states what's missing, points at the exact infra-kit.json field, lists available\n * names when known, and gives a concrete fix.\n *\n * @example\n * buildDopplerNotFoundMessage({ kind: 'project', project: 'infra-kit', config: 'dev', available: ['nomadream'] })\n * // => 'Doppler project \"infra-kit\" not found (set in infra-kit.json \u2192 envManagement.config.name).\\nAvailable projects: nomadream.\\nFix: ...'\n */\nexport const buildDopplerNotFoundMessage = ({\n kind,\n project,\n config,\n available,\n}: DopplerNotFoundMessageArgs): string => {\n const lines: string[] =\n kind === 'project'\n ? [`Doppler project \"${project}\" not found (set in infra-kit.json \u2192 envManagement.config.name).`]\n : [`Doppler config \"${config}\" not found in project \"${project}\".`]\n\n if (available && available.length > 0) {\n const label = kind === 'project' ? 'Available projects' : `Available configs in \"${project}\"`\n\n lines.push(`${label}: ${available.join(', ')}.`)\n }\n\n // The config half no longer points at a config file: there IS no declared env list any more. The name\n // came from a workflow, a token, or the `--config` flag, and the only place to fix a genuinely missing\n // one is Doppler itself.\n lines.push(\n kind === 'project'\n ? 'Fix: update envManagement.config.name to an existing project, or create it in Doppler.'\n : 'Fix: pass an existing config, or create it in Doppler.',\n )\n\n return lines.join('\\n')\n}\n", "import { $ } from 'zx'\n\nimport { classifyDopplerAuthFailure, classifyDopplerFailure } from 'src/integrations/doppler/doppler-errors'\nimport { extractStderr } from 'src/lib/errors/operation-error'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\n\n/**\n * Hard upper bound for the Doppler probe. It runs only on the diagnostic path (`doctor`), but a hung\n * VPN/connection must not stall it.\n */\nconst DOPPLER_PROBE_TIMEOUT_MS = 5_000\n\n/**\n * The one secret every Doppler payload carries, whose value is the config the token is scoped to\n * (SPIKE-0 Q2 \u2014 the CONFIG, not `DOPPLER_ENVIRONMENT`, which can differ: config `dev_personal` lives\n * in environment `dev`). Reading it back is what turns a liveness probe into a SCOPE probe.\n */\nconst SCOPE_KEY = 'DOPPLER_CONFIG'\n\n/**\n * Resolve Doppler project name from infra-kit.json at the project root\n */\nexport const getDopplerProject = async (): Promise<string> => {\n const { envManagement } = await getInfraKitConfig()\n\n return envManagement.config.name\n}\n\n/**\n * What a service token turned out to be, once Doppler was asked.\n *\n * `'unreachable'` is the load-bearing one and it means \"COULDN'T TELL\", never \"bad\": network,\n * timeout, VPN, Doppler down, a CLI that isn't installed. A caller that renders it as a definitive\n * verdict would tell a developer on a plane that their token was revoked. (Same `null`-vs-`[]`\n * contract the deleted `listDopplerProjects` carried, in enum form.)\n */\nexport type EnvTokenProbeOutcome = 'valid' | 'revoked' | 'mis-scoped' | 'unreachable'\n\nexport interface EnvTokenProbe {\n outcome: EnvTokenProbeOutcome\n /** The config the token actually resolved to, when Doppler told us. Never a token value. */\n scopedTo?: string\n}\n\ninterface EnvTokenProbeArgs {\n /**\n * The child environment carrying the token \u2014 built by `buildDopplerChildEnv`, which scrubs the\n * inherited `DOPPLER_*` vars and sets ours. Passed in rather than built here so the token travels\n * by ENV and never by argv (`ps` shows argv to every user on the box), and so this module stays\n * free of a cycle back through `commands/env-load`.\n */\n childEnv: NodeJS.ProcessEnv\n project: string\n config: string\n}\n\n/**\n * The cheapest combined VALIDITY + SCOPE probe of a Doppler service token (SPIKE-0): read one secret\n * back \u2014 the payload's own `DOPPLER_CONFIG` \u2014 and compare it to the config we asked for.\n *\n * `doppler me` is NOT enough: it works under a service token but returns no project/config, so it can\n * only prove the token is alive, never that it points where we think. One `secrets get` answers both\n * questions in one round trip, and the CLI enforces the scope for us on the wire.\n *\n * Never throws. Every failure becomes an outcome, and an unrecognized one becomes `'unreachable'`\n * (\"couldn't tell\") rather than a guess \u2014 the caller is `doctor`, whose whole value is that its\n * verdicts are true.\n *\n * @example\n * await probeEnvToken({ childEnv, project: 'api', config: 'dev' })\n * // => { outcome: 'valid', scopedTo: 'dev' }\n * // revoked token => { outcome: 'revoked' }\n * // token for prod => { outcome: 'mis-scoped' }\n * // offline => { outcome: 'unreachable' }\n */\nexport const probeEnvToken = async ({ childEnv, project, config }: EnvTokenProbeArgs): Promise<EnvTokenProbe> => {\n const prevQuiet = $.quiet\n\n $.quiet = true\n try {\n const result = await $({\n env: childEnv,\n })`doppler secrets get ${SCOPE_KEY} --plain --project ${project} --config ${config}`.timeout(\n DOPPLER_PROBE_TIMEOUT_MS,\n )\n const scopedTo = result.stdout.trim()\n\n // Exit 0 with a DIFFERENT config would mean the CLI's own scope enforcement let a mis-scoped token\n // through \u2014 belt and braces, but this is the check that would catch it.\n if (scopedTo !== config) return { outcome: 'mis-scoped', scopedTo }\n\n return { outcome: 'valid', scopedTo }\n } catch (error: unknown) {\n return { outcome: classifyProbeFailure(error) }\n } finally {\n $.quiet = prevQuiet\n }\n}\n\n/**\n * Turn a failed probe into an outcome. Only the two auth-class markers are definitive; a\n * project/config not-found is a config bug rather than a token verdict, so it collapses to\n * `'unreachable'` too \u2014 the token check must not claim a token is bad because the PROJECT name is.\n */\nconst classifyProbeFailure = (error: unknown): EnvTokenProbeOutcome => {\n const stderr = extractStderr(error) ?? (error instanceof Error ? error.message : String(error))\n\n if (classifyDopplerFailure(stderr) !== 'auth') return 'unreachable'\n\n return classifyDopplerAuthFailure(stderr) ?? 'unreachable'\n}\n", "import process from 'node:process'\n\nimport { getTokenStorePath, readTokenStore } from 'src/lib/env-tokens'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * The ONE environment variable that carries a Doppler service token into infra-kit (the CI / agent\n * path: no home directory, no token store, no interactive `env-token-set`).\n *\n * Deliberately NOT named `DOPPLER_TOKEN`. That name is contaminated on both ends: a Doppler project\n * may itself hold a secret called `DOPPLER_TOKEN`, and `env-load` exports the WHOLE project into the\n * shell \u2014 so a `DOPPLER_TOKEN` in the environment cannot be trusted to be the token WE were handed\n * (SPIKE-0 Q5: an inherited `DOPPLER_TOKEN` silently overrides everything else the CLI would use).\n * A private name keeps the input channel ours.\n */\nexport const INFRA_KIT_ENV_TOKEN_VAR = 'INFRA_KIT_ENV_TOKEN'\n\n/** Where a resolved token came from. Surfaced by `env-token-list`; never carries the token itself. */\nexport type EnvTokenSource = 'env' | 'store'\n\nexport interface ResolvedEnvToken {\n /** The Doppler service token. NEVER log, echo, or write this into a sourced file. */\n token: string\n source: EnvTokenSource\n}\n\n/**\n * Resolve the Doppler service token for one environment (= one Doppler config).\n *\n * Precedence, highest first:\n * 1. `INFRA_KIT_ENV_TOKEN` \u2014 the CI / agent channel. Checked BEFORE the store so a machine with no\n * home config (or a deliberately corrupted one) still loads, and so nothing on that path can\n * throw on a store it never needed.\n * 2. `envs[env]` from `~/.infra-kit/projects/<repo>/tokens.json` \u2014 the developer channel.\n * 3. Nothing \u21D2 THROW an {@link EnvAuthError}. Token-only auth has no fallback: there is no\n * `doppler login` account to degrade to, so a missing token is a hard, actionable stop rather than\n * a mysterious empty env. The CLASS matters as much as the message \u2014 see the throw below.\n *\n * An EMPTY `INFRA_KIT_ENV_TOKEN` is a MISS, not an empty token: `export INFRA_KIT_ENV_TOKEN=` (or an\n * unset var expanded by a CI template) must fall through to the store, not authenticate as \"\".\n *\n * @example\n * await resolveEnvToken('dev') // => { token: 'dp.st.dev.xxxx', source: 'store' }\n * // with INFRA_KIT_ENV_TOKEN set => { token: <that value>, source: 'env' }\n * // with neither => throws 'No Doppler service token for env \"dev\". \u2026'\n */\nexport const resolveEnvToken = async (env: string): Promise<ResolvedEnvToken> => {\n const fromEnv = process.env[INFRA_KIT_ENV_TOKEN_VAR]\n\n if (fromEnv) return { token: fromEnv, source: 'env' }\n\n const store = await readTokenStore()\n const fromStore = store?.envs[env]\n\n if (fromStore) return { token: fromStore, source: 'store' }\n\n // An EnvAuthError, not a plain Error: \"no token\" is the DURABLE, user-fixable auth failure \u2014 the\n // migration case, and the one case env auto-load's sticky marker exists to survive. A plain Error\n // here is classified TRANSIENT downstream, expires with the 30s backoff, and (on the backgrounded\n // shell-startup spawn, whose stderr is discarded) leaves the user with no channel at all: their env\n // silently stops loading and nothing ever says why. The class is what reaches them.\n throw new EnvAuthError(buildMissingTokenMessage(env, await getTokenStorePath()), env)\n}\n\n/**\n * Whether a token resolves for one env \u2014 the same precedence as {@link resolveEnvToken}, without\n * producing the token and without the refusal.\n *\n * For callers that must DECIDE rather than authenticate: env auto-load has to answer \"is this env\n * usable?\" at shell startup, and asking by catching {@link resolveEnvToken}'s throw would conflate two\n * very different failures \u2014 \"no token for this env\" (disable quietly, a typo'd `envAutoLoad.config`)\n * and \"the store itself is broken\" (surface loudly). This propagates the latter and reports the former\n * as a plain `false`.\n *\n * @example\n * await envTokenExists('dev') // => true\n * await envTokenExists('typo') // => false\n * // corrupt store => throws EnvAuthError (deliberately \u2014 the caller must not swallow that)\n */\nexport const envTokenExists = async (env: string): Promise<boolean> => {\n if (process.env[INFRA_KIT_ENV_TOKEN_VAR]) return true\n\n const store = await readTokenStore()\n\n return Boolean(store?.envs[env])\n}\n\n/**\n * The no-token refusal. It is the first thing an un-migrated user sees at update time, so it must be\n * fixable without reading any docs: it names the env, where to mint a token, the exact command, where\n * the token lands (and that it is NOT the repo), and the CI escape hatch.\n *\n * The fix command is a BACKTICK code span \u2014 the repo convention for naming a command to a human, and\n * the anchor `program.test.ts` scans to prove every command we print is a command we accept.\n *\n * (The @example names the command as `infra-kit env-token-set <env>` rather than with a literal arg\n * for that scan's benefit: a `<env>` placeholder ENDS the command, but a literal `dev` is\n * indistinguishable from a subcommand and would be reported as a dead one.)\n *\n * @example\n * buildMissingTokenMessage('dev', '/Users/x/.infra-kit/projects/api/tokens.json')\n * // => 'No Doppler service token for env \"dev\". Mint one at https://dashboard.doppler.com \u2026 run `infra-kit env-token-set <env>` \u2026'\n */\nconst buildMissingTokenMessage = (env: string, storePath: string): string => {\n return [\n `No Doppler service token for env \"${env}\".`,\n `Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config \"${env}\" \u2192 Access tab \u2192 \"Generate Service Token\".`,\n `Fix: run \\`infra-kit env-token-set ${env}\\` and paste it.`,\n `It is stored in ${tildify(storePath)} (mode 0600, never in the repo).`,\n `CI / agents: set ${INFRA_KIT_ENV_TOKEN_VAR} instead \u2014 it takes precedence and needs no home config.`,\n ].join('\\n')\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\nimport yaml from 'yaml'\n\nimport { getProjectRoot } from 'src/lib/git-utils'\n\n/** Where GitHub keeps dispatchable workflows. The only place we look for environment declarations. */\nconst WORKFLOWS_DIR = '.github/workflows'\n\n/**\n * The environment list a workflow will accept, read from its own `workflow_dispatch` `choice` input.\n *\n * This replaces `infra-kit.json \u2192 environments`, which was a THIRD copy of a fact GitHub already owns\n * and already enforces: a `choice` input is validated server-side on dispatch, so an out-of-range value\n * is rejected by GitHub whether or not we check it here. The copy had drifted \u2014 hulyo declared 6 envs\n * while every hulyo workflow declared 8, and the CLI's client-side check turned that drift into a\n * REFUSAL to deploy to `stage` and `prod`.\n *\n * So this is advisory ONLY: it sources the interactive picker, and callers must NOT veto against it.\n * The value returned here comes from the WORKING TREE, while the dispatch targets `--ref <branch>` \u2014\n * the two can legitimately differ, and an explicit `--env` must always win. Vetoing on a local read of\n * a remote fact is what created the bug this function exists to remove.\n *\n * Never throws. A repo with no such workflow (bridge has none), a `type: string` input, an absent\n * `options:` key, or malformed YAML all yield `[]` \u2014 an empty picker, never a dead command.\n *\n * @example\n * await readWorkflowEnvOptions('deploy-all.yml') // => ['dev', 'arthur', 'stage', 'prod']\n * await readWorkflowEnvOptions('absent.yml') // => []\n */\nexport const readWorkflowEnvOptions = async (workflowFile: string): Promise<string[]> => {\n const projectRoot = await getProjectRoot()\n\n return parseEnvOptions(path.resolve(projectRoot, WORKFLOWS_DIR, workflowFile))\n}\n\n/**\n * Every environment this repo declares anywhere \u2014 the union across ALL workflows.\n *\n * Deliberately a UNION, and deliberately not `deploy-all.yml` alone. Two repos prove why: travelist's\n * `deploy-all` omits `eliran` and `roman` (who both hold live tokens and ARE deployable via\n * `deploy-selected-services`), and bridge has no `deploy-all.yml` at all, so a single-file read would\n * report that it has zero environments.\n *\n * Note the asymmetry with {@link readWorkflowEnvOptions}, and keep it: this answers the REPO-scoped\n * question (\"what environments exist here?\") and so unions; the deploy pickers answer the\n * WORKFLOW-scoped question (\"where can THIS workflow deploy?\") and so must not.\n *\n * Never throws \u2014 an unreadable workflows directory yields `[]`.\n *\n * @example\n * await listWorkflowEnvs() // => ['dev', 'arthur', 'eliran', 'renana', 'roman', 'oriana', 'stage', 'prod']\n */\nexport const listWorkflowEnvs = async (): Promise<string[]> => {\n const projectRoot = await getProjectRoot()\n const workflowsDir = path.resolve(projectRoot, WORKFLOWS_DIR)\n\n let entries: string[]\n\n try {\n entries = await fs.readdir(workflowsDir)\n } catch {\n return []\n }\n\n const workflows = entries\n .filter((entry) => {\n return entry.endsWith('.yml') || entry.endsWith('.yaml')\n })\n .sort()\n\n const perWorkflow = await Promise.all(\n workflows.map((file) => {\n return parseEnvOptions(path.resolve(workflowsDir, file))\n }),\n )\n\n // First-seen order, de-duped: the picker reads best when `dev` leads, as it does in every workflow.\n return [...new Set(perWorkflow.flat())]\n}\n\n/**\n * Pull `on.workflow_dispatch.inputs.environment.options` out of one workflow, or `[]`.\n *\n * `yaml.parse` is untyped, and every hop here is a place a real workflow legitimately differs (a\n * `push`-only workflow has no `workflow_dispatch`; a reusable `_jobs.yml` takes `environment` as a\n * `type: string`). Hence the guards rather than a schema: absence is normal, not an error.\n *\n * @example\n * await parseEnvOptions('/repo/.github/workflows/deploy-all.yml') // => ['dev', 'prod']\n * await parseEnvOptions('/repo/.github/workflows/code-quality.yml') // => []\n */\nconst parseEnvOptions = async (workflowPath: string): Promise<string[]> => {\n let parsed: unknown\n\n try {\n parsed = yaml.parse(await fs.readFile(workflowPath, 'utf-8'))\n } catch {\n return []\n }\n\n // `on` is the YAML 1.1 boolean `true` under some parsers; `yaml@2` keeps it a string, but read\n // defensively \u2014 a wrong key here would silently empty every picker.\n const on = pick(parsed, 'on') ?? pick(parsed, 'true')\n const options = pick(pick(pick(pick(on, 'workflow_dispatch'), 'inputs'), 'environment'), 'options')\n\n if (!Array.isArray(options)) return []\n\n return options.filter((option): option is string => {\n return typeof option === 'string' && option.length > 0\n })\n}\n\n/** One safe hop into an unknown object graph. Returns `undefined` for anything that is not a record. */\nconst pick = (value: unknown, key: string): unknown => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n\n return (value as Record<string, unknown>)[key]\n}\n", "import { readTokenStore } from 'src/lib/env-tokens'\nimport { listWorkflowEnvs } from 'src/lib/workflow-envs'\n\n/** Where the knowledge that an environment EXISTS came from. Never says anything about credentials. */\nexport type ProjectEnvSource = 'gh-workflow' | 'token-only'\n\nexport interface ProjectEnv {\n env: string\n source: ProjectEnvSource\n}\n\n/**\n * Every environment this project has, from the two authorities that actually own the answer.\n *\n * `gh-workflow` \u2014 declared in a `workflow_dispatch` `environment.options` list. This is what a repo says\n * about itself, in git, reviewed, and enforced by GitHub on dispatch. It is the ONLY source that works\n * on a fresh clone with zero credentials, which is exactly when a new developer needs to be told the\n * env names they have to run `infra-kit env-token-set <env>` for.\n *\n * `token-only` \u2014 we hold a token for it, but no workflow mentions it. Real and reachable (hulyo's\n * `prod_observability` is exactly this), just not deployable from here.\n *\n * The union is the point. Neither source alone is the truth: the token store is a per-DEVELOPER cache\n * (a teammate's holds one entry; a fresh clone's holds none), and the workflows cannot know about an\n * env that exists only to be read from. Reading them together is what replaced `infra-kit.json \u2192\n * environments`, which was a hand-maintained third copy of both and had drifted from both.\n *\n * @example\n * await listProjectEnvs()\n * // => [{ env: 'dev', source: 'gh-workflow' }, \u2026, { env: 'prod_observability', source: 'token-only' }]\n */\nexport const listProjectEnvs = async (): Promise<ProjectEnv[]> => {\n const workflowEnvs = await listWorkflowEnvs()\n const store = await readTokenStore()\n\n const declared: ProjectEnv[] = workflowEnvs.map((env) => {\n return { env, source: 'gh-workflow' }\n })\n\n const known = new Set(workflowEnvs)\n\n const tokenOnly: ProjectEnv[] = Object.keys(store?.envs ?? {})\n .filter((env) => {\n return !known.has(env)\n })\n .sort()\n .map((env) => {\n return { env, source: 'token-only' }\n })\n\n // Workflow envs first, in the order the workflows declare them (`dev` leads everywhere), then the\n // strays. A picker reads best when the common choice is at the top.\n return [...declared, ...tokenOnly]\n}\n\n/** The env names alone, for the callers that only need choices. Same order as {@link listProjectEnvs}. */\nexport const listProjectEnvNames = async (): Promise<string[]> => {\n const envs = await listProjectEnvs()\n\n return envs.map((entry) => {\n return entry.env\n })\n}\n", "import fs from 'node:fs'\nimport { $ } from 'zx'\n\nimport { getProjectWarmCacheDir } from 'src/lib/constants'\nimport { logger } from 'src/lib/logger'\n\nimport { canonicalizeProjectRoot } from './warm-cache'\n\n/**\n * Warm-cache invalidation for a CREDENTIAL change (`env-token-set` / `env-token-remove`), as opposed\n * to the per-worktree invalidation `env-clear` does.\n *\n * The two keys do not line up, and that mismatch is the whole reason this exists:\n * - the WARM CACHE is keyed per WORKTREE \u2014 a sha of the realpath'd project dir ({@link\n * canonicalizeProjectRoot} + `warmCacheKey`), so every worktree of a repo has its OWN warm dir;\n * - the TOKEN STORE is keyed to the MAIN repo root \u2014 one store shared by every worktree.\n *\n * So rotating a token in one worktree would leave every OTHER worktree's warm file \u2014 up to 2h of\n * plaintext secrets fetched with the OLD token \u2014 sitting on disk, ready to be sourced at the next\n * shell prompt. A fresh token would silently lose to a stale cache. Hence: enumerate the worktrees\n * from git and purge all of them.\n */\n\n/**\n * Absolute worktree paths from `git worktree list --porcelain`, whose stanzas begin with a\n * `worktree <path>` line (the main checkout first, then each linked worktree).\n *\n * Pure, so the parse is testable without a repo.\n *\n * @example\n * parseWorktreePaths('worktree /repo\\nHEAD abc\\n\\nworktree /repo-wt/feat\\nHEAD def\\n')\n * // => ['/repo', '/repo-wt/feat']\n */\nexport const parseWorktreePaths = (porcelain: string): string[] => {\n return porcelain\n .split('\\n')\n .filter((line) => {\n return line.startsWith('worktree ')\n })\n .map((line) => {\n return line.slice('worktree '.length).trim()\n })\n .filter(Boolean)\n}\n\n/**\n * Delete the warm cache of EVERY worktree of the current repo. Returns the dirs actually removed, so\n * the caller can report the count.\n *\n * Best-effort by design: outside a git checkout (or when git fails) there are no worktrees to\n * enumerate and no warm files to lose \u2014 a token write must not fail because the purge could not run.\n * A purge that DOES fail is far less bad than a token that never gets stored.\n *\n * @example\n * await purgeRepoWarmCaches() // => ['/Users/x/.cache/infra-kit/projects/<sha>', \u2026]\n */\nexport const purgeRepoWarmCaches = async (): Promise<string[]> => {\n let porcelain: string\n\n try {\n const result = await $({ quiet: true })`git worktree list --porcelain`\n\n porcelain = result.stdout\n } catch (error) {\n logger.debug(`warm-cache purge skipped (not a git repo?): ${(error as Error).message}`)\n\n return []\n }\n\n const removed: string[] = []\n\n for (const worktree of parseWorktreePaths(porcelain)) {\n const canonical = canonicalizeProjectRoot(worktree)\n\n if (!canonical) continue\n\n const dir = getProjectWarmCacheDir(canonical)\n\n try {\n if (!fs.existsSync(dir)) continue\n\n fs.rmSync(dir, { recursive: true, force: true })\n removed.push(dir)\n } catch (error) {\n logger.debug(`warm-cache purge skipped for ${dir}: ${(error as Error).message}`)\n }\n }\n\n return removed\n}\n", "import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {\n DEFAULT_WARM_TTL_SECONDS,\n ENV_CLEAR_FILE,\n ENV_LOAD_FILE,\n atomicWriteFileSync,\n getProjectWarmCacheDir,\n getWarmCacheRoot,\n} from 'src/lib/constants'\nimport { logger } from 'src/lib/logger'\n\n/** Inputs for {@link shouldWriteWarm}. All derivable without I/O so the gate is pure. */\nexport interface ShouldWriteWarmInput {\n /** Was this an automatic load? Manual loads must never become the project default. */\n autoLoaded: boolean\n /** The canonical project dir the SHELL passed via `--project-dir` (undefined for cli-invocation / non-startup callers). */\n projectDir: string | undefined\n /** `realpath(git top-level)` for this load, or '' when non-git / unresolvable (see {@link canonicalizeProjectRoot}). */\n canonicalProjectRoot: string\n}\n\n/**\n * Decide whether an auto-load should ALSO write a project-scoped warm copy. Pure\n * (no I/O) so the full gate matrix is unit-testable. Warm requires ALL of:\n * - the load was automatic (a manual `env-load prod` must not warm the project);\n * - the shell passed a canonical `--project-dir` (warm is a shell-startup-only\n * optimization; the cli-invocation trigger passes none and gets no warm file);\n * - a non-empty git root (else every non-git project would collapse to one key\n * and cross-leak secrets);\n * - the realpath'd git root EQUALS the shell's canonical dir \u2014 the byte-identical\n * key contract. On any mismatch (symlink/nested-config monorepo) we skip warm\n * and degrade to the already-correct poll rather than write under a key the\n * shell will never look up.\n */\nexport const shouldWriteWarm = ({ autoLoaded, projectDir, canonicalProjectRoot }: ShouldWriteWarmInput): boolean => {\n if (!autoLoaded) return false\n if (!projectDir) return false\n if (!canonicalProjectRoot) return false\n\n return canonicalProjectRoot === projectDir\n}\n\n/** `realpath(projectRoot)`, or '' when projectRoot is empty or unresolvable. Never throws. */\nexport const canonicalizeProjectRoot = (projectRoot: string): string => {\n if (!projectRoot) return ''\n\n try {\n return fs.realpathSync(projectRoot)\n } catch {\n return ''\n }\n}\n\n/**\n * Write the warm copy of env-load.sh for a project (0o600). Best-effort: a warm\n * write must never break the real (session) load, so failures are swallowed to\n * debug. `contents` is the SAME bytes as the session file so a warm-source is\n * indistinguishable from a fresh one.\n */\nexport const writeWarmCache = (canonicalProjectDir: string, contents: string): void => {\n try {\n const dir = getProjectWarmCacheDir(canonicalProjectDir)\n\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n atomicWriteFileSync(path.join(dir, ENV_LOAD_FILE), contents, 0o600)\n } catch (error) {\n logger.debug(`warm-cache write skipped: ${(error as Error).message}`)\n }\n}\n\n/**\n * Delete every project's warm dir whose env-load.sh is older than the TTL. The\n * codebase has no cache reaper, so warm files (plaintext secrets) would otherwise\n * accumulate indefinitely at a stable path; each successful warm write sweeps the\n * whole `projects/` tree. The just-written project is fresh (mtime\u2248now) so it is\n * never swept. Best-effort, concurrency-tolerant (force), never throws.\n */\nexport const evictStaleWarmCaches = (\n nowMs: number = Date.now(),\n ttlSeconds: number = DEFAULT_WARM_TTL_SECONDS,\n): void => {\n const root = getWarmCacheRoot()\n\n let entries: fs.Dirent[]\n\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n return // no warm root yet \u2014 nothing to sweep\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue\n\n const projectDir = path.join(root, entry.name)\n\n try {\n const { mtimeMs } = fs.statSync(path.join(projectDir, ENV_LOAD_FILE))\n\n if (nowMs - mtimeMs >= ttlSeconds * 1000) {\n fs.rmSync(projectDir, { recursive: true, force: true })\n }\n } catch {\n // missing/unreadable warm file \u2014 leave the dir (a lone clear marker is harmless)\n }\n }\n}\n\n/**\n * Invalidate a project's warm cache on `env-clear`. `purge` removes the project's\n * warm dir outright (durable disable). Otherwise, when a warm file exists, write a\n * clear-marker (`env-clear.sh`) so the NEXT shell's startup gate skips warm-source\n * (it compares marker mtime vs warm mtime, clear wins). The marker is TRANSIENT: a\n * later successful auto-load writes a newer warm file and warm resumes \u2014 durable\n * disable requires `purge`. Best-effort, never throws.\n */\nexport const invalidateProjectWarmCache = (canonicalProjectDir: string, purge: boolean): void => {\n try {\n const dir = getProjectWarmCacheDir(canonicalProjectDir)\n\n if (purge) {\n fs.rmSync(dir, { recursive: true, force: true })\n\n return\n }\n\n // No warm file \u21D2 nothing to suppress; don't create a dir just to hold a marker.\n if (!fs.existsSync(path.join(dir, ENV_LOAD_FILE))) return\n\n atomicWriteFileSync(path.join(dir, ENV_CLEAR_FILE), '# infra-kit warm cache cleared\\n', 0o600)\n } catch (error) {\n logger.debug(`warm-cache invalidate skipped: ${(error as Error).message}`)\n }\n}\n", "import fs from 'node:fs'\nimport path from 'node:path'\n\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { hasManagedBlock, removeManagedBlock, upsertManagedBlock } from 'src/lib/managed-block'\n\nimport packageJson from '../../../package.json' with { type: 'json' }\n\n/** Markers for the generated guidance block (HTML comments \u2014 invisible in rendered markdown). */\nexport const AGENTS_MARKER_START = '<!-- infra-kit:begin -->'\nexport const AGENTS_MARKER_END = '<!-- infra-kit:end -->'\n/** The version line lives on its own line (OMC `OMC:VERSION:` precedent) so the markers stay constant-matchable. */\nconst AGENTS_VERSION_PREFIX = '<!-- infra-kit:version '\n\n/**\n * Marker pair for the legacy `@AGENTS.md` import region once injected into CLAUDE.md.\n * Migration-only now: `writeAgentFiles` strips this region so the full guidance body\n * can take its place. TODO(remove after ~2 release cycles once repos have re-run init).\n */\nexport const AGENTS_IMPORT_START = '<!-- infra-kit:import:begin -->'\nexport const AGENTS_IMPORT_END = '<!-- infra-kit:import:end -->'\n\nconst AGENTS_FILE = 'AGENTS.md'\nconst CLAUDE_FILE = 'CLAUDE.md'\n\nexport type WriteAction = 'created' | 'updated' | 'unchanged' | 'removed'\n\nexport interface AgentFileWrite {\n path: string\n action: WriteAction\n}\n\nexport interface WriteAgentFilesResult {\n /** True when run outside an infra-kit repo (no `infra-kit.json` at the git root). */\n skipped: boolean\n /** Repo root the files were written under, or null when skipped. */\n root: string | null\n written: AgentFileWrite[]\n}\n\n/** The version comment line, e.g. `<!-- infra-kit:version 0.1.105 -->`. */\nconst buildVersionLine = (version: string): string => {\n return `${AGENTS_VERSION_PREFIX}${version} -->`\n}\n\n/**\n * The generated guidance body (without the surrounding markers). Describes the\n * infra-kit CLI surface so any AI agent working in the repo learns it. Curated\n * from the real command set; the version line records which CLI version generated it.\n */\nconst buildAgentsBody = (version: string): string => {\n return [\n buildVersionLine(version),\n '',\n '# infra-kit',\n '',\n 'This repository uses the **infra-kit** CLI for environment, worktree, and release workflows.',\n 'This block is generated by `infra-kit init` \u2014 edit text *outside* the markers, never inside.',\n '',\n '## Commands (`ik` = `pnpm exec infra-kit`)',\n '',\n '- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.',\n '- `ik worktrees add` / `worktrees list` / `reopen` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.',\n '- `ik release create` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release desc-edit` \u2014 release-branch and deploy flow.',\n '- `ik release merge-dev` \u2014 merge the dev branch into every release branch.',\n '- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.',\n '- `ik doctor` \u2014 check gh / doppler / aws / rtk install + auth and repo setup.',\n '- `ik init` \u2014 (re)install shell integration and regenerate these agent-instruction files.',\n '',\n '## Conventions',\n '',\n '- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.',\n '- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.',\n ].join('\\n')\n}\n\nconst assertNotSymlink = (filePath: string): void => {\n if (fs.existsSync(filePath) && fs.lstatSync(filePath).isSymbolicLink()) {\n throw new Error(`Refusing to write ${filePath} because the destination is a symlink`)\n }\n}\n\n/** Copy a file to a timestamped `<file>.backup.<timestamp>` sibling. */\nconst backupFile = (filePath: string): void => {\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n\n fs.copyFileSync(filePath, `${filePath}.backup.${stamp}`)\n}\n\n/**\n * Write `nextContent` to `filePath` with OMC-style safety: refuse symlinks,\n * back up the prior file with a timestamp before overwriting, and skip the\n * write entirely when nothing changed (keeps re-runs churn-free).\n */\nconst writeManaged = (filePath: string, nextContent: string): WriteAction => {\n assertNotSymlink(filePath)\n\n const existed = fs.existsSync(filePath)\n const previous = existed ? fs.readFileSync(filePath, 'utf-8') : null\n\n if (previous === nextContent) return 'unchanged'\n\n if (existed) backupFile(filePath)\n\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n fs.writeFileSync(filePath, nextContent, 'utf-8')\n\n return existed ? 'updated' : 'created'\n}\n\nconst readOr = (filePath: string, fallback: string): string => {\n return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : fallback\n}\n\nconst assertBlockPresent = (filePath: string, start: string, end: string): void => {\n const content = fs.readFileSync(filePath, 'utf-8')\n\n if (!hasManagedBlock(content, start, end)) {\n throw new Error(`Post-write validation failed: managed block missing from ${filePath}`)\n }\n}\n\n/**\n * Migrate a legacy `AGENTS.md` now that the guidance lives solely in `CLAUDE.md`.\n * Strips the infra-kit managed block, then asymmetrically:\n * - no infra-kit block at all (hand-authored, not ours) \u2192 leave untouched (`unchanged`),\n * - file was purely generated (nothing but whitespace remains) \u2192 back up + delete (`removed`),\n * - hand-authored content surrounds the block \u2192 back up + write the block-free remainder (`updated`).\n * Every destructive path leaves a timestamped `.backup.` first.\n */\nconst migrateLegacyAgentsFile = (agentsPath: string): WriteAction => {\n if (!fs.existsSync(agentsPath)) return 'unchanged'\n\n assertNotSymlink(agentsPath)\n\n const content = fs.readFileSync(agentsPath, 'utf-8')\n const stripped = removeManagedBlock(content, AGENTS_MARKER_START, AGENTS_MARKER_END)\n\n if (stripped === null) return 'unchanged'\n\n if (stripped.trim() === '') {\n backupFile(agentsPath)\n fs.rmSync(agentsPath)\n\n return 'removed'\n }\n\n return writeManaged(agentsPath, stripped)\n}\n\n/**\n * Generate (or refresh) the repo agent-instruction guidance, now hosted solely in\n * `CLAUDE.md` (preserving hand-authored content outside the markers). Also migrates\n * legacy setups \u2014 stripping the old `@AGENTS.md` import region from `CLAUDE.md` and\n * backing up/removing a now-redundant `AGENTS.md`. Repo-gated: a no-op outside an\n * infra-kit repo. Idempotent (within a CLI version) and non-destructive.\n *\n * @example\n * await writeAgentFiles()\n * // INFO: Agent-instruction files synced (infra-kit 0.1.105)\n */\nexport const writeAgentFiles = async (): Promise<WriteAgentFilesResult> => {\n let mainConfigPath: string\n\n try {\n mainConfigPath = (await getInfraKitConfigPaths()).main\n } catch {\n logger.info('Skipped agent-instruction files \u2014 not inside an infra-kit repo')\n\n return { skipped: true, root: null, written: [] }\n }\n\n if (!fs.existsSync(mainConfigPath)) {\n logger.info('Skipped agent-instruction files \u2014 no infra-kit.json at the repo root')\n\n return { skipped: true, root: null, written: [] }\n }\n\n const root = path.dirname(mainConfigPath)\n const version = packageJson.version\n const body = buildAgentsBody(version)\n\n const agentsPath = path.join(root, AGENTS_FILE)\n const claudePath = path.join(root, CLAUDE_FILE)\n\n // CLAUDE.md now hosts the full guidance body. Strip the legacy `@AGENTS.md`\n // import region first (if present), then upsert the body under the begin/end\n // markers \u2014 disjoint marker pairs, so the two operations never collide.\n let claudeContent = readOr(claudePath, '')\n\n claudeContent = removeManagedBlock(claudeContent, AGENTS_IMPORT_START, AGENTS_IMPORT_END) ?? claudeContent\n claudeContent = upsertManagedBlock({\n content: claudeContent,\n body,\n startMarker: AGENTS_MARKER_START,\n endMarker: AGENTS_MARKER_END,\n placement: 'replace-in-place',\n })\n\n // CLAUDE.md is the only file we manage. A legacy AGENTS.md is migrated away.\n const written: AgentFileWrite[] = [\n { path: claudePath, action: writeManaged(claudePath, claudeContent) },\n { path: agentsPath, action: migrateLegacyAgentsFile(agentsPath) },\n ]\n\n assertBlockPresent(claudePath, AGENTS_MARKER_START, AGENTS_MARKER_END)\n\n for (const file of written) {\n // Always report CLAUDE.md; only mention a migrated file when it actually changed.\n if (file.action === 'unchanged' && file.path !== claudePath) continue\n\n logger.info(` ${file.action.padEnd(9)} ${path.relative(root, file.path)}`)\n }\n\n logger.info(`Agent-instruction files synced (infra-kit ${version})`)\n\n return { skipped: false, root, written }\n}\n", "/**\n * Generic \"managed block\" helpers \u2014 a marker-delimited region a tool owns and\n * rewrites idempotently while never touching content outside the markers.\n *\n * This is the same mechanism `infra-kit init` already uses for the `~/.zshrc`\n * shell block (`# -- infra-kit:begin -- \u2026 # -- infra-kit:end --`), lifted here so\n * it can be reused for the repo agent-instruction guidance block in `CLAUDE.md`.\n * It mirrors the design of OMC's\n * `<!-- OMC:START --> \u2026 <!-- OMC:END -->` CLAUDE.md installer.\n */\n\n/**\n * Where a freshly upserted block lands relative to existing content.\n *\n * - `replace-in-place`: if the block already exists, rewrite it where it sits\n * (surrounding text untouched, verbatim); if absent, append it at end-of-file.\n * - `append-end`: strip any existing block from wherever it is, then append the\n * fresh block at end-of-file (i.e. always relocate to the end). This preserves\n * the historical `~/.zshrc` behavior of `removeExistingBlock` + append.\n */\nexport type BlockPlacement = 'replace-in-place' | 'append-end'\n\nexport interface UpsertManagedBlockArgs {\n /** Existing file content (`''` for a new file). */\n content: string\n /** Inner body to place between the markers (WITHOUT the markers). */\n body: string\n startMarker: string\n endMarker: string\n /** Defaults to `replace-in-place`. */\n placement?: BlockPlacement\n}\n\n/**\n * Whether `content` contains a well-formed `start \u2026 end` block. A reversed pair\n * (end before start) is treated as absent \u2014 the same guard `doctor.ts` applies\n * to the zshrc block, ported here so corrupted markers never match.\n *\n * @example\n * hasManagedBlock('a<!--s-->x<!--e-->b', '<!--s-->', '<!--e-->') // => true\n * hasManagedBlock('<!--e--><!--s-->', '<!--s-->', '<!--e-->') // => false (reversed)\n */\nexport const hasManagedBlock = (content: string, startMarker: string, endMarker: string): boolean => {\n const startIdx = content.indexOf(startMarker)\n const endIdx = content.indexOf(endMarker)\n\n return startIdx !== -1 && endIdx !== -1 && endIdx >= startIdx\n}\n\n/**\n * Remove the first complete `start \u2026 end` block, preserving surrounding text.\n * Returns `null` when no well-formed block is present (no markers, or reversed),\n * so callers can fall through to legacy-format handling \u2014 this matches the\n * `string | null` contract of `init.ts`'s original `removeBetween`, with the\n * added reversed-marker guard.\n *\n * @example\n * removeManagedBlock('top\\n<!--s-->mid<!--e-->\\nbot', '<!--s-->', '<!--e-->')\n * // => 'top\\nbot'\n */\nexport const removeManagedBlock = (content: string, startMarker: string, endMarker: string): string | null => {\n const startIdx = content.indexOf(startMarker)\n const endIdx = content.indexOf(endMarker)\n\n if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) return null\n\n // eslint-disable-next-line sonarjs/super-linear-regex\n const before = content.slice(0, startIdx).replace(/\\n+$/, '')\n const after = content.slice(endIdx + endMarker.length).replace(/^\\n+/, '')\n\n return before + (after ? `\\n${after}` : '')\n}\n\n/**\n * Read the version token that follows `versionPrefix` (e.g.\n * `'<!-- infra-kit:version '`). Returns the token up to the next whitespace or\n * `>`, or `null` if the prefix is absent. Mirrors OMC's `OMC:VERSION:` line.\n *\n * @example\n * extractVersion('<!-- infra-kit:version 0.1.105 -->', '<!-- infra-kit:version ')\n * // => '0.1.105'\n */\nexport const extractVersion = (content: string, versionPrefix: string): string | null => {\n const idx = content.indexOf(versionPrefix)\n\n if (idx === -1) return null\n\n const rest = content.slice(idx + versionPrefix.length)\n const match = rest.match(/^([^\\s>]+)/)\n\n return match ? match[1]! : null\n}\n\n/**\n * Compose a full block string: `start\\n{body}\\nend`. Kept identical in shape to\n * the historical `buildShellBlock()` output so doctor's exact-match comparison\n * stays valid.\n */\nexport const buildManagedBlock = (startMarker: string, body: string, endMarker: string): string => {\n return `${startMarker}\\n${body}\\n${endMarker}`\n}\n\n/**\n * Insert or update a managed block in `content`, preserving everything outside\n * the markers. Idempotent: re-running with the same body yields the same block\n * and never nests duplicates.\n *\n * @example\n * // fresh file\n * upsertManagedBlock({ content: '', body: 'hi', startMarker: '<!--s-->', endMarker: '<!--e-->' })\n * // => '<!--s-->\\nhi\\n<!--e-->\\n'\n *\n * @example\n * // existing block replaced in place, surrounding text kept\n * upsertManagedBlock({\n * content: 'top\\n<!--s-->\\nold\\n<!--e-->\\nbot',\n * body: 'new', startMarker: '<!--s-->', endMarker: '<!--e-->',\n * })\n * // => 'top\\n<!--s-->\\nnew\\n<!--e-->\\nbot'\n */\nexport const upsertManagedBlock = ({\n content,\n body,\n startMarker,\n endMarker,\n placement = 'replace-in-place',\n}: UpsertManagedBlockArgs): string => {\n const block = buildManagedBlock(startMarker, body, endMarker)\n const present = hasManagedBlock(content, startMarker, endMarker)\n\n if (placement === 'replace-in-place' && present) {\n const startIdx = content.indexOf(startMarker)\n const endIdx = content.indexOf(endMarker) + endMarker.length\n\n return content.slice(0, startIdx) + block + content.slice(endIdx)\n }\n\n // append-end, or replace-in-place with no existing block: drop any stale block\n // then append the fresh one at end-of-file.\n const stripped = present ? (removeManagedBlock(content, startMarker, endMarker) ?? content) : content\n // eslint-disable-next-line sonarjs/super-linear-regex\n const base = stripped.replace(/\\n+$/, '')\n\n return base.length > 0 ? `${base}\\n${block}\\n` : `${block}\\n`\n}\n", "import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { seedCreatedMessage, seedUserProjectConfig } from 'src/lib/config-bootstrap'\nimport { CONFIG_STUB, buildUserGlobalExample, buildVendorExample } from 'src/lib/config-templates'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { removeManagedBlock, upsertManagedBlock } from 'src/lib/managed-block'\n\nimport { writeAgentFiles } from './agent-files'\nimport {\n migrateFactoryConfigToJson,\n migrateLegacyConfig,\n migrateUserGlobalConfigFilename,\n normalizeLegacyIdeStructures,\n} from './migrate-config'\n\nexport const MARKER_START = '# -- infra-kit:begin --'\nexport const MARKER_END = '# -- infra-kit:end --'\n\nconst LEGACY_PAIRED: [start: string, end: string][] = [['# region infra-kit', '# endregion infra-kit']]\nconst LEGACY_SINGLE = '# infra-kit shell functions'\n\n/**\n * Append infra-kit shell functions to .zshrc, migrate any legacy `infra-kit.yml`\n * config layers to JSON, normalize existing JSON configs from the old IDE structure\n * (strip the removed `ide.config.mode`), convert a legacy factory `vendor.config.ts`\n * to `vendor.json`, and seed the user-global config at ~/.infra-kit/infra-kit.json on\n * first run. Idempotent: a subsequent run replaces the existing zshrc block in place,\n * has nothing left to migrate or normalize, and leaves the REAL config files\n * (infra-kit.json / vendor.json) untouched \u2014 but the annotated `.example.jsonc`\n * reference files are refreshed on every run so they always reflect the current schema.\n *\n * @example\n * // CLI: `infra-kit init` (or via the `pnpm dx-init` alias)\n * // INFO: Added infra-kit shell functions to /Users/me/.zshrc\n * // INFO: Wrote user-global config to /Users/me/.infra-kit/infra-kit.json (see \u2026/infra-kit.example.jsonc \u2026)\n * // INFO: Run `source ~/.zshrc` or open a new terminal to activate.\n */\nexport const init = async (): Promise<void> => {\n const zshrcPath = path.join(os.homedir(), '.zshrc')\n\n // Strip any prior block (current or legacy markers) anywhere in the file, then\n // append a fresh block at end-of-file via the shared managed-block utility \u2014\n // the historical `removeExistingBlock` + append behavior, now centralized.\n const existing = fs.existsSync(zshrcPath) ? removeExistingBlock(fs.readFileSync(zshrcPath, 'utf-8')) : ''\n\n const updated = upsertManagedBlock({\n content: existing,\n body: buildShellBody(),\n startMarker: MARKER_START,\n endMarker: MARKER_END,\n placement: 'append-end',\n })\n\n fs.writeFileSync(zshrcPath, updated)\n\n logger.info(`Added infra-kit shell functions to ${zshrcPath}`)\n\n // Convert any legacy infra-kit.yml config layers to JSON before seeding, so a\n // migrated infra-kit.json is not re-seeded as an empty stub.\n await migrateLegacyConfig()\n\n // Migrate existing JSON configs from the old IDE structure to the new one\n // (strip the removed `ide.config.mode` field). No-op for already-clean configs.\n await normalizeLegacyIdeStructures()\n\n // Rename a legacy user-global config.json \u2192 infra-kit.json (single canonical\n // filename). MUST run before seeding: otherwise the seeder checks the new name,\n // doesn't find it, and writes an empty stub that shadows the user's real config.\n await migrateUserGlobalConfigFilename()\n\n // Convert a legacy machine-local factory config from executable TS\n // (~/.infra-kit/vendor.config.ts) to static JSON (~/.infra-kit/vendor.json).\n // Independent of the infra-kit.json layers; grouped with the other migrations.\n await migrateFactoryConfigToJson()\n\n seedUserGlobalConfig()\n\n // Best-effort, non-fatal, repo-gated: keep the agent-instruction files in sync\n // with the CLI surface. A no-op outside an infra-kit repo.\n await writeAgentFiles()\n\n // Close the legacy-yml migration gap so a single `dx-init` leaves EVERY example current.\n await reseedUserProjectConfig()\n\n // The shell integration is zsh-only (zmodload zsh/stat, add-zsh-hook, ${dir:h}).\n // Warn non-fatally if the user's login shell isn't zsh so the block isn't a\n // silent no-op for them.\n const shell = process.env.SHELL ?? ''\n\n if (!shell.includes('zsh')) {\n logger.warn(\n `Your login shell ($SHELL=${shell || 'unset'}) is not zsh. The infra-kit shell integration (env-load/env-clear/auto-load) is zsh-only and won't activate in bash/fish.`,\n )\n }\n\n logger.info('Run `source ~/.zshrc` or open a new terminal to activate.')\n}\n\n/**\n * Seed the user-global config on first run and (re)write the annotated reference\n * files. The real `~/.infra-kit/infra-kit.json` (empty `{}`) is written only when\n * absent so user edits are preserved. The non-loaded `.example.jsonc` reference\n * files (`infra-kit.example.jsonc` + `vendor.example.jsonc`) are rewritten on EVERY\n * run so existing users always get the current, complete schema documentation.\n *\n * Deliberately seeds NO real `vendor.json` \u2014 that is scaffolded by\n * `infra-kit vendor config --init` (a stub here would block `--init`, trip the\n * factory migration's no-overwrite guard, and fail the schema's `targets.min(1)`).\n *\n * @example\n * seedUserGlobalConfig()\n * // first call: writes ~/.infra-kit/infra-kit.json ({}) + both .example.jsonc files\n * // later calls: leaves infra-kit.json alone, refreshes both .example.jsonc files\n */\nexport const seedUserGlobalConfig = (): void => {\n const userConfigDir = path.join(os.homedir(), '.infra-kit')\n const userConfigPath = path.join(userConfigDir, 'infra-kit.json')\n\n fs.mkdirSync(userConfigDir, { recursive: true })\n\n // Reference examples are non-loaded docs \u2014 always refresh them so re-running init\n // delivers the current schema (and the newly-added vendor example) to existing users.\n fs.writeFileSync(path.join(userConfigDir, 'infra-kit.example.jsonc'), buildUserGlobalExample(), 'utf-8')\n fs.writeFileSync(path.join(userConfigDir, 'vendor.example.jsonc'), buildVendorExample(), 'utf-8')\n\n if (fs.existsSync(userConfigPath)) {\n logger.info(`User-global config already present at ${userConfigPath} (refreshed reference examples)`)\n\n return\n }\n\n fs.writeFileSync(userConfigPath, CONFIG_STUB, 'utf-8')\n\n logger.info(`Wrote user-global config to ${userConfigPath} (see the sibling .example.jsonc files for reference)`)\n}\n\n/**\n * Re-run the layer-3 seed at the END of `init()`, closing the legacy-yml migration gap.\n *\n * The per-command seed lives in the program's preAction hook, which evaluates its \"is this an\n * infra-kit repo?\" gate (does `<repo-root>/infra-kit.json` exist?) BEFORE the action body runs. On\n * the legacy-yml migration path `init()` itself CREATES that file (`migrateLegacyConfig`), so the\n * gate had already declined and this very run would otherwise leave the layer-3 example unwritten \u2014\n * self-healing only on the user's next command. Re-running the gate here makes one `dx-init` enough.\n *\n * The UNGATED primitive, deliberately: `ensureUserProjectConfig()` is an ENTRY-BOUNDARY primitive\n * whose once-per-process guard has ALREADY fired in preAction, so calling it here would be a silent\n * no-op. It is unusable as a re-seed hook. Anything else (no git repo, no project config, an\n * unwritable `$HOME`) degrades to a debug line \u2014 seeding a reference file must never fail `init`.\n *\n * Separate from {@link seedUserGlobalConfig}, which keeps its layer-2-only duty and stays sync.\n *\n * Honours `INFRA_KIT_NO_SEED` itself: the primitive is ungated by design, so without this check the\n * kill switch would be airtight on every path EXCEPT `init`.\n *\n * @example\n * await reseedUserProjectConfig()\n * // after a legacy infra-kit.yml migration:\n * // INFO: Created ~/.infra-kit/projects/api/infra-kit.json \u2014 see \u2026/infra-kit.example.jsonc \u2026\n */\nconst reseedUserProjectConfig = async (): Promise<void> => {\n if (process.env.INFRA_KIT_NO_SEED) return\n\n try {\n const paths = await getInfraKitConfigPaths()\n\n // The same D2 gate the preAction seed applies \u2014 re-evaluated now that the migrations have run.\n if (!fs.existsSync(paths.main)) return\n\n const result = await seedUserProjectConfig(paths)\n\n if (result.createdConfig) {\n logger.info(seedCreatedMessage(result))\n }\n } catch (err) {\n logger.debug({ err, msg: 'Skipped seeding the user-project config (init).' })\n }\n}\n\nconst isBlockLine = (line: string): boolean => {\n return (\n line.startsWith('#') ||\n line.startsWith('alias ') ||\n line.startsWith('env-load') ||\n line.startsWith('env-clear') ||\n line.startsWith('env-status') ||\n line.startsWith('if ') ||\n line.startsWith(' export INFRA_KIT_SESSION') ||\n line.startsWith('export _INFRA_KIT_') ||\n line.startsWith(': ${_INFRA_KIT_') ||\n line.startsWith('fi') ||\n line.startsWith('zmodload ') ||\n line.startsWith('autoload ') ||\n line.startsWith('add-zsh-hook ') ||\n line.startsWith('_infra_kit_autoload')\n )\n}\n\nexport const removeExistingBlock = (content: string): string => {\n // 1. Current markers\n const result = removeManagedBlock(content, MARKER_START, MARKER_END)\n\n if (result !== null) return result\n\n // 2. Legacy paired markers (# region / # endregion)\n for (const [start, end] of LEGACY_PAIRED) {\n const legacyResult = removeManagedBlock(content, start, end)\n\n if (legacyResult !== null) return legacyResult\n }\n\n // 3. Oldest format: single marker + heuristic scan\n const legacyIdx = content.indexOf(LEGACY_SINGLE)\n\n if (legacyIdx === -1) return content\n\n // eslint-disable-next-line sonarjs/super-linear-regex\n const before = content.slice(0, legacyIdx).replace(/\\n+$/, '')\n const afterLines = content.slice(legacyIdx).split('\\n')\n\n let i = 0\n\n while (i < afterLines.length && isBlockLine(afterLines[i]!)) {\n i++\n }\n\n const remaining = afterLines.slice(i).join('\\n')\n\n return before + (remaining ? `\\n${remaining}` : '')\n}\n\n/**\n * The inner shell-function lines (no markers). Composed into the full marked\n * block by {@link buildShellBlock} and fed to `upsertManagedBlock` by `init()`.\n */\nexport const buildShellBody = (): string => {\n const runCmd = 'pnpm exec infra-kit'\n\n return [\n 'zmodload zsh/stat 2>/dev/null',\n 'zmodload zsh/datetime 2>/dev/null',\n 'zmodload zsh/sched 2>/dev/null',\n // eslint-disable-next-line no-template-curly-in-string\n 'if [[ -z \"${INFRA_KIT_SESSION}\" ]]; then',\n ' export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)',\n 'fi',\n // eslint-disable-next-line no-template-curly-in-string\n ': ${_INFRA_KIT_LAST_LOAD_MTIME:=0}',\n // eslint-disable-next-line no-template-curly-in-string\n ': ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}',\n // eslint-disable-next-line no-template-curly-in-string\n ': ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}',\n // Warm-cache source TTL (seconds); MUST equal DEFAULT_WARM_TTL_SECONDS (node\n // eviction) \u2014 both 2h. A warm file older than this is not sourced at startup.\n // eslint-disable-next-line no-template-curly-in-string\n ': ${_INFRA_KIT_WARM_TTL:=7200}',\n 'export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED _INFRA_KIT_WARM_TTL',\n `env-load() { local f m; f=$(${runCmd} env-load \"$@\") || return; m=$(zstat +mtime -- \"$f\" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source \"$f\"; ${runCmd} env-status; }`,\n `env-clear() { local f m; f=$(${runCmd} env-clear \"$@\") || return; m=$(zstat +mtime -- \"$f\" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source \"$f\"; ${runCmd} env-status; }`,\n `env-status() { ${runCmd} env-status; }`,\n // No `alias ik=\u2026` here: a global install provides real `infra-kit` and `ik` bins, and an alias\n // would SHADOW the global `ik`, forcing the project-local `pnpm exec` even when a global CLI exists.\n // (`isBlockLine` still lists `alias ` so re-running `init` strips the stale alias from old configs.)\n // Print an async notice without corrupting an already-drawn prompt. The\n // startup poll fires via `sched` at an IDLE prompt (ZLE active) which does\n // NOT redraw the prompt, so a bare `print` lands appended to the visible\n // prompt line and looks like un-removable typed input. When ZLE is active we\n // erase the current line (CR + clear-to-EOL), print the message on its own\n // line, then `zle reset-prompt` to redraw the prompt below it. In precmd /\n // shell-startup (ZLE inactive) `zle` is false and this is a plain stderr\n // print above the about-to-be-drawn prompt \u2014 unchanged behavior.\n '_infra_kit_notify() {',\n // When ZLE is active, erase the current prompt line first and redraw after;\n // both are no-ops when ZLE is inactive so this stays a plain stderr print.\n \" zle && print -u2 -n $'\\\\r\\\\e[K'\",\n ' print -u2 -- \"$1\"',\n ' zle && zle reset-prompt',\n '}',\n '_infra_kit_autoload() {',\n ' [[ -z \"$INFRA_KIT_SESSION\" ]] && return',\n // eslint-disable-next-line no-template-curly-in-string\n ' local cache_root=\"${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit\"',\n ' local dir=\"$cache_root/$INFRA_KIT_SESSION\"',\n ' local load_file=\"$dir/env-load.sh\"',\n ' local clear_file=\"$dir/env-clear.sh\"',\n ' local load_mtime=0 clear_mtime=0',\n ' [[ -f \"$load_file\" ]] && load_mtime=$(zstat +mtime -- \"$load_file\" 2>/dev/null || echo 0)',\n ' [[ -f \"$clear_file\" ]] && clear_mtime=$(zstat +mtime -- \"$clear_file\" 2>/dev/null || echo 0)',\n ' if (( load_mtime > _INFRA_KIT_LAST_LOAD_MTIME && load_mtime >= _INFRA_KIT_SHELL_STARTED && load_mtime >= clear_mtime )); then',\n ' source \"$load_file\"',\n ' _INFRA_KIT_LAST_LOAD_MTIME=$load_mtime',\n // eslint-disable-next-line no-template-curly-in-string\n ' _infra_kit_notify \"infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}\"',\n ' fi',\n ' if (( clear_mtime > _INFRA_KIT_LAST_CLEAR_MTIME && clear_mtime >= _INFRA_KIT_SHELL_STARTED && clear_mtime > load_mtime )); then',\n ' source \"$clear_file\"',\n ' _INFRA_KIT_LAST_CLEAR_MTIME=$clear_mtime',\n ' _infra_kit_notify \"infra-kit: auto-cleared env\"',\n ' fi',\n '}',\n 'autoload -Uz add-zsh-hook',\n 'if (( _INFRA_KIT_SHELL_STARTED > 0 )); then',\n ' add-zsh-hook precmd _infra_kit_autoload',\n 'fi',\n // Non-blocking startup poll: the shell-startup spawn (below) writes env-load.sh\n // asynchronously (node + Doppler fetch, ~0.5-2s), so the FIRST precmd \u2014 which\n // fires before the first prompt \u2014 runs before the file lands and sources nothing;\n // without this the vars only appear after the user's first command. This one-shot\n // re-arming poll re-runs the precmd sourcer once per second, at the idle prompt\n // with NO user command, until it sources the freshly written file (its mtime is\n // >= _INFRA_KIT_SHELL_STARTED so the existing gate accepts it) OR the startup\n // window closes. _infra_kit_autoload sets _INFRA_KIT_LAST_LOAD_MTIME on a\n // successful source, which lifts it to >= _INFRA_KIT_SHELL_STARTED and stops the\n // re-arm. Bounded to WINDOW seconds so an unconfigured project / down Doppler\n // that never writes a file only costs a handful of no-op ticks, then falls back\n // to the precmd hook. Sources the same freshly written file as precmd, so there\n // is no stale/last-known-good secrets window.\n '_INFRA_KIT_AUTOLOAD_WINDOW=6',\n 'export _INFRA_KIT_AUTOLOAD_WINDOW',\n '_infra_kit_poll_autoload() {',\n ' _infra_kit_autoload',\n // eslint-disable-next-line no-template-curly-in-string\n ' if (( _INFRA_KIT_LAST_LOAD_MTIME < _INFRA_KIT_SHELL_STARTED )) && (( ${EPOCHSECONDS:-0} - _INFRA_KIT_SHELL_STARTED < _INFRA_KIT_AUTOLOAD_WINDOW )); then',\n ' (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload',\n ' fi',\n '}',\n // Warm cache: source the project-scoped last-known-good env-load.sh INSTANTLY at\n // startup (pure zsh, no node/Doppler) so vars are present at prompt-0, before the\n // backgrounded refresh lands. `key` is sha256 of the canonical project dir passed\n // in by the caller \u2014 byte-identical to node's warmCacheKey (printf %s | shasum,\n // full 64-hex). Skips when: no sha tool (degrade to poll), no warm file, a project\n // clear-marker is at least as new (clear wins ties), or the file is past TTL\n // (bounds a rotated secret served at prompt-0). Deliberately does NOT set\n // _INFRA_KIT_LAST_LOAD_MTIME (leaves it 0) so the poll/precmd still source the\n // fresh SESSION file (different path, newer mtime) and upgrade warm->fresh.\n '_infra_kit_warm_source() {',\n ' local canon=\"$1\" key',\n ' if (( $+commands[shasum] )); then',\n ' key=$(printf %s \"$canon\" | shasum -a 256 | cut -c1-64)',\n ' elif (( $+commands[sha256sum] )); then',\n ' key=$(printf %s \"$canon\" | sha256sum | cut -c1-64)',\n ' else',\n ' return',\n ' fi',\n // eslint-disable-next-line no-template-curly-in-string\n ' local cache_root=\"${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit\"',\n ' local warm=\"$cache_root/projects/$key/env-load.sh\"',\n ' local wclear=\"$cache_root/projects/$key/env-clear.sh\"',\n ' [[ -f \"$warm\" ]] || return',\n ' local wm=0 cm=0',\n ' wm=$(zstat +mtime -- \"$warm\" 2>/dev/null || echo 0)',\n ' [[ -f \"$wclear\" ]] && cm=$(zstat +mtime -- \"$wclear\" 2>/dev/null || echo 0)',\n ' (( cm >= wm )) && return',\n // eslint-disable-next-line no-template-curly-in-string\n ' (( ${EPOCHSECONDS:-0} - wm >= _INFRA_KIT_WARM_TTL )) && return',\n ' source \"$warm\"',\n // eslint-disable-next-line no-template-curly-in-string\n ' _infra_kit_notify \"infra-kit: loaded cached vars for ${INFRA_KIT_ENV_CONFIG:-?} (refreshing\u2026)\"',\n '}',\n // One-shot env auto-load when a NEW shell opens inside an infra-kit project\n // or worktree (config: envAutoLoad.trigger \"shell-startup\"). Cheap pure-zsh\n // project gate (walk up for infra-kit.json) avoids spawning node in unrelated\n // shells; the spawn is skipped only when the already-loaded env belongs to THIS\n // project root (INFRA_KIT_ENV_PROJECT_ROOT), so cd'ing into a DIFFERENT project\n // re-loads instead of silently keeping the previous project's secrets. The spawn\n // is DETACHED+backgrounded ( ... & ) so it never blocks the prompt; it only\n // WRITES env-load.sh. The startup poll armed right after (and the precmd hook as\n // a later-prompt fallback) sources the file once it lands. Trade-off: the gate\n // can't read the merged JSON config, so a fresh shell in a project WITHOUT\n // envAutoLoad still spawns one background process that resolves config, finds\n // nothing, and exits.\n '_infra_kit_startup_autoload() {',\n ' [[ -z \"$INFRA_KIT_SESSION\" ]] && return',\n ' local dir=\"$PWD\" prev=\"\"',\n ' while [[ -n \"$dir\" && \"$dir\" != \"$prev\" ]]; do',\n ' if [[ -f \"$dir/infra-kit.json\" ]]; then',\n ' [[ -n \"$INFRA_KIT_ENV_CONFIG\" && \"$dir\" == \"$INFRA_KIT_ENV_PROJECT_ROOT\" ]] && return',\n // canon = realpath of the project dir; the SAME string node hashes for the warm\n // key (passed via --project-dir), so the two keys are byte-identical.\n // eslint-disable-next-line no-template-curly-in-string\n ' local canon=\"${dir:A}\"',\n ' _infra_kit_warm_source \"$canon\"',\n ` ( ${runCmd} env-autoload --project-dir \"$canon\" & ) >/dev/null 2>&1`,\n ' (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload',\n ' return',\n ' fi',\n ' prev=\"$dir\"',\n // eslint-disable-next-line no-template-curly-in-string\n ' dir=\"${dir:h}\"',\n ' done',\n '}',\n 'if (( _INFRA_KIT_SHELL_STARTED > 0 )); then',\n ' _infra_kit_startup_autoload',\n 'fi',\n ].join('\\n')\n}\n\n/**\n * The full marker-delimited shell block (`MARKER_START \u2026 MARKER_END`). Kept as\n * a single composed string so `doctor`'s exact-match freshness check stays valid.\n */\nexport const buildShellBlock = (): string => {\n return `${MARKER_START}\\n${buildShellBody()}\\n${MARKER_END}`\n}\n", "// DEFAULT import, deliberately: the module is used as `fs.writeFile(...)` / `fs.mkdir(...)` so every\n// call is a property lookup on the live module object, which is what `vi.spyOn(fs, 'writeFile')`\n// patches. A named import (`import { writeFile }`) is bound at import time and the spy silently does\n// NOT intercept it \u2014 verified empirically (default form: spy sees 1 call; named form: spy sees 0\n// calls AND the real write still happens). The \"0 writes in steady state\" tests would then be false\n// greens while the seed churned the disk on every command. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { CONFIG_STUB, buildUserProjectExample } from 'src/lib/config-templates'\nimport { getInfraKitConfigPaths, resetMergedConfigCache } from 'src/lib/infra-kit-config'\nimport type { InfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { fileExists, tildify } from 'src/lib/path-display'\n\nexport interface SeedUserProjectResult {\n configPath: string\n examplePath: string\n createdConfig: boolean\n refreshedExample: boolean\n}\n\n/**\n * Once-per-process guard for {@link ensureUserProjectConfig}. The MCP server is long-lived and\n * handles N tool calls in one process \u2014 without this it would re-stat the config on every call.\n */\nlet seeded = false\n\n/**\n * Derive the non-loaded `.example.jsonc` sibling for a config path. The config loader only globs the\n * three exact `infra-kit.json` filenames, so the sibling never enters the merge chain.\n *\n * @example\n * exampleSiblingPath('/u/.infra-kit/projects/api/infra-kit.json')\n * // => '/u/.infra-kit/projects/api/infra-kit.example.jsonc'\n */\nconst exampleSiblingPath = (jsonPath: string): string => {\n return jsonPath.replace(/\\.json$/, '.example.jsonc')\n}\n\n/**\n * Read a file, degrading a missing/unreadable file to `null` so callers can content-compare without\n * branching on ENOENT.\n *\n * @example\n * await readFileOrNull('/nope.jsonc') // => null\n */\nconst readFileOrNull = async (filePath: string): Promise<string | null> => {\n try {\n return await fs.readFile(filePath, 'utf-8')\n } catch {\n return null\n }\n}\n\n/**\n * Create the layer-3 user-project override file (`~/.infra-kit/projects/<repo>/infra-kit.json`) and\n * keep its annotated `.example.jsonc` sibling in sync with the current schema.\n *\n * UNGATED and MAY THROW \u2014 this is the primitive, shared by `config edit` and by the entry-boundary\n * wrapper {@link ensureUserProjectConfig}. It deliberately does NOT honour `INFRA_KIT_NO_SEED`\n * (that kill switch guards the wrapper only) and does NOT check for a committed project config.\n *\n * An existing `infra-kit.json` is NEVER touched \u2014 user bytes are sacred. The example is rewritten\n * only when its content differs (content compare, not mtime), so the steady state performs zero\n * writes. The MERGED config cache is reset only when the `.json` was actually created: the `.jsonc`\n * example is not part of the merge chain, so refreshing it invalidates nothing. The path memo is\n * left alone either way \u2014 see {@link resetMergedConfigCache}.\n *\n * @example\n * const paths = await getInfraKitConfigPaths()\n * await seedUserProjectConfig(paths)\n * // => { configPath: '/u/.infra-kit/projects/api/infra-kit.json',\n * // examplePath: '/u/.infra-kit/projects/api/infra-kit.example.jsonc',\n * // createdConfig: true, refreshedExample: true }\n */\nexport const seedUserProjectConfig = async (paths: InfraKitConfigPaths): Promise<SeedUserProjectResult> => {\n const configPath = paths.userProject\n const examplePath = exampleSiblingPath(configPath)\n\n await fs.mkdir(path.dirname(configPath), { recursive: true })\n\n const createdConfig = !(await fileExists(configPath))\n\n if (createdConfig) {\n // JSON can't carry comments, so seed an empty-but-valid config and drop the annotated guidance\n // next to it in a non-loaded .example.jsonc.\n await fs.writeFile(configPath, CONFIG_STUB, 'utf-8')\n }\n\n const example = buildUserProjectExample(paths.projectName)\n const refreshedExample = (await readFileOrNull(examplePath)) !== example\n\n if (refreshedExample) {\n await fs.writeFile(examplePath, example, 'utf-8')\n }\n\n if (createdConfig) {\n // Only the .json is a real merge layer \u2014 never invalidate the cache for a .jsonc-only refresh.\n // MERGED cache only: the new layer changes the merge result, but the resolved paths are a pure\n // function of cwd + homedir, so dropping the path memo here would re-spawn both `git rev-parse`\n // calls on the one run that creates the file.\n resetMergedConfigCache()\n }\n\n return { configPath, examplePath, createdConfig, refreshedExample }\n}\n\n/**\n * The one INFO line announcing a freshly created layer-3 config. Shared by all three seed call sites\n * (the entry-boundary bootstrap below, `config edit`, and `init`) \u2014 they announce the same event and\n * must not drift into three wordings.\n *\n * @example\n * seedCreatedMessage(result)\n * // => 'Created ~/.infra-kit/projects/api/infra-kit.json \u2014 see ~/.infra-kit/projects/api/infra-kit.example.jsonc for the annotated reference.'\n */\nexport const seedCreatedMessage = (result: SeedUserProjectResult): string => {\n return `Created ${tildify(result.configPath)} \u2014 see ${tildify(result.examplePath)} for the annotated reference.`\n}\n\n/**\n * Entry-boundary bootstrap: gate, seed, swallow. NEVER throws and NEVER changes the exit code, so it\n * is safe to await from a CLI preAction hook or an MCP tool-call boundary.\n *\n * Order: the `INFRA_KIT_NO_SEED` kill switch (truthiness, so `vi.stubEnv(\u2026, '')` disarms it), the\n * once-per-process guard, path resolution (throws outside a git repo \u2192 silent no-op), then the D2\n * gate \u2014 no committed `<repo-root>/infra-kit.json` means this is not an infra-kit project, so\n * nothing is ever created under `~/.infra-kit/projects/` for it.\n *\n * Any seed failure (EACCES / EROFS / ENOSPC / read-only HOME) is `logger.debug`-ed and swallowed.\n * Exactly one `logger.info` line is emitted, and only when the `.json` was actually created; an\n * example-only refresh is `logger.debug` (rewriting a non-loaded reference file is not news).\n * Steady state is completely silent.\n *\n * @example\n * // CLI preAction / MCP tool boundary\n * await ensureUserProjectConfig()\n * // first run in an infra-kit repo \u2014 INFO: Created ~/.infra-kit/projects/api/infra-kit.json \u2014 \u2026\n * // every later run \u2014 silent, zero writes\n */\nexport const ensureUserProjectConfig = async (): Promise<void> => {\n if (process.env.INFRA_KIT_NO_SEED) {\n return\n }\n\n if (seeded) {\n return\n }\n\n seeded = true\n\n let paths: InfraKitConfigPaths\n\n try {\n paths = await getInfraKitConfigPaths()\n } catch {\n // Outside a git repo `git rev-parse --show-toplevel` fails. Not an infra-kit project \u2014 no-op.\n return\n }\n\n if (!(await fileExists(paths.main))) {\n return\n }\n\n try {\n const result = await seedUserProjectConfig(paths)\n\n if (result.createdConfig) {\n logger.info(seedCreatedMessage(result))\n } else if (result.refreshedExample) {\n logger.debug(`Refreshed ${tildify(result.examplePath)} to match the current schema.`)\n }\n } catch (err) {\n logger.debug({ err, msg: `Skipped seeding ${tildify(paths.userProject)} (config bootstrap failed).` })\n }\n}\n\n/**\n * Clear the once-per-process seed guard. Tests only \u2014 production seeds exactly once per process.\n *\n * @example\n * resetUserProjectSeedGuard()\n * await ensureUserProjectConfig() // resolves paths again instead of short-circuiting\n */\nexport const resetUserProjectSeedGuard = (): void => {\n seeded = false\n}\n", "/**\n * The annotated JSONC reference templates for every infra-kit config file, in one\n * place. Extracted from `commands/init` (layers 2 + vendor) and `commands/config`\n * (layer 3), which each carried a private copy that drifted out of sync with the\n * schema.\n *\n * PURE by construction: strings only, zero I/O \u2014 no `node:fs`, `node:os` or\n * `node:path` here. Callers own the writing; this module owns the words. That is\n * what lets `config-templates.test.ts` diff the templates against\n * `infraKitConfigObject.shape` with no filesystem fakes.\n */\n\n/**\n * The real config files are strict JSON and cannot carry comments, so every seeded\n * `infra-kit.json` starts life as an empty-but-valid object; the guidance lives in\n * the non-loaded `.example.jsonc` sibling built below.\n */\nexport const CONFIG_STUB = '{}\\n'\n\n// The documented key set, shared verbatim by the layer-2 (user-global) and layer-3\n// (user-project) examples so the two can never disagree about what the schema is.\n// Covers ALL eight top-level keys of `infraKitConfigObject` \u2014 `config-templates.test.ts`\n// fails the build if a ninth is added to the schema and not documented here.\n//\n// Every line is a `//` comment: the surrounding braces are the only live JSON, so the\n// file always parses to `{}` once the comments are stripped.\nconst CONFIG_KEY_DOCS = ` // \"envManagement\": { // required in layer 1; provider-tagged\n // \"provider\": \"doppler\",\n // \"config\": { \"name\": \"my-doppler-project\" }\n // },\n //\n // \"ide\": {\n // \"provider\": \"cursor\",\n // \"config\": { \"workspaceConfigPath\": \"/path/to/your.code-workspace\" }\n // },\n // // Or, for Zed (no workspace file \u2014 one window with all worktrees via \"zed <root> <wt...>\"):\n // \"ide\": { \"provider\": \"zed\", \"config\": {} },\n // // Or drive BOTH editors at once with an array (at most one entry per provider):\n // \"ide\": [\n // { \"provider\": \"cursor\", \"config\": { \"workspaceConfigPath\": \"/path/to/your.code-workspace\" } },\n // { \"provider\": \"zed\", \"config\": {} }\n // ],\n //\n // \"taskManager\": {\n // \"provider\": \"jira\",\n // \"config\": { \"baseUrl\": \"https://acme.atlassian.net\", \"projectId\": 123 }\n // },\n //\n // \"worktrees\": {\n // \"openInGithubDesktop\": false,\n // \"openInCmux\": true,\n // // cmux pane layout for opened worktrees: \"two-columns\" (default, left | right)\n // // or \"three-pane\" (left split top/bottom + full-height right).\n // \"cmux\": { \"layout\": \"two-columns\" }\n // },\n //\n // // Auto-load Doppler env when working inside this project/worktree. Omit to\n // // disable. \"trigger\" (pick one): \"shell-startup\" (new shells) | \"cli-invocation\"\n // // (before each infra-kit command, primes subsequent commands). \"config\" is the\n // // environment to load \u2014 must have a service token (infra-kit env-token-set) or\n // // auto-load quietly disables. Requires the committed infra-kit.json at the git\n // // repo root, and the zsh shell integration (infra-kit init + a new shell). zsh only.\n // \"envAutoLoad\": { \"trigger\": \"shell-startup\", \"config\": \"dev\" },\n //\n // // Per-app local-dev overrides, keyed by APP FOLDER name (the directory under\n // // apps/). Both fields optional: \"port\" pins the local listen port (otherwise\n // // <APP>_PORT / PORT / a built-in default), \"prefixUrl\" pins the URL prefix the\n // // app is served under. An unknown app name is ignored at resolve time, never a\n // // parse error.\n // \"dev\": {\n // \"client\": { \"port\": 4001, \"prefixUrl\": \"/api\" }\n // },\n //\n // // Named \\`infra-kit dev <preset>\\` sessions. The keys under \"apps\" are PACKAGES \u2014\n // // \"<app>/api\" or \"<app>/ui\". A bare \"<app>\" is a FOLDER, not a package, and is\n // // REJECTED. Per target: \"watchDeps\" (api targets) rebuilds the shared-package\n // // dependency closure and restarts on change; \"proxy\" maps a route path to\n // // \"local\" | \"cloud\" for this session only. \"cmux\": true runs each launched target\n // // in its own cmux pane. Omit \"apps\" entirely to launch every discovered target.\n // \"devServersPresets\": {\n // \"backend\": {\n // \"apps\": {\n // \"client/api\": { \"watchDeps\": true, \"proxy\": { \"/api\": \"local\", \"/auth\": \"cloud\" } },\n // \"client/ui\": {}\n // },\n // \"cmux\": true\n // }\n // },\n //\n // // DEPRECATED \u2014 accepted but IGNORED; safe to delete. Remove it and this note in a\n // // future release.\n // //\n // // The proxy port is no longer configurable. Every dev URL is now\n // // https://<release>.<package>.localhost with NO port, and the only port that can\n // // serve a port-free HTTPS URL is 443 \u2014 so a setting here could only put the port\n // // back into the URL. Set up the daemon once (the install is the only step needing\n // // root; trusting its local CA does not). Run \\`infra-kit doctor\\`: it checks both and\n // // prints each fix as a command you can paste, with the paths filled in for your\n // // machine. Do not type a bare \\`portless\\` \u2014 it lives in node_modules, not on PATH.\n // // infra-kit itself never elevates.\n // \"devProxy\": { \"port\": 443 }\n //\n // // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in\n // // tokens.json \u2014 a SIBLING of this file, at ~/.infra-kit/projects/<repo>/tokens.json (mode 0600) \u2014\n // // shaped { \"envs\": { \"<env>\": \"dp.st\u2026\" } }. Write it with \\`infra-kit env-token-set <env>\\` (which\n // // also fixes its modes), or by hand: both are supported, which is why the store carries no\n // // repo-identity field and no mandatory version. Pasting a token into an\n // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke\n // // the token first, because a config file can be committed, backed up by your editor, or shared.`\n\n/**\n * Annotated JSONC reference for the user-global (layer 2) config, written next to the\n * real `~/.infra-kit/infra-kit.json` by `infra-kit init`. Documents every top-level\n * key of the schema.\n *\n * @example\n * buildUserGlobalExample()\n * // => '// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json\\n\u2026\\n{\\n // \"envManagement\": \u2026\\n}\\n'\n */\nexport const buildUserGlobalExample = (): string => {\n return `// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json\n//\n// Merge chain (later layers override earlier ones at top-level keys):\n// 1. <repo>/infra-kit.json \u2014 committed project config (required)\n// 2. ~/.infra-kit/infra-kit.json \u2014 user-global (the sibling of this file)\n// 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override\n//\n// Merge is shallow: setting a top-level key replaces that whole section from\n// layer 1. Arrays do not concatenate. Top-level keys recognized:\n// envManagement, ide, taskManager, worktrees, envAutoLoad, dev,\n// devServersPresets, devProxy. The schema is strict \u2014 an unrecognized top-level\n// key is a parse error, not a silently ignored one.\n//\n// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global\n// overrides in the sibling infra-kit.json (strict JSON: no comments, double-quoted\n// keys). Per-project tweaks belong in layer 3 \u2014 run \\`infra-kit config edit\\`.\n//\n// Every recognized key is documented below. NOTE: \\`envManagement\\` is REQUIRED in\n// the committed project infra-kit.json (layer 1) and is usually NOT set in this\n// user-global layer \u2014 it is shown here only to document the full, valid config shape.\n{\n${CONFIG_KEY_DOCS}\n}\n`\n}\n\n/**\n * Annotated JSONC reference for the user-scope per-project override (layer 3), written\n * alongside the real `~/.infra-kit/projects/<projectName>/infra-kit.json`. Same key\n * documentation as layer 2 \u2014 only the header differs. Deterministic: the project name\n * is the only input, and no path or timestamp from the host leaks into the output.\n *\n * @example\n * buildUserProjectExample('hulyo-monorepo')\n * // => '// infra-kit user override for hulyo-monorepo \u2014 ~/.infra-kit/projects/hulyo-monorepo/infra-kit.json\\n\u2026'\n */\nexport const buildUserProjectExample = (projectName: string): string => {\n return `// infra-kit user override for ${projectName} \u2014 ~/.infra-kit/projects/${projectName}/infra-kit.json\n//\n// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of\n// <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a\n// top-level key set here replaces that whole section wholesale; arrays do not\n// concatenate. Top-level keys recognized: envManagement, ide,\n// taskManager, worktrees, envAutoLoad, dev, devServersPresets, devProxy. The schema\n// is strict \u2014 an unrecognized top-level key is a parse error, not a silently ignored\n// one.\n//\n// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides\n// in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).\n//\n// Every recognized key is documented below. NOTE: \\`envManagement\\` is REQUIRED in\n// the committed project infra-kit.json (layer 1) and is usually NOT set in this\n// override layer \u2014 it is shown here only to document the full, valid config shape.\n{\n${CONFIG_KEY_DOCS}\n}\n`\n}\n\n/**\n * Annotated JSONC reference for the machine-local factory registry\n * (`~/.infra-kit/vendor.json`). Independent of the infra-kit.json merge chain: the real\n * file is scaffolded by `infra-kit vendor config --init`, never seeded by `init`.\n *\n * @example\n * buildVendorExample()\n * // => '// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json\\n\u2026\\n{\\n // \"workspaceDir\": \u2026\\n}\\n'\n */\nexport const buildVendorExample = (): string => {\n return `// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json\n//\n// Machine-local registry the vendor commands (sync/manifest/diff) read to know\n// where your project repos live and which ones to stamp. This .example.jsonc is\n// reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling\n// vendor.json (no comments, double-quoted keys); run \\`infra-kit vendor config --init\\`\n// to scaffold it.\n{\n // \"workspaceDir\": \"~/projects\", // string (absolute or ~-prefixed) \u2014 where target repos are cloned\n // \"targets\": [\"my-repo-a\", \"my-repo-b\"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir\n}\n`\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport yaml from 'yaml'\nimport { z } from 'zod'\n\nimport {\n getInfraKitConfigPaths,\n infraKitConfigSchema,\n infraKitOverrideConfigSchema,\n resetInfraKitConfigCache,\n} from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { fileExists, tildify } from 'src/lib/path-display'\nimport { getFactoryConfigPath } from 'src/lib/vendor/factory-config'\nimport { factoryConfigSchema } from 'src/lib/vendor/factory-config-schema'\n\ninterface MigrateLayer {\n label: string\n /** Legacy YAML source path. */\n yml: string\n /** Target JSON path. */\n json: string\n /** Validates the parsed object before any write (main vs override schema). */\n schema: z.ZodType\n}\n\n/**\n * Swap a resolved `.json` config path back to its legacy `.yml` sibling.\n *\n * @example\n * legacyYmlPath('/repo/infra-kit.json') // => '/repo/infra-kit.yml'\n */\nconst legacyYmlPath = (jsonPath: string): string => {\n return jsonPath.replace(/\\.json$/, '.yml')\n}\n\n/**\n * Convert any legacy `infra-kit.yml` config layers to `infra-kit.json` as part\n * of `infra-kit init`. Best-effort and non-fatal: each merge-chain layer\n * (project, user-global, user-project) is migrated independently, and a\n * conflict (both `.yml` and `.json` present) or an invalid `.yml` warns and\n * skips that layer rather than aborting init or touching the other layers.\n * Idempotent \u2014 already-JSON layers are left untouched.\n *\n * @example\n * await migrateLegacyConfig()\n * // INFO: \u2713 Migrated infra-kit.yml \u2192 infra-kit.json\n * // (no output when there is nothing legacy to convert)\n */\nexport const migrateLegacyConfig = async (): Promise<void> => {\n let paths: Awaited<ReturnType<typeof getInfraKitConfigPaths>>\n\n try {\n paths = await getInfraKitConfigPaths()\n } catch {\n // No resolvable project (e.g. init run outside a repo) \u2014 nothing to migrate.\n return\n }\n\n const layers: MigrateLayer[] = [\n { label: 'infra-kit.json', yml: legacyYmlPath(paths.main), json: paths.main, schema: infraKitConfigSchema },\n {\n label: '~/.infra-kit/infra-kit.json',\n // The user-global JSON filename changed (config.json \u2192 infra-kit.json), but\n // the legacy YAML it converts from kept the old `config.yml` name. Pin it\n // here so it does not drift to `infra-kit.yml` via legacyYmlPath(); the\n // main/userProject layers keep deriving their `.yml` sibling normally\n // because their `.json` filename never changed.\n yml: path.join(path.dirname(paths.userGlobal), 'config.yml'),\n json: paths.userGlobal,\n schema: infraKitOverrideConfigSchema,\n },\n {\n label: `~/.infra-kit/projects/${paths.projectName}/infra-kit.json`,\n yml: legacyYmlPath(paths.userProject),\n json: paths.userProject,\n schema: infraKitOverrideConfigSchema,\n },\n ]\n\n let migrated = 0\n\n for (const layer of layers) {\n const [ymlExists, jsonExists] = await Promise.all([fileExists(layer.yml), fileExists(layer.json)])\n\n if (!ymlExists) continue\n\n if (jsonExists) {\n logger.info(\n `\u26A0 Skipped ${tildify(layer.yml)} \u2014 ${tildify(layer.json)} already exists (remove the stale .yml manually)`,\n )\n\n continue\n }\n\n // Keep per-layer migration non-fatal even for malformed YAML or I/O errors\n // (TOCTOU after the existence probe, EACCES, read-only FS): warn and skip\n // so one bad layer never aborts `init` or the other layers.\n try {\n const raw = await fs.readFile(layer.yml, 'utf-8')\n const parsed = (yaml.parse(raw) ?? {}) as unknown\n const result = layer.schema.safeParse(parsed)\n\n if (!result.success) {\n logger.info(`\u26A0 Skipped ${tildify(layer.yml)} \u2014 invalid config: ${z.prettifyError(result.error)}`)\n\n continue\n }\n\n await fs.mkdir(path.dirname(layer.json), { recursive: true })\n await fs.writeFile(layer.json, `${JSON.stringify(result.data, null, 2)}\\n`, 'utf-8')\n await fs.rm(layer.yml, { force: true })\n\n logger.info(`\u2713 Migrated ${tildify(layer.yml)} \u2192 ${tildify(layer.json)}`)\n migrated++\n } catch (err) {\n logger.info(`\u26A0 Skipped ${tildify(layer.yml)} \u2014 ${(err as Error).message}`)\n }\n }\n\n if (migrated > 0) {\n resetInfraKitConfigCache()\n }\n}\n\n/**\n * Rename the user-global config from the legacy `config.json` filename to the\n * canonical `infra-kit.json` (and its `config.example.jsonc` reference to\n * `infra-kit.example.jsonc`), so every merge-chain layer shares one filename.\n * Run by `infra-kit init` before the user-global config is seeded, so a user's\n * existing overrides are carried forward instead of being shadowed by a fresh\n * `{}` stub written under the new name.\n *\n * Best-effort and non-fatal per file: a missing source is skipped silently\n * (idempotent \u2014 nothing to rename on a second run), and an already-present\n * target is never overwritten (the stale `config.json` is left in place so no\n * bytes are lost \u2014 the user reconciles it manually). Resets the config cache\n * when anything was renamed.\n *\n * @example\n * await migrateUserGlobalConfigFilename()\n * // \u2713 Renamed ~/.infra-kit/config.json \u2192 ~/.infra-kit/infra-kit.json\n * // (no output when there is nothing legacy to rename)\n */\nexport const migrateUserGlobalConfigFilename = async (): Promise<void> => {\n let paths: Awaited<ReturnType<typeof getInfraKitConfigPaths>>\n\n try {\n paths = await getInfraKitConfigPaths()\n } catch {\n // No resolvable project (e.g. init run outside a repo) \u2014 nothing to rename.\n return\n }\n\n const dir = path.dirname(paths.userGlobal)\n // The config.json \u2192 infra-kit.json rename carries forward a user's REAL config and\n // is load-bearing. The example-file rename is now largely redundant: seedUserGlobalConfig\n // rewrites infra-kit.example.jsonc unconditionally moments later, so a renamed legacy\n // example is overwritten anyway (and if infra-kit.example.jsonc already exists, the\n // no-overwrite guard simply leaves an orphaned config.example.jsonc behind \u2014 harmless).\n const pairs: { from: string; to: string }[] = [\n { from: path.join(dir, 'config.json'), to: paths.userGlobal },\n { from: path.join(dir, 'config.example.jsonc'), to: path.join(dir, 'infra-kit.example.jsonc') },\n ]\n\n let renamed = 0\n\n for (const { from, to } of pairs) {\n const [fromExists, toExists] = await Promise.all([fileExists(from), fileExists(to)])\n\n if (!fromExists) continue\n\n if (toExists) {\n logger.info(`\u26A0 Skipped ${tildify(from)} \u2014 ${tildify(to)} already exists (remove the stale file manually)`)\n\n continue\n }\n\n // Same-directory rename is atomic; per-file try/catch keeps a TOCTOU race or\n // I/O error (EACCES, read-only FS) non-fatal so one bad file never aborts init.\n try {\n await fs.mkdir(path.dirname(to), { recursive: true })\n await fs.rename(from, to)\n\n logger.info(`\u2713 Renamed ${tildify(from)} \u2192 ${tildify(to)}`)\n renamed++\n } catch (err) {\n logger.info(`\u26A0 Skipped ${tildify(from)} \u2014 ${(err as Error).message}`)\n }\n }\n\n if (renamed > 0) {\n resetInfraKitConfigCache()\n }\n}\n\n/**\n * Convert a legacy machine-local factory config from executable TypeScript\n * (`~/.infra-kit/vendor.config.ts`) to static JSON (`~/.infra-kit/vendor.json`) as\n * part of `infra-kit init`. The factory config used to be a `.ts` module loaded via\n * dynamic `import()`; it is now strict JSON read with `JSON.parse`. This one-shot\n * migration dynamic-imports the old `.ts` (the ONLY remaining dynamic import of the\n * factory file), resolves a factory-function or object default export, validates it,\n * writes `vendor.json`, and removes the old `.ts`.\n *\n * Best-effort, non-fatal, idempotent (no old `.ts` \u2192 no-op), and never overwrites an\n * existing `vendor.json`. When the old export was a FUNCTION, its resolved output is\n * frozen into static JSON \u2014 so a DISTINCT warning is emitted (not a plain\n * `\u2713 Migrated`) because dynamic re-evaluation (env vars, directory globbing) no\n * longer happens. No `resetInfraKitConfigCache()` \u2014 the factory loader shares no\n * cache with the `infra-kit.json` layers.\n *\n * @example\n * await migrateFactoryConfigToJson()\n * // \u2713 Migrated ~/.infra-kit/vendor.config.ts \u2192 ~/.infra-kit/vendor.json\n * // (no output when there is nothing legacy to convert)\n */\nexport const migrateFactoryConfigToJson = async (): Promise<void> => {\n const newJson = getFactoryConfigPath() // ~/.infra-kit/vendor.json\n const dir = path.dirname(newJson)\n const oldTs = path.join(dir, 'vendor.config.ts')\n\n const [oldExists, newExists] = await Promise.all([fileExists(oldTs), fileExists(newJson)])\n\n if (!oldExists) return // idempotent: nothing to migrate (incl. after a prior successful run)\n\n if (newExists) {\n logger.info(\n `\u26A0 Skipped ${tildify(oldTs)} \u2014 ${tildify(newJson)} already exists (remove the stale vendor.config.ts manually)`,\n )\n\n return\n }\n\n // The factory `.ts` is executable; read it once via dynamic import (Node native\n // type stripping) with an mtime cache-bust, resolving a factory-function or object\n // default export. Per-file try/catch keeps a malformed module or I/O error\n // non-fatal so one bad file never aborts init.\n try {\n const stat = await fs.stat(oldTs)\n const moduleUrl = `${pathToFileURL(oldTs).href}?mtime=${Number(stat.mtimeMs)}`\n const imported = (await import(moduleUrl)) as { default?: unknown }\n const raw = imported.default\n const wasFunction = typeof raw === 'function'\n const resolved = wasFunction ? await (raw as () => unknown)() : raw\n\n const result = factoryConfigSchema.safeParse(resolved)\n\n if (!result.success) {\n logger.info(`\u26A0 Skipped ${tildify(oldTs)} \u2014 invalid factory config: ${z.prettifyError(result.error)}`)\n\n return // leave the old .ts in place so the user can fix and re-run; do not delete unconverted data\n }\n\n await fs.mkdir(dir, { recursive: true })\n await fs.writeFile(newJson, `${JSON.stringify(result.data, null, 2)}\\n`, 'utf-8')\n await fs.rm(oldTs, { force: true })\n\n if (wasFunction) {\n // The old export was a function: its values were resolved ONCE and frozen into\n // static JSON. Disclose the lost dynamism instead of reporting a clean success.\n logger.info(\n `\u26A0 Migrated ${tildify(oldTs)} \u2192 ${tildify(newJson)} as a STATIC SNAPSHOT \u2014 the old file was a ` +\n `function (export default () => ({...})); computed values (env vars, directory globbing) were ` +\n `frozen at their current values and no longer re-evaluate. Edit ${tildify(newJson)} directly to change them.`,\n )\n } else {\n logger.info(`\u2713 Migrated ${tildify(oldTs)} \u2192 ${tildify(newJson)}`)\n }\n } catch (err) {\n logger.info(`\u26A0 Skipped ${tildify(oldTs)} \u2014 ${(err as Error).message}`)\n }\n}\n\n/**\n * Surgically strip the removed `ide.config.mode` field from a parsed config\n * object (single-provider or array form). The windows-removal made `mode` a dead\n * key \u2014 the loader already ignores it, so this only matters for keeping the\n * on-disk file clean. Returns `changed: false` (and the input untouched) when\n * there is no `mode` to remove, so callers can skip rewriting clean files.\n *\n * Only `mode` is removed \u2014 every other key is preserved verbatim (no full-schema\n * re-validation), so a config that is otherwise invalid or carries forward-compat\n * keys is never altered beyond the dead field.\n */\nconst stripLegacyIdeMode = (parsed: Record<string, unknown>): { changed: boolean; result: Record<string, unknown> } => {\n const ide = parsed.ide\n\n if (ide === null || typeof ide !== 'object') {\n return { changed: false, result: parsed }\n }\n\n let changed = false\n\n const stripEntry = (entry: unknown): unknown => {\n if (entry === null || typeof entry !== 'object' || !('config' in entry)) {\n return entry\n }\n\n const config = (entry as { config: unknown }).config\n\n if (config === null || typeof config !== 'object' || !('mode' in config)) {\n return entry\n }\n\n changed = true\n\n const restConfig = Object.fromEntries(\n Object.entries(config as Record<string, unknown>).filter(([key]) => {\n return key !== 'mode'\n }),\n )\n\n return { ...(entry as Record<string, unknown>), config: restConfig }\n }\n\n const nextIde = Array.isArray(ide) ? ide.map(stripEntry) : stripEntry(ide)\n\n if (!changed) {\n return { changed: false, result: parsed }\n }\n\n return { changed: true, result: { ...parsed, ide: nextIde } }\n}\n\n/**\n * Normalize any existing `infra-kit.json` config layers (project, user-global,\n * user-project) from the old IDE structure to the new one by removing the\n * removed `ide.config.mode` field. Run by `infra-kit init` after the YAML\u2192JSON\n * migration. Best-effort and non-fatal per layer; only rewrites a file when its\n * `ide` config actually carries the dead key, so clean configs are left byte-for-\n * byte untouched (idempotent). Resets the config cache when anything changed.\n *\n * @example\n * await normalizeLegacyIdeStructures()\n * // \u2713 Normalized ide config in infra-kit.json (removed legacy \"mode\")\n * // (no output when no config carries a legacy \"mode\")\n */\nexport const normalizeLegacyIdeStructures = async (): Promise<void> => {\n let paths: Awaited<ReturnType<typeof getInfraKitConfigPaths>>\n\n try {\n paths = await getInfraKitConfigPaths()\n } catch {\n return\n }\n\n const jsonPaths = [paths.main, paths.userGlobal, paths.userProject]\n\n let normalized = 0\n\n for (const jsonPath of jsonPaths) {\n if (!(await fileExists(jsonPath))) continue\n\n try {\n const raw = await fs.readFile(jsonPath, 'utf-8')\n\n if (raw.trim() === '') continue\n\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const { changed, result } = stripLegacyIdeMode(parsed)\n\n if (!changed) continue\n\n await fs.writeFile(jsonPath, `${JSON.stringify(result, null, 2)}\\n`, 'utf-8')\n\n logger.info(`\u2713 Normalized ide config in ${tildify(jsonPath)} (removed legacy \"mode\")`)\n normalized++\n } catch (err) {\n logger.info(`\u26A0 Skipped normalizing ${tildify(jsonPath)} \u2014 ${(err as Error).message}`)\n }\n }\n\n if (normalized > 0) {\n resetInfraKitConfigCache()\n }\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/infra-kit-config'\n\nimport { FACTORY_CONFIG_FILE, factoryConfigSchema } from './factory-config-schema'\nimport type { FactoryConfig } from './factory-config-schema'\n\n/**\n * Absolute path to the machine-local factory config (`~/.infra-kit/vendor.json`).\n * Always returned, even when the file does not exist, so callers can surface a\n * \"where would it go?\" prompt.\n *\n * @example\n * getFactoryConfigPath() // => '/Users/arthur/.infra-kit/vendor.json'\n */\nexport const getFactoryConfigPath = (): string => {\n return path.join(os.homedir(), USER_CONFIG_DIR_NAME, FACTORY_CONFIG_FILE)\n}\n\n/**\n * Expand a leading `~` to the home dir. Absolute paths pass through unchanged.\n * A non-absolute, non-`~` value throws \u2014 cwd-relative resolution is ambiguous\n * across CLI vs long-running MCP-server invocations, so we reject it loudly.\n *\n * @example\n * expandTilde('~') // => '/Users/arthur'\n * expandTilde('~/projects') // => '/Users/arthur/projects'\n * expandTilde('/abs/dir') // => '/abs/dir'\n * expandTilde('rel/dir') // throws\n */\nexport const expandTilde = (p: string): string => {\n if (p === '~') return os.homedir()\n if (p.startsWith('~/')) return path.join(os.homedir(), p.slice(2))\n if (path.isAbsolute(p)) return p\n\n throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${p}`)\n}\n\n/**\n * Load and validate the user-global factory config at `~/.infra-kit/vendor.json`.\n * Reads the static JSON with `JSON.parse` (an empty/whitespace-only file is treated\n * as `{}`), then validates against {@link factoryConfigSchema}.\n *\n * Reads the file on every call (no module cache to bust \u2014 unlike a `.ts`\n * `import()`, `JSON.parse` always sees the current bytes), so an absent \u2192 present\n * transition works within one process: a `--init` scaffold followed by a load\n * succeeds, and a long-running MCP server picks up edits without a restart.\n * Throws an actionable error pointing at `infra-kit vendor config --init` when the\n * file is absent.\n *\n * @example\n * const { workspaceDir, targets } = await loadFactoryConfig()\n */\nexport const loadFactoryConfig = async (): Promise<FactoryConfig> => {\n const configPath = getFactoryConfigPath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(configPath, 'utf-8')\n } catch {\n throw new Error(\n `Factory config not found at ${configPath}. infra-kit needs a machine-local factory ` +\n `registry to know where your project repos live and which to stamp. Run ` +\n `\\`infra-kit vendor config --init\\` to scaffold it, or create it manually as JSON:\\n\\n` +\n ` {\\n` +\n ` \"workspaceDir\": \"~/projects\",\\n` +\n ` \"targets\": [\"my-repo\"]\\n` +\n ` }\\n`,\n )\n }\n\n let data: unknown\n\n try {\n data = raw.trim() === '' ? {} : JSON.parse(raw)\n } catch (err) {\n throw new Error(`Invalid JSON in vendor.json at ${configPath}: ${(err as Error).message}`)\n }\n\n const parsed = factoryConfigSchema.safeParse(data)\n\n if (!parsed.success) {\n throw new Error(`Invalid factory config at ${configPath}: ${z.prettifyError(parsed.error)}`)\n }\n\n return parsed.data\n}\n", "import { z } from 'zod'\n\n/**\n * Pure (node-free) factory config schema. Kept separate from `factory-config.ts`\n * (which imports node builtins for the runtime loader) so the public lib entry can\n * re-export the `FactoryConfig` type without dragging node types into the emitted\n * `.d.ts` \u2014 same split as `config-schema.ts` / `config.ts`.\n */\n\n/**\n * Basename of the machine-local factory config, which lives at\n * `~/.infra-kit/vendor.json`. It is static JSON (no longer an executable `.ts`\n * module): the loader reads it with `JSON.parse`. The committed SOURCE-repo config\n * keeps the `vendor.config.ts` basename \u2014 always refer to this one as \"the\n * user-global factory config\".\n */\nexport const FACTORY_CONFIG_FILE = 'vendor.json'\n\n/**\n * The machine-local factory registry. Answers \"where do my project repos live\"\n * (`workspaceDir`) and \"which ones does the factory stamp\" (`targets`). The\n * portable \"what to vendor\" definition (`copy[]`) lives in the committed SOURCE\n * `vendor.config.ts`, never here. `.strict()` rejects a stray `copy` key so a\n * misplaced source config produces a clear error.\n */\nexport const factoryConfigSchema = z\n .object({\n /** Absolute (or `~`-prefixed) dir where the target project repos are cloned. */\n workspaceDir: z.string().min(1),\n /** Target repo directory names, resolved under `workspaceDir`. */\n targets: z.array(z.string()).min(1),\n })\n .strict()\n\nexport type FactoryConfig = z.infer<typeof factoryConfigSchema>\n", "import fs from 'node:fs/promises'\n\nexport interface OverrideSummary {\n /** True only when the layer-3 file parses AND carries at least one top-level key. */\n hasOverrides: boolean\n /** Raw top-level keys, in file order. Empty when absent, empty-object, or unreadable. */\n overrideKeys: string[]\n /** True when the file exists but could not be read or parsed as a JSON object. */\n unreadable: boolean\n}\n\n/**\n * Summarize the layer-3 user-project override file for the read-only diagnostics (`config path`,\n * `doctor`). ONE JSON-tolerance policy, shared \u2014 the two diagnostics must never disagree about what\n * a given file on disk means.\n *\n * RAW keys, deliberately \u2014 `Object.keys(JSON.parse(raw))`, never the config loader's `loadLayer`.\n * That one throws on malformed JSON and on schema failure, and the schema object is strict, so a\n * single typo'd top-level key would invalidate the whole layer and turn these diagnostic commands\n * into throwers \u2014 precisely when the user reaches for them. Raw keys also surface the typo (a\n * misspelled `devServersPreset` shows up in the list) instead of swallowing it.\n *\n * Any read/parse failure degrades to \"no overrides\" plus `unreadable: true`. An empty or\n * whitespace-only file is treated as `{}` (the same tolerance `loadLayer` has). A file that parses\n * but is NOT a plain object (`[1,2,3]`, `\"x\"`, `null`, `7`) is also `unreadable` \u2014 it cannot be a\n * merge layer, and reporting an array's indices as `(3 override(s): 0, 1, 2)` would be a lie.\n *\n * @example\n * await readOverrideSummary('/u/.infra-kit/projects/api/infra-kit.json', true)\n * // => { hasOverrides: true, overrideKeys: ['ide', 'dev'], unreadable: false }\n */\nexport const readOverrideSummary = async (filePath: string, exists: boolean): Promise<OverrideSummary> => {\n if (!exists) {\n return { hasOverrides: false, overrideKeys: [], unreadable: false }\n }\n\n try {\n const raw = await fs.readFile(filePath, 'utf-8')\n const parsed: unknown = raw.trim() === '' ? {} : JSON.parse(raw)\n\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return { hasOverrides: false, overrideKeys: [], unreadable: true }\n }\n\n const keys = Object.keys(parsed)\n\n return { hasOverrides: keys.length > 0, overrideKeys: keys, unreadable: false }\n } catch {\n return { hasOverrides: false, overrideKeys: [], unreadable: true }\n }\n}\n\n/**\n * The human-readable suffix for a layer-3 file that EXISTS. Callers own the absent case: `config\n * path` already prints a `[ ]` marker for it, while `doctor` must call it out as a possible seed\n * failure (every command seeds layer 3, so an absent file is no longer \"not yet created\").\n *\n * @example\n * describeOverrides({ hasOverrides: true, overrideKeys: ['ide', 'dev'], unreadable: false })\n * // => '(2 override(s): ide, dev)'\n */\nexport const describeOverrides = (summary: OverrideSummary): string => {\n if (summary.unreadable) {\n return '(unreadable \u2014 invalid JSON)'\n }\n\n if (summary.overrideKeys.length === 0) {\n return '(empty \u2014 no overrides)'\n }\n\n return `(${summary.overrideKeys.length} override(s): ${summary.overrideKeys.join(', ')})`\n}\n", "import { Chalk } from 'chalk'\nimport process from 'node:process'\n\nimport { DEFAULT_DEV_PROXY_PORT } from 'src/lib/infra-kit-config'\n\nimport type { CheckResult } from './doctor'\n\n/**\n * Presentation layer for `infra-kit doctor`. Everything here is PURE: it takes the already-computed\n * `CheckResult[]` and returns lines. It never probes, never writes, and never reorders its input.\n *\n * Why this is not the logger: doctor emits ~24 checks, and pino-pretty rendered every one as an\n * identical `INFO:` line \u2014 so a single FAIL was invisible in a wall of PASS. This module groups the\n * checks into labelled sections with per-section rollups and a summary, which is the whole point.\n *\n * Why this is not Ink: this is a ONE-SHOT report, not a live region. Ink writes `ESC[3J` (erase saved\n * lines) whenever a frame overflows the viewport, which wipes the user's terminal SCROLLBACK \u2014 the\n * hazard `src/tui/safe-stderr.ts` exists to contain for the dev-ui. A report that is routinely taller\n * than the viewport is exactly the shape that triggers it, for no benefit a string[] does not already\n * give us.\n *\n * REDACTION INVARIANT \u2014 read before adding a check message: these lines are written straight to\n * stderr, which BYPASSES pino's `REDACT_PATHS` backstop (see `lib/logger`). Every doctor message is\n * pre-redacted by construction (`describeEntries` reports a token's SOURCE, never its value;\n * `checkEnvTokenValid` never interpolates the token). Any new check message must hold to that.\n */\n\n/** A named group of checks, in the order they are printed. */\nexport interface DoctorSection {\n label: string\n checks: CheckResult[]\n}\n\nconst SECTION_TOOLS = 'Tools & CLIs'\nconst SECTION_SHELL = 'Shell & integration'\nconst SECTION_CONFIG = 'Project config'\nconst SECTION_TOKENS = 'Doppler env tokens'\nconst SECTION_PROXY = 'Dev proxy (portless)'\n\n/**\n * The `portless serving TLS on :443` check builds its name by interpolating the proxy port, so this\n * key is derived from the SAME constant. A frozen `':443'` literal would silently drop the check into\n * `Other` the day that port changes.\n */\nconst PORTLESS_SERVING_NAME = `portless serving TLS on :${DEFAULT_DEV_PROXY_PORT}`\n\n/**\n * Which section each check belongs to, in print order. Keyed by check `name` rather than carried as a\n * `category` field on `CheckResult` so the 24 check functions (and their tests) stay untouched \u2014 the\n * grouping knowledge lives in exactly one place instead of being smeared across `doctor.ts`.\n *\n * A name that is missing here is NOT dropped: it falls into `Other` at runtime (see {@link groupChecks}).\n * The drift is caught by tests instead \u2014 `report.test.ts` asserts every name in\n * {@link DOCTOR_CHECK_NAMES} maps to a non-`Other` section, and that the inventory itself still equals\n * what a real `doctor()` run produces.\n */\nconst SECTION_MEMBERS: ReadonlyArray<readonly [string, readonly string[]]> = [\n [\n SECTION_TOOLS,\n [\n 'gh installed',\n 'gh authenticated',\n 'doppler installed',\n 'aws installed',\n 'rtk installed',\n 'typescript-language-server installed',\n 'cmux installed',\n 'ide installed',\n ],\n ],\n [\n SECTION_SHELL,\n ['rtk configured', 'zshrc init block', 'warm cache', 'pnpm enableGlobalVirtualStore', 'CLAUDE.md block'],\n ],\n [SECTION_CONFIG, ['infra-kit config valid', 'user override path', 'legacy user-global config']],\n [SECTION_TOKENS, ['env tokens configured', 'env token valid', 'tokens.json perms']],\n [\n SECTION_PROXY,\n ['portless installed', PORTLESS_SERVING_NAME, 'portless CA chain valid', 'portless CA trusted', 'portless routes'],\n ],\n]\n\n/** The bucket for any check name not in {@link SECTION_MEMBERS} \u2014 a safety net, never a destination. */\nexport const OTHER_SECTION = 'Other'\n\n/** The section order used for printing. */\nconst SECTION_ORDER: readonly string[] = SECTION_MEMBERS.map(([label]) => {\n return label\n})\n\n/** name \u2192 section label. */\nconst SECTION_BY_NAME = new Map<string, string>(\n SECTION_MEMBERS.flatMap(([label, names]) => {\n return names.map((name): [string, string] => {\n return [name, label]\n })\n }),\n)\n\n/**\n * Every check name `doctor()` can produce. This is the inventory the coverage test asserts the section\n * map covers, and that a deterministic `doctor()` run is reconciled against \u2014 so a new check that\n * updates neither this list nor {@link SECTION_MEMBERS} fails CI instead of quietly landing in `Other`.\n */\nexport const DOCTOR_CHECK_NAMES: readonly string[] = SECTION_MEMBERS.flatMap(([, names]) => {\n return names\n})\n\n/**\n * The checks `infra-kit doctor --fix` can actually resolve \u2014 stale portless routes\n * ({@link import('./doctor').pruneStalePortlessRoutes}) and loose token-store modes\n * ({@link import('./doctor').checkTokenStorePerms}). The summary's remediation hint is driven by this\n * set rather than by matching message text, so it cannot drift from the real `--fix` code paths.\n */\nexport const FIXABLE_NAMES: ReadonlySet<string> = new Set(['portless routes', 'tokens.json perms'])\n\n/**\n * Group checks into printable sections. NON-MUTATING by contract: `structuredContent.checks` is built\n * from the same array in `doctor()`, and its order is part of that payload's compatibility surface, so\n * this must never sort or splice the input.\n *\n * Empty sections are omitted (a machine with no portless binary reports one portless check, not five),\n * and any unmapped name lands in a trailing {@link OTHER_SECTION} rather than disappearing.\n *\n * @example\n * groupChecks([{ name: 'gh installed', status: 'pass', message: '\u2026' }])\n * // => [{ label: 'Tools & CLIs', checks: [ \u2026 ] }]\n */\nexport const groupChecks = (checks: readonly CheckResult[]): DoctorSection[] => {\n const buckets = new Map<string, CheckResult[]>()\n\n for (const check of checks) {\n const label = SECTION_BY_NAME.get(check.name) ?? OTHER_SECTION\n const bucket = buckets.get(label)\n\n if (bucket) bucket.push(check)\n else buckets.set(label, [check])\n }\n\n const ordered = [...SECTION_ORDER, OTHER_SECTION]\n\n return ordered.flatMap((label): DoctorSection[] => {\n const bucket = buckets.get(label)\n\n return bucket && bucket.length > 0 ? [{ label, checks: bucket }] : []\n })\n}\n\nexport interface DoctorReportOptions {\n /** Emit ANSI colour. When false the output contains zero escape bytes. */\n color?: boolean\n /** Use `\u2713`/`\u2717` glyphs. When false, ASCII `ok`/`FAIL` markers are used instead. */\n unicode?: boolean\n /** Terminal width to wrap long messages against. */\n width?: number\n}\n\n/**\n * Every character that differs between unicode and ASCII mode, in ONE table. Each variant's `pass`\n * and `fail` are equal-width, and `separator` is a single column in both \u2014 which is what makes a\n * section header's measured width independent of the glyph mode.\n *\n * SCOPE: this governs the report's own chrome (markers, separator, rule). It does NOT sanitise check\n * MESSAGES, which come from `doctor.ts` and already contain non-ASCII punctuation (em-dashes, curly\n * quotes). `--ascii` therefore means \"don't require box-drawing/symbol glyphs\", not \"emit pure ASCII\".\n */\nconst GLYPHS = {\n unicode: { pass: '\u2713', fail: '\u2717', separator: '\u00B7', rule: '\u2500' },\n ascii: { pass: 'ok', fail: '!!', separator: '-', rule: '-' },\n} as const\n\ntype Glyphs = (typeof GLYPHS)[keyof typeof GLYPHS]\n\n/**\n * Never wrap a message into a column narrower than this, however small the terminal claims to be.\n *\n * This is a readability floor, NOT a fit guarantee: the message column starts after the widest check\n * name in the WHOLE report (`typescript-language-server installed` alone is 36 chars), so on a genuinely\n * narrow terminal a row can still exceed `width`. Wrapping messages into a 4-column ribbon would be\n * worse than overflowing, and the alternative \u2014 truncating \u2014 is ruled out because these messages carry\n * the commands the user has to copy.\n */\nconst MIN_MESSAGE_WIDTH = 24\n\n/**\n * Greedy word wrap. Words longer than `width` (a URL, a long `node \u2026/cli.js \u2026` command) are emitted\n * whole on their own line rather than being broken \u2014 a fix command split mid-token is not runnable,\n * and printing these commands runnable is the entire reason doctor renders them.\n */\nconst wrapText = (text: string, width: number): string[] => {\n const words = text.split(/\\s+/).filter((word) => {\n return word.length > 0\n })\n const lines: string[] = []\n let current = ''\n\n for (const word of words) {\n if (current.length === 0) current = word\n else if (`${current} ${word}`.length <= width) current = `${current} ${word}`\n else {\n lines.push(current)\n current = word\n }\n }\n if (current.length > 0) lines.push(current)\n\n return lines.length > 0 ? lines : ['']\n}\n\n/** Per-section pass/fail tallies. */\nconst tally = (checks: readonly CheckResult[]): { passed: number; failed: number } => {\n const failed = checks.filter((check) => {\n return check.status === 'fail'\n }).length\n\n return { passed: checks.length - failed, failed }\n}\n\ninterface Palette {\n header: (text: string) => string\n pass: (text: string) => string\n fail: (text: string) => string\n dim: (text: string) => string\n bold: (text: string) => string\n}\n\n/**\n * A palette seeded from an EXPLICIT colour decision rather than chalk's global auto-detection.\n * That default keys on `process.stdout`, but this report is written to `process.stderr` \u2014 so relying\n * on it would strip colour from `doctor | cat` (stdout piped, stderr still a terminal) and write raw\n * ANSI into `doctor 2>report.txt`. Both backwards.\n */\nconst createPalette = (color: boolean): Palette => {\n const chalk = new Chalk({ level: color ? 1 : 0 })\n\n return {\n header: (text): string => {\n return chalk.bold.cyan(text)\n },\n pass: (text): string => {\n return chalk.green(text)\n },\n fail: (text): string => {\n return chalk.red(text)\n },\n dim: (text): string => {\n return chalk.dim(text)\n },\n bold: (text): string => {\n return chalk.bold(text)\n },\n }\n}\n\n/**\n * `7/7 ok` / `4/5 \u00B7 1 failed` \u2014 a section's verdict at a glance.\n *\n * Returns the VISIBLE width alongside the (coloured) text. The caller needs that width to right-align\n * the rollup and cannot recover it from the string, because colour has already been baked in. An\n * earlier version reconstructed a plain stand-in template instead and got it wrong in both directions\n * \u2014 all-pass headers stopped 6 columns short, and failing headers overshot by 2 and WRAPPED, which\n * mangled the one line the grouping exists to make obvious. Never measure a coloured string.\n */\nconst formatRollup = (\n counts: { passed: number; failed: number },\n total: number,\n palette: Palette,\n glyphs: Glyphs,\n): { text: string; plainWidth: number } => {\n if (counts.failed === 0) {\n const plain = `${total}/${total} ok`\n\n return { text: palette.pass(plain), plainWidth: plain.length }\n }\n\n const ratio = `${counts.passed}/${total}`\n const failed = `${counts.failed} failed`\n\n return {\n text: `${palette.dim(ratio)} ${glyphs.separator} ${palette.fail(failed)}`,\n // +3 = the space, the single-column separator, and the space.\n plainWidth: ratio.length + failed.length + 3,\n }\n}\n\nconst INDENT = ' '\nconst ROW_INDENT = ' '\n\n/**\n * A section heading with its rollup pushed to the right margin (or one space away, when the label and\n * rollup together already fill the line). The gap is computed entirely from VISIBLE widths, so the\n * rendered header is exactly `width` columns and never wraps.\n */\nconst formatSectionHeader = (section: DoctorSection, palette: Palette, glyphs: Glyphs, width: number): string => {\n const counts = tally(section.checks)\n const rollup = formatRollup(counts, section.checks.length, palette, glyphs)\n const gap = Math.max(1, width - INDENT.length - section.label.length - rollup.plainWidth)\n\n return `${INDENT}${palette.header(section.label)}${' '.repeat(gap)}${rollup.text}`\n}\n\n/**\n * One check, as one or more lines: ` \u2713 name message`, with any wrapped continuation\n * hanging-indented to the message column so the two-column shape survives a long message.\n *\n * Colour is applied AFTER padding, never before: `padEnd` counts ANSI escape bytes as visible\n * characters, so colouring the glyph or name first would silently skew every column on the coloured\n * (i.e. the primary, interactive) path \u2014 the one a strip-and-assert test cannot see.\n */\nconst formatCheckRow = (\n check: CheckResult,\n nameWidth: number,\n palette: Palette,\n glyphs: { pass: string; fail: string },\n width: number,\n): string[] => {\n const failed = check.status === 'fail'\n // Both glyph pairs are internally equal-width (`\u2713`/`\u2717` = 1, `ok`/`!!` = 2), so the marker needs no\n // padding \u2014 but the column arithmetic below still has to account for its width.\n const glyphWidth = glyphs.pass.length\n const plainGlyph = failed ? glyphs.fail : glyphs.pass\n const plainName = check.name.padEnd(nameWidth)\n const glyph = failed ? palette.fail(plainGlyph) : palette.pass(plainGlyph)\n const name = failed ? palette.fail(plainName) : plainName\n const messageColumn = ROW_INDENT.length + glyphWidth + 1 + nameWidth + 2\n const messageWidth = Math.max(MIN_MESSAGE_WIDTH, width - messageColumn)\n const [first, ...rest] = wrapText(check.message, messageWidth)\n const paint = (text: string): string => {\n return failed ? text : palette.dim(text)\n }\n // `trimEnd` so a check with an empty message does not leave trailing whitespace on the line.\n const head = `${ROW_INDENT}${glyph} ${name} ${paint(first ?? '')}`.trimEnd()\n\n return [\n head,\n ...rest.map((line) => {\n return `${' '.repeat(messageColumn)}${paint(line)}`\n }),\n ]\n}\n\n/** The closing rule + totals, plus a `--fix` hint only when a FAILING check is actually fixable. */\nconst formatSummary = (checks: readonly CheckResult[], palette: Palette, glyphs: Glyphs, width: number): string[] => {\n const counts = tally(checks)\n const rule = glyphs.rule.repeat(Math.max(12, Math.min(width - INDENT.length, 56)))\n const fixable = checks.filter((check) => {\n return check.status === 'fail' && FIXABLE_NAMES.has(check.name)\n }).length\n const passed = palette.pass(`${counts.passed} passed`)\n const failed = palette.fail(`${counts.failed} failed`)\n const totals = counts.failed === 0 ? passed : `${passed} ${glyphs.separator} ${failed}`\n const hintText = palette.dim(`${fixable} fixable \u2014 run \\`infra-kit doctor --fix\\``)\n const hint = fixable > 0 ? ` ${hintText}` : ''\n\n return [`${INDENT}${palette.dim(rule)}`, `${INDENT}${totals}${hint}`]\n}\n\n/**\n * Render the whole report. Pure: same input, same lines, no I/O and no environment sniffing \u2014 every\n * capability is passed in (see {@link resolveReportCapabilities}), which is what makes the colour,\n * ASCII and narrow-width behaviours unit-testable rather than machine-dependent.\n *\n * @example\n * formatDoctorReport([{ name: 'gh installed', status: 'pass', message: 'installed' }], { color: false })\n * // => ['infra-kit doctor', '', ' Tools & CLIs \u2026', ' \u2713 gh installed installed', \u2026]\n */\nexport const formatDoctorReport = (checks: readonly CheckResult[], options: DoctorReportOptions = {}): string[] => {\n const color = options.color ?? false\n const unicode = options.unicode ?? true\n const width = options.width ?? 80\n const palette = createPalette(color)\n const glyphs = unicode ? GLYPHS.unicode : GLYPHS.ascii\n\n if (checks.length === 0) return [palette.bold('infra-kit doctor'), '', `${INDENT}${palette.dim('No checks ran.')}`]\n\n // ONE name column for the whole report, not one per section: the message column is the eye's\n // vertical guide down the page, and re-measuring it per section made it jump at every heading.\n // Costs a few spaces of padding in the sections whose names are short \u2014 worth it.\n const nameWidth = Math.max(\n ...checks.map((check) => {\n return check.name.length\n }),\n )\n\n const sections = groupChecks(checks).flatMap((section): string[] => {\n return [\n formatSectionHeader(section, palette, glyphs, width),\n ...section.checks.flatMap((check) => {\n return formatCheckRow(check, nameWidth, palette, glyphs, width)\n }),\n '',\n ]\n })\n\n return [palette.bold('infra-kit doctor'), '', ...sections, ...formatSummary(checks, palette, glyphs, width)]\n}\n\n/** Values of `FORCE_COLOR` that mean \"off\" \u2014 `'0'` is chalk's documented disable, and `Boolean('0')` is `true`. */\nconst FORCE_COLOR_OFF = new Set(['', '0', 'false', 'none'])\n\n/** The locale variables consulted for UTF-8 capability, in POSIX precedence order. */\nconst LOCALE_VARS = ['LC_ALL', 'LC_CTYPE', 'LANG'] as const\n\nexport interface ReportCapabilityInput {\n /** The `--ascii` flag: forces ASCII glyphs regardless of locale. */\n ascii?: boolean\n env?: NodeJS.ProcessEnv\n /** The stream the report is written to \u2014 `process.stderr`, NOT stdout. */\n stream?: { isTTY?: boolean; columns?: number }\n}\n\n/** `NO_COLOR` (any non-empty value) wins; then `FORCE_COLOR`; then whether the target stream is a TTY. */\nconst resolveColor = (env: NodeJS.ProcessEnv, stream: { isTTY?: boolean }): boolean => {\n if (env.NO_COLOR !== undefined && env.NO_COLOR !== '') return false\n\n if (env.FORCE_COLOR !== undefined) return !FORCE_COLOR_OFF.has(env.FORCE_COLOR.toLowerCase())\n\n return Boolean(stream.isTTY)\n}\n\n/**\n * UTF-8 unless a locale variable is SET and says otherwise. The \"is set\" guard is load-bearing: an\n * unset locale is the common case (launchd, CI, bare `sh`), and testing an empty string against\n * `/UTF-?8/` would force ASCII on every one of those terminals, all of which render the glyphs fine.\n */\nconst resolveUnicode = (env: NodeJS.ProcessEnv, ascii: boolean): boolean => {\n if (ascii) return false\n\n const locale = LOCALE_VARS.map((name) => {\n return env[name]\n }).find((value) => {\n return value !== undefined && value !== ''\n })\n\n return locale === undefined ? true : /UTF-?8/i.test(locale)\n}\n\n/**\n * Resolve colour / unicode / width from the environment and the TARGET stream. Split out from\n * {@link formatDoctorReport} so the formatter stays pure and these three rules stay testable without\n * mutating `process.env`.\n *\n * @example\n * resolveReportCapabilities({ env: { NO_COLOR: '1' }, stream: { isTTY: true, columns: 120 } })\n * // => { color: false, unicode: true, width: 120 }\n */\nexport const resolveReportCapabilities = (input: ReportCapabilityInput = {}): Required<DoctorReportOptions> => {\n const env = input.env ?? process.env\n const stream = input.stream ?? process.stderr\n\n return {\n color: resolveColor(env, stream),\n unicode: resolveUnicode(env, input.ascii ?? false),\n width: stream.columns ?? 80,\n }\n}\n\nexport interface PrintDoctorReportDeps extends ReportCapabilityInput {\n /** Where the report goes. Defaults to a single `process.stderr.write`. */\n write?: (text: string) => void\n}\n\n/**\n * Write the report to stderr \u2014 humans on stderr, machines on stdout, which is what keeps\n * `doctor --json | jq` and the MCP stdio transport clean.\n *\n * ONE write, deliberately: pino also targets fd 2, and emitting 30 separate writes would let any\n * concurrent `logger.*` call tear a line straight through the middle of the report.\n */\nexport const printDoctorReport = (checks: readonly CheckResult[], deps: PrintDoctorReportDeps = {}): void => {\n const write =\n deps.write ??\n ((text: string): void => {\n process.stderr.write(text)\n })\n\n write(`${formatDoctorReport(checks, resolveReportCapabilities(deps)).join('\\n')}\\n`)\n}\n", "import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport {\n ENV_CLEAR_FILE,\n ENV_LOAD_FILE,\n INFRA_KIT_ENV_AUTOLOADED_VAR,\n INFRA_KIT_ENV_CLEARED_VAR,\n INFRA_KIT_ENV_CONFIG_VAR,\n INFRA_KIT_ENV_LOADED_AT_VAR,\n INFRA_KIT_ENV_PROJECT_ROOT_VAR,\n INFRA_KIT_ENV_PROJECT_VAR,\n INFRA_KIT_ENV_VAR,\n atomicWriteFileSync,\n getSessionCacheDir,\n parseVarNamesFromEnvFile,\n} from 'src/lib/constants'\nimport { getProjectRoot } from 'src/lib/git-utils'\nimport { canonicalizeProjectRoot, invalidateProjectWarmCache } from 'src/lib/warm-cache'\nimport { defineMcpTool, textContent } from 'src/types'\n\nexport interface EnvClearArgs {\n /**\n * Also invalidate this project's WARM cache. `false` (default) writes a transient\n * clear-marker so the next shell skips warm-source once; `true` deletes the warm\n * dir outright (durable \u2014 warm won't resume until the next auto-load rewrites it).\n */\n purge?: boolean\n}\n\n/**\n * Invalidate the current project's warm cache alongside the session clear, so a\n * NEW shell doesn't warm-load what the user just cleared. Resolves the project root\n * itself (git top-level, realpath'd) to match the warm key; a non-git project never\n * had a warm file, so it is a no-op. Best-effort \u2014 never blocks the session clear.\n */\nconst clearProjectWarmCache = async (purge: boolean): Promise<void> => {\n let projectRoot = ''\n\n try {\n projectRoot = await getProjectRoot()\n } catch {\n return // non-git: no warm cache to invalidate\n }\n\n const canon = canonicalizeProjectRoot(projectRoot)\n\n if (canon) invalidateProjectWarmCache(canon, purge)\n}\n\n/**\n * Build the lines for env-clear.sh: `unset` every loaded var plus the session\n * metadata (config/project/loadedAt) and the auto-load marker, then EXPORT the\n * clear sentinel so cli-invocation auto-load stays suppressed in this shell until\n * an explicit `env-load` (which unsets it) or a new shell. Pure for testability.\n */\nexport const buildEnvClearLines = (varNames: string[]): string[] => {\n return [\n ...varNames.map((v) => {\n return `unset ${v}`\n }),\n `unset ${INFRA_KIT_ENV_VAR}`,\n `unset ${INFRA_KIT_ENV_CONFIG_VAR}`,\n `unset ${INFRA_KIT_ENV_PROJECT_VAR}`,\n `unset ${INFRA_KIT_ENV_PROJECT_ROOT_VAR}`,\n `unset ${INFRA_KIT_ENV_LOADED_AT_VAR}`,\n `unset ${INFRA_KIT_ENV_AUTOLOADED_VAR}`,\n `export ${INFRA_KIT_ENV_CLEARED_VAR}='1'`,\n ]\n}\n\n/**\n * Clear loaded env vars. Prints a file path to stdout that must be sourced to apply.\n * The env-clear shell alias does this automatically. Also invalidates the project's\n * WARM cache so a new shell doesn't re-load what was just cleared. Throws when no env\n * is loaded AND `--purge` was not passed (a bare clear needs something to clear; a\n * purge is a standalone warm-cache wipe that works regardless of session state).\n */\nexport const envClear = async ({ purge = false }: EnvClearArgs = {}) => {\n const cacheDir = getSessionCacheDir()\n const envLoadPath = path.join(cacheDir, ENV_LOAD_FILE)\n const hasLoadedEnv = fs.existsSync(envLoadPath)\n\n if (!hasLoadedEnv && !purge) {\n throw new Error('No loaded environment found. Run `env-load` first.')\n }\n\n // Warm invalidation is independent of the current session's load state.\n await clearProjectWarmCache(purge)\n\n const varNames = hasLoadedEnv ? parseVarNamesFromEnvFile(envLoadPath) : []\n\n const unsetLines = buildEnvClearLines(varNames)\n\n const clearFilePath = path.resolve(cacheDir, ENV_CLEAR_FILE)\n\n fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 })\n\n atomicWriteFileSync(clearFilePath, `${unsetLines.join('\\n')}\\n`, 0o600)\n\n // REQUIRED\n process.stdout.write(`${clearFilePath}\\n`)\n\n // Remove env load file so the next env-clear call correctly reports \"no env loaded\".\n // `force` so concurrent clears don't throw ENOENT when another already removed it.\n if (hasLoadedEnv) fs.rmSync(envLoadPath, { force: true })\n\n const structuredContent = {\n filePath: clearFilePath,\n variableCount: varNames.length,\n unsetStatements: unsetLines,\n purged: purge,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const envClearMcpTool = defineMcpTool({\n name: 'env-clear',\n description:\n 'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit init` has installed the zsh shell integration, the user\\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source \"<filePath>\" themselves or surface it to the user. Errors if no env is currently loaded.',\n requiresHumanConfirm: true,\n inputSchema: {\n confirm: z\n .boolean()\n .optional()\n .describe('Set true to execute; omit for a dry-run gate that echoes the resolved action.'),\n },\n outputSchema: {\n filePath: z.string().describe('Path to the file that must be sourced to apply'),\n variableCount: z.number().describe('Number of variables cleared'),\n unsetStatements: z.array(z.string()).describe('Unset statements generated'),\n purged: z.boolean().describe('Whether the project warm cache was purged outright'),\n },\n handler: () => {\n return envClear()\n },\n})\n", "import process from 'node:process'\nimport { z } from 'zod'\n\nimport { getDopplerProject } from 'src/integrations/doppler/doppler-project'\nimport { INFRA_KIT_ENV_TOKEN_VAR } from 'src/integrations/doppler/token-resolver'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { logger } from 'src/lib/logger'\nimport type { ProjectEnv, ProjectEnvSource } from 'src/lib/project-envs'\nimport { listProjectEnvs } from 'src/lib/project-envs'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/** One row of the token column: an env, where we learned it exists, and whether a token resolves. */\nexport interface EnvTokenStatus {\n env: string\n /** `gh-workflow` \u2014 declared in a workflow's dispatch options. `token-only` \u2014 we hold a token, no workflow names it. */\n source: ProjectEnvSource\n hasToken: boolean\n}\n\n/**\n * Build the token column: one row per known environment, reporting only WHETHER a token resolves \u2014\n * never the token itself. Mirrors `resolveEnvToken`'s precedence (`INFRA_KIT_ENV_TOKEN` shadows the\n * store for every env) without importing it, so this stays a pure, no-I/O function the same way\n * `buildEnvTokenRows` in `env-token-list` is.\n *\n * @example\n * buildEnvTokenStatus([{ env: 'dev', source: 'gh-workflow' }], { dev: 'dp.st.dev.xxxx' }, undefined)\n * // => [{ env: 'dev', source: 'gh-workflow', hasToken: true }]\n */\nexport const buildEnvTokenStatus = (\n envs: ProjectEnv[],\n storeTokens: Record<string, string>,\n envToken: string | undefined,\n): EnvTokenStatus[] => {\n return envs.map(({ env, source }) => {\n return { env, source, hasToken: Boolean(envToken || storeTokens[env]) }\n })\n}\n\n/** Column headers for the environments table, in render order. */\nconst ENV_TABLE_HEADERS = ['Environment', 'Source', 'Token'] as const\n\n/**\n * Render the environments as an aligned, vertical-bar-separated table \u2014 the same columnar shape as\n * `gh-release-list`, with explicit `|` column rules. Display only: the structured/MCP payload is built\n * separately in {@link buildResult} from the same rows, so the machine contract never depends on this\n * formatting. Deliberately prints no fix command \u2014 setting a token is a manual `env-token-set` step,\n * not something this read-only listing spells out.\n *\n * @example\n * formatEnvTable([{ env: 'dev', source: 'gh-workflow', hasToken: true }])\n * // => ['Environments:', '', 'Environment | Source | Token', '\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2026', 'dev | gh-workflow | set']\n */\nconst formatEnvTable = (rows: EnvTokenStatus[]): string[] => {\n const cells = rows.map((row) => {\n return [row.env, row.source, row.hasToken ? 'set' : 'not set']\n })\n\n const widths = ENV_TABLE_HEADERS.map((header, col) => {\n return Math.max(\n header.length,\n ...cells.map((cell) => {\n return (cell[col] ?? '').length\n }),\n )\n })\n\n const renderRow = (values: readonly string[]): string => {\n return values\n .map((value, col) => {\n return value.padEnd(widths[col] ?? 0)\n })\n .join(' | ')\n .trimEnd()\n }\n\n const separator = widths\n .map((width) => {\n return '\u2500'.repeat(width)\n })\n .join('\u2500\u253C\u2500')\n\n return ['Environments:', '', renderRow(ENV_TABLE_HEADERS), separator, ...cells.map(renderRow)]\n}\n\n/**\n * List the environments this project has, alongside whether a service token resolves for each one.\n *\n * Purely local: reads the repo's workflows and the local token store, and does not call Doppler \u2014 so\n * it works before any service token exists, which is exactly when a user needs to see the env names\n * they have to run `infra-kit env-token-set <env>` for. (A Doppler SERVICE token could not answer this\n * anyway: it is config-scoped and enumerates only its own config.) The token PRESENCE check is a local\n * file read, not a network probe \u2014 validating that a stored token is still accepted stays\n * `env-token-list --check`'s job.\n *\n * @example\n * await envList()\n * // logs an aligned table: 'dev | gh-workflow | set', 'stage | gh-workflow | not set'\n */\nexport const envList = async () => {\n const project = await getDopplerProject()\n const envs = await listProjectEnvs()\n const store = await readTokenStore()\n const envToken = process.env[INFRA_KIT_ENV_TOKEN_VAR]\n\n const tokens = buildEnvTokenStatus(envs, store?.envs ?? {}, envToken)\n\n logger.info(`Doppler project: ${project}\\n`)\n\n if (tokens.length === 0) {\n // Not an error \u2014 a repo can legitimately declare no dispatchable environment. But an empty list with\n // no explanation is the one thing this command must never print: it is read precisely by the person\n // who does not yet know what the env names ARE.\n logger.info('No environments found.')\n logger.info(` Declare them in a workflow's \\`workflow_dispatch\\` \\`environment.options\\`,`)\n logger.info(' or add a token for one manually.')\n\n return buildResult({ project, envs: tokens })\n }\n\n for (const line of formatEnvTable(tokens)) {\n logger.info(line)\n }\n\n return buildResult({ project, envs: tokens })\n}\n\n/** Shared tail for both exits above \u2014 the empty state is a first-class result, not an error. */\nconst buildResult = ({ project, envs }: { project: string; envs: EnvTokenStatus[] }) => {\n const structuredContent = {\n project,\n configs: envs.map((row) => {\n return row.env\n }),\n tokens: envs,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const envListMcpTool = defineMcpTool({\n name: 'env-list',\n description:\n \"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.\",\n inputSchema: {},\n outputSchema: {\n project: z.string().describe('Detected Doppler project name'),\n configs: z.array(z.string()).describe('Every environment name known to this project'),\n tokens: z\n .array(\n z.object({\n env: z.string().describe('Environment / Doppler config name'),\n source: z\n .enum(['gh-workflow', 'token-only'])\n .describe('Where we learned this environment exists \u2014 a workflow declaration, or a token we hold'),\n hasToken: z.boolean().describe('Whether a service token resolves locally for this environment'),\n }),\n )\n .describe('Per-environment token presence \u2014 never the token value'),\n },\n handler: envList,\n})\n", "import path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport {\n ENV_LOAD_FILE,\n INFRA_KIT_ENV_AUTOLOADED_VAR,\n INFRA_KIT_ENV_CLEARED_VAR,\n INFRA_KIT_ENV_CONFIG_VAR,\n INFRA_KIT_ENV_LOADED_AT_VAR,\n INFRA_KIT_ENV_PROJECT_VAR,\n INFRA_KIT_SESSION_VAR,\n getSessionCacheDir,\n parseVarNamesFromEnvFile,\n} from 'src/lib/constants'\nimport { logger } from 'src/lib/logger'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/**\n * Report which env is currently loaded in the terminal session. Pure local\n * introspection: reads only `process.env` + the cached env-load.sh \u2014 it makes NO\n * Doppler call (use `doctor` for auth/CLI checks), so it works offline and never\n * hangs. Surfaces whether the env was auto-loaded vs manually loaded and whether a\n * clear is currently suppressing auto-load.\n */\nexport const envStatus = async () => {\n logger.info('Environment session status:')\n\n // Check session-loaded vars \u2014 getSessionCacheDir() throws if INFRA_KIT_SESSION is unset\n const cacheDir = getSessionCacheDir()\n\n const sessionId = process.env[INFRA_KIT_SESSION_VAR]!\n const envLoadPath = path.join(cacheDir, ENV_LOAD_FILE)\n\n let sessionLoadedCount = 0\n let sessionTotalCount = 0\n\n const sessionConfig = process.env[INFRA_KIT_ENV_CONFIG_VAR] ?? null\n const sessionProject = process.env[INFRA_KIT_ENV_PROJECT_VAR] ?? null\n const sessionLoadedAt = process.env[INFRA_KIT_ENV_LOADED_AT_VAR] ?? null\n const autoLoaded = process.env[INFRA_KIT_ENV_AUTOLOADED_VAR] === '1'\n const cleared = Boolean(process.env[INFRA_KIT_ENV_CLEARED_VAR])\n\n if (sessionConfig) {\n const varNames = parseVarNamesFromEnvFile(envLoadPath)\n\n if (varNames.length > 0) {\n sessionTotalCount = varNames.length\n sessionLoadedCount = varNames.filter((v) => {\n return v in process.env\n }).length\n }\n\n const loadedAtDisplay = sessionLoadedAt?.replace(/\\.\\d{3}Z$/, '') ?? null\n const origin = autoLoaded ? 'auto-loaded' : 'manually loaded'\n\n logger.info(\n ` ${sessionConfig}: ${sessionLoadedCount} of ${sessionTotalCount} vars loaded (${origin}, project: ${sessionProject}, loadedAt: ${loadedAtDisplay}, session: ${sessionId})\\n`,\n )\n\n if (sessionTotalCount > 0 && sessionLoadedCount < sessionTotalCount) {\n const missing = sessionTotalCount - sessionLoadedCount\n\n logger.warn(\n ` ${missing} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`,\n )\n }\n } else {\n const clearedNote = cleared ? ' (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)' : ''\n\n logger.info(` Session ${sessionId}: no env loaded${clearedNote}\\n`)\n }\n\n const structuredContent = {\n sessionId,\n sessionLoadedCount,\n sessionTotalCount,\n sessionConfig,\n sessionProject,\n sessionLoadedAt,\n autoLoaded,\n cleared,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const envStatusMcpTool = defineMcpTool({\n name: 'env-status',\n description:\n 'Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session.',\n inputSchema: {},\n outputSchema: {\n sessionId: z.string().describe('Current terminal session ID'),\n sessionLoadedCount: z.number().describe('Number of cached vars active in the current session'),\n sessionTotalCount: z.number().describe('Total number of cached var names'),\n sessionConfig: z.string().nullable().describe('Doppler config name of the loaded session (environment name)'),\n sessionProject: z.string().nullable().describe('Doppler project name of the loaded session'),\n sessionLoadedAt: z.string().nullable().describe('ISO 8601 timestamp of when the env was loaded'),\n autoLoaded: z.boolean().describe('True when the loaded env was applied by env auto-load (not a manual env-load)'),\n cleared: z.boolean().describe('True when env-clear is currently suppressing auto-load in this shell'),\n },\n handler: envStatus,\n})\n", "import process from 'node:process'\nimport { z } from 'zod'\n\nimport { buildDopplerChildEnv } from 'src/commands/env-load'\nimport { INFRA_KIT_ENV_TOKEN_VAR, getDopplerProject, probeEnvToken } from 'src/integrations/doppler'\nimport type { EnvTokenProbeOutcome } from 'src/integrations/doppler'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { logger } from 'src/lib/logger'\nimport { listProjectEnvNames } from 'src/lib/project-envs'\nimport { redactToken } from 'src/lib/redact'\nimport { defineMcpTool, textContent } from 'src/types'\n\nexport interface EnvTokenListArgs {\n /** Additionally ask Doppler whether each token is alive AND scoped where it claims. One call per env. */\n check?: boolean\n}\n\n/** Where an env's token came from, rendered for the table. `-` when there is none. */\ntype TokenSource = 'store' | `env:${typeof INFRA_KIT_ENV_TOKEN_VAR}` | '-'\n\ninterface EnvTokenRow {\n env: string\n source: TokenSource\n /** Redacted \u2014 at most the last 4 chars. The raw token NEVER leaves this module. */\n redactedToken: string\n present: boolean\n /** Only with `--check`. `unreachable` means COULDN'T TELL, never \"bad\". */\n status?: EnvTokenProbeOutcome\n}\n\n/**\n * Build one row per declared environment. Pure apart from the two reads it is handed, so the\n * precedence rule \u2014 `INFRA_KIT_ENV_TOKEN` shadows the store for EVERY env, exactly as `resolveEnvToken`\n * resolves it \u2014 is testable and provably the same rule the loader uses.\n *\n * The env var is reported against every env because that is what it does: it is a single value with no\n * env dimension, so a developer with it exported is using it everywhere, whatever their store says.\n *\n * @example\n * buildEnvTokenRows(['dev'], { dev: 'dp.st.dev.abcd1234' }, undefined)\n * // => [{ env: 'dev', source: 'store', redactedToken: '****1234', present: true }]\n */\nexport const buildEnvTokenRows = (\n environments: string[],\n storeTokens: Record<string, string>,\n envToken: string | undefined,\n): EnvTokenRow[] => {\n return environments.map((env) => {\n const token = envToken || storeTokens[env]\n\n if (!token) return { env, source: '-' as const, redactedToken: '-', present: false }\n\n return {\n env,\n source: envToken ? (`env:${INFRA_KIT_ENV_TOKEN_VAR}` as const) : ('store' as const),\n redactedToken: redactToken(token),\n present: true,\n }\n })\n}\n\n/** The rendered table's columns, in order. `CHECK` only appears when `--check` was asked for. */\nconst BASE_COLUMNS = ['ENV', 'SOURCE', 'TOKEN', 'PRESENT'] as const\n\n/**\n * Render the rows as an aligned table. Values are ALREADY redacted by {@link buildEnvTokenRows} \u2014\n * this function never sees a raw token, which is the point of doing the redaction upstream.\n *\n * @example\n * formatEnvTokenTable([{ env: 'dev', source: 'store', redactedToken: '****1234', present: true }], false)\n * // => ['ENV SOURCE TOKEN PRESENT', 'dev store ****1234 yes']\n */\nexport const formatEnvTokenTable = (rows: EnvTokenRow[], checked: boolean): string[] => {\n const header = [...BASE_COLUMNS, ...(checked ? ['CHECK'] : [])]\n\n const cells = rows.map((row) => {\n return [row.env, row.source, row.redactedToken, row.present ? 'yes' : 'no', ...(checked ? [row.status ?? '-'] : [])]\n })\n\n const widths = header.map((column, index) => {\n return Math.max(\n column.length,\n ...cells.map((cell) => {\n return (cell[index] ?? '').length\n }),\n )\n })\n\n return [header, ...cells].map((row) => {\n return row\n .map((cell, index) => {\n return cell.padEnd(widths[index]!)\n })\n .join(' ')\n .trimEnd()\n })\n}\n\n/**\n * Show which environments have a service token, where it came from, and (with `--check`) whether\n * Doppler still accepts it for that config.\n *\n * The ONLY env-token command exposed over MCP, and it can only ever emit redacted values \u2014 the raw\n * token is read here and never rendered, logged, or returned.\n */\nexport const envTokenList = async ({ check }: EnvTokenListArgs = {}) => {\n // Every env the project has, not just the ones with a token \u2014 a missing token is the row worth\n // printing. See `lib/project-envs` for why this is a union of the workflows and the store.\n const envs = await listProjectEnvNames()\n const store = await readTokenStore()\n const envToken = process.env[INFRA_KIT_ENV_TOKEN_VAR]\n\n const rows = buildEnvTokenRows(envs, store?.envs ?? {}, envToken)\n\n if (check) {\n const project = await getDopplerProject()\n\n for (const row of rows) {\n if (!row.present) continue\n\n // The RAW token is re-read here (never from the row, which only carries the redaction) and goes\n // straight into the child env \u2014 by ENV, never argv.\n const token = envToken || store!.envs[row.env]!\n\n const probe = await probeEnvToken({\n childEnv: buildDopplerChildEnv(token),\n project,\n config: row.env,\n })\n\n row.status = probe.outcome\n }\n }\n\n for (const line of formatEnvTokenTable(rows, Boolean(check))) {\n logger.info(line)\n }\n\n const missing = rows.filter((row) => {\n return !row.present\n })\n\n if (missing.length > 0) {\n logger.info(\n `\\nNo token for: ${missing\n .map((row) => {\n return row.env\n })\n .join(', ')}. Add one with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const structuredContent = { tokens: rows }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\n//\n// The ONLY env-token command that is an MCP tool, and the reason is the same one that keeps\n// `doctor --fix` CLI-only: `lib/tool-handler` injects `confirmedCommand: true` into EVERY tool call,\n// so the MCP boundary auto-confirms by construction. An agent must never be one call away from\n// writing a credential (`env-token-set`) or destroying one (`env-token-remove`). This command only\n// READS, and only ever emits redacted values. Do not \"fix\" this by exposing the other two.\nexport const envTokenListMcpTool = defineMcpTool({\n name: 'env-token-list',\n description:\n 'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; \"unreachable\" means the probe could not tell, NOT that the token is bad). Read-only.',\n inputSchema: {\n check: z\n .boolean()\n .optional()\n .describe('Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).'),\n },\n outputSchema: {\n tokens: z\n .array(\n z.object({\n env: z.string().describe('Environment / Doppler config name'),\n source: z.string().describe('\"store\", \"env:INFRA_KIT_ENV_TOKEN\", or \"-\" when absent'),\n redactedToken: z.string().describe('Redacted token \u2014 last 4 chars at most, never the raw value'),\n present: z.boolean().describe('Whether a token is configured for this environment'),\n status: z.string().optional().describe('Only with check=true: valid | revoked | mis-scoped | unreachable'),\n }),\n )\n .describe('One row per declared environment'),\n },\n handler: envTokenList,\n})\n", "/**\n * The single redaction primitive for the CLI. Before this module there was none: every place that\n * wanted to show \"which token is this\" hand-rolled a slice, and a hand-rolled slice is exactly how a\n * credential ends up on a terminal (or in `/tmp/mcp-infra-kit.log`) in full.\n *\n * The rule it encodes: a rendered token shows AT MOST its last 4 characters, and never enough to\n * reconstruct it. Everything user-facing that names a token \u2014 `env-token-set`, `env-token-list`,\n * `doctor` \u2014 renders it through here, so the policy has ONE definition and one place to tighten.\n */\n\n/** How many trailing characters a redacted token may reveal. Never raise this. */\nconst VISIBLE_SUFFIX_LENGTH = 4\n\n/**\n * Below this length a token reveals NOTHING: showing the last 4 of a 6-char string hands over most of\n * it. Real Doppler service tokens are ~40+ chars, so this only ever fires for garbage input \u2014 which\n * is precisely when we must not be helpful.\n */\nconst MIN_LENGTH_FOR_SUFFIX = 8\n\n/** The fixed-width mask. Fixed on purpose: a mask whose length tracked the token would leak its length. */\nconst MASK = '****'\n\n/**\n * Render a token for human eyes: the mask, plus at most the last 4 characters.\n *\n * Total function \u2014 an empty, short, or malformed value returns the bare mask rather than throwing.\n * A redaction helper that can throw is a redaction helper that gets wrapped in a try/catch whose\n * fallback prints the raw value.\n *\n * @example\n * redactToken('dp.st.dev.abcdefgh1234') // => '****1234'\n * redactToken('short') // => '****' (too short to reveal anything)\n * redactToken('') // => '****'\n */\nexport const redactToken = (token: string): string => {\n if (typeof token !== 'string' || token.length < MIN_LENGTH_FOR_SUFFIX) return MASK\n\n return `${MASK}${token.slice(-VISIBLE_SUFFIX_LENGTH)}`\n}\n", "import { z } from 'zod'\nimport { $ } from 'zx'\n\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { commandEcho, confirmOrExit } from 'src/lib/command-echo'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { assertManagementContext } from 'src/lib/git-guard'\nimport { logger } from 'src/lib/logger'\nimport { pickReleaseBranches } from 'src/lib/prompts/release-picker'\nimport {\n detectReleaseType,\n formatBranchPickerItems,\n getJiraDescriptions,\n releaseBranchLabels,\n} from 'src/lib/release-utils'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { RequiredConfirmedOptionArg } from 'src/types'\n\ninterface GhMergeDevArgs extends RequiredConfirmedOptionArg {\n all?: boolean\n}\n\n/**\n * Merge dev into every release branch\n */\nexport const ghMergeDev = async (args: GhMergeDevArgs) => {\n const { all, confirmedCommand } = args\n\n // Branch-agnostic: this self-switches onto a freshly fetched dev below, after\n // the confirmation prompt, so only the worktree + clean-tree legs apply.\n await assertManagementContext({ operation: 'merge dev into release branches' })\n\n // Only merge dev into regular releases (not hotfixes, which target main)\n const allPRs = await getReleasePRsWithInfo()\n const releasePRsList = allPRs\n .filter((pr) => {\n return detectReleaseType(pr.title) === 'regular'\n })\n .map((pr) => {\n return pr.branch\n })\n\n if (releasePRsList.length === 0) {\n logger.info('\u2139\uFE0F No open release branches found')\n\n commandEcho.print()\n\n return {\n content: textContent(\n JSON.stringify({ successfulMerges: 0, failedMerges: 0, failedBranches: [], totalBranches: 0 }, null, 2),\n ),\n structuredContent: { successfulMerges: 0, failedMerges: 0, failedBranches: [], totalBranches: 0 },\n }\n }\n\n let selectedReleaseBranches: string[] = []\n\n if (all) {\n selectedReleaseBranches = releasePRsList\n } else {\n commandEcho.setInteractive()\n\n const descriptions = await getJiraDescriptions()\n\n selectedReleaseBranches = await pickReleaseBranches(\n formatBranchPickerItems({ branches: releasePRsList, descriptions }),\n { required: true },\n )\n }\n\n // Track --all flag if all branches were selected (either via flag or interactively)\n const allSelected = selectedReleaseBranches.length === releasePRsList.length\n\n if (allSelected) {\n commandEcho.addOption('--all', true)\n } else {\n commandEcho.addOption('--versions', releaseBranchLabels(selectedReleaseBranches))\n }\n\n await confirmOrExit(\n confirmedCommand,\n `Are you sure you want to merge dev into these branches: ${selectedReleaseBranches.join(', ')}?`,\n )\n\n // Track --yes flag if confirmation was interactive (user confirmed)\n if (!confirmedCommand) {\n commandEcho.addOption('--yes', true)\n }\n\n $.quiet = true\n\n // The guard no longer requires dev, so this switch is a real operation rather\n // than the no-op it used to be \u2014 most plausibly failing when dev is checked\n // out in a linked worktree. Fails closed: nothing has been merged or pushed\n // yet.\n try {\n await $`git fetch origin`\n await $`git switch dev`\n await $`git pull origin dev`\n } catch (error) {\n $.quiet = false\n\n throw new OperationError(error, {\n operation: 'switch to dev before merging',\n remediation: 'dev may be checked out in another worktree \u2014 check `git worktree list`',\n })\n }\n\n const failedBranches: string[] = []\n\n // Merge dev into each branch\n for (const branch of selectedReleaseBranches) {\n const success = await mergeDev(branch)\n\n if (!success) {\n failedBranches.push(branch)\n }\n }\n\n $.quiet = false\n\n if (failedBranches.length > 0) {\n logger.info(`\\n\u26A0\uFE0F ${failedBranches.length} branch(es) failed to merge automatically.\\n`)\n logger.info('\uD83D\uDCCB Manual merge script for failed branches:')\n for (const branch of failedBranches) {\n logger.info(\n `# Merge dev into ${branch} and resolve conflicts if any \\n\\ngit switch ${branch} && git pull origin ${branch} && git merge origin/dev\\ngit push origin ${branch} && git switch dev\\n`,\n )\n }\n logger.info(\n `\u2705 ${selectedReleaseBranches.length - failedBranches.length}/${selectedReleaseBranches.length} merges completed successfully.`,\n )\n } else {\n logger.info('\u2705 All merges completed successfully!\\n')\n }\n\n commandEcho.print()\n\n const structuredContent = {\n successfulMerges: selectedReleaseBranches.length - failedBranches.length,\n failedMerges: failedBranches.length,\n failedBranches,\n totalBranches: selectedReleaseBranches.length,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\nconst mergeDev = async (branch: string): Promise<boolean> => {\n try {\n await $`git switch ${branch}`\n\n await $`git pull origin ${branch}`\n\n await $`git merge origin/dev --no-edit`\n\n await $`git push origin ${branch}`\n\n await $`git switch dev`\n\n logger.info(`Successfully merged dev into ${branch}`)\n\n return true\n } catch (error: unknown) {\n const err = new OperationError(error, {\n operation: `merge dev into ${branch}`,\n remediation: \"resolve conflicts manually or rerun after 'git fetch origin'\",\n })\n\n logger.error({ error, branch, msg: err.message })\n\n await $`git merge --abort`\n\n return false\n }\n}\n\n// MCP Tool Registration\nexport const ghMergeDevMcpTool = defineMcpTool({\n name: 'gh-merge-dev',\n description:\n 'Merge origin/dev into every open regular (non-hotfix) release branch and push the result. Mutates local git state and the remote release branches. When invoked via MCP, pass all=true \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.',\n requiresHumanConfirm: true,\n inputSchema: {\n all: z\n .boolean()\n .optional()\n .describe(\n 'Target every open regular release branch. Must be true for MCP calls (the interactive picker is unavailable without a TTY).',\n ),\n confirm: z\n .boolean()\n .optional()\n .describe('Set true to execute; omit for a dry-run gate that echoes the resolved action.'),\n },\n outputSchema: {\n successfulMerges: z.number().describe('Number of successful merges'),\n failedMerges: z.number().describe('Number of failed merges'),\n failedBranches: z.array(z.string()).describe('List of branches that failed to merge'),\n totalBranches: z.number().describe('Total number of branches processed'),\n },\n handler: ghMergeDev,\n})\n", "import { $ } from 'zx'\n\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { logger } from 'src/lib/logger'\n\n/**\n * Validate GitHub CLI installation and authentication status and throw an error if not valid\n */\nexport const validateGitHubCliAndAuth = async () => {\n try {\n await $`gh --version`\n } catch (error: unknown) {\n logger.error({ error }, 'Error: GitHub CLI (gh) is not installed.')\n throw new OperationError(error, {\n operation: 'verify GitHub CLI is installed',\n remediation: 'install gh from https://cli.github.com/',\n })\n }\n\n try {\n await $`gh auth status`\n } catch (error: unknown) {\n logger.error({ error }, 'Error: GitHub CLI (gh) is not authenticated.')\n throw new OperationError(error, {\n operation: 'verify GitHub CLI authentication',\n remediation: 'run \"gh auth login\" (https://cli.github.com/manual/gh_auth_login)',\n })\n }\n}\n", "import { $ } from 'zx'\n\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { logger } from 'src/lib/logger'\nimport { compareReleaseIds, formatBranchName, formatPrTitle, parseBranchName } from 'src/lib/release-id'\nimport type { ReleaseId } from 'src/lib/release-id'\nimport { getBaseBranch } from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\n\ninterface ReleasePR {\n headRefName: string\n number: number\n state: string\n title: string\n baseRefName: string\n createdAt: string\n}\n\nexport interface ReleasePRInfo {\n branch: string\n title: string\n createdAt: string\n}\n\n/**\n * Sort release head refs in the locked deterministic order (versions block\n * first by semver ascending, then names by PR creation date). Head refs that\n * are not valid release branches (parseBranchName \u2192 null) are filtered out\n * rather than throwing or NaN-sorting, so a stray junk branch can never break\n * discovery. Carries each PR's createdAt for name ordering.\n */\nconst sortReleasePRs = (prs: ReleasePR[]): ReleasePR[] => {\n return prs\n .map((pr) => {\n return { pr, id: parseBranchName(pr.headRefName) }\n })\n .filter((entry): entry is { pr: ReleasePR; id: NonNullable<typeof entry.id> } => {\n return entry.id !== null\n })\n .sort((a, b) => {\n return compareReleaseIds(a.id, b.id, { a: a.pr.createdAt, b: b.pr.createdAt })\n })\n .map((entry) => {\n return entry.pr\n })\n}\n\n/**\n * Fetch all open release/hotfix PRs from GitHub.\n * Searches both dev (regular) and main (hotfix) base branches.\n * Returns deduplicated ReleasePR objects.\n */\nconst fetchAllReleasePRs = async (): Promise<ReleasePR[]> => {\n const releasePRs =\n await $`gh pr list --search \"Release in:title\" --base dev --json number,title,headRefName,state,baseRefName,createdAt`\n\n const hotfixPRs =\n await $`gh pr list --search \"Hotfix in:title\" --base main --json number,title,headRefName,state,baseRefName,createdAt`\n\n const all: ReleasePR[] = [...JSON.parse(releasePRs.stdout), ...JSON.parse(hotfixPRs.stdout)]\n\n // Deduplicate by headRefName\n const seen = new Set<string>()\n\n return all.filter((pr) => {\n if (seen.has(pr.headRefName)) return false\n\n seen.add(pr.headRefName)\n\n return true\n })\n}\n\n/**\n * Fetch, guard against empty, and sort all open release PRs in the locked\n * deterministic order. Shared core of the two public variants below; wraps the\n * gh calls so a fetch failure surfaces as an OperationError.\n */\nconst loadSortedReleasePRs = async (): Promise<ReleasePR[]> => {\n try {\n const prs = await fetchAllReleasePRs()\n\n if (prs.length === 0) {\n throw new OperationError(undefined, {\n operation: 'find open release PRs',\n remediation: 'open a release PR first, or check you are in the right repo',\n })\n }\n\n return sortReleasePRs(prs)\n } catch (error) {\n if (error instanceof OperationError) throw error\n\n logger.error({ error }, '\u274C Error fetching release PRs')\n\n throw new OperationError(error, { operation: 'fetch release PRs' })\n }\n}\n\n/**\n * Fetch open release PRs from GitHub with 'Release' or 'Hotfix' in the title.\n * Returns an array of headRefName strings in the locked deterministic order\n * (version branches first by semver ascending, then named branches by PR\n * creation date). Unparseable head refs are filtered out.\n *\n * @returns [release/v1.18.22, release/v1.18.23, release/checkout-redesign]\n */\nexport const getReleasePRs = async (): Promise<string[]> => {\n const prs = await loadSortedReleasePRs()\n\n return prs.map((pr) => {\n return pr.headRefName\n })\n}\n\n/**\n * Fetch open release PRs with title info (for detecting release type).\n * Returns ReleasePRInfo objects in the locked deterministic order (version\n * branches first by semver ascending, then named branches by PR creation\n * date). Unparseable head refs are filtered out.\n */\nexport const getReleasePRsWithInfo = async (): Promise<ReleasePRInfo[]> => {\n const prs = await loadSortedReleasePRs()\n\n return prs.map((pr) => {\n return {\n branch: pr.headRefName,\n title: pr.title,\n createdAt: pr.createdAt,\n }\n })\n}\n\ninterface UpdateReleasePRBodyArgs {\n branch: string\n body: string\n}\n\n/**\n * Update the body of an open release PR identified by its head branch.\n */\nexport const updateReleasePRBody = async (args: UpdateReleasePRBodyArgs): Promise<void> => {\n const { branch, body } = args\n\n try {\n $.quiet = true\n await $`gh pr edit ${branch} --body ${body}`\n $.quiet = false\n } catch (error: unknown) {\n logger.error({ error, branch }, `Error updating release PR body for ${branch}`)\n throw error\n }\n}\n\ninterface CreateReleaseBranchArgs {\n id: ReleaseId\n jiraVersionUrl: string\n type: ReleaseType\n description?: string\n}\n\n// Function to create a release branch\nexport const createReleaseBranch = async (\n args: CreateReleaseBranchArgs,\n): Promise<{ branchName: string; prUrl: string }> => {\n const { id, jiraVersionUrl, type, description } = args\n const prTitle = formatPrTitle(id, type)\n const baseBranch = getBaseBranch(type)\n\n const branchName = formatBranchName(id)\n\n const body = description && description.trim() !== '' ? `${jiraVersionUrl}\\n\\n${description}` : `${jiraVersionUrl} \\n`\n\n try {\n $.quiet = true\n\n await $`git switch ${baseBranch}`\n await $`git pull origin ${baseBranch}`\n await $`git checkout -b ${branchName}`\n await $`git push -u origin ${branchName}`\n await $`git commit --allow-empty-message --allow-empty --message ''`\n await $`git push origin ${branchName}`\n\n // Create PR and capture URL\n const prResult = await $`gh pr create --title ${prTitle} --body ${body} --base ${baseBranch} --head ${branchName}`\n\n const prLink = prResult.stdout.trim()\n\n await $`git switch ${baseBranch}`\n\n $.quiet = false\n\n return {\n branchName,\n prUrl: prLink,\n }\n } catch (error: unknown) {\n logger.error({ error, branchName }, `Error creating release branch ${branchName}`)\n\n throw error\n }\n}\n", "import { $ } from 'zx'\n\nimport { createReleaseBranch } from 'src/integrations/gh'\nimport { createJiraVersion, getProjectVersions, loadJiraConfigOptional } from 'src/integrations/jira'\nimport type { JiraConfig } from 'src/integrations/jira'\nimport { OperationError } from 'src/lib/errors/operation-error'\n// Type-only cross-layer import: src/lib/prompts/types.ts is intentionally a\n// zero-import leaf so it can be imported from any layer (including this one)\n// without creating a cycle.\nimport type { BranchPickerItem } from 'src/lib/prompts/types'\nimport { displayLabel, formatBranchName, formatJiraName, parseBranchName, parseReleaseRef } from 'src/lib/release-id'\nimport type { ReleaseId } from 'src/lib/release-id'\n\n/** Sentinel ref for deploying from the `dev` branch instead of a release branch. */\nexport const DEV_REF = 'dev'\n\nexport type ReleaseType = 'regular' | 'hotfix'\n\n/**\n * Get the base branch for a release type.\n * Regular releases branch from/to dev, hotfixes branch from/to main.\n */\nexport const getBaseBranch = (type: ReleaseType): string => {\n return type === 'hotfix' ? 'main' : 'dev'\n}\n\nexport interface ReleaseCreationResult {\n version: string\n type: ReleaseType\n branchName: string\n prUrl: string\n jiraVersionUrl: string\n}\n\n/**\n * Prepare git repository for release creation\n * Fetches latest changes, switches to base branch, and pulls latest\n */\nexport const prepareGitForRelease = async (type: ReleaseType = 'regular'): Promise<void> => {\n const baseBranch = getBaseBranch(type)\n\n $.quiet = true\n\n await $`git fetch origin`\n await $`git switch ${baseBranch}`\n await $`git pull origin ${baseBranch}`\n\n $.quiet = false\n}\n\ninterface CreateSingleReleaseArgs {\n id: ReleaseId\n jiraConfig: JiraConfig\n description?: string\n type?: ReleaseType\n}\n\n/**\n * Create a single release by creating both Jira version and GitHub release branch\n */\nexport const createSingleRelease = async (args: CreateSingleReleaseArgs): Promise<ReleaseCreationResult> => {\n const { id, jiraConfig, description, type = 'regular' } = args\n // 1. Create Jira version (mandatory). For versioned releases this is\n // \"v1.2.3\" (byte-identical to before); for named releases it is \"<name>\".\n const versionName = formatJiraName(id)\n\n const result = await createJiraVersion(\n {\n name: versionName,\n projectId: jiraConfig.projectId,\n description: description || '',\n released: false,\n archived: false,\n },\n jiraConfig,\n )\n\n // Construct user-friendly Jira URL using project key from API response\n const jiraVersionUrl = `${jiraConfig.baseUrl}/projects/${result.version!.projectId}/versions/${result.version!.id}/tab/release-report-all-issues`\n\n // 2. Create GitHub release branch\n const releaseInfo = await createReleaseBranch({ id, jiraVersionUrl, type, description })\n\n return {\n version: displayLabel(id),\n type,\n branchName: releaseInfo.branchName,\n prUrl: releaseInfo.prUrl,\n jiraVersionUrl,\n }\n}\n\n/**\n * Fetch Jira version descriptions mapped by version name (e.g., \"v1.2.5\" \u2192 \"Some description\")\n * Gracefully returns empty map if Jira is unavailable\n */\nexport const getJiraDescriptions = async (): Promise<Map<string, string>> => {\n const descriptions = new Map<string, string>()\n\n const jiraConfig = await loadJiraConfigOptional()\n\n if (!jiraConfig) return descriptions\n\n try {\n const versions = await getProjectVersions(jiraConfig)\n\n for (const version of versions) {\n if (version.description) {\n descriptions.set(version.name, version.description)\n }\n }\n } catch {\n // Jira fetch failed, continue without descriptions\n }\n\n return descriptions\n}\n\n/**\n * Format a version string with its release type tag, e.g. \"1.2.5 [regular]\"\n * When maxVersionLength is provided, pads the version for alignment.\n */\nexport const formatVersionLabel = (version: string, type: ReleaseType, maxVersionLength?: number): string => {\n const padding = maxVersionLength ? ' '.repeat(maxVersionLength - version.length + 3) : ' '\n const tag = `[${type}]`.padEnd(11)\n\n return `${version}${padding}${tag}`\n}\n\n/**\n * Detect release type from PR title.\n * PRs titled \"Hotfix v...\" are hotfix, everything else is regular.\n */\nexport const detectReleaseType = (title: string): ReleaseType => {\n return title.toLowerCase().startsWith('hotfix') ? 'hotfix' : 'regular'\n}\n\ninterface FormatBranchChoicesArgs {\n branches: string[]\n descriptions: Map<string, string>\n types?: Map<string, ReleaseType>\n}\n\ninterface ParsedBranchChoice {\n branch: string\n id: ReleaseId\n /** Human display label: `1.2.3` | `<name>`. */\n label: string\n}\n\n/**\n * Parse branches into release ids, dropping any that do not parse (lenient\n * discovery source). Exported for unit testing the version/name/junk split.\n */\nexport const parseBranchChoices = (branches: string[]): ParsedBranchChoice[] => {\n return branches.flatMap((branch) => {\n const id = parseBranchName(branch)\n\n if (!id) return []\n\n return [{ branch, id, label: displayLabel(id) }]\n })\n}\n\n/**\n * Resolve an operator-supplied release ref (version `1.2.3` / `v1.2.3` or name\n * `checkout-redesign`) to its branch name (`release/v1.2.3` | `release/<name>`).\n * Strict: surfaces a parse failure as an OperationError with remediation text.\n */\nexport const resolveReleaseBranch = (versionArg: string): string => {\n try {\n return formatBranchName(parseReleaseRef(versionArg))\n } catch (error) {\n throw new OperationError(error, {\n operation: `resolve release ref \"${versionArg}\"`,\n remediation: 'pass a version (e.g. \"1.2.5\") or a release name (e.g. \"checkout-redesign\")',\n })\n }\n}\n\n/**\n * Render the human display label for a release branch. Returns the `dev`\n * sentinel unchanged; otherwise derives `1.2.3` | `<name>` from the branch.\n * Falls back to the raw branch when it does not parse as a release id.\n */\nexport const releaseLabelFromBranch = (branch: string): string => {\n if (branch === DEV_REF) return DEV_REF\n\n const id = parseBranchName(branch)\n\n return id ? displayLabel(id) : branch\n}\n\n/**\n * Render human display labels for a list of release branches, dropping any\n * branch that does not parse as a release id (lenient discovery contract).\n */\nexport const releaseBranchLabels = (branches: string[]): string[] => {\n return branches.flatMap((branch) => {\n const id = parseBranchName(branch)\n\n return id ? [displayLabel(id)] : []\n })\n}\n\nconst deriveBranchType = (branch: string, types?: Map<string, ReleaseType>): ReleaseType | undefined => {\n return types ? types.get(branch) || 'regular' : undefined\n}\n\n/**\n * Format release branch names as Ink picker items. Labels and descriptions\n * are returned as separate fields \u2014 the picker renders and pads them itself.\n */\nexport const formatBranchPickerItems = (args: FormatBranchChoicesArgs): BranchPickerItem[] => {\n const { branches, descriptions, types } = args\n\n return parseBranchChoices(branches).map(({ branch, id, label }) => {\n return {\n value: branch,\n label,\n // Jira-descriptions map is keyed by the Jira version NAME (`v1.2.3` | `<name>`).\n description: descriptions.get(formatJiraName(id)),\n type: deriveBranchType(branch, types),\n }\n })\n}\n", "import process from 'node:process'\n\nimport { logger } from 'src/lib/logger'\n\nimport type {\n CreateJiraVersionParams,\n CreateJiraVersionResult,\n DeliverJiraReleaseParams,\n DeliverJiraReleaseResult,\n JiraConfig,\n JiraVersion,\n UpdateJiraVersionParams,\n UpdateJiraVersionResult,\n} from './types.js'\n\n/**\n * Throws a normalized error when a Jira API response is not OK, logging the\n * status, statusText, and response body under the given context message.\n * @param response - The fetch Response to check\n * @param context - Log message describing the failed operation\n */\nconst assertJiraOk = async (response: Response, context: string): Promise<void> => {\n if (response.ok) {\n return\n }\n\n const errorText = await response.text()\n\n logger.error(\n {\n status: response.status,\n statusText: response.statusText,\n error: errorText,\n },\n context,\n )\n\n throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n}\n\n/**\n * Creates a new version in Jira using the REST API\n * @param params - Version creation parameters\n * @param config - Jira configuration (baseUrl, token, projectId)\n * @returns Result containing created version or error\n */\nexport const createJiraVersion = async (\n params: CreateJiraVersionParams,\n config: JiraConfig,\n): Promise<CreateJiraVersionResult> => {\n try {\n const { baseUrl, token, email, projectId } = config\n\n const requestBody = {\n name: params.name,\n projectId: params.projectId || projectId,\n description: params.description || '',\n released: params.released || false,\n archived: params.archived || false,\n }\n\n const url = `${baseUrl}/rest/api/3/version`\n\n // Create Basic auth credentials\n const credentials = btoa(`${email}:${token}`)\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: `Basic ${credentials}`,\n },\n body: JSON.stringify(requestBody),\n })\n\n await assertJiraOk(response, 'Failed to create Jira version')\n\n const version = (await response.json()) as JiraVersion\n\n return {\n success: true,\n version,\n }\n } catch (error) {\n logger.error({ error }, 'Error creating Jira version')\n\n throw error\n }\n}\n\n/**\n * Gets all versions for a project from Jira\n * @param config - Jira configuration\n * @returns Array of JiraVersion objects\n */\nexport const getProjectVersions = async (config: JiraConfig): Promise<JiraVersion[]> => {\n try {\n const { baseUrl, token, email, projectId } = config\n\n const url = `${baseUrl}/rest/api/3/project/${projectId}/versions`\n const credentials = btoa(`${email}:${token}`)\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n Authorization: `Basic ${credentials}`,\n },\n })\n\n await assertJiraOk(response, 'Failed to get Jira project versions')\n\n const versions = (await response.json()) as JiraVersion[]\n\n return versions\n } catch (error) {\n logger.error({ error }, 'Error getting Jira project versions')\n\n throw error\n }\n}\n\n/**\n * Finds a Jira version by name in the project\n * @param versionName - Name of the version to find (e.g., \"v1.33.10\")\n * @param config - Jira configuration\n * @returns JiraVersion if found, null otherwise\n */\nexport const findVersionByName = async (versionName: string, config: JiraConfig): Promise<JiraVersion | null> => {\n try {\n const versions = await getProjectVersions(config)\n const version = versions.find((v) => {\n return v.name === versionName\n })\n\n return version || null\n } catch (error) {\n logger.error({ error, versionName }, 'Error finding Jira version by name')\n\n throw error\n }\n}\n\n/**\n * Updates an existing Jira version\n * @param params - Update parameters\n * @param config - Jira configuration\n * @returns Result containing updated version or error\n */\nexport const updateJiraVersion = async (\n params: UpdateJiraVersionParams,\n config: JiraConfig,\n): Promise<UpdateJiraVersionResult> => {\n try {\n const { baseUrl, token, email } = config\n\n // Only include fields the caller explicitly passed.\n const requestBody: Record<string, any> = {}\n\n if (params.released !== undefined) requestBody.released = params.released\n if (params.archived !== undefined) requestBody.archived = params.archived\n if (params.releaseDate !== undefined) requestBody.releaseDate = params.releaseDate\n if (params.description !== undefined) requestBody.description = params.description\n\n const url = `${baseUrl}/rest/api/3/version/${params.versionId}`\n const credentials = btoa(`${email}:${token}`)\n\n const response = await fetch(url, {\n method: 'PUT',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: `Basic ${credentials}`,\n },\n body: JSON.stringify(requestBody),\n })\n\n await assertJiraOk(response, 'Failed to update Jira version')\n\n const version = (await response.json()) as JiraVersion\n\n return {\n success: true,\n version,\n }\n } catch (error) {\n logger.error({ error }, 'Error updating Jira version')\n\n throw error\n }\n}\n\n/**\n * Delivers a Jira release by marking it as released with the current date\n * @param params - Parameters containing the version name\n * @param config - Jira configuration\n * @returns Result containing updated version\n * @throws Error if version not found or update fails\n */\nexport const deliverJiraRelease = async (\n params: DeliverJiraReleaseParams,\n config: JiraConfig,\n): Promise<DeliverJiraReleaseResult> => {\n try {\n const { versionName } = params\n\n // Find the version by name\n const version = await findVersionByName(versionName, config)\n\n if (!version) {\n logger.error({ versionName }, 'Jira version not found')\n throw new Error(`Version \"${versionName}\" not found in Jira project`)\n }\n\n // Update the version to mark it as released\n const result = await updateJiraVersion(\n {\n versionId: version.id,\n released: true,\n releaseDate: new Date().toISOString().split('T')[0], // Current date in YYYY-MM-DD format\n },\n config,\n )\n\n return result\n } catch (error) {\n logger.error({ error }, 'Error delivering Jira release')\n throw error\n }\n}\n\n/**\n * Loads Jira configuration from environment variables\n * @throws Error with detailed message if configuration is missing or invalid\n * @returns Promise<JiraConfig>\n */\nexport const loadJiraConfig = async (): Promise<JiraConfig> => {\n const baseUrl = process.env.JIRA_BASE_URL\n const token = process.env.JIRA_TOKEN || process.env.JIRA_API_TOKEN\n const projectIdStr = process.env.JIRA_PROJECT_ID\n const email = process.env.JIRA_EMAIL\n\n const missingVars: string[] = []\n\n if (!baseUrl) missingVars.push('JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)')\n if (!token) missingVars.push('JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)')\n if (!projectIdStr) missingVars.push('JIRA_PROJECT_ID (numeric project ID)')\n if (!email) missingVars.push('JIRA_EMAIL (your Jira email address)')\n\n if (missingVars.length > 0) {\n const errorMessage = [\n 'Jira configuration is required but incomplete.',\n 'Please configure the following environment variables:',\n ...missingVars.map((v) => {\n return ` - ${v}`\n }),\n '',\n 'You can set these in your .env file or as environment variables.',\n ].join('\\n')\n\n throw new Error(errorMessage)\n }\n\n const projectId = Number.parseInt(projectIdStr!, 10)\n\n if (Number.isNaN(projectId)) {\n throw new TypeError(`Invalid JIRA_PROJECT_ID: \"${projectIdStr}\" must be a numeric value (e.g., 10001)`)\n }\n\n return {\n baseUrl: baseUrl!.replace(/\\/$/, ''), // Remove trailing slash\n token: token!,\n projectId,\n email: email!,\n }\n}\n\n/**\n * Attempts to load Jira configuration from environment variables\n * Returns null if configuration is missing or invalid (for optional Jira integration)\n * @returns Promise<JiraConfig | null>\n */\nexport const loadJiraConfigOptional = async (): Promise<JiraConfig | null> => {\n try {\n const config = await loadJiraConfig()\n\n return config\n } catch (error) {\n logger.warn({ error }, 'Jira configuration not available, skipping Jira integration')\n\n return null\n }\n}\n", "import { OperationError } from 'src/lib/errors/operation-error'\nimport { isInsideLinkedWorktree, isWorkingTreeClean } from 'src/lib/git-utils'\n\nexport interface AssertManagementContextArgs {\n /** Operation name surfaced in the failure message, e.g. 'create release'. */\n operation: string\n}\n\n/**\n * Guard release- and worktree-management commands so they run only from the\n * main repository checkout, with a clean working tree.\n *\n * Deliberately says nothing about which branch you are on. The commands that\n * need a canonical branch (`release-create`, `gh-merge-dev`) switch onto it\n * themselves, after their confirmation prompt and behind a `git fetch`, which a\n * guard running before consent could do neither of; the rest (`worktrees-*`)\n * address branches by name and never read `HEAD`. A branch assertion here would\n * only refuse work that is about to succeed anyway.\n *\n * What is left are the two states no command can recover from on the operator's\n * behalf: a linked worktree (wrong checkout entirely) and a dirty tree (their\n * uncommitted work is at stake). Both throw {@link OperationError}, which\n * surfaces uniformly to CLI users and MCP-connected agents.\n */\nexport const assertManagementContext = async (args: AssertManagementContextArgs): Promise<void> => {\n const { operation } = args\n\n if (await isInsideLinkedWorktree()) {\n throw new OperationError(undefined, {\n operation,\n remediation: 'run this from the main repository checkout, not a linked git worktree',\n stderrExcerpt: 'command run from inside a linked worktree',\n })\n }\n\n if (!(await isWorkingTreeClean())) {\n throw new OperationError(undefined, {\n operation,\n remediation: 'commit or stash your changes, then retry',\n stderrExcerpt: 'working tree has uncommitted changes',\n })\n }\n}\n", "import process from 'node:process'\n\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { PromptCancelledError } from 'src/lib/errors/prompt-cancelled-error'\nimport { jsonOutput } from 'src/lib/json-output'\nimport { isMcpMode } from 'src/lib/mcp-mode'\n\nimport type { BranchPickerItem } from './types'\n\n/**\n * Gate the interactive Ink picker. Bails (throwing a clear `OperationError`,\n * never loading React) when there is no interactive input OR when structured\n * output is requested \u2014 `--json` is registered on every command and sets\n * `jsonOutput.enabled`, so `--json` on a TTY without an explicit arg would\n * otherwise pass a TTY-only gate and dynamically import the TUI (leaking React\n * onto the `--json` path).\n *\n * The predicate is `stdin.isTTY` only \u2014 deliberately NOT the palette's\n * `stdout && stdin`. These prompts render to stderr, so an interactive run whose\n * STDOUT is redirected (e.g. `worktrees-remove > log.txt`) must still prompt;\n * requiring `stdout.isTTY` would regress that. Input-side interactivity is what\n * the picker actually needs.\n *\n * The MCP clause is LOAD-BEARING, not defensive: `worktrees-add` and `gh-merge-dev`\n * are `mcpExposed: true` with ALL of their branch inputs `.optional()`, so an MCP\n * call with those args omitted DOES enter the interactive branch. Without a guard it\n * would render an Ink picker into the JSON-RPC stream (and load React there).\n *\n * That guard keys on `isMcpMode()`, NOT on `!process.stdin.isTTY`. The TTY check\n * alone does not hold: `commands/mcp/mcp.ts` spawns the server with `stdio: 'inherit'`,\n * so a terminal-launched `infra-kit mcp` hands the child a real TTY stdin and an\n * isTTY-keyed guard does NOT fire. It only looks sufficient because Claude Code\n * happens to spawn the server with piped stdio \u2014 a property of one client, not a\n * guarantee. The `!isTTY` clause stays as well, for genuinely non-interactive runs\n * (pipes, CI).\n */\nconst assertInteractive = () => {\n if (isMcpMode() || !process.stdin.isTTY || jsonOutput.enabled) {\n throw new OperationError(undefined, {\n operation: 'interactive branch selection',\n remediation:\n 'pass the branch selection explicitly (CLI: `--version`/`--versions`/`--all`; MCP: the `version`/`versions`/`all` fields) for non-interactive, --json, or MCP runs',\n })\n }\n}\n\n/**\n * Prompt for a single release branch via the searchable Ink picker. Throws an\n * `OperationError` on non-interactive/`--json`/MCP runs (see `assertInteractive`)\n * and a `PromptCancelledError` if the user backs out with Esc/Ctrl-C. The Ink\n * TUI is reached only through a dynamic import so React never loads on the\n * bail paths.\n */\nexport const pickReleaseBranch = async (items: BranchPickerItem[]): Promise<string> => {\n assertInteractive()\n const { runBranchPicker } = await import('src/tui/boot')\n const value = await runBranchPicker(items)\n\n if (value === null) throw new PromptCancelledError()\n\n return value\n}\n\n/**\n * Prompt for one or more release branches via the searchable Ink multi-picker.\n * Same guard and cancellation semantics as {@link pickReleaseBranch}; returns\n * the selected values.\n */\nexport const pickReleaseBranches = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[]> => {\n assertInteractive()\n const { runBranchMultiPicker } = await import('src/tui/boot')\n const values = await runBranchMultiPicker(items, opts)\n\n if (values === null) throw new PromptCancelledError()\n\n return values\n}\n", "/**\n * Thrown by the Ink branch pickers (via the `release-picker` shim) when the user\n * presses Esc or Ctrl-C.\n *\n * The name is honest \u2014 `PromptCancelledError`, not a borrowed `@inquirer/core`\n * class name. It is registered in `CANCELLATION_ERROR_NAMES` so\n * {@link ./is-prompt-cancellation.isPromptCancellation} recognises it through the\n * same by-name mechanism it already uses for the `@inquirer` cancel errors. That\n * keeps the contract honest if `@inquirer` is ever dropped, and survives anyone\n * adding an `instanceof` fast-path for the real inquirer classes.\n *\n * @example\n * try {\n * await pickReleaseBranch(items)\n * } catch (err) {\n * if (isPromptCancellation(err)) process.exit(0) // user backed out\n * throw err\n * }\n */\nexport class PromptCancelledError extends Error {\n override name = 'PromptCancelledError'\n\n constructor() {\n super('Prompt cancelled')\n }\n}\n", "import type { Command } from 'commander'\nimport process from 'node:process'\n\n/**\n * `--json` output mode for the CLI. This is a presentation concern only: every\n * command handler already returns a `structuredContent` payload (the same one\n * the MCP surface consumes). Human/log output goes to stderr (see lib/logger),\n * so writing the structured payload to stdout never collides with it.\n */\n\nexport interface CommandResult {\n structuredContent?: unknown\n}\n\n/** Mutable holder (object so `prefer-const` holds while the flag toggles per run). */\nexport const jsonOutput = { enabled: false }\n\n/**\n * In `--json` mode, write a command result's `structuredContent` to stdout as\n * pretty JSON and return the result unchanged. Outside `--json` mode it is a\n * no-op pass-through. The writer is injectable for testing.\n */\nexport const emit = <T extends CommandResult | void>(\n result: T,\n write: (text: string) => void = (text) => {\n process.stdout.write(text)\n },\n): T => {\n if (jsonOutput.enabled && result && result.structuredContent != null) {\n write(`${JSON.stringify(result.structuredContent, null, 2)}\\n`)\n }\n\n return result\n}\n\n/** Register `--json` on a command and every nested subcommand (idempotent). */\nexport const addJsonOption = (cmd: Command): void => {\n const alreadyHasJson = cmd.options.some((option) => {\n return option.long === '--json'\n })\n\n if (!alreadyHasJson) {\n cmd.option('--json', 'Output the structured result as JSON on stdout (human logs stay on stderr)')\n }\n\n cmd.commands.forEach(addJsonOption)\n}\n", "import { z } from 'zod'\nimport { $ } from 'zx'\n\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { deliverJiraRelease, loadJiraConfigOptional } from 'src/integrations/jira'\nimport { commandEcho, confirmOrExit } from 'src/lib/command-echo'\nimport { WORKTREES_DIR_SUFFIX } from 'src/lib/constants'\nimport { formatZxError } from 'src/lib/errors/format-zx-error'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { assertManagementContext } from 'src/lib/git-guard'\nimport { deleteLocalBranch, deleteRemoteBranch, getCurrentWorktrees, getProjectRoot } from 'src/lib/git-utils'\nimport { logger } from 'src/lib/logger'\nimport { pickReleaseBranch } from 'src/lib/prompts/release-picker'\nimport { displayLabel, formatJiraName, formatRcTitle, parseBranchName } from 'src/lib/release-id'\nimport type { ReleaseId } from 'src/lib/release-id'\nimport {\n detectReleaseType,\n formatBranchPickerItems,\n getJiraDescriptions,\n resolveReleaseBranch,\n} from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\nimport { removeWorktrees } from 'src/lib/worktrees'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { RequiredConfirmedOptionArg } from 'src/types'\n\ninterface GhReleaseDeliverArgs extends RequiredConfirmedOptionArg {\n version: string\n}\n\ntype PRState = 'OPEN' | 'MERGED' | 'CLOSED'\n\ninterface PRStatus {\n number: number\n state: PRState\n title: string\n}\n\n/**\n * Wrap a delivery step so its failure logs structured zx fields and surfaces\n * an `OperationError` whose message names the actual step that failed \u2014\n * instead of the previous blanket \"merging release branch into dev\" message.\n */\nconst runStep = async <T>(operation: string, remediation: string, fn: () => Promise<T>): Promise<T> => {\n try {\n return await fn()\n } catch (error) {\n logger.error({ err: formatZxError(error) }, `\u274C Failed to ${operation}`)\n throw new OperationError(error, { operation, remediation })\n }\n}\n\n/**\n * Fetch the (most-recent) PR for the given head branch, across all states, so\n * we can resume a partially-completed delivery: a PR merged on a prior attempt\n * still appears here as `state: 'MERGED'`, letting the caller skip the merge.\n */\nconst fetchPRByHead = async (head: string): Promise<PRStatus | null> => {\n const result = await $`gh pr list --head ${head} --state all --json number,state,title --limit 1`\n const prs = JSON.parse(result.stdout) as PRStatus[]\n\n return prs[0] ?? null\n}\n\n/**\n * Find a MERGED RC PR (dev \u2192 main) whose title matches the given version, used\n * to detect that a prior delivery run already merged the RC and we should skip\n * the merge step on resume. Title-matched on purpose: an older MERGED RC PR\n * from a different release must not short-circuit this version's flow.\n */\nconst fetchMergedRcPRForVersion = async (id: ReleaseId): Promise<PRStatus | null> => {\n const expectedTitle = formatRcTitle(id)\n const result = await $`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`\n const prs = JSON.parse(result.stdout) as PRStatus[]\n const match = prs.find((pr) => {\n return pr.title === expectedTitle\n })\n\n return match ?? null\n}\n\n/**\n * Find an open dev \u2192 main PR, if any. GitHub allows at most one open PR per\n * head/base pair, so an existing open PR here is the RC PR for this release \u2014\n * even if its title was set by a previous (failed) delivery run. Adopting it\n * is what makes the flow recoverable after a mid-run failure.\n */\nconst fetchOpenDevToMainPR = async (): Promise<PRStatus | null> => {\n const result = await $`gh pr list --head dev --base main --state open --json number,state,title --limit 5`\n const prs = JSON.parse(result.stdout) as PRStatus[]\n\n return prs[0] ?? null\n}\n\ninterface ResolvedTarget {\n selectedReleaseBranch: string\n releasePrTitle: string\n}\n\nconst resolveTargetFromVersion = async (version: string): Promise<ResolvedTarget> => {\n const selectedReleaseBranch = resolveReleaseBranch(version)\n const pr = await fetchPRByHead(selectedReleaseBranch)\n\n if (!pr) {\n logger.error(`\u274C No PR found for branch ${selectedReleaseBranch}.`)\n throw new OperationError(undefined, {\n operation: `deliver release ${selectedReleaseBranch}`,\n remediation: `confirm a PR exists ('gh pr list --head ${selectedReleaseBranch} --state all')`,\n })\n }\n\n return { selectedReleaseBranch, releasePrTitle: pr.title }\n}\n\nconst resolveTargetInteractively = async (): Promise<ResolvedTarget> => {\n const releasePRsInfo = await getReleasePRsWithInfo()\n\n const branches = releasePRsInfo.map((pr) => {\n return pr.branch\n })\n\n const releaseTypes = new Map<string, ReleaseType>(\n releasePRsInfo.map((pr) => {\n return [pr.branch, detectReleaseType(pr.title)]\n }),\n )\n\n commandEcho.setInteractive()\n\n const descriptions = await getJiraDescriptions()\n\n const selectedReleaseBranch = await pickReleaseBranch(\n formatBranchPickerItems({ branches, descriptions, types: releaseTypes }),\n )\n\n const prInfo = releasePRsInfo.find((pr) => {\n return pr.branch === selectedReleaseBranch\n })\n\n if (!prInfo) {\n logger.error(`\u274C Release branch ${selectedReleaseBranch} not found in open PRs.`)\n throw new OperationError(undefined, {\n operation: `deliver release ${selectedReleaseBranch}`,\n remediation: `confirm an open PR exists for ${selectedReleaseBranch} ('gh pr list')`,\n })\n }\n\n return { selectedReleaseBranch, releasePrTitle: prInfo.title }\n}\n\n/**\n * `gh pr merge --delete-branch` also deletes the local branch, which fails if a\n * worktree has it checked out (the actual root cause of the \"Failed to merge\n * release PR\" surface error). Pre-remove any worktree for the release branch\n * so the local delete can succeed.\n */\nconst removeReleaseWorktreeIfPresent = async (releaseBranch: string): Promise<void> => {\n const worktreeBranches = await getCurrentWorktrees('release')\n\n if (!worktreeBranches.includes(releaseBranch)) return\n\n const projectRoot = await getProjectRoot()\n const worktreeDir = `${projectRoot}${WORKTREES_DIR_SUFFIX}`\n\n const removed = await removeWorktrees({ branches: [releaseBranch], worktreeDir })\n\n if (removed.length === 0) {\n throw new OperationError(undefined, {\n operation: `remove worktree for ${releaseBranch} before merge`,\n remediation: `run manually: git worktree remove ${worktreeDir}/${releaseBranch} (use --force if uncommitted changes)`,\n })\n }\n}\n\ninterface MergeReleasePRArgs {\n selectedReleaseBranch: string\n releaseType: ReleaseType\n}\n\nconst mergeReleasePR = async (args: MergeReleasePRArgs): Promise<void> => {\n const { selectedReleaseBranch, releaseType } = args\n\n const mergeTarget = releaseType === 'hotfix' ? 'main' : 'dev'\n\n const releasePr = await fetchPRByHead(selectedReleaseBranch)\n\n if (!releasePr) {\n throw new OperationError(undefined, {\n operation: `look up release PR for ${selectedReleaseBranch}`,\n remediation: `verify the PR exists in GitHub`,\n })\n }\n\n if (releasePr.state === 'MERGED') {\n logger.info(`\u2713 Release PR ${selectedReleaseBranch} already merged \u2014 skipping`)\n\n return\n }\n\n if (releasePr.state === 'CLOSED') {\n throw new OperationError(undefined, {\n operation: `merge release PR ${selectedReleaseBranch} into ${mergeTarget}`,\n remediation: `the PR is closed without merge; reopen it or create a new release`,\n })\n }\n\n await runStep(\n `merge release PR ${selectedReleaseBranch} into ${mergeTarget}`,\n `check 'gh pr view ${selectedReleaseBranch}' for mergeability and required reviews`,\n async () => {\n await $`gh pr merge ${selectedReleaseBranch} --squash --admin --delete-branch`\n },\n )\n}\n\nconst resolveRcPRNumber = async (id: ReleaseId): Promise<number> => {\n const selectedLabel = displayLabel(id)\n const expectedTitle = formatRcTitle(id)\n const existingOpen = await fetchOpenDevToMainPR()\n\n // Adopt any existing open dev\u2192main PR. GitHub permits only one open PR per\n // head/base pair, so a stale open RC PR (left behind by a prior failed run\n // \u2014 the single most common cause of \"Error merging release branch into\n // dev\") blocks `gh pr create`. Retitle it instead of fighting it.\n if (existingOpen) {\n const rcNumber = existingOpen.number\n\n if (existingOpen.title !== expectedTitle) {\n logger.info(\n `Adopting open dev \u2192 main PR #${rcNumber} (\"${existingOpen.title}\") and retitling for ${selectedLabel}`,\n )\n await runStep(\n `retitle dev \u2192 main PR #${rcNumber} to \"${expectedTitle}\"`,\n `update manually: gh pr edit ${rcNumber} --title \"${expectedTitle}\"`,\n async () => {\n await $`gh pr edit ${rcNumber} --title ${expectedTitle}`\n },\n )\n }\n\n return rcNumber\n }\n\n await runStep(\n `create RC PR (dev \u2192 main) for ${selectedLabel}`,\n `run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)`,\n async () => {\n await $`gh pr create --base main --head dev --title ${expectedTitle} --body \"\"`\n },\n )\n\n const created = await fetchOpenDevToMainPR()\n\n if (!created) {\n throw new OperationError(undefined, {\n operation: `look up RC PR for ${selectedLabel}`,\n remediation: `verify the RC PR was created ('gh pr list --head dev --base main')`,\n })\n }\n\n return created.number\n}\n\nconst ensureRcPRMerged = async (id: ReleaseId): Promise<void> => {\n const selectedLabel = displayLabel(id)\n const alreadyMerged = await fetchMergedRcPRForVersion(id)\n\n if (alreadyMerged) {\n logger.info(`\u2713 RC PR for ${selectedLabel} already merged into main \u2014 skipping`)\n\n return\n }\n\n const rcNumber = await resolveRcPRNumber(id)\n\n await runStep(\n `merge RC PR #${rcNumber} (dev \u2192 main) for ${selectedLabel}`,\n `check 'gh pr view ${rcNumber}' for mergeability and required reviews`,\n async () => {\n await $`gh pr merge ${rcNumber} --squash --admin`\n },\n )\n}\n\nconst dispatchDeployWorkflow = async (): Promise<void> => {\n $.quiet = false\n\n await runStep(\n `dispatch deploy-all workflow on main`,\n `check 'gh workflow list' and that you have permission to dispatch deploy-all.yml`,\n async () => {\n await $`gh workflow run deploy-all.yml --ref main -f environment=prod`\n },\n )\n\n $.quiet = true\n}\n\nconst syncMainIntoDev = async (): Promise<void> => {\n await runStep(\n `sync main back into dev`,\n `run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`,\n async () => {\n await $`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`\n },\n )\n}\n\n/**\n * Best-effort cleanup of the delivered release branch, locally and on `origin`.\n *\n * Idempotent backstop to `gh pr merge --delete-branch` (in `mergeReleasePR`):\n * that flag is skipped when the release PR was already merged on a prior\n * attempt, so an idempotent re-run would otherwise leave the branch behind.\n * Each delete is isolated \u2014 a failure (e.g. the branch checked out in a stray\n * worktree, or a remote hiccup) logs a warning naming the branch and never\n * aborts delivery, since the irreversible merge and deploy already happened.\n */\nconst removeDeliveredReleaseBranch = async (branch: string): Promise<void> => {\n try {\n await deleteLocalBranch(branch)\n } catch (error) {\n logger.warn({ err: formatZxError(error) }, `Failed to delete local branch ${branch} (non-blocking)`)\n }\n\n try {\n await deleteRemoteBranch(branch)\n } catch (error) {\n logger.warn({ err: formatZxError(error) }, `Failed to delete remote branch ${branch} (non-blocking)`)\n }\n}\n\nconst deliverJiraReleaseSafely = async (id: ReleaseId): Promise<void> => {\n const jiraConfig = await loadJiraConfigOptional()\n\n if (!jiraConfig) {\n logger.info('\uD83D\uDD14 Jira is not configured, skipping Jira release delivery')\n\n return\n }\n\n try {\n // Jira fix version name: `v1.2.3` | `<name>` \u2014 must match create-time formatJiraName.\n const versionName = formatJiraName(id)\n\n await deliverJiraRelease({ versionName }, jiraConfig)\n } catch (error) {\n logger.error({ err: formatZxError(error) }, 'Failed to deliver Jira release (non-blocking)')\n }\n}\n\n/**\n * Deliver a release branch to production. Each network/git step is run inside\n * `runStep` so the surfaced error names the failing operation and includes the\n * subprocess stderr. PR-merge steps are idempotent: if the release PR or RC PR\n * is already MERGED, the step is skipped, so re-running after a mid-flight\n * failure picks up where it stopped.\n */\nexport const ghReleaseDeliver = async (args: GhReleaseDeliverArgs) => {\n const { version, confirmedCommand } = args\n\n // Branch-agnostic (operates on release/RC PRs via gh and self-switches), so\n // only the worktree + clean-tree legs apply.\n await assertManagementContext({ operation: 'deliver release' })\n\n const { selectedReleaseBranch, releasePrTitle } = version\n ? await resolveTargetFromVersion(version)\n : await resolveTargetInteractively()\n\n // selectedReleaseBranch is always a release branch (operator ref strictly\n // parsed, or picked from discovery-filtered choices) so this cannot be null.\n const releaseId = parseBranchName(selectedReleaseBranch)\n\n if (!releaseId) {\n throw new OperationError(undefined, {\n operation: `deliver release ${selectedReleaseBranch}`,\n remediation: 'pass a version (e.g. \"1.2.5\") or a release name (e.g. \"checkout-redesign\")',\n })\n }\n\n const selectedVersion = displayLabel(releaseId)\n\n commandEcho.addOption('--version', selectedVersion)\n logger.info(`Delivering ${releaseId.kind === 'name' ? 'named release' : 'version'} ${selectedReleaseBranch}`)\n\n const releaseType: ReleaseType = detectReleaseType(releasePrTitle)\n\n await confirmOrExit(\n confirmedCommand,\n `Are you sure you want to deliver version ${selectedReleaseBranch} to production?`,\n )\n\n // Track --yes flag if confirmation was interactive (user confirmed)\n commandEcho.addOption('--yes', true)\n\n $.quiet = true\n\n await removeReleaseWorktreeIfPresent(selectedReleaseBranch)\n await mergeReleasePR({ selectedReleaseBranch, releaseType })\n\n if (releaseType !== 'hotfix') {\n await ensureRcPRMerged(releaseId)\n }\n\n await dispatchDeployWorkflow()\n await syncMainIntoDev()\n await removeDeliveredReleaseBranch(selectedReleaseBranch)\n\n $.quiet = false\n\n await deliverJiraReleaseSafely(releaseId)\n\n logger.info(`Successfully delivered ${selectedReleaseBranch} to production!`)\n\n commandEcho.print()\n\n const structuredContent = {\n releaseBranch: selectedReleaseBranch,\n version: selectedVersion,\n type: releaseType,\n success: true,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const ghReleaseDeliverMcpTool = defineMcpTool({\n name: 'gh-release-deliver',\n description:\n 'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. \"version\" is required when invoked via MCP (the picker is unreachable without a TTY).',\n inputSchema: {\n version: z\n .string()\n .describe(\n 'Accepts a release version (e.g. \"1.2.5\") OR a release name (e.g. \"checkout-redesign\") to deliver to production. Required for MCP calls.',\n ),\n },\n outputSchema: {\n releaseBranch: z.string().describe('The release branch that was delivered'),\n version: z.string().describe('The version that was delivered'),\n type: z.enum(['regular', 'hotfix']).describe('Release type'),\n success: z.boolean().describe('Whether the delivery was successful'),\n },\n handler: ghReleaseDeliver,\n})\n", "const STDERR_EXCERPT_MAX_BYTES = 500\nconst STDOUT_EXCERPT_MAX_BYTES = 200\n\nexport interface ZxErrorFields {\n exitCode?: number | null\n stderr?: string\n stdout?: string\n message?: string\n name?: string\n}\n\nconst readTrimmedString = (value: unknown, max: number): string | undefined => {\n if (typeof value !== 'string' || value.length === 0) return undefined\n\n return value.slice(-max).trim()\n}\n\n/**\n * Extract loggable fields from an error for `logger.error({ err: formatZxError(e) }, ...)`.\n *\n * pino's default `err` serializer handles `Error` subclasses but renders zx's\n * `ProcessOutput` as `{}` because its informative fields (`stderr`, `stdout`,\n * `exitCode`) are non-enumerable / on the prototype. This helper duck-types\n * those fields so subprocess failures surface in logs instead of vanishing.\n */\nexport const formatZxError = (error: unknown): ZxErrorFields => {\n if (error === null || typeof error !== 'object') {\n return { message: String(error) }\n }\n\n const rec = error as Record<string, unknown>\n const fields: ZxErrorFields = {}\n\n if (error instanceof Error) {\n fields.name = error.name\n fields.message = error.message\n } else if (typeof rec.message === 'string') {\n fields.message = rec.message\n }\n\n const exitCode = rec.exitCode\n\n if (typeof exitCode === 'number' || exitCode === null) fields.exitCode = exitCode\n\n const stderr = readTrimmedString(rec.stderr, STDERR_EXCERPT_MAX_BYTES)\n\n if (stderr) fields.stderr = stderr\n\n const stdout = readTrimmedString(rec.stdout, STDOUT_EXCERPT_MAX_BYTES)\n\n if (stdout) fields.stdout = stdout\n\n return fields\n}\n", "import { $ } from 'zx'\n\nimport { closeCmuxWorkspaceByCwd } from 'src/integrations/cmux'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { logger } from 'src/lib/logger'\n\ninterface RemoveWorktreesArgs {\n branches: string[]\n worktreeDir: string\n pruneFolder?: boolean\n}\n\n/**\n * Close any cmux workspace for each branch and run `git worktree remove`,\n * returning the branches that were removed cleanly. Failures are logged but\n * never thrown, so a single bad worktree doesn't poison a batch removal.\n *\n * When `pruneFolder` is true and every branch was removed, also run\n * `git worktree prune` to clear stale worktree metadata. The `<repo>-worktrees`\n * container directory and its `release/`/`feature/` subfolders are deliberately\n * left in place so the per-repo worktree scaffold persists even when empty.\n */\nexport const removeWorktrees = async (args: RemoveWorktreesArgs): Promise<string[]> => {\n const { branches, worktreeDir, pruneFolder = false } = args\n\n const results = await Promise.allSettled(\n branches.map(async (branch) => {\n const worktreePath = `${worktreeDir}/${branch}`\n\n // Close the cmux workspace by its cwd (the worktree path still exists here \u2014\n // close runs before `git worktree remove`). Anchors are excluded, so a group\n // header is never closed.\n await closeCmuxWorkspaceByCwd(worktreePath)\n\n await $`git worktree remove ${worktreePath}`\n\n return branch\n }),\n )\n\n const removed: string[] = []\n\n for (const [index, result] of results.entries()) {\n if (result.status === 'fulfilled') {\n removed.push(result.value)\n } else {\n const branch = branches[index]\n const err = new OperationError(result.reason, {\n operation: `remove worktree for ${branch}`,\n remediation: \"check 'git worktree list' for the path; uncommitted changes block removal\",\n })\n\n logger.error({ error: result.reason, msg: err.message })\n }\n }\n\n // `git worktree remove` deletes only the leaf worktree. We intentionally leave\n // the `<repo>-worktrees` container and its `release/`/`feature/` group folders\n // in place so the worktree scaffold survives an empty state (it is recreated\n // lazily by `worktrees-add` via `mkdir -p` regardless).\n if (pruneFolder && removed.length === branches.length) {\n await $`git worktree prune`\n }\n\n return removed\n}\n", "import confirm from '@inquirer/confirm'\nimport { z } from 'zod'\nimport { $ } from 'zx'\n\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { commandEcho } from 'src/lib/command-echo'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { logger } from 'src/lib/logger'\nimport { pickEnv } from 'src/lib/prompts/env-picker'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { pickReleaseBranch } from 'src/lib/prompts/release-picker'\nimport {\n detectReleaseType,\n formatBranchPickerItems,\n getJiraDescriptions,\n releaseLabelFromBranch,\n resolveReleaseBranch,\n} from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\nimport { readWorkflowEnvOptions } from 'src/lib/workflow-envs'\nimport { assertDeployable, deployableEnvs } from 'src/lib/workflow-envs/protected-envs'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/** The workflow this command dispatches. Its own `environment` choices are the env list. */\nconst DEPLOY_ALL_WORKFLOW = 'deploy-all.yml'\n\ninterface GhReleaseDeployAllArgs {\n version: string\n env: string\n skipTerraform?: boolean\n confirmedCommand?: boolean\n}\n\ninterface ConfirmDeployArgs {\n confirmedCommand?: boolean\n branch: string\n env: string\n}\n\n/**\n * Gate the workflow dispatch behind an interactive confirmation. Returns true to\n * proceed; `confirmedCommand` (CLI `--yes`) skips the prompt. Mirrors the\n * confirm+commandEcho pattern used by worktrees-remove.\n */\nconst confirmDeploy = async (args: ConfirmDeployArgs): Promise<boolean> => {\n const { confirmedCommand, branch, env } = args\n\n if (confirmedCommand) return true\n\n commandEcho.setInteractive()\n\n const answer = await withEscape((context) => {\n return confirm({ message: `Deploy ${branch} \u2192 ${env}?`, default: false }, context)\n })\n\n if (answer) commandEcho.addOption('--yes', true)\n\n return answer\n}\n\n/**\n * Deploy a release branch to an environment\n */\nexport const ghReleaseDeployAll = async (args: GhReleaseDeployAllArgs) => {\n const { version, env, skipTerraform, confirmedCommand } = args\n\n let selectedReleaseBranch = '' // \"release/v1.8.0\" | \"release/checkout-redesign\" | \"dev\"\n\n if (version) {\n selectedReleaseBranch = version === 'dev' ? 'dev' : resolveReleaseBranch(version)\n } else {\n commandEcho.setInteractive()\n\n const releasePRsInfo = await getReleasePRsWithInfo()\n\n const branches = releasePRsInfo.map((pr) => {\n return pr.branch\n })\n\n const releaseTypes = new Map<string, ReleaseType>(\n releasePRsInfo.map((pr) => {\n return [pr.branch, detectReleaseType(pr.title)]\n }),\n )\n\n const descriptions = await getJiraDescriptions()\n\n selectedReleaseBranch = await pickReleaseBranch([\n { value: 'dev', label: 'dev' },\n ...formatBranchPickerItems({ branches, descriptions, types: releaseTypes }),\n ])\n }\n\n const selectedVersion = releaseLabelFromBranch(selectedReleaseBranch)\n\n commandEcho.addOption('--version', selectedVersion)\n\n // The workflow's own `environment` choices, minus the ones reserved for the delivery flow. This is\n // what `infra-kit.json \u2192 environments` used to hand-maintain in five copies: the same list, minus\n // `prod`, written out by hand and drifted (travelist's copy offered `roman` and `eliran`, whom its own\n // deploy-all.yml does not accept). Derived here from the two things that actually decide it \u2014 what the\n // workflow declares, and what policy forbids.\n const envOptions = deployableEnvs(await readWorkflowEnvOptions(DEPLOY_ALL_WORKFLOW))\n\n let selectedEnv = ''\n\n if (env) {\n selectedEnv = env\n } else {\n commandEcho.setInteractive()\n\n selectedEnv = await pickEnv(envOptions, 'launch deploy-all workflow')\n }\n\n commandEcho.addOption('--env', selectedEnv)\n\n // The ONLY client-side veto: `prod` is delivered, never deployed ad-hoc. GitHub cannot enforce this \u2014\n // from its side `-f environment=prod` is a valid choice \u2014 so it has to be ours. Note what is NOT\n // vetoed: an env absent from the local YAML still dispatches, because this read is of the working tree\n // while the run targets `--ref <branch>`, and GitHub validates the choice itself.\n assertDeployable(selectedEnv, 'launch deploy-all workflow')\n\n const shouldSkipTerraform = skipTerraform ?? false\n\n if (shouldSkipTerraform) {\n commandEcho.addOption('--skip-terraform', true)\n }\n\n if (!(await confirmDeploy({ confirmedCommand, branch: selectedReleaseBranch, env: selectedEnv }))) {\n logger.info('Deployment cancelled')\n\n const structuredContent = {\n releaseBranch: selectedReleaseBranch,\n version: selectedVersion,\n environment: selectedEnv,\n skipTerraformDeploy: shouldSkipTerraform,\n success: false,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n }\n\n try {\n $.quiet = true\n\n const skipTerraformFlag = shouldSkipTerraform ? ['-f', 'skip_terraform_deploy=true'] : []\n\n await $`gh workflow run deploy-all.yml --ref ${selectedReleaseBranch} -f environment=${selectedEnv} ${skipTerraformFlag}`\n\n $.quiet = false\n\n logger.info(\n `Successfully launched deploy-all workflow_dispatch for release branch: ${selectedReleaseBranch} and environment: ${selectedEnv}`,\n )\n\n commandEcho.print()\n\n const structuredContent = {\n releaseBranch: selectedReleaseBranch,\n version: selectedVersion,\n environment: selectedEnv,\n skipTerraformDeploy: shouldSkipTerraform,\n success: true,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n } catch (error: unknown) {\n logger.error({ error }, '\u274C Error launching workflow')\n throw new OperationError(error, {\n operation: 'launch deploy-all workflow',\n remediation: \"check 'gh workflow list' and that deploy-all.yml exists on the target ref\",\n })\n }\n}\n\n// MCP Tool Registration\nexport const ghReleaseDeployAllMcpTool = defineMcpTool({\n name: 'gh-release-deploy-all',\n description:\n 'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version=\"dev\" to deploy from the dev branch instead of a release branch. Both \"version\" and \"env\" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',\n requiresHumanConfirm: true,\n inputSchema: {\n version: z\n .string()\n .describe(\n 'Accepts a release version (e.g. \"1.2.5\") OR a release name (e.g. \"checkout-redesign\") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass \"dev\" to deploy from the dev branch instead. Required for MCP calls.',\n ),\n env: z\n .string()\n .describe(\n 'Target environment name \u2014 must match an env configured for the project (e.g. \"dev\", \"renana\", \"oriana\"). Required for MCP calls.',\n ),\n skipTerraform: z.boolean().optional().describe('Skip the terraform deployment stage.'),\n confirm: z\n .boolean()\n .optional()\n .describe('Set true to execute; omit for a dry-run gate that echoes the resolved action.'),\n },\n outputSchema: {\n releaseBranch: z.string().describe('The release branch that was deployed'),\n version: z.string().describe('The version that was deployed'),\n environment: z.string().describe('The environment deployed to'),\n skipTerraformDeploy: z.boolean().describe('Whether terraform deployment was skipped'),\n success: z.boolean().describe('Whether the deployment was successful'),\n },\n handler: ghReleaseDeployAll,\n})\n", "import select from '@inquirer/select'\n\nimport { OperationError } from 'src/lib/errors/operation-error'\n\nimport { withEscape } from './escapable-context'\n\n/**\n * Ask which environment to deploy to, given the options the target workflow declares.\n *\n * `options` may legitimately be empty: the repo may have no such workflow (bridge has none), the\n * `environment` input may be free-text (`type: string`) rather than a `choice`, or the YAML may not\n * parse. None of those is a broken repo, so none of them may kill the command \u2014 but there is also\n * nothing to put in a picker, so this asks for `--env` by name instead of showing an empty menu.\n *\n * Note what this does NOT do: it never rejects an env for being absent from `options`. The list is read\n * from the WORKING TREE while the dispatch targets `--ref <branch>`, so the two can legitimately differ,\n * and GitHub validates the `choice` server-side regardless. Vetoing on a local read of a remote fact is\n * what made `stage` and `prod` undeployable under the old `environments` array.\n *\n * @example\n * await pickEnv(['dev', 'stage'], 'launch deploy-all workflow') // => select prompt\n * await pickEnv([], 'launch deploy-all workflow') // => throws, naming --env\n */\nexport const pickEnv = async (options: string[], operation: string): Promise<string> => {\n if (options.length === 0) {\n throw new OperationError(undefined, {\n operation,\n remediation: 'pass --env <name> explicitly',\n stderrExcerpt: 'the workflow declares no `environment` choices to pick from',\n })\n }\n\n return withEscape((context) => {\n return select(\n {\n message: '\uD83E\uDDEA Select environment',\n choices: options.map((option) => {\n return {\n name: option,\n value: option,\n }\n }),\n },\n context,\n )\n })\n}\n", "import { OperationError } from 'src/lib/errors/operation-error'\n\n/**\n * Environments that must NOT be reachable from the ad-hoc deploy commands.\n *\n * `prod` is not a deploy target \u2014 it is a DELIVERY target. `gh-release-deliver` is the only sanctioned\n * path to it, and it is a whole flow, not a dispatch: squash-merge the release branch to `main`, open\n * and merge the RC PR, dispatch `deploy-all.yml --ref main -f environment=prod` (see\n * `gh-release-deliver.ts`), then release the matching Jira fix version. Letting\n * `gh-release-deploy-all --env prod` dispatch straight from a release branch would skip every one of\n * those steps and ship production from an unmerged ref.\n *\n * `stage` is deliberately NOT here. The old per-repo allowlists excluded it, but nothing delivers to it\n * either \u2014 so it was simply unreachable, which was an oversight rather than a policy. It is an ad-hoc\n * deploy target like any other.\n *\n * This is a POLICY, which is why it lives in code rather than in each repo's config. The workflows\n * themselves legitimately declare `prod` in their `environment` options (the delivery flow needs it);\n * what is forbidden is the CLI's ad-hoc path reaching it. That rule used to be encoded as a\n * hand-maintained `environments` array in five `infra-kit.json` files \u2014 five copies of one rule, which\n * drifted (travelist's listed `roman` and `eliran`, whom its own `deploy-all.yml` does not accept).\n */\nexport const PROTECTED_ENVS = ['prod']\n\n/** Whether an environment is reserved for the delivery flow rather than ad-hoc deploys. */\nexport const isProtectedEnv = (env: string): boolean => {\n return PROTECTED_ENVS.includes(env)\n}\n\n/** Drop the delivery-only environments from a workflow's declared options \u2014 the ad-hoc deploy picker. */\nexport const deployableEnvs = (options: string[]): string[] => {\n return options.filter((env) => {\n return !isProtectedEnv(env)\n })\n}\n\n/**\n * Refuse a delivery-only environment, naming the flow that DOES own it.\n *\n * The one client-side veto worth keeping. Everything else about the old `environments` check was a\n * stale local copy of a list GitHub already enforces \u2014 but GitHub cannot enforce this, because from its\n * side `-f environment=prod` is a perfectly valid choice. The rule being protected is ours.\n *\n * @example\n * assertDeployable('dev', 'launch deploy-all workflow') // ok\n * assertDeployable('prod', 'launch deploy-all workflow') // throws \u2014 use `infra-kit release deliver`\n */\nexport const assertDeployable = (env: string, operation: string): void => {\n if (!isProtectedEnv(env)) return\n\n throw new OperationError(undefined, {\n operation,\n remediation:\n `use \\`infra-kit release deliver\\` \u2014 it merges the release to main, opens the RC PR, ` +\n `deploys from main, and releases the Jira version`,\n stderrExcerpt: `\"${env}\" is delivered, not deployed ad-hoc`,\n })\n}\n", "import checkbox from '@inquirer/checkbox'\nimport confirm from '@inquirer/confirm'\nimport fs from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport yaml from 'yaml'\nimport { z } from 'zod'\nimport { $ } from 'zx'\n\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { commandEcho } from 'src/lib/command-echo'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { getProjectRoot } from 'src/lib/git-utils'\nimport { logger } from 'src/lib/logger'\nimport { pickEnv } from 'src/lib/prompts/env-picker'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { pickReleaseBranch } from 'src/lib/prompts/release-picker'\nimport {\n detectReleaseType,\n formatBranchPickerItems,\n getJiraDescriptions,\n releaseLabelFromBranch,\n resolveReleaseBranch,\n} from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\nimport { readWorkflowEnvOptions } from 'src/lib/workflow-envs'\nimport { assertDeployable, deployableEnvs } from 'src/lib/workflow-envs/protected-envs'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/** The workflow this command dispatches. Its own inputs are both the env list and the service list. */\nconst DEPLOY_SELECTED_WORKFLOW = 'deploy-selected-services.yml'\n\n/** A `workflow_dispatch` boolean that is a flag, not a service \u2014 the one exclusion from the service list. */\nconst SKIP_TERRAFORM_INPUT = 'skip_terraform_deploy'\n\ninterface GhReleaseDeploySelectedArgs {\n version: string\n env: string\n services: string[]\n skipTerraform?: boolean\n confirmedCommand?: boolean\n}\n\ninterface ConfirmDeployArgs {\n confirmedCommand?: boolean\n branch: string\n env: string\n}\n\n/**\n * Gate the workflow dispatch behind an interactive confirmation. Returns true to\n * proceed; `confirmedCommand` (CLI `--yes`) skips the prompt. Mirrors the\n * confirm+commandEcho pattern used by worktrees-remove.\n */\nconst confirmDeploy = async (args: ConfirmDeployArgs): Promise<boolean> => {\n const { confirmedCommand, branch, env } = args\n\n if (confirmedCommand) return true\n\n commandEcho.setInteractive()\n\n const answer = await withEscape((context) => {\n return confirm({ message: `Deploy ${branch} \u2192 ${env}?`, default: false }, context)\n })\n\n if (answer) commandEcho.addOption('--yes', true)\n\n return answer\n}\n\n/**\n * Deploy selected services from a release branch to an environment\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity\nexport const ghReleaseDeploySelected = async (args: GhReleaseDeploySelectedArgs) => {\n const { version, env, services, skipTerraform, confirmedCommand } = args\n\n let selectedReleaseBranch = ''\n\n if (version) {\n selectedReleaseBranch = version === 'dev' ? 'dev' : resolveReleaseBranch(version)\n } else {\n commandEcho.setInteractive()\n\n const releasePRsInfo = await getReleasePRsWithInfo()\n\n const branches = releasePRsInfo.map((pr) => {\n return pr.branch\n })\n\n const releaseTypes = new Map<string, ReleaseType>(\n releasePRsInfo.map((pr) => {\n return [pr.branch, detectReleaseType(pr.title)]\n }),\n )\n\n const descriptions = await getJiraDescriptions()\n\n selectedReleaseBranch = await pickReleaseBranch([\n { value: 'dev', label: 'dev' },\n ...formatBranchPickerItems({ branches, descriptions, types: releaseTypes }),\n ])\n }\n\n const selectedVersion = releaseLabelFromBranch(selectedReleaseBranch)\n\n commandEcho.addOption('--version', selectedVersion)\n\n // This workflow's own `environment` choices, minus the delivery-only ones. Read PER WORKFLOW, not once\n // per repo: travelist's `deploy-all.yml` and `deploy-selected-services.yml` genuinely declare different\n // environments, so a single repo-level list could only ever be wrong for one of them \u2014 as the old\n // `environments` array was.\n const envOptions = deployableEnvs(await readWorkflowEnvOptions(DEPLOY_SELECTED_WORKFLOW))\n\n let selectedEnv = ''\n\n if (env) {\n selectedEnv = env\n } else {\n commandEcho.setInteractive()\n\n selectedEnv = await pickEnv(envOptions, 'launch deploy-selected workflow')\n }\n\n commandEcho.addOption('--env', selectedEnv)\n\n // `prod` is delivered, never deployed ad-hoc \u2014 see gh-release-deliver. The one rule GitHub cannot\n // enforce for us.\n assertDeployable(selectedEnv, 'launch deploy-selected workflow')\n\n // Available services, from the same workflow's boolean inputs. Unlike the env list this one is still\n // enforced below \u2014 a `choice` value is validated by GitHub, but an undeclared `-f <service>=true` is\n // NOT known to be rejected, and a typo that GitHub shrugs at would dispatch a run that deploys\n // nothing and reports success. Until that is proven otherwise, the local check stays.\n const availableServices = await parseServicesFromWorkflow()\n\n // Genuinely fatal for THIS command \u2014 there is nothing to pick from. (The failure it replaces was an\n // uncaught ENOENT from `fs.readFile`, which is how a repo with no such workflow, like bridge, used to\n // die here with a raw stack trace instead of a sentence.)\n if (availableServices.length === 0) {\n throw new OperationError(undefined, {\n operation: 'launch deploy-selected workflow',\n remediation: `declare boolean service inputs in .github/workflows/${DEPLOY_SELECTED_WORKFLOW}`,\n stderrExcerpt: `no services found in .github/workflows/${DEPLOY_SELECTED_WORKFLOW}`,\n })\n }\n\n let selectedServices: string[] = []\n\n if (services && services.length > 0) {\n selectedServices = services\n } else {\n commandEcho.setInteractive()\n\n selectedServices = await withEscape((context) => {\n return checkbox(\n {\n message: '\uD83D\uDE80 Select services to deploy (space to select, enter to confirm)',\n choices: availableServices.map((svc) => {\n return {\n name: svc,\n value: svc,\n }\n }),\n },\n context,\n )\n })\n }\n\n commandEcho.addOption('--services', selectedServices)\n\n if (selectedServices.length === 0) {\n throw new OperationError(undefined, {\n operation: 'launch deploy-selected workflow',\n remediation: `pass at least one service from: ${availableServices.join(', ')}`,\n stderrExcerpt: 'no services selected',\n })\n }\n\n // Validate all selected services\n const invalidServices = selectedServices.filter((svc) => {\n return !availableServices.includes(svc)\n })\n\n if (invalidServices.length > 0) {\n throw new OperationError(undefined, {\n operation: 'launch deploy-selected workflow',\n remediation: `pass services from: ${availableServices.join(', ')}`,\n stderrExcerpt: `invalid services: ${invalidServices.join(', ')}`,\n })\n }\n\n const shouldSkipTerraform = skipTerraform ?? false\n\n if (shouldSkipTerraform) {\n commandEcho.addOption('--skip-terraform', true)\n }\n\n const buildResult = (success: boolean) => {\n const structuredContent = {\n releaseBranch: selectedReleaseBranch,\n version: selectedVersion,\n environment: selectedEnv,\n services: selectedServices,\n skipTerraformDeploy: shouldSkipTerraform,\n success,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n }\n\n if (!(await confirmDeploy({ confirmedCommand, branch: selectedReleaseBranch, env: selectedEnv }))) {\n logger.info('Deployment cancelled')\n\n return buildResult(false)\n }\n\n try {\n $.quiet = true\n\n // Build the workflow command with boolean flags for each selected service\n const serviceFlags = selectedServices.flatMap((svc) => {\n return ['-f', `${svc}=true`]\n })\n const skipTerraformFlag = shouldSkipTerraform ? ['-f', 'skip_terraform_deploy=true'] : []\n\n await $`gh workflow run deploy-selected-services.yml --ref ${selectedReleaseBranch} -f environment=${selectedEnv} ${serviceFlags} ${skipTerraformFlag}`\n\n $.quiet = false\n\n logger.info(\n `Successfully launched deploy-selected-services workflow_dispatch for release branch: ${selectedReleaseBranch}, environment: ${selectedEnv}, services: ${selectedServices.join(', ')}`,\n )\n\n commandEcho.print()\n\n return buildResult(true)\n } catch (error: unknown) {\n logger.error({ error }, '\u274C Error launching workflow')\n throw new OperationError(error, {\n operation: 'launch deploy-selected workflow',\n remediation: \"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref\",\n })\n }\n}\n\n/**\n * The services this workflow can deploy: its `workflow_dispatch` boolean inputs, minus the flags that\n * are not services.\n *\n * Returns `[]` rather than throwing when the workflow is missing or unreadable \u2014 the caller turns that\n * into a sentence. Previously an absent file (bridge has no `deploy-selected-services.yml`) escaped as\n * a raw `ENOENT` from `fs.readFile`, and a workflow with no `workflow_dispatch` as a `TypeError` on\n * `parsed.on.workflow_dispatch`.\n *\n * @example\n * await parseServicesFromWorkflow() // => ['client-be', 'client-fe']\n * // no such workflow => []\n */\nconst parseServicesFromWorkflow = async (): Promise<string[]> => {\n const projectRoot = await getProjectRoot()\n\n const workflowPath = resolve(projectRoot, '.github/workflows', DEPLOY_SELECTED_WORKFLOW)\n\n let parsed: unknown\n\n try {\n parsed = yaml.parse(await fs.readFile(workflowPath, 'utf-8'))\n } catch {\n return []\n }\n\n const on = (parsed as { on?: unknown } | null)?.on\n const inputs = (on as { workflow_dispatch?: { inputs?: unknown } } | undefined)?.workflow_dispatch?.inputs\n\n if (typeof inputs !== 'object' || inputs === null) return []\n\n return Object.entries(inputs)\n .filter(([key, value]) => {\n return (value as { type?: string } | null)?.type === 'boolean' && key !== SKIP_TERRAFORM_INPUT\n })\n .map(([key]) => {\n return key\n })\n}\n\n// MCP Tool Registration\nexport const ghReleaseDeploySelectedMcpTool = defineMcpTool({\n name: 'gh-release-deploy-selected',\n requiresHumanConfirm: true,\n description:\n 'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. \"version\", \"env\", and \"services\" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',\n inputSchema: {\n version: z\n .string()\n .describe(\n 'Accepts a release version (e.g. \"1.2.5\") OR a release name (e.g. \"checkout-redesign\") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass \"dev\" to deploy from the dev branch instead. Required for MCP calls.',\n ),\n env: z\n .string()\n .describe(\n 'Target environment name \u2014 must match an env configured for the project (e.g. \"dev\", \"renana\", \"oriana\"). Required for MCP calls.',\n ),\n services: z\n .array(z.string())\n .describe(\n 'Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. \"client-be\", \"client-fe\"). Required for MCP calls.',\n ),\n skipTerraform: z.boolean().optional().describe('Skip the terraform deployment stage.'),\n confirm: z\n .boolean()\n .optional()\n .describe('Set true to execute; omit for a dry-run gate that echoes the resolved action.'),\n },\n outputSchema: {\n releaseBranch: z.string().describe('The release branch that was deployed'),\n version: z.string().describe('The version that was deployed'),\n environment: z.string().describe('The environment deployed to'),\n services: z.array(z.string()).describe('The services that were deployed'),\n skipTerraformDeploy: z.boolean().describe('Whether terraform deployment was skipped'),\n success: z.boolean().describe('Whether the deployment was successful'),\n },\n handler: ghReleaseDeploySelected,\n})\n", "import { z } from 'zod'\n\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { logger } from 'src/lib/logger'\nimport { displayLabel, formatJiraName, parseBranchName } from 'src/lib/release-id'\nimport { detectReleaseType, formatVersionLabel, getJiraDescriptions } from 'src/lib/release-utils'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/**\n * List all open release branches\n */\nexport const ghReleaseList = async () => {\n const releasePRs = await getReleasePRsWithInfo()\n\n // Skip branches that do not parse as release ids (lenient discovery source).\n const releases = releasePRs.flatMap((pr) => {\n const id = parseBranchName(pr.branch)\n\n if (!id) return []\n\n return [\n {\n // Human display label: `1.2.3` | `<name>`.\n version: displayLabel(id),\n // Jira-descriptions map is keyed by the Jira version NAME (`v1.2.3` | `<name>`).\n jiraKey: formatJiraName(id),\n type: detectReleaseType(pr.title),\n },\n ]\n })\n\n const jiraDescriptions = await getJiraDescriptions()\n\n const maxVersionLength = Math.max(\n ...releases.map((r) => {\n return r.version.length\n }),\n )\n\n const formattedLines = releases.map((release) => {\n const label = formatVersionLabel(release.version, release.type, maxVersionLength)\n const description = jiraDescriptions.get(release.jiraKey)\n\n if (description) {\n return `${label} ${description}`\n }\n\n return label\n })\n\n logger.info('All release branches: \\n')\n logger.info(`\\n${formattedLines.join('\\n')}\\n`)\n\n const structuredContent = {\n releases: releases.map((release) => {\n return {\n version: release.version,\n type: release.type,\n description: jiraDescriptions.get(release.jiraKey) || null,\n }\n }),\n count: releases.length,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const ghReleaseListMcpTool = defineMcpTool({\n name: 'gh-release-list',\n description:\n 'List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.',\n inputSchema: {},\n outputSchema: {\n releases: z\n .array(\n z.object({\n version: z.string().describe('Release version'),\n type: z.enum(['regular', 'hotfix']).describe('Release type'),\n description: z.string().nullable().describe('Jira version description'),\n }),\n )\n .describe('List of all release branches'),\n count: z.number().describe('Number of release branches'),\n },\n handler: ghReleaseList,\n})\n", "import confirm from '@inquirer/confirm'\nimport input from '@inquirer/input'\nimport select from '@inquirer/select'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport { loadJiraConfig } from 'src/integrations/jira'\nimport { commandEcho, confirmOrExit } from 'src/lib/command-echo'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { assertManagementContext } from 'src/lib/git-guard'\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { InvalidReleaseNameError, displayLabel, validateName } from 'src/lib/release-id'\nimport { createSingleRelease, prepareGitForRelease } from 'src/lib/release-utils'\nimport type { ReleaseCreationResult, ReleaseType } from 'src/lib/release-utils'\nimport {\n NoPriorVersionsError,\n computeNextVersion,\n formatReleaseSpec,\n hasNextToken,\n loadExistingVersions,\n parseVersion,\n resolveReleaseEntries,\n} from 'src/lib/version-utils'\nimport type { ReleaseEntry, ReleaseInput, SemVer } from 'src/lib/version-utils'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { RequiredConfirmedOptionArg } from 'src/types'\n\ninterface ReleaseCreateArgs extends RequiredConfirmedOptionArg {\n releases?: ReleaseInput[]\n}\n\nconst VERSION_PROMPT_HINT = '\"1.2.5\" or \"next\"'\n\nconst trySuggestNext = (known: SemVer[], type: ReleaseType): string | null => {\n try {\n return computeNextVersion(known, type)\n } catch (err) {\n if (err instanceof NoPriorVersionsError) return null\n\n throw err\n }\n}\n\nconst resolveOrExit = (entries: ReleaseInput[], known: SemVer[]): ReleaseEntry[] => {\n try {\n return resolveReleaseEntries(entries, known)\n } catch (err) {\n if (err instanceof NoPriorVersionsError) {\n throw new OperationError(err, {\n operation: 'resolve release version',\n remediation: 'pass an explicit version (e.g. \"1.2.5\") instead of \"next\" when there are no prior versions',\n })\n }\n\n if (err instanceof InvalidReleaseNameError) {\n throw new OperationError(err, {\n operation: 'validate release name',\n remediation:\n 'use a kebab-case name like \"checkout-redesign\" (lowercase, digits, single hyphens, not a reserved word)',\n })\n }\n\n throw err\n }\n}\n\n/** Exported for test only \u2014 the empty-answer fallback below is observable no other way. */\nexport const promptForVersionInput = async (running: SemVer[], type: ReleaseType): Promise<string> => {\n const suggestion = trySuggestNext(running, type)\n const defaultHint = suggestion ? ` [${suggestion}]` : ''\n // The suggestion stays in the MESSAGE and is applied by the empty-answer fallback below \u2014\n // deliberately not inquirer's `default:`, which prefills the editable buffer and would change\n // both what the user sees and what an empty submit returns.\n const versionAnswer = (\n await withEscape((context) => {\n return input({ message: ` Version (e.g. ${VERSION_PROMPT_HINT})${defaultHint}: ` }, context)\n })\n ).trim()\n const versionInput = versionAnswer === '' ? (suggestion ?? '') : versionAnswer\n\n if (versionInput === '') {\n logger.error('No version provided. Exiting...')\n process.exit(1)\n }\n\n return versionInput\n}\n\nconst promptForNameInput = async (): Promise<string> => {\n const name = (\n await withEscape((context) => {\n return input({ message: ' Name (kebab-case, e.g. \"checkout-redesign\"): ' }, context)\n })\n ).trim()\n\n if (name === '') {\n logger.error('No name provided. Exiting...')\n process.exit(1)\n }\n\n try {\n validateName(name)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n\n logger.error(`${reason} Exiting...`)\n process.exit(1)\n }\n\n return name\n}\n\nconst promptForReleasesInteractive = async (ensureKnown: () => Promise<SemVer[]>): Promise<ReleaseEntry[]> => {\n commandEcho.setInteractive()\n\n let baseKnown: SemVer[] | null = null\n const running: SemVer[] = []\n const ensureRunning = async (): Promise<SemVer[]> => {\n if (baseKnown === null) {\n baseKnown = await ensureKnown()\n running.push(...baseKnown)\n }\n\n return running\n }\n\n const entries: ReleaseEntry[] = []\n let addAnother = true\n\n while (addAnother) {\n const ordinal = entries.length + 1\n const kind = await withEscape((context) => {\n return select<'version' | 'name'>(\n {\n message: `Release #${ordinal} \u2014 version or name?`,\n choices: [\n { name: 'version (semver / next)', value: 'version' },\n { name: 'name (free-form)', value: 'name' },\n ],\n default: 'version',\n },\n context,\n )\n })\n\n const type = await withEscape((context) => {\n return select<ReleaseType>(\n {\n message: `Release #${ordinal} \u2014 select type:`,\n choices: [\n { name: 'regular', value: 'regular' },\n { name: 'hotfix', value: 'hotfix' },\n ],\n default: 'regular',\n },\n context,\n )\n })\n\n let resolved: ReleaseEntry\n\n if (kind === 'name') {\n const name = await promptForNameInput()\n\n resolved = resolveOrExit([{ name, type }], [])[0] as ReleaseEntry\n } else {\n // Versions may need prior versions for \"next\"; load lazily.\n const versionInput = await promptForVersionInput(await ensureRunning(), type)\n\n resolved = resolveOrExit([{ version: versionInput, type }], running)[0] as ReleaseEntry\n\n if (resolved.id.kind === 'version') {\n running.push(parseVersion(`v${resolved.id.raw}`))\n }\n }\n\n const description = (\n await withEscape((context) => {\n return input({ message: ' Description (optional, press Enter to skip): ' }, context)\n })\n ).trim()\n\n entries.push({ ...resolved, ...(description !== '' ? { description } : {}) })\n\n addAnother = await withEscape((context) => {\n return confirm({ message: 'Add another release?', default: false }, context)\n })\n }\n\n return entries\n}\n\nconst formatReleaseSummary = (entry: ReleaseEntry): string => {\n const label = entry.id.kind === 'version' ? `v${entry.id.raw}` : entry.id.name\n const parts = [label, entry.type]\n\n if (entry.description) parts.push(entry.description)\n\n return parts.join(' \u00B7 ')\n}\n\nconst echoReleases = (entries: ReleaseEntry[]): void => {\n // Every entry \u2014 versions, \"next\" (resolved to a concrete version), and named\n // releases alike \u2014 echoes through the single --release flag. formatReleaseSpec\n // produces a spec that parseReleaseSpec parses back into the same entry.\n for (const entry of entries) {\n commandEcho.addOption('--release', formatReleaseSpec(entry))\n }\n}\n\ninterface FailedRelease {\n version: string\n error: string\n}\n\nconst collectEntries = async (\n inputReleases: ReleaseInput[] | undefined,\n ensureKnown: () => Promise<SemVer[]>,\n): Promise<ReleaseEntry[]> => {\n if (inputReleases && inputReleases.length > 0) {\n const known = hasNextToken(inputReleases) ? await ensureKnown() : []\n const resolved = resolveOrExit(inputReleases, known)\n\n echoReleases(resolved)\n\n return resolved\n }\n\n const interactive = await promptForReleasesInteractive(ensureKnown)\n\n echoReleases(interactive)\n\n return interactive\n}\n\n/**\n * Reject a batch that mixes regular and hotfix releases.\n *\n * No longer a technical limit: `prepareGitForRelease` runs per entry, so a mixed\n * batch would switch to each release's own base and work. It is kept because the\n * confirmation prompt summarises the batch as one thing \u2014 an operator approving\n * \"these releases\" should not be silently agreeing to cut some off `dev` and\n * others off `main`. Splitting the invocation makes that choice explicit.\n *\n * Exported for unit testing without running the side-effecting handler.\n */\nexport const assertHomogeneousReleaseType = (entries: ReleaseEntry[]): void => {\n const types = new Set(\n entries.map((entry) => {\n return entry.type\n }),\n )\n\n if (types.size > 1) {\n throw new OperationError(undefined, {\n operation: 'create release',\n remediation: 'create regular and hotfix releases in separate invocations',\n stderrExcerpt: 'mixed regular and hotfix releases in one batch are not supported',\n })\n }\n}\n\nconst confirmReleases = async (entries: ReleaseEntry[], confirmedCommand: boolean): Promise<void> => {\n const summary = entries.map(formatReleaseSummary).join('\\n - ')\n\n await confirmOrExit(confirmedCommand, `Create the following ${entries.length} release(s)?\\n - ${summary}\\n`)\n\n commandEcho.addOption('--yes', true)\n}\n\ninterface ExecuteOneArgs {\n entry: ReleaseEntry\n jiraConfig: Awaited<ReturnType<typeof loadJiraConfig>>\n}\n\nconst executeOne = async (\n args: ExecuteOneArgs,\n): Promise<{ result?: ReleaseCreationResult; failure?: FailedRelease }> => {\n const { entry, jiraConfig } = args\n const label = displayLabel(entry.id)\n const prTitleLabel = entry.id.kind === 'version' ? `v${entry.id.raw}` : entry.id.name\n\n try {\n await prepareGitForRelease(entry.type)\n\n const result = await createSingleRelease({\n id: entry.id,\n jiraConfig,\n description: entry.description,\n type: entry.type,\n })\n\n logger.info(`\u2705 Successfully created release: ${prTitleLabel} (${entry.type})`)\n logger.info(`\uD83D\uDD17 GitHub PR: ${result.prUrl}`)\n logger.info(`\uD83D\uDD17 Jira Version: ${result.jiraVersionUrl}\\n`)\n\n return { result }\n } catch (error) {\n const err = new OperationError(error, {\n operation: `create release ${prTitleLabel} (${entry.type})`,\n remediation: 'verify the version or name is unique and the base branch is clean',\n })\n\n logger.error(`\u274C ${err.message}\\n`)\n\n return { failure: { version: label, error: err.message } }\n }\n}\n\nconst logFinalSummary = (total: number, successCount: number, failureCount: number): void => {\n if (successCount === total) {\n logger.info(`\u2705 All ${total} release branch(es) were created successfully.`)\n } else if (successCount > 0) {\n logger.warn(`\u26A0\uFE0F ${successCount} of ${total} release branches were created successfully.`)\n logger.warn(`\u274C ${failureCount} release(s) failed.`)\n } else {\n logger.error(`\u274C All ${total} release branch(es) failed to create.`)\n }\n}\n\n/**\n * Create one or more release branches. Each release carries its own type\n * (regular/hotfix) and optional Jira description. All entries in a single\n * invocation must share the same type \u2014 regular and hotfix releases branch off\n * different bases (dev vs main), so mixed batches are rejected and must be\n * created separately.\n */\nexport const releaseCreate = async (args: ReleaseCreateArgs) => {\n const { releases: inputReleases, confirmedCommand } = args\n\n const jiraConfig = await loadJiraConfig()\n\n let known: SemVer[] | null = null\n const ensureKnown = async (): Promise<SemVer[]> => {\n if (known === null) known = await loadExistingVersions()\n\n return known\n }\n\n const entries = await collectEntries(inputReleases, ensureKnown)\n\n if (entries.length === 0) {\n throw new OperationError(undefined, {\n operation: 'create release',\n remediation: 'pass at least one entry in \"releases\" (e.g. [{ version: \"1.2.5\", type: \"regular\" }])',\n stderrExcerpt: 'no releases provided',\n })\n }\n\n assertHomogeneousReleaseType(entries)\n\n // Branch-agnostic: `prepareGitForRelease` self-switches onto a freshly fetched\n // base branch below, after the confirmation prompt, so only the worktree +\n // clean-tree legs apply.\n await assertManagementContext({ operation: 'create release' })\n\n await confirmReleases(entries, Boolean(confirmedCommand))\n\n const created: ReleaseCreationResult[] = []\n const failed: FailedRelease[] = []\n\n for (const entry of entries) {\n const { result, failure } = await executeOne({ entry, jiraConfig })\n\n if (result) created.push(result)\n if (failure) failed.push(failure)\n }\n\n logFinalSummary(entries.length, created.length, failed.length)\n\n commandEcho.print()\n\n const structuredContent = {\n createdBranches: created.map((r) => {\n return r.branchName\n }),\n successCount: created.length,\n failureCount: failed.length,\n releases: created,\n failedReleases: failed,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const releaseCreateMcpTool = defineMcpTool({\n name: 'release-create',\n requiresHumanConfirm: true,\n description:\n 'Create one or more releases in a single call. Each entry in \"releases\" carries EITHER a \"version\" (semver or the literal token \"next\") OR a \"name\" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token \"next\" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple \"next\" tokens advance sequentially. Named releases never auto-bump and \"next\" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',\n inputSchema: {\n releases: z\n .array(\n z\n .object({\n version: z\n .string()\n .optional()\n .describe(\n 'Version to create (e.g., \"1.2.5\") or the literal token \"next\" for auto-increment. Mutually exclusive with \"name\".',\n ),\n name: z\n .string()\n .optional()\n .describe(\n 'Free-form kebab-case release name (e.g., \"checkout-redesign\"). Mutually exclusive with \"version\". Named releases never auto-bump.',\n ),\n type: z\n .enum(['regular', 'hotfix'])\n .optional()\n .default('regular')\n .describe('Release type: \"regular\" (branches off dev) or \"hotfix\" (branches off main).'),\n description: z.string().optional().describe('Optional description for the Jira version.'),\n })\n .refine(\n (entry) => {\n return (entry.version === undefined) !== (entry.name === undefined)\n },\n {\n message: 'Each release entry must have exactly one of \"version\" or \"name\" (they are mutually exclusive).',\n },\n )\n .transform((entry): ReleaseInput => {\n return entry.name !== undefined\n ? { name: entry.name, type: entry.type, ...(entry.description ? { description: entry.description } : {}) }\n : {\n version: entry.version as string,\n type: entry.type,\n ...(entry.description ? { description: entry.description } : {}),\n }\n }),\n )\n .min(1)\n .describe(\n 'One or more releases to create. Each entry has exactly one of \"version\" or \"name\", plus its own type and optional description.',\n ),\n confirm: z\n .boolean()\n .optional()\n .describe('Set true to execute; omit for a dry-run gate that echoes the resolved action.'),\n },\n outputSchema: {\n createdBranches: z.array(z.string()).describe('List of created release branch names'),\n successCount: z.number().describe('Number of releases created successfully'),\n failureCount: z.number().describe('Number of releases that failed'),\n releases: z\n .array(\n z.object({\n version: z.string().describe('Version number'),\n type: z.enum(['regular', 'hotfix']).describe('Release type'),\n branchName: z.string().describe('Release branch name'),\n prUrl: z.string().describe('GitHub PR URL'),\n jiraVersionUrl: z.string().describe('Jira version URL'),\n }),\n )\n .describe('Detailed information for each created release with URLs'),\n failedReleases: z\n .array(\n z.object({\n version: z.string().describe('Version number that failed'),\n error: z.string().describe('Error message'),\n }),\n )\n .describe('List of releases that failed with error messages'),\n },\n handler: releaseCreate,\n})\n", "import { $ } from 'zx'\n\nimport { getProjectVersions, loadJiraConfigOptional } from 'src/integrations/jira'\nimport { logger } from 'src/lib/logger'\nimport { parseBranchName } from 'src/lib/release-id'\n\nimport { collectKnownVersions } from './next-version'\nimport type { SemVer } from './next-version'\n\n/**\n * Extract version-branch tokens from raw `git ls-remote` stdout. Each line is\n * `<sha>\\t<ref>`; refs are routed through release-id's lenient\n * {@link parseBranchName} and only `kind: 'version'` ids are kept (named\n * `release/<name>` branches are irrelevant to `next`-bump math and are dropped).\n * Returns the no-`v` semver tokens (e.g. `1.2.3`) that\n * {@link collectKnownVersions} parses as versions. Pure \u2014 no I/O \u2014 so it is\n * unit-testable without the network.\n */\nexport const extractVersionBranches = (lsRemoteStdout: string): string[] => {\n return lsRemoteStdout\n .split('\\n')\n .map((line) => {\n const tab = line.indexOf('\\t')\n\n if (tab === -1) return null\n\n return parseBranchName(line.slice(tab + 1))\n })\n .filter((id): id is NonNullable<typeof id> => {\n return id !== null && id.kind === 'version'\n })\n .map((id) => {\n return id.raw\n })\n}\n\nconst parseRemoteRefs = async (): Promise<string[]> => {\n const previousQuiet = $.quiet\n\n try {\n $.quiet = true\n const result = await $`git ls-remote --heads origin 'release/v*'`\n\n return extractVersionBranches(result.stdout)\n } finally {\n $.quiet = previousQuiet\n }\n}\n\nconst fetchJiraVersionNames = async (): Promise<string[]> => {\n const config = await loadJiraConfigOptional()\n\n if (!config) return []\n\n const versions = await getProjectVersions(config)\n\n return versions.map((v) => {\n return v.name\n })\n}\n\n/**\n * Load known release versions from the union of:\n * - remote release branches (`release/v*` on origin)\n * - Jira fix versions (when configured)\n *\n * Each source is queried in parallel; if either fails, we log a warning\n * and continue with the other so a transient outage doesn't block release\n * creation.\n */\nexport const loadExistingVersions = async (): Promise<SemVer[]> => {\n const [branchesResult, jiraResult] = await Promise.allSettled([parseRemoteRefs(), fetchJiraVersionNames()])\n\n if (branchesResult.status === 'rejected') {\n logger.warn({ error: branchesResult.reason }, 'Failed to list remote release branches; continuing without them')\n }\n\n if (jiraResult.status === 'rejected') {\n logger.warn({ error: jiraResult.reason }, 'Failed to fetch Jira versions; continuing without them')\n }\n\n return collectKnownVersions({\n remoteBranches: branchesResult.status === 'fulfilled' ? branchesResult.value : [],\n jiraVersions: jiraResult.status === 'fulfilled' ? jiraResult.value : [],\n })\n}\n", "/**\n * Parse a `v<semver>` token into major, minor, patch numbers.\n *\n * SemVer-ONLY: this assumes a `v<semver>` token and will produce `NaN`s for\n * anything else. Callers that may see branch names or named releases\n * (`release/<name>`) MUST use the `release-id` module (`parseBranchName` /\n * `parseReleaseRef` + `compareReleaseIds`) instead. Only provably names-free\n * callers (the `collectKnownVersions` / `next`-bump math path) may use this.\n */\nexport const parseVersion = (versionStr: string): [number, number, number] => {\n return versionStr.slice(1).split('.').map(Number) as [number, number, number]\n}\n\n/**\n * Sort version strings in ascending order.\n * Note: Returns a new sorted array without mutating the original.\n *\n * SemVer-ONLY: relies on {@link parseVersion} and will NaN-sort named releases.\n * Name-aware callers MUST use `compareReleaseIds` from the `release-id` module.\n */\nexport const sortVersions = (versions: string[]): string[] => {\n return [...versions].sort((a, b) => {\n const [majA, minA, patchA] = parseVersion(a)\n const [majB, minB, patchB] = parseVersion(b)\n\n if (majA !== majB) return (majA ?? 0) - (majB ?? 0)\n if (minA !== minB) return (minA ?? 0) - (minB ?? 0)\n\n return (patchA ?? 0) - (patchB ?? 0)\n })\n}\n", "import { parseReleaseRef, validateName } from 'src/lib/release-id'\nimport type { ReleaseId } from 'src/lib/release-id'\nimport type { ReleaseType } from 'src/lib/release-utils'\n\nimport { parseVersion, sortVersions } from './version-utils'\n\nexport const NEXT_TOKEN = 'next'\n\nexport type SemVer = readonly [number, number, number]\n\nexport interface ExistingVersionsSources {\n remoteBranches?: string[]\n jiraVersions?: string[]\n}\n\nconst VERSION_RE = /^v?(\\d+)\\.(\\d+)\\.(\\d+)$/\n\nconst stripBranchPrefix = (raw: string): string => {\n return raw.replace(/^.*release\\//, '')\n}\n\nconst tryParse = (raw: string): SemVer | null => {\n const cleaned = stripBranchPrefix(raw.trim())\n const match = VERSION_RE.exec(cleaned)\n\n if (!match) return null\n\n return [Number(match[1]), Number(match[2]), Number(match[3])]\n}\n\nconst semverKey = (v: SemVer): string => {\n return `${v[0]}.${v[1]}.${v[2]}`\n}\n\nexport const collectKnownVersions = (sources: ExistingVersionsSources): SemVer[] => {\n const all = [...(sources.remoteBranches ?? []), ...(sources.jiraVersions ?? [])]\n const parsed: SemVer[] = []\n const seen = new Set<string>()\n\n for (const raw of all) {\n const v = tryParse(raw)\n\n if (!v) continue\n\n const key = semverKey(v)\n\n if (seen.has(key)) continue\n\n seen.add(key)\n parsed.push(v)\n }\n\n return sortVersions(\n parsed.map((v) => {\n return semverKey(v)\n }),\n ).map((s) => {\n return parseVersion(`v${s}`)\n })\n}\n\nexport class NoPriorVersionsError extends Error {\n constructor() {\n super('No prior release versions found from git or Jira. Specify the version explicitly.')\n this.name = 'NoPriorVersionsError'\n }\n}\n\n/**\n * Compute the next semantic version based on release type.\n * - regular: bump minor, reset patch to 0\n * - hotfix: bump patch on the highest minor (any patch)\n *\n * Returns the version without the leading \"v\" (e.g. \"1.64.0\").\n */\nexport const computeNextVersion = (known: SemVer[], type: ReleaseType): string => {\n if (known.length === 0) throw new NoPriorVersionsError()\n\n const max = known[known.length - 1] as SemVer\n\n if (type === 'hotfix') {\n const [major, minor] = max\n\n const highestPatchOnMinor = known.reduce((acc, v) => {\n if (v[0] === major && v[1] === minor) return Math.max(acc, v[2])\n\n return acc\n }, 0)\n\n return `${major}.${minor}.${highestPatchOnMinor + 1}`\n }\n\n const [major, minor] = max\n\n return `${major}.${minor + 1}.0`\n}\n\nconst isNextToken = (token: string): boolean => {\n return token.trim().toLowerCase() === NEXT_TOKEN\n}\n\n/**\n * A release spec is the parsed form of a versioned release request: a raw\n * version token (`\"1.2.5\"` or `\"next\"`) plus its type and optional\n * description. This is the unchanged output of {@link parseReleaseSpec} and the\n * versioned-input shape consumed by {@link resolveReleaseEntries}.\n */\nexport interface ReleaseSpec {\n version: string\n type: ReleaseType\n description?: string\n}\n\n/**\n * A named release request: a bare kebab-case name plus its type and optional\n * description. Named releases never auto-bump; `\"next\"` is version-only.\n */\nexport interface NamedReleaseInput {\n name: string\n type: ReleaseType\n description?: string\n}\n\n/** Either a versioned spec or a named release request. */\nexport type ReleaseInput = ReleaseSpec | NamedReleaseInput\n\n/**\n * A fully resolved release entry. The {@link ReleaseId} carries the concrete\n * identity (version or name) and is the single source for branch/PR/Jira\n * formatting via the `release-id` module.\n */\nexport interface ReleaseEntry {\n id: ReleaseId\n type: ReleaseType\n description?: string\n}\n\nconst isReleaseType = (value: string): value is ReleaseType => {\n return value === 'regular' || value === 'hotfix'\n}\n\nconst isNamedReleaseInput = (input: ReleaseInput): input is NamedReleaseInput => {\n return 'name' in input\n}\n\n/**\n * Parse a CLI release spec of the form `<token>[:type[:description]]` into a\n * {@link ReleaseInput}. The token determines the kind: a semver (`\"1.2.5\"`) or\n * the literal `\"next\"` yields a versioned {@link ReleaseSpec}; anything else is\n * treated as a named release ({@link NamedReleaseInput}) \u2014 the name is not\n * validated here, {@link resolveReleaseEntries} runs `validateName` later. Type\n * defaults to \"regular\". Description is everything after the second colon, so\n * colons inside descriptions are preserved.\n */\nexport const parseReleaseSpec = (raw: string): ReleaseInput => {\n const spec = raw.trim()\n\n if (spec === '') throw new Error('Release spec is empty')\n\n const firstColon = spec.indexOf(':')\n let token = spec\n let type: ReleaseType = 'regular'\n let description = ''\n\n if (firstColon !== -1) {\n token = spec.slice(0, firstColon).trim()\n const rest = spec.slice(firstColon + 1)\n const secondColon = rest.indexOf(':')\n const typeRaw = secondColon === -1 ? rest.trim() : rest.slice(0, secondColon).trim()\n\n description = secondColon === -1 ? '' : rest.slice(secondColon + 1).trim()\n const typeLower = typeRaw.toLowerCase()\n\n if (!isReleaseType(typeLower)) {\n throw new Error(`Invalid release type \"${typeRaw}\". Expected \"regular\" or \"hotfix\".`)\n }\n\n type = typeLower\n }\n\n // A semver token or the \"next\" token is a versioned release; everything else\n // is a named release. parseReleaseRef applies the same precedence downstream.\n // Note: tryParse strips a leading \"release/\" prefix, so \"release/1.2.3\" reads\n // as the version 1.2.3 (a real name can never contain a slash anyway).\n if (isNextToken(token) || tryParse(token) !== null) {\n const entry: ReleaseSpec = { version: token, type }\n\n if (description !== '') entry.description = description\n\n return entry\n }\n\n const entry: NamedReleaseInput = { name: token, type }\n\n if (description !== '') entry.description = description\n\n return entry\n}\n\n/**\n * Render a resolved {@link ReleaseEntry} as the canonical `--release` spec that\n * reproduces it \u2014 the inverse of {@link parseReleaseSpec} composed with\n * {@link resolveReleaseEntries}. The form is minimal: the bare token when the\n * release is `regular` with no description, `token:hotfix` for a hotfix with no\n * description, and `token:type:description` whenever a description is present\n * (the type segment is required to reach the description segment). The token is\n * the resolved {@link ReleaseId.raw} \u2014 a concrete semver for versions (so a\n * resolved `\"next\"` pins its computed version) or the name for named releases.\n */\nexport const formatReleaseSpec = (entry: ReleaseEntry): string => {\n const token = entry.id.raw\n\n if (entry.description !== undefined && entry.description !== '') {\n return `${token}:${entry.type}:${entry.description}`\n }\n\n if (entry.type === 'hotfix') return `${token}:hotfix`\n\n return token\n}\n\nconst withDescription = (base: { id: ReleaseId; type: ReleaseType }, description?: string): ReleaseEntry => {\n return description !== undefined && description !== '' ? { ...base, description } : base\n}\n\nconst resolveNamedInput = (input: NamedReleaseInput): ReleaseEntry => {\n const name = input.name.trim()\n\n // validateName throws InvalidReleaseNameError with a specific message.\n validateName(name)\n\n return withDescription({ id: { kind: 'name', name, raw: name }, type: input.type }, input.description)\n}\n\n/**\n * Resolve a list of release inputs into entries carrying a concrete\n * {@link ReleaseId}. Versioned inputs use the existing spec format: the\n * `\"next\"` token advances based on the running max so successive `\"next\"`\n * tokens produce sequential versions (even across mixed types), then the\n * concrete version is wrapped in a {@link ReleaseId}. Named inputs are\n * validated via `validateName` and never auto-bump.\n */\nexport const resolveReleaseEntries = (entries: ReleaseInput[], known: SemVer[]): ReleaseEntry[] => {\n const running: SemVer[] = [...known]\n\n return entries.map((entry) => {\n if (isNamedReleaseInput(entry)) {\n return resolveNamedInput(entry)\n }\n\n const trimmed = entry.version.trim()\n\n if (trimmed === '') {\n throw new Error('Release entry has an empty version')\n }\n\n if (isNextToken(trimmed)) {\n const next = computeNextVersion(running, entry.type)\n\n running.push(parseVersion(`v${next}`))\n\n return withDescription({ id: parseReleaseRef(next), type: entry.type }, entry.description)\n }\n\n const parsed = tryParse(trimmed)\n\n if (!parsed) {\n throw new Error(`Invalid version \"${trimmed}\". Expected semver like \"1.2.5\" or the token \"next\".`)\n }\n\n const explicit = `${parsed[0]}.${parsed[1]}.${parsed[2]}`\n\n running.push(parsed)\n\n return withDescription({ id: parseReleaseRef(explicit), type: entry.type }, entry.description)\n })\n}\n\nexport const hasNextToken = (entries: ReleaseInput[]): boolean => {\n return entries.some((e) => {\n return !isNamedReleaseInput(e) && isNextToken(e.version)\n })\n}\n", "import input from '@inquirer/input'\nimport { z } from 'zod'\n\nimport { getReleasePRsWithInfo, updateReleasePRBody } from 'src/integrations/gh'\nimport { findVersionByName, loadJiraConfig, updateJiraVersion } from 'src/integrations/jira'\nimport type { JiraConfig, JiraVersion } from 'src/integrations/jira'\nimport { commandEcho, confirmOrExit } from 'src/lib/command-echo'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { pickReleaseBranch as pickReleaseBranchPrompt } from 'src/lib/prompts/release-picker'\nimport { displayLabel, formatJiraName, parseBranchName } from 'src/lib/release-id'\nimport {\n detectReleaseType,\n formatBranchPickerItems,\n getJiraDescriptions,\n resolveReleaseBranch,\n} from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { RequiredConfirmedOptionArg } from 'src/types'\n\ninterface ReleaseDescEditArgs extends RequiredConfirmedOptionArg {\n version?: string\n description?: string\n}\n\nconst buildJiraVersionUrl = (jiraConfig: JiraConfig, version: JiraVersion): string => {\n return `${jiraConfig.baseUrl}/projects/${version.projectId}/versions/${version.id}/tab/release-report-all-issues`\n}\n\nconst buildPRBody = (jiraVersionUrl: string, description: string): string => {\n return description.trim() !== '' ? `${jiraVersionUrl}\\n\\n${description}` : `${jiraVersionUrl} \\n`\n}\n\nconst pickReleaseBranch = async (): Promise<{ branch: string; type: ReleaseType }> => {\n const releasePRsInfo = await getReleasePRsWithInfo()\n const branches = releasePRsInfo.map((pr) => {\n return pr.branch\n })\n const types = new Map<string, ReleaseType>(\n releasePRsInfo.map((pr) => {\n return [pr.branch, detectReleaseType(pr.title)]\n }),\n )\n const descriptions = await getJiraDescriptions()\n\n const branch = await pickReleaseBranchPrompt(formatBranchPickerItems({ branches, descriptions, types }))\n\n return { branch, type: types.get(branch) || 'regular' }\n}\n\nconst verifyReleasePRExists = async (selectedBranch: string): Promise<ReleaseType> => {\n const releasePRsInfo = await getReleasePRsWithInfo()\n const prInfo = releasePRsInfo.find((pr) => {\n return pr.branch === selectedBranch\n })\n\n if (!prInfo) {\n throw new OperationError(undefined, {\n operation: `edit description for ${selectedBranch}`,\n remediation: `confirm an open PR exists for ${selectedBranch} ('gh pr list')`,\n })\n }\n\n return detectReleaseType(prInfo.title)\n}\n\n/**\n * Exported for test only. The keep-current semantics below turn on exactly how the answer is\n * whitespace-normalised, which is the detail that changed when this stopped being a zx `question`.\n */\nexport const promptDescription = async (current: string): Promise<string> => {\n const hint = current === '' ? '(no current description)' : `current: \"${current}\"`\n // SINGLE-LINE message on purpose. The hint used to sit on its own line via an embedded `\\n`,\n // which zx wrote raw and inquirer cannot: inquirer re-renders on every keystroke and derives\n // its ANSI erase-line count from the rendered message, so a manual newline miscounts and\n // leaves orphaned prompt fragments on screen. Inlining the hint removes the hazard outright\n // rather than testing around it.\n const answer = await withEscape((context) => {\n return input({ message: ` New description ${hint} (press Enter to keep current): ` }, context)\n })\n // `.trim()`, where the zx version only stripped a trailing newline. Whitespace-only input now\n // means keep-current instead of overwriting the description with blanks.\n const trimmed = answer.trim()\n\n return trimmed === '' ? current : trimmed\n}\n\n/**\n * Edit a release's description in Jira (fix version) and in the matching\n * GitHub release PR body. The PR body is rewritten canonically to\n * `<jiraVersionUrl>\\n\\n<description>` (matching `release-create`).\n */\nexport const releaseDescEdit = async (args: ReleaseDescEditArgs) => {\n const { version: versionArg, description: descriptionArg, confirmedCommand } = args\n\n const jiraConfig = await loadJiraConfig()\n\n let selectedBranch: string\n\n if (versionArg) {\n selectedBranch = resolveReleaseBranch(versionArg)\n await verifyReleasePRExists(selectedBranch)\n } else {\n commandEcho.setInteractive()\n const picked = await pickReleaseBranch()\n\n selectedBranch = picked.branch\n }\n\n // selectedBranch is always a release branch here (operator ref strictly parsed,\n // or picked from discovery-filtered choices), so parseBranchName cannot be null.\n const releaseId = parseBranchName(selectedBranch)\n\n if (!releaseId) {\n throw new OperationError(undefined, {\n operation: `edit description for ${selectedBranch}`,\n remediation: 'pass a version (e.g. \"1.2.5\") or a release name (e.g. \"checkout-redesign\")',\n })\n }\n\n const selectedVersion = displayLabel(releaseId)\n\n commandEcho.addOption('--version', selectedVersion)\n\n // Jira fix version is named by the Jira convention: `v1.2.3` | `<name>`.\n const versionName = formatJiraName(releaseId)\n const jiraVersion = await findVersionByName(versionName, jiraConfig)\n\n if (!jiraVersion) {\n throw new OperationError(undefined, {\n operation: `edit description for ${versionName}`,\n remediation: `create the Jira fix version \"${versionName}\" first or pick a different release`,\n })\n }\n\n const previousDescription = jiraVersion.description ?? ''\n\n let newDescription: string\n\n if (descriptionArg !== undefined) {\n newDescription = descriptionArg\n commandEcho.addOption('--description', newDescription)\n } else {\n commandEcho.setInteractive()\n newDescription = await promptDescription(previousDescription)\n }\n\n const buildResult = (changed: boolean) => {\n const structuredContent = {\n version: selectedVersion,\n branch: selectedBranch,\n jiraVersionUrl: buildJiraVersionUrl(jiraConfig, jiraVersion),\n previousDescription,\n newDescription,\n changed,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n }\n\n if (newDescription === previousDescription) {\n logger.info(`No change \u2014 description for ${versionName} is already: \"${previousDescription}\"`)\n commandEcho.print()\n\n return buildResult(false)\n }\n\n await confirmOrExit(\n confirmedCommand,\n `Update description for ${versionName}?\\n from: \"${previousDescription}\"\\n to: \"${newDescription}\"\\n`,\n )\n\n commandEcho.addOption('--yes', true)\n\n await updateJiraVersion({ versionId: jiraVersion.id, description: newDescription }, jiraConfig)\n\n const jiraVersionUrl = buildJiraVersionUrl(jiraConfig, jiraVersion)\n const body = buildPRBody(jiraVersionUrl, newDescription)\n\n await updateReleasePRBody({ branch: selectedBranch, body })\n\n logger.info(`\u2705 Updated description for ${versionName}`)\n logger.info(`\uD83D\uDD17 Jira Version: ${jiraVersionUrl}`)\n logger.info(`\uD83D\uDD17 PR branch: ${selectedBranch}\\n`)\n\n commandEcho.print()\n\n return buildResult(true)\n}\n\n// MCP Tool Registration\nexport const releaseDescEditMcpTool = defineMcpTool({\n name: 'release-desc-edit',\n description:\n \"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\\\n\\\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.\",\n inputSchema: {\n version: z\n .string()\n .describe('Accepts a release version (e.g. \"1.2.5\") OR a release name (e.g. \"checkout-redesign\").'),\n description: z.string().describe('New description. Empty string clears the description.'),\n },\n outputSchema: {\n version: z.string().describe('Release version'),\n branch: z.string().describe('Release branch name (e.g. \"release/v1.2.5\" or \"release/checkout-redesign\")'),\n jiraVersionUrl: z.string().describe('Jira fix version URL'),\n previousDescription: z.string().describe('The description before the update'),\n newDescription: z.string().describe('The description after the update'),\n changed: z.boolean().describe('Whether the description actually changed'),\n },\n handler: releaseDescEdit,\n})\n", "import { execFile } from 'node:child_process'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport {\n buildCmuxWorkspaceTitle,\n closeCmuxWorkspaceByCwd,\n createCmuxGroupFrom,\n findCmuxGroupRefByName,\n listCmuxWorkspacesByCwd,\n openCmuxWorkspaceWithLayout,\n realpathForCmuxCwd,\n} from 'src/integrations/cmux'\nimport { ideProviderLabel, openIdeWorkspace } from 'src/integrations/ide'\nimport { commandEcho } from 'src/lib/command-echo'\nimport { WORKTREES_DIR_SUFFIX } from 'src/lib/constants'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { getMainRepoRoot, getProjectRoot, listWorktrees } from 'src/lib/git-utils'\nimport type { WorktreeEntry } from 'src/lib/git-utils'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { discoverInfraKitProjects } from 'src/lib/project-discovery'\nimport type { DiscoveredProject } from 'src/lib/project-discovery'\nimport { isReleaseBranch } from 'src/lib/release-id'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { ToolsExecutionResult } from 'src/types'\n\ninterface ReopenArgs {\n /** Cross-project fan-out \u2014 dispatches to {@link reopenAll} instead of the single-project path. */\n all?: boolean\n /** Narrow `--all` to these project names. Ignored without `--all`. */\n project?: string[]\n /** Discovery roots for `--all` (falls back to the workspace dir when omitted). Ignored without `--all`. */\n root?: string[]\n /** Restrict to release worktrees (reproduces the legacy `worktrees reload` scope). */\n releaseOnly?: boolean\n /** Close each cmux workspace first, then reopen (the legacy `worktrees reload` behaviour). */\n force?: boolean\n /** Print the plan and spawn nothing. */\n dryRun?: boolean\n}\n\ninterface ReopenResult {\n repo: string\n dryRun: boolean\n releaseOnly: boolean\n /** Absolute folder set handed to the editor (root-first, exactly as opened). */\n worktreePaths: string[]\n ideProviders: string[]\n /** cmux titles opened this run (additive mode: only the ones not already open). */\n cmuxOpened: string[]\n /** cmux titles skipped because their workspace was already open (additive mode). */\n cmuxSkipped: string[]\n /** cmux titles closed first (only in `--force` mode). */\n cmuxClosed: string[]\n}\n\n/** One cmux workspace to (re)open: its canonical-friendly title and the cwd it runs in. */\ninterface CmuxTarget {\n title: string\n cwd: string\n}\n\n/**\n * Per-repo outcome of an `--all` sweep: either the child's parsed\n * {@link ReopenResult} (with `ok: true`), or an isolated failure record. `repo`\n * is the discovered project name (the child's own `repo` field is overwritten so\n * the aggregate keys off the name the parent discovered).\n */\nexport type ReopenAllRepoResult =\n (ReopenResult & { repo: string; ok: true }) | { repo: string; ok: false; error: string }\n\n/** Aggregated result of `infra-kit reopen --all` across every discovered project. */\nexport interface ReopenAllResult {\n all: true\n dryRun: boolean\n projects: DiscoveredProject[]\n results: ReopenAllRepoResult[]\n}\n\n/**\n * Entry point for `infra-kit reopen`. Dispatches on `--all`: without it, reopen\n * the current project (see {@link reopenCurrentProject}); with it, discover every\n * infra-kit project and fan out one child process per repo (see\n * {@link reopenAll}). Kept as a thin dispatcher so the single-project path and\n * its MCP tool return the narrow {@link ReopenResult} unchanged.\n */\nexport const reopen = async (\n options: ReopenArgs = {},\n): Promise<ToolsExecutionResult<ReopenResult | ReopenAllResult>> => {\n return options.all ? reopenAll(options) : reopenCurrentProject(options)\n}\n\n/**\n * Reopen editor + cmux windows for every *active* worktree in the current\n * project. \"Active\" = a `git worktree list` record that is neither bare nor\n * prunable \u2014 the main checkout plus every linked worktree (release, feature,\n * detached), regardless of branch. Additive and idempotent by default: cmux\n * workspaces already open are skipped, so running twice does not double the\n * windows. `--force` closes each cmux workspace first (the legacy reload\n * behaviour); `--release-only` narrows the set to release worktrees.\n *\n * Non-destructive to git \u2014 only cmux/editor view state is touched.\n */\nexport const reopenCurrentProject = async (options: ReopenArgs = {}): Promise<ToolsExecutionResult<ReopenResult>> => {\n const { releaseOnly = false, force = false, dryRun = false } = options\n\n // GUARD (placement is load-bearing): must stay ABOVE the `try` block below. Its catch rethrows only\n // OperationError; getInfraKitConfig's missing-config throw is a PLAIN Error, so a read inside the try\n // is rewrapped and its text is silently dropped by buildMessage \u2014 AC3b would fail green.\n await getInfraKitConfig()\n\n try {\n const projectRoot = await getProjectRoot()\n const worktreeDir = `${projectRoot}${WORKTREES_DIR_SUFFIX}`\n // cmux titles are keyed on the STABLE main-repo name (the basename of the main\n // checkout), not the worktree-local basename: running `reopen` from inside a\n // linked worktree must produce the same titles `worktrees add` created from the\n // main checkout, or dedup misses and every run duplicates the windows.\n const repoName = path.basename(await getMainRepoRoot(projectRoot))\n\n const entries = await listWorktrees(projectRoot)\n const active = selectActive(entries, releaseOnly)\n\n // The exact folder set to open (root-first, harvested from git \u2014 the main\n // checkout's own record is already in `entries`, so root is included here).\n const worktreePaths = active.map((entry) => {\n return entry.path\n })\n\n // Cursor's `.code-workspace` reconcile is release-branch-shaped, so it stays\n // branch-based on the release subset (Zed consumes the paths above).\n const currentBranches = active\n .map((entry) => {\n return entry.branch\n })\n .filter((branch): branch is string => {\n return isReleaseBranch(branch)\n })\n\n const targets: CmuxTarget[] = active.map((entry) => {\n return {\n // Detached / branch-less worktrees have no branch to title from; fall back\n // to the leaf directory so the title is still stable and meaningful.\n title: buildCmuxWorkspaceTitle({ branch: entry.branch ?? path.basename(entry.path) }),\n cwd: entry.path,\n }\n })\n\n if (dryRun) {\n const result = await planReopen({ repo: repoName, releaseOnly, force, worktreePaths, targets })\n\n logDryRun(result, worktreeDir)\n commandEcho.print()\n\n return { content: textContent(JSON.stringify(result, null, 2)), structuredContent: result }\n }\n\n const [ideOutcomes, cmux] = await Promise.all([\n openIdeWorkspace({ projectRoot, worktreeDir, worktreePaths, currentBranches }),\n runCmux({ targets, force, repoName }),\n ])\n\n const result: ReopenResult = {\n repo: repoName,\n dryRun: false,\n releaseOnly,\n worktreePaths,\n ideProviders: ideOutcomes\n .filter((outcome) => {\n return outcome.ran\n })\n .map((outcome) => {\n return outcome.provider\n }),\n cmuxOpened: cmux.opened,\n cmuxSkipped: cmux.skipped,\n cmuxClosed: cmux.closed,\n }\n\n logResults(result, {\n ideRan: ideOutcomes.some((outcome) => {\n return outcome.ran\n }),\n })\n\n commandEcho.print()\n\n return { content: textContent(JSON.stringify(result, null, 2)), structuredContent: result }\n } catch (error) {\n if (error instanceof OperationError) throw error\n\n logger.error({ error }, '\u274C Error reopening worktree windows')\n throw new OperationError(error, {\n operation: 'reopen worktrees',\n remediation: \"run `infra-kit doctor` to check this project's setup\",\n })\n }\n}\n\n/**\n * Active = neither bare nor prunable. `--release-only` further restricts to\n * release worktrees (reproducing the legacy reload scope). This is a FILTER we\n * must write: `git worktree list` reports bare/prunable records with marker\n * lines, it does not omit them.\n */\nconst selectActive = (entries: WorktreeEntry[], releaseOnly: boolean): WorktreeEntry[] => {\n return entries.filter((entry) => {\n if (entry.bare || entry.prunable) return false\n\n return releaseOnly ? isReleaseBranch(entry.branch) : true\n })\n}\n\ninterface RunCmuxArgs {\n targets: CmuxTarget[]\n force: boolean\n /** Stable repo name (basename of the main-repo root) \u2192 the sidebar group name. */\n repoName: string\n}\n\ninterface RunCmuxOutcome {\n opened: string[]\n skipped: string[]\n closed: string[]\n}\n\n/**\n * Open a cmux workspace for every target, each inside the repo's sidebar group.\n * Default is ADDITIVE + DEDUPED by workspace cwd: a target whose worktree cwd is\n * already open is skipped, which makes `reopen` idempotent (running twice opens\n * nothing new \u2014 including the main checkout, whose cwd the group anchor shares but\n * which the cwd map excludes). `--force` closes each target first, then force-opens\n * with no dedup \u2014 the escape hatch that recovers the legacy reload behaviour and\n * doubles as the migration for pre-group ungrouped windows.\n */\nconst runCmux = async (args: RunCmuxArgs): Promise<RunCmuxOutcome> => {\n const { targets, force, repoName } = args\n\n // Resolve the group ONCE, before the close loop \u2014 closing the last member of a\n // group leaves it empty-but-pinned, and a later lookup must not race that.\n const groupRef = await findCmuxGroupRefByName(repoName)\n\n const closed = force ? await closeCmux({ targets }) : []\n\n const { opened, skipped } = await reopenCmux({ targets, force, repoName, groupRef })\n\n return { opened, skipped, closed }\n}\n\ninterface CloseCmuxArgs {\n targets: CmuxTarget[]\n}\n\n/**\n * Close the cmux workspace for each target that is currently open, matched BY CWD\n * (never by title \u2014 titles are no longer unique across repos, and a cwd match\n * excludes group anchors so a group header can never be closed). Snapshots the\n * open set up front so the returned list reflects which were actually open; the\n * close itself is best-effort per target.\n */\nexport const closeCmux = async (args: CloseCmuxArgs): Promise<string[]> => {\n const { targets } = args\n\n if (targets.length === 0) {\n return []\n }\n\n const openByCwd = await listCmuxWorkspacesByCwd()\n\n const closed: string[] = []\n\n for (const target of targets) {\n if (!openByCwd.has(await realpathForCmuxCwd(target.cwd))) {\n continue\n }\n\n await closeCmuxWorkspaceByCwd(target.cwd)\n closed.push(target.title)\n }\n\n return closed\n}\n\ninterface ReopenCmuxArgs {\n targets: CmuxTarget[]\n force: boolean\n repoName: string\n /** Existing group ref, or null/undefined to bootstrap one from the first opened workspace. */\n groupRef?: string | null\n}\n\ninterface ReopenCmuxOutcome {\n opened: string[]\n skipped: string[]\n}\n\n/**\n * Partition targets into those that need opening vs. those already open, against a\n * set of open workspace cwds (realpath'd, anchors excluded). `force` bypasses dedup\n * entirely \u2014 every target lands in `toOpen`. Shared by {@link reopenCmux} and\n * {@link planReopen}.\n */\nconst partitionCmuxTargets = async (\n targets: CmuxTarget[],\n openCwds: Set<string>,\n force: boolean,\n): Promise<{ toOpen: CmuxTarget[]; skipped: string[] }> => {\n const toOpen: CmuxTarget[] = []\n const skipped: string[] = []\n\n for (const target of targets) {\n if (!force && openCwds.has(await realpathForCmuxCwd(target.cwd))) {\n skipped.push(target.title)\n } else {\n toOpen.push(target)\n }\n }\n\n return { toOpen, skipped }\n}\n\n/**\n * (Re)open a cmux workspace per target, inside the repo's sidebar group. Additive\n * by default \u2014 skips any target whose worktree cwd is already open, so a second run\n * opens 0 new workspaces. If no group exists yet, the FIRST opened workspace seeds\n * it via `--from` (capture-free); the rest open straight into it. Under `force`,\n * dedup is bypassed and every target is force-opened (callers close first).\n */\nexport const reopenCmux = async (args: ReopenCmuxArgs): Promise<ReopenCmuxOutcome> => {\n const { targets, force, repoName, groupRef = null } = args\n\n // `listCmuxWorkspacesByCwd` returns `\u2205` when cmux is down or unreadable; its\n // contract says treat empty as \"unknown, proceed as if nothing is open\", which\n // is exactly force-open behaviour \u2014 acceptable here.\n const openCwds = force ? new Set<string>() : new Set((await listCmuxWorkspacesByCwd()).keys())\n const { toOpen, skipped } = await partitionCmuxTargets(targets, openCwds, force)\n\n const opened: string[] = []\n let group = groupRef\n let bootstrapAttempted = false\n\n for (const target of toOpen) {\n try {\n if (group) {\n await openCmuxWorkspaceWithLayout({ cwd: target.cwd, title: target.title, group })\n } else {\n const workspaceRef = await openCmuxWorkspaceWithLayout({ cwd: target.cwd, title: target.title })\n\n // Seed the group from the first workspace we open, once. `--from` makes\n // creation capture-free; if it fails, remaining targets open ungrouped\n // rather than spawning a second group per iteration.\n if (!bootstrapAttempted) {\n group = await createCmuxGroupFrom(repoName, [workspaceRef])\n bootstrapAttempted = true\n }\n }\n\n opened.push(target.title)\n } catch (error) {\n logger.warn({ error, title: target.title }, `\u26A0\uFE0F Failed to reopen cmux workspace ${target.title}`)\n }\n }\n\n return { opened, skipped }\n}\n\ninterface PlanReopenArgs {\n repo: string\n releaseOnly: boolean\n force: boolean\n worktreePaths: string[]\n targets: CmuxTarget[]\n}\n\n/**\n * Build the dry-run plan: which folders would open in the editor and which cmux\n * titles would open vs. are already open. Reads the live cmux workspace list but\n * spawns nothing.\n */\nconst planReopen = async (args: PlanReopenArgs): Promise<ReopenResult> => {\n const { repo, releaseOnly, force, worktreePaths, targets } = args\n\n const openCwds = force ? new Set<string>() : new Set((await listCmuxWorkspacesByCwd()).keys())\n const { toOpen, skipped } = await partitionCmuxTargets(targets, openCwds, force)\n\n return {\n repo,\n dryRun: true,\n releaseOnly,\n worktreePaths,\n ideProviders: [],\n cmuxOpened: toOpen.map((target) => {\n return target.title\n }),\n cmuxSkipped: skipped,\n cmuxClosed: [],\n }\n}\n\nconst logDryRun = (result: ReopenResult, worktreeDir: string): void => {\n logger.info(`\uD83D\uDD0E reopen --dry-run for ${result.repo} (worktrees dir: ${worktreeDir})`)\n logger.info(`\uD83D\uDCC2 Would open ${result.worktreePaths.length} folder(s) in the editor:`)\n for (const folder of result.worktreePaths) {\n logger.info(` ${folder}`)\n }\n\n if (result.cmuxOpened.length > 0) {\n logger.info(`\uD83E\uDE9F Would open ${result.cmuxOpened.length} cmux workspace(s):`)\n for (const title of result.cmuxOpened) {\n logger.info(` ${title}`)\n }\n }\n\n if (result.cmuxSkipped.length > 0) {\n logger.info(`\u21A9\uFE0F Already open (would skip) ${result.cmuxSkipped.length} cmux workspace(s):`)\n for (const title of result.cmuxSkipped) {\n logger.info(` ${title}`)\n }\n }\n}\n\ninterface LogResultsContext {\n ideRan: boolean\n}\n\nconst logResults = (result: ReopenResult, context: LogResultsContext): void => {\n if (result.cmuxClosed.length > 0) {\n logger.info(`\uD83E\uDDF9 Closed ${result.cmuxClosed.length} cmux workspace(s)`)\n }\n\n if (context.ideRan) {\n const ideLabels = result.ideProviders\n .map((provider) => {\n return ideProviderLabel(provider as Parameters<typeof ideProviderLabel>[0])\n })\n .join(', ')\n\n logger.info(`\u2705 Opened editor workspace(s): ${ideLabels}`)\n }\n\n if (result.cmuxOpened.length > 0) {\n logger.info('\u2705 Opened cmux workspaces:')\n for (const title of result.cmuxOpened) {\n logger.info(title)\n }\n }\n\n if (result.cmuxSkipped.length > 0) {\n logger.info(`\u21A9\uFE0F ${result.cmuxSkipped.length} cmux workspace(s) already open \u2014 skipped`)\n }\n\n if (!context.ideRan && result.cmuxOpened.length === 0 && result.cmuxClosed.length === 0) {\n logger.info('\u2139\uFE0F Nothing to reopen')\n }\n}\n\n/**\n * Cross-project fan-out for `--all`. Discovers every live infra-kit project\n * (scanning `--root` or `dirname(getMainRepoRoot())`), then spawns ONE child\n * `reopen --json [flags]` per repo, SERIALLY. Serial is deliberate: concurrent\n * node procs racing the same cmux GUI is the focus-stealing mess serial avoids.\n * Per-child failures are isolated \u2014 a repo that errors is recorded and the sweep\n * continues. Renders one aggregated summary and returns one combined result.\n */\nconst reopenAll = async (options: ReopenArgs): Promise<ToolsExecutionResult<ReopenAllResult>> => {\n const { project = [], root = [], releaseOnly = false, force = false, dryRun = false } = options\n\n const discovered = await discoverInfraKitProjects({ roots: root })\n const projects = filterProjects(discovered, project)\n const childFlags = buildChildFlags({ releaseOnly, force, dryRun })\n\n // SERIAL. Not parallel \u2014 N node procs racing the cmux GUI is the mess this avoids.\n const results: ReopenAllRepoResult[] = []\n\n for (const proj of projects) {\n results.push(await runRepoChild(proj, childFlags))\n }\n\n const result: ReopenAllResult = { all: true, dryRun, projects, results }\n\n logReopenAll(result)\n commandEcho.print()\n\n return { content: textContent(JSON.stringify(result, null, 2)), structuredContent: result }\n}\n\n/**\n * Narrow the discovered set to `--project` names. Empty \u2192 keep all. Names that\n * match nothing are warned and skipped (they never silently widen the sweep).\n */\nconst filterProjects = (discovered: DiscoveredProject[], names: string[]): DiscoveredProject[] => {\n if (names.length === 0) return discovered\n\n const discoveredNames = new Set(\n discovered.map((proj) => {\n return proj.name\n }),\n )\n\n for (const name of names) {\n if (!discoveredNames.has(name)) {\n logger.warn(`\u26A0\uFE0F --project ${name} matched no discovered project \u2014 skipping`)\n }\n }\n\n return discovered.filter((proj) => {\n return names.includes(proj.name)\n })\n}\n\n/**\n * The child passthrough flags. `--all` is NEVER passed (it would recurse\n * infinitely); `--project` / `--root` are parent-only and NEVER passed to\n * children. `--json` is added by the spawn itself, not here.\n */\nconst buildChildFlags = (args: { releaseOnly: boolean; force: boolean; dryRun: boolean }): string[] => {\n const flags: string[] = []\n\n if (args.dryRun) flags.push('--dry-run')\n if (args.releaseOnly) flags.push('--release-only')\n if (args.force) flags.push('--force')\n\n return flags\n}\n\n/**\n * Run one child `reopen --json` in `proj.repoRoot` and parse its single JSON\n * result off stdout. Any failure (non-zero exit, unparseable stdout, spawn\n * error) is isolated into an error record so the caller's sweep continues.\n */\nconst runRepoChild = async (proj: DiscoveredProject, childFlags: string[]): Promise<ReopenAllRepoResult> => {\n try {\n const stdout = await spawnReopenChild(proj.repoRoot, childFlags)\n const childResult = JSON.parse(stdout) as ReopenResult\n\n return { ...childResult, repo: proj.name, ok: true }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n\n logger.warn({ error }, `\u26A0\uFE0F reopen failed for ${proj.name} \u2014 continuing`)\n\n return { repo: proj.name, ok: false, error: message }\n }\n}\n\n/**\n * Spawn `<node> <this cli.js> reopen --json [flags]` in `cwd` and resolve its\n * stdout. Resolves the CLI via `process.execPath` + `process.argv[1]` \u2014 NEVER\n * PATH and NEVER `pnpm exec` (PATH/`pnpm exec` resolution of our own bin is a\n * repeatedly-relearned mistake). Rejects on spawn error or non-zero exit.\n */\nconst spawnReopenChild = (cwd: string, childFlags: string[]): Promise<string> => {\n const selfCli = process.argv[1]\n\n if (selfCli === undefined) {\n return Promise.reject(new Error('cannot resolve the infra-kit CLI entry \u2014 process.argv[1] is undefined'))\n }\n\n return new Promise((resolve, reject) => {\n const args = [selfCli, 'reopen', '--json', ...childFlags]\n\n execFile(process.execPath, args, { cwd, maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => {\n if (error) {\n reject(error)\n\n return\n }\n\n resolve(stdout)\n })\n })\n}\n\n/** Render one aggregated summary for the whole `--all` sweep (parent owns all rendering). */\nconst logReopenAll = (result: ReopenAllResult): void => {\n const okCount = result.results.filter((repo) => {\n return repo.ok\n }).length\n const failedCount = result.results.length - okCount\n\n logger.info(`\uD83C\uDF10 reopen --all${result.dryRun ? ' --dry-run' : ''}: ${result.projects.length} project(s)`)\n\n let totalOpened = 0\n let totalSkipped = 0\n\n for (const repo of result.results) {\n if (repo.ok) {\n totalOpened += repo.cmuxOpened.length\n totalSkipped += repo.cmuxSkipped.length\n\n logger.info(\n ` \u2705 ${repo.repo}: ${repo.worktreePaths.length} folder(s), ${repo.cmuxOpened.length} cmux ${result.dryRun ? 'planned' : 'opened'}, ${repo.cmuxSkipped.length} skipped`,\n )\n } else {\n logger.info(` \u274C ${repo.repo}: ${repo.error}`)\n }\n }\n\n logger.info(\n `\uD83D\uDCCA ${okCount} ok, ${failedCount} failed \u2014 ${totalOpened} cmux ${result.dryRun ? 'planned' : 'opened'}, ${totalSkipped} already open`,\n )\n}\n\n// MCP Tool Registration\nexport const reopenMcpTool = defineMcpTool({\n name: 'reopen',\n description:\n 'Reopen editor + cmux windows for every active worktree in the current project \u2014 the main checkout plus every linked worktree (release, feature, detached). Additive and idempotent by default: cmux workspaces already open are skipped, so running twice does not double the windows. Zed opens the exact folder set; Cursor reconciles its release-branch-shaped workspace. Set releaseOnly to restrict to release worktrees (the legacy reload scope). Set force to close each cmux workspace first, then reopen (disruptive). Set dryRun to return the plan without spawning anything. Non-destructive to git \u2014 only cmux/editor view state is touched.',\n inputSchema: {\n releaseOnly: z\n .boolean()\n .optional()\n .describe('Restrict to release worktrees (reproduces the legacy worktrees-reload scope)'),\n force: z.boolean().optional().describe('Close each cmux workspace first, then reopen (disruptive)'),\n dryRun: z.boolean().optional().describe('Return the plan (paths + cmux titles) without spawning anything'),\n },\n outputSchema: {\n repo: z.string().describe('Repository name the reopen ran for'),\n dryRun: z.boolean().describe('Whether this was a dry run (nothing was spawned)'),\n releaseOnly: z.boolean().describe('Whether the set was restricted to release worktrees'),\n worktreePaths: z.array(z.string()).describe('Absolute folder set handed to the editor (root-first)'),\n ideProviders: z.array(z.string()).describe('Configured IDE providers that opened (cursor | zed); empty in dry run'),\n cmuxOpened: z.array(z.string()).describe('Titles of cmux workspaces opened this run'),\n cmuxSkipped: z.array(z.string()).describe('Titles of cmux workspaces skipped because already open (additive mode)'),\n cmuxClosed: z.array(z.string()).describe('Titles of cmux workspaces closed first (force mode only)'),\n },\n handler: reopenCurrentProject,\n})\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\n\ninterface AddFoldersToCursorWorkspaceArgs {\n workspacePath: string\n folderPaths: string[]\n}\n\ninterface AddFoldersToCursorWorkspaceResult {\n added: string[]\n skipped: string[]\n}\n\ninterface WorkspaceFolderEntry {\n path: string\n name?: string\n}\n\ninterface WorkspaceFile {\n folders?: WorkspaceFolderEntry[]\n [key: string]: unknown\n}\n\n/**\n * Adds folders to a Cursor (`.code-workspace`) file's `folders` array, skipping\n * entries that already point to the same absolute path. Folder paths are written\n * as relative to the workspace file's directory to match Cursor's default style.\n */\nexport const addFoldersToCursorWorkspace = async (\n args: AddFoldersToCursorWorkspaceArgs,\n): Promise<AddFoldersToCursorWorkspaceResult> => {\n const { workspacePath, folderPaths } = args\n\n const workspaceDir = path.dirname(workspacePath)\n\n let raw: string\n\n try {\n raw = await fs.readFile(workspacePath, 'utf-8')\n } catch (error) {\n throw new Error(`Cursor workspace file not found at ${workspacePath}: ${(error as Error).message}`)\n }\n\n let parsed: WorkspaceFile\n\n try {\n parsed = JSON.parse(raw) as WorkspaceFile\n } catch (error) {\n throw new Error(\n `Failed to parse ${workspacePath} as JSON. Comments (JSONC) are not supported. ${(error as Error).message}`,\n )\n }\n\n const existingFolders = parsed.folders ?? []\n const existingAbsolutePaths = new Set(\n existingFolders.map((entry) => {\n return path.resolve(workspaceDir, entry.path)\n }),\n )\n\n const added: string[] = []\n const skipped: string[] = []\n\n for (const folderPath of folderPaths) {\n const absolutePath = path.resolve(folderPath)\n\n if (existingAbsolutePaths.has(absolutePath)) {\n skipped.push(folderPath)\n continue\n }\n\n const relativePath = path.relative(workspaceDir, absolutePath)\n\n existingFolders.push({ path: relativePath })\n existingAbsolutePaths.add(absolutePath)\n added.push(folderPath)\n }\n\n parsed.folders = existingFolders\n\n await fs.writeFile(workspacePath, `${JSON.stringify(parsed, null, 2)}\\n`, 'utf-8')\n\n return { added, skipped }\n}\n", "import { $ } from 'zx'\n\n/**\n * Spawns Cursor against a `.code-workspace` file (or any path). Centralised here\n * \u2014 rather than inlined at each call site \u2014 so the editor spawn lives inside the\n * cursor provider module and is covered by a single `vi.mock('src/integrations/cursor')`.\n * Keeping it out of the IDE-orchestration layer is what stops tests that mock the\n * provider (but not `zx`) from shelling out to a real editor.\n */\nexport const launchCursor = async (workspacePath: string): Promise<void> => {\n await $`cursor ${workspacePath}`\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport { addFoldersToCursorWorkspace } from './add-folders-to-workspace'\nimport { removeFoldersFromCursorWorkspace } from './remove-folders-from-workspace'\n\ninterface ReconcileCursorWorkspaceFoldersArgs {\n workspacePath: string\n worktreeDir: string\n currentBranches: string[]\n}\n\ninterface ReconcileCursorWorkspaceFoldersResult {\n added: string[]\n removed: string[]\n}\n\ninterface WorkspaceFolderEntry {\n path: string\n name?: string\n}\n\ninterface WorkspaceFile {\n folders?: WorkspaceFolderEntry[]\n [key: string]: unknown\n}\n\n/**\n * Reconciles the configured Cursor workspace's `folders` array against the\n * actual set of release worktrees on disk:\n * - Adds any worktree folders that aren't already listed.\n * - Removes entries whose absolute path lives under `${worktreeDir}/release/`\n * but no longer corresponds to a current branch (drift from manual\n * `git worktree remove`, deleted branches, etc.).\n *\n * Non-worktree folder entries are left untouched.\n */\nexport const reconcileCursorWorkspaceFolders = async (\n args: ReconcileCursorWorkspaceFoldersArgs,\n): Promise<ReconcileCursorWorkspaceFoldersResult> => {\n const { workspacePath, worktreeDir, currentBranches } = args\n\n const workspaceDir = path.dirname(workspacePath)\n const releaseRoot = path.resolve(`${worktreeDir}/release`)\n\n const raw = await fs.readFile(workspacePath, 'utf-8')\n const parsed = JSON.parse(raw) as WorkspaceFile\n\n const existingFolders = parsed.folders ?? []\n\n const desiredAbsolutePaths = new Set(\n currentBranches.map((branch) => {\n return path.resolve(`${worktreeDir}/${branch}`)\n }),\n )\n\n const danglingFolderPaths: string[] = []\n\n for (const entry of existingFolders) {\n const entryAbsolutePath = path.resolve(workspaceDir, entry.path)\n\n const isReleaseShaped = entryAbsolutePath === releaseRoot || entryAbsolutePath.startsWith(`${releaseRoot}/`)\n\n if (isReleaseShaped && !desiredAbsolutePaths.has(entryAbsolutePath)) {\n danglingFolderPaths.push(entryAbsolutePath)\n }\n }\n\n let removed: string[] = []\n\n if (danglingFolderPaths.length > 0) {\n const result = await removeFoldersFromCursorWorkspace({\n workspacePath,\n folderPaths: danglingFolderPaths,\n })\n\n removed = result.removed\n }\n\n const desiredFolderPaths = currentBranches.map((branch) => {\n return `${worktreeDir}/${branch}`\n })\n\n const { added } =\n desiredFolderPaths.length > 0\n ? await addFoldersToCursorWorkspace({ workspacePath, folderPaths: desiredFolderPaths })\n : { added: [] as string[] }\n\n return { added, removed }\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\n\ninterface RemoveFoldersFromCursorWorkspaceArgs {\n workspacePath: string\n folderPaths: string[]\n}\n\ninterface RemoveFoldersFromCursorWorkspaceResult {\n removed: string[]\n notFound: string[]\n}\n\ninterface WorkspaceFolderEntry {\n path: string\n name?: string\n}\n\ninterface WorkspaceFile {\n folders?: WorkspaceFolderEntry[]\n [key: string]: unknown\n}\n\n/**\n * Removes folders from a Cursor (`.code-workspace`) file's `folders` array. Entries\n * are matched by resolved absolute path, so relative and absolute entries pointing\n * at the same folder are both removed.\n */\nexport const removeFoldersFromCursorWorkspace = async (\n args: RemoveFoldersFromCursorWorkspaceArgs,\n): Promise<RemoveFoldersFromCursorWorkspaceResult> => {\n const { workspacePath, folderPaths } = args\n\n const workspaceDir = path.dirname(workspacePath)\n\n let raw: string\n\n try {\n raw = await fs.readFile(workspacePath, 'utf-8')\n } catch (error) {\n throw new Error(`Cursor workspace file not found at ${workspacePath}: ${(error as Error).message}`)\n }\n\n let parsed: WorkspaceFile\n\n try {\n parsed = JSON.parse(raw) as WorkspaceFile\n } catch (error) {\n throw new Error(\n `Failed to parse ${workspacePath} as JSON. Comments (JSONC) are not supported. ${(error as Error).message}`,\n )\n }\n\n const existingFolders = parsed.folders ?? []\n const targetAbsolutePaths = new Set(\n folderPaths.map((folderPath) => {\n return path.resolve(folderPath)\n }),\n )\n\n const removedAbsolutePaths = new Set<string>()\n\n const filteredFolders = existingFolders.filter((entry) => {\n const entryAbsolutePath = path.resolve(workspaceDir, entry.path)\n\n if (targetAbsolutePaths.has(entryAbsolutePath)) {\n removedAbsolutePaths.add(entryAbsolutePath)\n\n return false\n }\n\n return true\n })\n\n parsed.folders = filteredFolders\n\n await fs.writeFile(workspacePath, `${JSON.stringify(parsed, null, 2)}\\n`, 'utf-8')\n\n const removed: string[] = []\n const notFound: string[] = []\n\n for (const folderPath of folderPaths) {\n const absolutePath = path.resolve(folderPath)\n\n if (removedAbsolutePaths.has(absolutePath)) {\n removed.push(folderPath)\n } else {\n notFound.push(folderPath)\n }\n }\n\n return { removed, notFound }\n}\n", "import path from 'node:path'\n\n/**\n * Resolves the configured Cursor workspace path against the project root.\n * Absolute paths are returned unchanged.\n */\nexport const resolveCursorWorkspacePath = (configValue: string, projectRoot: string): string => {\n if (path.isAbsolute(configValue)) {\n return configValue\n }\n\n return path.resolve(projectRoot, configValue)\n}\n", "import { logger } from 'src/lib/logger'\n\nimport { launchCursor } from './launch-cursor'\nimport { reconcileCursorWorkspaceFolders } from './reconcile-workspace-folders'\nimport { resolveCursorWorkspacePath } from './resolve-workspace-path'\n\ninterface OpenCursorWorkspaceArgs {\n projectRoot: string\n worktreeDir: string\n currentBranches: string[]\n /**\n * The Cursor entry's config, selected by the facade from the (possibly\n * multi-IDE) infra-kit config. Passed in rather than re-read here so this\n * opener acts on the exact entry the caller chose \u2014 essential once `ide` can\n * be an array of providers.\n */\n cursorConfig: { workspaceConfigPath: string }\n}\n\ninterface OpenCursorWorkspaceOutcome {\n ran: boolean\n added: number\n removed: number\n}\n\n/**\n * Reconciles the configured Cursor `.code-workspace` `folders` array against the\n * set of release worktrees on disk, then launches Cursor against it (the folder\n * reconcile still runs when there are no worktrees, but the relaunch is skipped\n * so `reopen` never pops an empty Cursor window). Used by\n * `reopen`.\n *\n * No-ops (returns `ran: false`) when the Cursor entry has no `workspaceConfigPath`.\n * All failures are swallowed into a warning \u2014 opening Cursor is best-effort.\n */\nexport const openCursorWorkspace = async (args: OpenCursorWorkspaceArgs): Promise<OpenCursorWorkspaceOutcome> => {\n const { projectRoot, worktreeDir, currentBranches, cursorConfig } = args\n\n if (!cursorConfig.workspaceConfigPath) {\n logger.warn('\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set.')\n\n return { ran: false, added: 0, removed: 0 }\n }\n\n const workspacePath = resolveCursorWorkspacePath(cursorConfig.workspaceConfigPath, projectRoot)\n\n try {\n const { added, removed } = await reconcileCursorWorkspaceFolders({\n workspacePath,\n worktreeDir,\n currentBranches,\n })\n\n if (currentBranches.length > 0) {\n await launchCursor(workspacePath)\n }\n\n return { ran: true, added: added.length, removed: removed.length }\n } catch (error) {\n logger.warn({ error }, `\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${workspacePath}`)\n\n return { ran: false, added: 0, removed: 0 }\n }\n}\n", "import { $ } from 'zx'\n\ninterface AddFoldersToZedWorkspaceArgs {\n folderPaths: string[]\n}\n\ninterface AddFoldersToZedWorkspaceResult {\n added: string[]\n}\n\n/**\n * Adds folders to Zed's current workspace via `zed --add <path>` per folder.\n * This is the only legitimate use of `--add` (it targets the most-recent\n * workspace, so it is reserved for the incremental add-only path right after\n * `worktrees-add` creates new worktrees \u2014 never for the full cold-start open).\n *\n * Zed has no folder-remove CLI and no skip-if-present concept, so every folder\n * is reported as added (no `skipped` set, unlike the Cursor `.code-workspace`).\n */\nexport const addFoldersToZedWorkspace = async (\n args: AddFoldersToZedWorkspaceArgs,\n): Promise<AddFoldersToZedWorkspaceResult> => {\n const { folderPaths } = args\n\n for (const folderPath of folderPaths) {\n await $`zed --add ${folderPath}`\n }\n\n return { added: folderPaths }\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface OpenZedWorkspaceArgs {\n /**\n * The exact folder set to open, as absolute paths \u2014 the caller includes the\n * repo root (Zed realizes a multi-folder workspace from multiple path\n * arguments). Path-carrying rather than reconstructing `${worktreeDir}/${branch}`\n * so detached-HEAD and out-of-convention worktrees open too.\n */\n worktreePaths: string[]\n}\n\ninterface OpenZedWorkspaceOutcome {\n ran: boolean\n added: number\n removed: number\n}\n\n/**\n * Opens a single Zed workspace from the given folder paths, via one\n * `zed <path...>` invocation. Skips the launch when the set is empty so it never\n * pops a bare Zed window.\n *\n * Zed has no portable workspace file and no folder-remove CLI, so there is\n * nothing to reconcile: `added` is the number of folders opened and `removed`\n * is always 0. All failures are swallowed into a warning \u2014 opening Zed is\n * best-effort, mirroring the Cursor integration.\n */\nexport const openZedWorkspace = async (args: OpenZedWorkspaceArgs): Promise<OpenZedWorkspaceOutcome> => {\n const { worktreePaths } = args\n\n if (worktreePaths.length === 0) {\n return { ran: false, added: 0, removed: 0 }\n }\n\n try {\n await $`zed ${worktreePaths}`\n\n return { ran: true, added: worktreePaths.length, removed: 0 }\n } catch (error) {\n logger.warn({ error }, '\u26A0\uFE0F Failed to open Zed workspace')\n\n return { ran: false, added: 0, removed: 0 }\n }\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface ReuseZedWorkspaceArgs {\n projectRoot: string\n worktreeDir: string\n remainingBranches: string[]\n}\n\ninterface ReuseZedWorkspaceOutcome {\n ran: boolean\n}\n\n/**\n * Reflects a worktree removal in the open Zed window by running\n * `zed --reuse <root> <remaining release worktrees...>`.\n *\n * IMPORTANT \u2014 this is destructive: `--reuse` REPLACES the focused window's\n * ENTIRE folder set with exactly these paths. The remaining set is built from\n * release worktrees only (`getCurrentWorktrees('release')`), so any other folder\n * open in that window \u2014 feature worktrees, scratch dirs, user-added dirs \u2014 is\n * DROPPED and is NOT recoverable by infra-kit (Zed offers no undo and we keep no\n * record of the prior set). The caller MUST therefore only invoke this on an\n * interactive path where a human is present and can re-add folders via\n * `zed --add`. We emit a disclosure log line saying as much.\n *\n * Distinct from `openZedWorkspace`, which runs `zed <paths>` WITHOUT `--reuse`\n * to realize a multi-folder workspace; that does not replace a focused window.\n *\n * Best-effort: any launch failure is swallowed into a warning, mirroring\n * `openZedWorkspace`. Root is always included so the path list is never empty.\n */\nexport const reuseZedWorkspace = async (args: ReuseZedWorkspaceArgs): Promise<ReuseZedWorkspaceOutcome> => {\n const { projectRoot, worktreeDir, remainingBranches } = args\n\n const paths = [\n projectRoot,\n ...remainingBranches.map((branch) => {\n return `${worktreeDir}/${branch}`\n }),\n ]\n\n try {\n await $`zed --reuse ${paths}`\n\n logger.info(\n `\u21BB Refreshed Zed workspace to root + ${remainingBranches.length} release worktree(s) (other folders in the focused window are not preserved)`,\n )\n\n return { ran: true }\n } catch (error) {\n logger.warn({ error }, '\u26A0\uFE0F Failed to refresh Zed workspace')\n\n return { ran: false }\n }\n}\n", "/**\n * Exhaustiveness guard for discriminated unions. Place in the `default` branch of\n * a `switch` over a union: once every case is handled the argument narrows to\n * `never`, so adding a new variant later turns this into a compile error.\n *\n * @example\n * switch (provider) {\n * case 'cursor': return openCursor()\n * case 'zed': return openZed()\n * default: return assertNever(provider) // compile error if a provider is unhandled\n * }\n */\nexport const assertNever = (value: never): never => {\n throw new Error(`Unexpected value: ${JSON.stringify(value)}`)\n}\n", "import { addFoldersToCursorWorkspace, launchCursor, resolveCursorWorkspacePath } from 'src/integrations/cursor'\nimport { addFoldersToZedWorkspace } from 'src/integrations/zed'\nimport { assertNever } from 'src/lib/assert-never'\nimport { getInfraKitConfig, resolveConfiguredIdes } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\n\nimport type { AddIdeWorktreeFoldersOutcome } from './types'\n\ninterface AddIdeWorktreeFoldersArgs {\n projectRoot: string\n worktreeDir: string\n branches: string[]\n}\n\n/**\n * Workspace-mode add (used by `worktrees-add`): append the given worktree folders\n * to every configured editor's workspace and open it. Returns one outcome per\n * configured provider (empty array when no IDE is configured), iterating\n * sequentially.\n *\n * Cursor appends to the `.code-workspace` `folders` array (reporting `skipped`\n * for already-present entries) then runs `cursor <workspace>`. Zed has no\n * workspace file, so it `zed --add`s each folder (`skipped` is always 0).\n */\nexport const addIdeWorktreeFolders = async (\n args: AddIdeWorktreeFoldersArgs,\n): Promise<AddIdeWorktreeFoldersOutcome[]> => {\n const { projectRoot, worktreeDir, branches } = args\n\n const config = await getInfraKitConfig()\n const ides = resolveConfiguredIdes(config)\n\n const folderPaths = branches.map((branch) => {\n return `${worktreeDir}/${branch}`\n })\n\n const outcomes: AddIdeWorktreeFoldersOutcome[] = []\n\n for (const ide of ides) {\n switch (ide.provider) {\n case 'cursor': {\n if (!ide.config.workspaceConfigPath) {\n logger.warn('\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config')\n\n outcomes.push({ ran: false, provider: 'cursor', added: 0, skipped: 0 })\n break\n }\n\n const workspacePath = resolveCursorWorkspacePath(ide.config.workspaceConfigPath, projectRoot)\n\n const { added, skipped } = await addFoldersToCursorWorkspace({ workspacePath, folderPaths })\n\n const skippedSuffix = skipped.length > 0 ? ` (${skipped.length} already present)` : ''\n\n logger.info(`\u2705 Added ${added.length} folder(s) to ${workspacePath}${skippedSuffix}`)\n\n await launchCursor(workspacePath)\n\n outcomes.push({ ran: true, provider: 'cursor', added: added.length, skipped: skipped.length })\n break\n }\n case 'zed': {\n const { added } = await addFoldersToZedWorkspace({ folderPaths })\n\n logger.info(`\u2705 Added ${added.length} folder(s) to Zed workspace`)\n\n outcomes.push({ ran: true, provider: 'zed', added: added.length, skipped: 0 })\n break\n }\n default: {\n assertNever(ide)\n }\n }\n }\n\n return outcomes\n}\n", "import { openCursorWorkspace } from 'src/integrations/cursor'\nimport { openZedWorkspace } from 'src/integrations/zed'\nimport { assertNever } from 'src/lib/assert-never'\nimport { getInfraKitConfig, resolveConfiguredIdes } from 'src/lib/infra-kit-config'\n\nimport type { OpenIdeWorkspaceOutcome } from './types'\n\ninterface OpenIdeWorkspaceArgs {\n projectRoot: string\n worktreeDir: string\n /**\n * The exact absolute folder set to open (root-first). Consumed by Zed, which\n * launches paths directly \u2014 this is what lets detached-HEAD and\n * out-of-convention worktrees open.\n */\n worktreePaths: string[]\n /**\n * Release branches, for Cursor's `.code-workspace` reconcile (its folder model\n * is release-branch-shaped, so it stays branch-based rather than path-carrying).\n */\n currentBranches: string[]\n}\n\n/**\n * Provider-agnostic entry point for the reload open: for every configured\n * editor, reconciles (or, for Zed, simply assembles) the workspace against the\n * release worktrees on disk and launches it \u2014 skipping the launch when there are\n * no worktrees, so `reopen` never pops a bare editor window. Returns\n * one outcome per configured provider (empty array when no IDE is configured).\n * Iterates sequentially \u2014 `reopen` already wraps this call in an outer\n * `Promise.all` with cmux, so a `Promise.all` here would compound editor-spawn\n * concurrency. Best-effort \u2014 every provider swallows failures into a warning.\n */\nexport const openIdeWorkspace = async (args: OpenIdeWorkspaceArgs): Promise<OpenIdeWorkspaceOutcome[]> => {\n const config = await getInfraKitConfig()\n const ides = resolveConfiguredIdes(config)\n\n const { projectRoot, worktreeDir, worktreePaths, currentBranches } = args\n\n const outcomes: OpenIdeWorkspaceOutcome[] = []\n\n for (const ide of ides) {\n switch (ide.provider) {\n case 'cursor': {\n // Cursor reconciles a release-branch-shaped `.code-workspace` file, so it\n // stays branch-based rather than consuming the harvested paths.\n const outcome = await openCursorWorkspace({\n projectRoot,\n worktreeDir,\n currentBranches,\n cursorConfig: ide.config,\n })\n\n outcomes.push({ ...outcome, provider: 'cursor' })\n break\n }\n case 'zed': {\n const outcome = await openZedWorkspace({ worktreePaths })\n\n outcomes.push({ ...outcome, provider: 'zed' })\n break\n }\n default: {\n assertNever(ide)\n }\n }\n }\n\n return outcomes\n}\n", "import { assertNever } from 'src/lib/assert-never'\n\nimport type { IdeProvider } from './types'\n\n/**\n * Human-facing display name for an IDE provider, used in log lines. Falls back to\n * a generic \"IDE\" when no provider is configured.\n */\nexport const ideProviderLabel = (provider: IdeProvider | undefined): string => {\n switch (provider) {\n case 'cursor': {\n return 'Cursor'\n }\n case 'zed': {\n return 'Zed'\n }\n case undefined: {\n return 'IDE'\n }\n default: {\n return assertNever(provider)\n }\n }\n}\n", "import { removeFoldersFromCursorWorkspace, resolveCursorWorkspacePath } from 'src/integrations/cursor'\nimport { reuseZedWorkspace } from 'src/integrations/zed'\nimport { assertNever } from 'src/lib/assert-never'\nimport { getInfraKitConfig, resolveConfiguredIdes } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\n\nimport type { RemoveIdeWorktreeFoldersOutcome } from './types'\n\ninterface RemoveIdeWorktreeFoldersArgs {\n projectRoot: string\n worktreeDir: string\n /** All release worktrees BEFORE removal (release-only \u2014 see Zed note below). */\n currentWorktrees: string[]\n /** The subset of `currentWorktrees` that was just removed. */\n removedWorktrees: string[]\n /**\n * Whether the caller is on an interactive path where firing Zed's destructive\n * `zed --reuse` is acceptable (a human is present and confirming). Interactive\n * `worktrees-remove` passes `!confirmedCommand`; `worktrees-sync` and every\n * non-interactive/MCP run pass `false`.\n */\n allowEditorRelaunch: boolean\n}\n\n/**\n * Strip removed worktrees from every configured editor's workspace (used by\n * `worktrees-remove` and `worktrees-sync`). Returns one outcome per configured\n * provider (empty array when no IDE is configured or no worktrees were removed),\n * iterating sequentially.\n *\n * Cursor surgically edits the `.code-workspace` `folders` array \u2014 it removes\n * only the named paths and leaves everything else intact.\n *\n * Zed has no surgical remove. The only mutation mechanism, `zed --reuse`,\n * REPLACES the focused window's entire folder set, so it can only re-state the\n * release worktrees we know about and silently drops any other open folder\n * (`remaining` is built from release worktrees only). Because that is\n * destructive and unrecoverable, it fires ONLY when `allowEditorRelaunch` is\n * true (interactive `worktrees-remove`). On the non-interactive/MCP path it is a\n * deliberate no-op (`supported: true`, `removed: []`) with an info message \u2014 the\n * capability exists; skipping is a policy choice, not a missing capability.\n *\n * Zed's `removed` is ALWAYS `[]`: `--reuse` performs no diff, so it confirms no\n * specific removal and we never report intended-but-unverified paths.\n */\nexport const removeIdeWorktreeFolders = async (\n args: RemoveIdeWorktreeFoldersArgs,\n): Promise<RemoveIdeWorktreeFoldersOutcome[]> => {\n const { projectRoot, worktreeDir, currentWorktrees, removedWorktrees, allowEditorRelaunch } = args\n\n if (removedWorktrees.length === 0) {\n return []\n }\n\n const config = await getInfraKitConfig()\n const ides = resolveConfiguredIdes(config)\n\n const folderPaths = removedWorktrees.map((branch) => {\n return `${worktreeDir}/${branch}`\n })\n\n const remainingBranches = currentWorktrees.filter((branch) => {\n return !removedWorktrees.includes(branch)\n })\n\n const outcomes: RemoveIdeWorktreeFoldersOutcome[] = []\n\n for (const ide of ides) {\n switch (ide.provider) {\n case 'cursor': {\n outcomes.push(await removeFromCursor({ ide, projectRoot, folderPaths }))\n break\n }\n case 'zed': {\n outcomes.push(await removeFromZed({ projectRoot, worktreeDir, remainingBranches, allowEditorRelaunch }))\n break\n }\n default: {\n assertNever(ide)\n }\n }\n }\n\n return outcomes\n}\n\ninterface RemoveFromCursorArgs {\n ide: Extract<ReturnType<typeof resolveConfiguredIdes>[number], { provider: 'cursor' }>\n projectRoot: string\n folderPaths: string[]\n}\n\n/** Surgically strip the removed folder paths from the Cursor `.code-workspace`. */\nconst removeFromCursor = async (args: RemoveFromCursorArgs): Promise<RemoveIdeWorktreeFoldersOutcome> => {\n const { ide, projectRoot, folderPaths } = args\n\n if (!ide.config.workspaceConfigPath) {\n return { provider: 'cursor', supported: true, removed: [] }\n }\n\n const workspacePath = resolveCursorWorkspacePath(ide.config.workspaceConfigPath, projectRoot)\n\n try {\n const { removed } = await removeFoldersFromCursorWorkspace({ workspacePath, folderPaths })\n\n if (removed.length > 0) {\n logger.info(`\u2705 Removed ${removed.length} folder(s) from ${workspacePath}`)\n }\n\n return { provider: 'cursor', supported: true, removed }\n } catch (error) {\n logger.warn({ error }, `\u26A0\uFE0F Failed to update Cursor workspace at ${workspacePath}`)\n\n return { provider: 'cursor', supported: true, removed: [] }\n }\n}\n\ninterface RemoveFromZedArgs {\n projectRoot: string\n worktreeDir: string\n remainingBranches: string[]\n allowEditorRelaunch: boolean\n}\n\n/**\n * Reflect the removal in Zed by relaunching the focused window onto the\n * remaining set \u2014 but ONLY on an interactive path (see the module doc for why\n * `zed --reuse` is destructive). Otherwise a deliberate no-op. `removed` is\n * always `[]` because `--reuse` performs no diff.\n */\nconst removeFromZed = async (args: RemoveFromZedArgs): Promise<RemoveIdeWorktreeFoldersOutcome> => {\n const { projectRoot, worktreeDir, remainingBranches, allowEditorRelaunch } = args\n\n if (!allowEditorRelaunch) {\n logger.info(\n '\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed.',\n )\n\n return { provider: 'zed', supported: true, removed: [] }\n }\n\n await reuseZedWorkspace({ projectRoot, worktreeDir, remainingBranches })\n\n return { provider: 'zed', supported: true, removed: [] }\n}\n", "export type IdeProvider = 'cursor' | 'zed'\n\n/**\n * CLI-level open modes for `worktrees-add` (`--ide`). `workspace` adds each\n * created worktree to the configured editor's workspace and opens it (the only\n * attach style); `none` means \"don't open any editor\".\n */\nexport const IDE_MODES = ['workspace', 'none'] as const\nexport type IdeMode = (typeof IDE_MODES)[number]\n\n// Each facade returns one outcome PER configured provider (an array), so every\n// outcome is tagged with its `provider`.\nexport interface OpenIdeWorkspaceOutcome {\n ran: boolean\n provider: IdeProvider\n added: number\n removed: number\n}\n\nexport interface AddIdeWorktreeFoldersOutcome {\n ran: boolean\n provider: IdeProvider\n added: number\n skipped: number\n}\n\nexport interface RemoveIdeWorktreeFoldersOutcome {\n provider: IdeProvider\n /**\n * True when the provider can reflect a removal. Both providers now report\n * `true`; `false` is reserved for a future provider with no remove capability.\n */\n supported: boolean\n /**\n * Folders confirmed removed. For Cursor this is the real diff of the\n * `.code-workspace` `folders` array. For Zed it is ALWAYS `[]`: the only\n * mechanism (`zed --reuse`) replaces the whole window without producing a\n * diff, so it confirms no specific removal even when it refreshed the window.\n */\n removed: string[]\n}\n", "import type { Dirent } from 'node:fs'\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { getMainRepoRoot } from 'src/lib/git-utils'\n\n/**\n * A live infra-kit project found by scanning a workspace root. `repoRoot` is\n * realpath'd so two entries that resolve to the same directory (a symlink, a\n * `/var`\u2192`/private/var` alias) collapse to one.\n */\nexport interface DiscoveredProject {\n name: string\n repoRoot: string\n}\n\nexport interface DiscoverInfraKitProjectsOptions {\n /**\n * Explicit discovery roots. When non-empty these win outright; otherwise the\n * scan falls back to `dirname(getMainRepoRoot())` (the workspace dir).\n */\n roots?: string[]\n}\n\n/** True iff `target` exists (file or dir); tolerates ENOENT and any other stat error. */\nconst pathExists = async (target: string): Promise<boolean> => {\n try {\n await fs.access(target)\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Resolve the scan roots per the discovery ladder: explicit `roots` win; else\n * `[dirname(await getMainRepoRoot())]`. Throws an `OperationError` with a\n * remediation hint when neither is available (not inside a git repo, no roots).\n */\nconst resolveRoots = async (roots?: string[]): Promise<string[]> => {\n if (roots && roots.length > 0) return roots\n\n try {\n const mainRepoRoot = await getMainRepoRoot()\n\n return [path.dirname(mainRepoRoot)]\n } catch (error) {\n throw new OperationError(error, {\n operation: 'discover infra-kit projects',\n remediation: 'run inside an infra-kit repo, or pass --root <dir>',\n })\n }\n}\n\n/** A candidate is worth stat-ing only if it is a directory or a symlink to one. */\nconst isScanCandidate = (child: Dirent): boolean => {\n return child.isDirectory() || child.isSymbolicLink()\n}\n\n/**\n * Resolve one direct child of a root into a {@link DiscoveredProject}, or `null`\n * when it is not a live infra-kit project. Live = BOTH `<candidate>/.git` (file\n * or dir \u2014 worktrees use a `.git` file) and `<candidate>/infra-kit.json` exist.\n * `repoRoot` is realpath'd; an unresolvable path yields `null`.\n */\nconst resolveCandidate = async (root: string, child: Dirent): Promise<DiscoveredProject | null> => {\n if (!isScanCandidate(child)) return null\n\n const candidate = path.join(root, child.name)\n\n const [hasGit, hasConfig] = await Promise.all([\n pathExists(path.join(candidate, '.git')),\n pathExists(path.join(candidate, 'infra-kit.json')),\n ])\n\n if (!hasGit || !hasConfig) return null\n\n try {\n const repoRoot = await fs.realpath(candidate)\n\n return { name: path.basename(candidate), repoRoot }\n } catch {\n return null\n }\n}\n\n/** Read a root's direct children; a missing or unreadable root yields none. */\nconst readRootChildren = async (root: string): Promise<Dirent[]> => {\n try {\n return await fs.readdir(root, { withFileTypes: true })\n } catch {\n return []\n }\n}\n\n/**\n * Scan the workspace for live infra-kit projects.\n *\n * SCAN-BASED \u2014 the registry (`~/.infra-kit/projects/`) is never read. For each\n * root (per {@link resolveRoots}), read its DIRECT children (depth 1 only \u2014 a\n * recursive home crawl is a `node_modules` latency bomb) and keep the ones that\n * {@link resolveCandidate} deems live. Entries are deduped by realpath'd\n * `repoRoot` and returned sorted by name.\n */\nexport const discoverInfraKitProjects = async (\n options: DiscoverInfraKitProjectsOptions = {},\n): Promise<DiscoveredProject[]> => {\n const roots = await resolveRoots(options.roots)\n\n const byRepoRoot = new Map<string, DiscoveredProject>()\n\n for (const root of roots) {\n const children = await readRootChildren(root)\n\n for (const child of children) {\n const project = await resolveCandidate(root, child)\n\n if (project && !byRepoRoot.has(project.repoRoot)) {\n byRepoRoot.set(project.repoRoot, project)\n }\n }\n }\n\n return [...byRepoRoot.values()].sort((a, b) => {\n return a.name.localeCompare(b.name)\n })\n}\n", "import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport { getProjectRoot } from 'src/lib/git-utils'\nimport { logger } from 'src/lib/logger'\nimport { MANIFEST_FILE, VENDOR_DIR, compareToManifest, isUnknownSchema, readManifest } from 'src/lib/vendor'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/** Max drifted paths to print per category before truncating. */\nconst MAX_REPORTED = 30\n\ntype VendorCheckStatus = 'clean' | 'drift' | 'skipped' | 'missing-manifest' | 'unknown-schema'\n\ninterface VendorCheckOptions {\n /** Repo root to check. Defaults to the git toplevel. */\n cwd?: string\n}\n\nconst report = (label: string, list: string[]): void => {\n if (list.length === 0) {\n return\n }\n\n logger.info(`\\n${label} (${list.length}):`)\n\n for (const rel of list.slice(0, MAX_REPORTED)) {\n logger.info(` ${rel}`)\n }\n\n if (list.length > MAX_REPORTED) {\n logger.info(` \u2026and ${list.length - MAX_REPORTED} more`)\n }\n}\n\n/**\n * Verify that files under `vendor/` still match the checksums recorded in\n * `vendor/.sync-manifest.json`. Config-free and self-contained (no source repo,\n * no `vendor.config.ts`, no rsync) so it runs in any consumer's CI. Read-only \u2014\n * never calls `process.exit`; the CLI action maps `structuredContent.ok` to the\n * exit code, and the MCP tool reuses the same handler.\n *\n * Exit-code contract (preserved from the legacy `vendor-check.mjs`):\n * clean \u2192 ok; drift \u2192 not ok; missing `vendor/` \u2192 ok (skip);\n * missing manifest \u2192 not ok; unknown (newer) schemaVersion \u2192 not ok (fail-closed).\n *\n * @example\n * await vendorCheck() // checks the current repo's vendor/\n * await vendorCheck({ cwd: '/repo' }) // checks a specific root (tests)\n */\nexport const vendorCheck = async (options: VendorCheckOptions = {}) => {\n const root = options.cwd ?? (await getProjectRoot())\n const vendorRoot = path.join(root, VENDOR_DIR)\n\n const base = { modified: [] as string[], added: [] as string[], removed: [] as string[], fileCount: 0 }\n\n if (!existsSync(vendorRoot)) {\n logger.info(`\u2139\uFE0F No ${VENDOR_DIR}/ folder found \u2014 nothing to check.`)\n const structuredContent = { status: 'skipped' as VendorCheckStatus, ok: true, ...base }\n\n return { content: textContent(JSON.stringify(structuredContent, null, 2)), structuredContent }\n }\n\n if (!existsSync(path.join(vendorRoot, MANIFEST_FILE))) {\n logger.error(`\u274C Missing ${VENDOR_DIR}/${MANIFEST_FILE}. Re-run the vendor sync to generate it.`)\n const structuredContent = { status: 'missing-manifest' as VendorCheckStatus, ok: false, ...base }\n\n return { content: textContent(JSON.stringify(structuredContent, null, 2)), structuredContent }\n }\n\n const manifest = readManifest(vendorRoot)\n\n if (isUnknownSchema(manifest)) {\n logger.error(\n `\u274C ${VENDOR_DIR}/${MANIFEST_FILE} has a newer schemaVersion (${String(manifest.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`,\n )\n const structuredContent = { status: 'unknown-schema' as VendorCheckStatus, ok: false, ...base }\n\n return { content: textContent(JSON.stringify(structuredContent, null, 2)), structuredContent }\n }\n\n const { modified, added, removed } = compareToManifest(vendorRoot, manifest)\n const drifted = modified.length > 0 || added.length > 0 || removed.length > 0\n\n if (drifted) {\n logger.error(`\u274C ${VENDOR_DIR}/ has drifted from ${VENDOR_DIR}/${MANIFEST_FILE}.`)\n logger.error(' These files are mirrored from the source repo \u2014 edit them upstream, not here.')\n report('Modified', modified)\n report('Added (not in manifest)', added)\n report('Removed (in manifest, now missing)', removed)\n } else {\n logger.info(`\u2705 ${VENDOR_DIR}/ matches manifest (${manifest.fileCount} files).`)\n }\n\n const structuredContent = {\n status: (drifted ? 'drift' : 'clean') as VendorCheckStatus,\n ok: !drifted,\n fileCount: manifest.fileCount,\n modified,\n added,\n removed,\n }\n\n return { content: textContent(JSON.stringify(structuredContent, null, 2)), structuredContent }\n}\n\nconst vendorCheckOutputSchema = {\n status: z.enum(['clean', 'drift', 'skipped', 'missing-manifest', 'unknown-schema']),\n ok: z.boolean().describe('Whether the vendor tree matches its manifest (false \u2192 CI should fail)'),\n fileCount: z.number(),\n modified: z.array(z.string()),\n added: z.array(z.string()),\n removed: z.array(z.string()),\n}\n\n// MCP Tool Registration (read-only; safe to expose).\nexport const vendorCheckMcpTool = defineMcpTool({\n name: 'vendor-check',\n description:\n 'Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.',\n inputSchema: {},\n outputSchema: vendorCheckOutputSchema,\n handler: () => {\n return vendorCheck({ cwd: process.cwd() })\n },\n})\n", "import { createHash } from 'node:crypto'\nimport { readFileSync } from 'node:fs'\n\n/**\n * SHA-256 of a file's contents, hex-encoded. Matches the legacy scripts'\n * `createHash('sha256').update(readFileSync(path)).digest('hex')`.\n *\n * `readFileSync` follows symlinks, so a symlinked file is hashed by its target\n * content \u2014 the behavior both legacy scripts already relied on.\n *\n * @example\n * sha256('/repo/vendor/configs/eslint-config/index.js') // => 'a1b2c3...'\n */\nexport const sha256 = (filePath: string): string => {\n return createHash('sha256').update(readFileSync(filePath)).digest('hex')\n}\n", "import { readFileSync, writeFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { sha256 } from './hash'\nimport { walkVendorTree } from './walk'\n\n/** Filename of the integrity manifest inside a `vendor/` tree. */\nexport const MANIFEST_FILE = '.sync-manifest.json'\n\n/**\n * Manifest schema version the CLI understands. A manifest with a HIGHER version\n * than this was written by a newer CLI and is treated as drift (fail-closed) \u2014\n * see {@link isUnknownSchema}. Legacy manifests carry no `schemaVersion` field\n * and read as compatible.\n */\nexport const CURRENT_SCHEMA_VERSION = 1\n\n/**\n * `schemaVersion` is OPTIONAL with no default: legacy manifests written by\n * `writeVendorMeta` have no such field, and a required field would make\n * `vendor check` fail-closed on every existing manifest. Absent is read as\n * \"compatible\" (current). `writeManifest` always emits the current version.\n */\nconst manifestSchema = z.object({\n schemaVersion: z.number().optional(),\n source: z.string(),\n commit: z.string(),\n syncedAt: z.string(),\n fileCount: z.number(),\n files: z.record(z.string(), z.string()),\n})\n\nexport type VendorManifest = z.infer<typeof manifestSchema>\n\nexport interface ManifestDiff {\n modified: string[]\n added: string[]\n removed: string[]\n}\n\n/**\n * Whether a manifest's `schemaVersion` is newer than this CLI supports. Absent\n * (legacy) reads as compatible; only a strictly-greater version is unknown.\n */\nexport const isUnknownSchema = (manifest: VendorManifest): boolean => {\n return (manifest.schemaVersion ?? CURRENT_SCHEMA_VERSION) > CURRENT_SCHEMA_VERSION\n}\n\n/**\n * Walk the vendor tree and hash every file into a `{ relativePath: sha256 }`\n * map (sorted by walk order \u2192 stable). A file that cannot be read (e.g. a\n * dangling symlink) surfaces an explicit error rather than crashing with a raw\n * fs stack.\n */\nexport const buildFilesMap = (vendorRoot: string): Record<string, string> => {\n const files: Record<string, string> = {}\n\n for (const rel of walkVendorTree(vendorRoot)) {\n try {\n files[rel] = sha256(path.join(vendorRoot, rel))\n } catch (cause) {\n const reason = cause instanceof Error ? cause.message : String(cause)\n\n throw new Error(`Cannot hash vendor file \"${rel}\" (broken symlink or unreadable file): ${reason}`)\n }\n }\n\n return files\n}\n\n/**\n * Read and validate the manifest at `<vendorRoot>/.sync-manifest.json`. Throws a\n * descriptive error if the file is missing or malformed.\n */\nexport const readManifest = (vendorRoot: string): VendorManifest => {\n const manifestPath = path.join(vendorRoot, MANIFEST_FILE)\n\n let raw: string\n\n try {\n raw = readFileSync(manifestPath, 'utf8')\n } catch {\n throw new Error(`Missing ${MANIFEST_FILE} at ${manifestPath}`)\n }\n\n const parsed = manifestSchema.safeParse(JSON.parse(raw))\n\n if (!parsed.success) {\n throw new Error(`Invalid ${MANIFEST_FILE} at ${manifestPath}: ${z.prettifyError(parsed.error)}`)\n }\n\n return parsed.data\n}\n\n/**\n * Build and write a fresh manifest for the current content of `vendorRoot`.\n * Emits the CURRENT schema version, the supplied `source`/`commit`, an ISO\n * `syncedAt`, and the per-file checksum map. Returns the written manifest.\n *\n * The `files` map and field set (minus `schemaVersion`) match legacy\n * `writeVendorMeta`, so a regenerated manifest differs from a legacy one only by\n * the added `schemaVersion` and the `syncedAt` timestamp.\n */\nexport const writeManifest = (vendorRoot: string, meta: { source: string; commit: string }): VendorManifest => {\n const files = buildFilesMap(vendorRoot)\n\n const manifest: VendorManifest = {\n schemaVersion: CURRENT_SCHEMA_VERSION,\n source: meta.source,\n commit: meta.commit,\n syncedAt: new Date().toISOString(),\n fileCount: Object.keys(files).length,\n files,\n }\n\n writeFileSync(path.join(vendorRoot, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`)\n\n return manifest\n}\n\n/**\n * Compare the live `vendorRoot` tree against a manifest's recorded checksums.\n * Returns the modified / added (present, not in manifest) / removed (in\n * manifest, now missing) relative paths.\n */\nexport const compareToManifest = (vendorRoot: string, manifest: VendorManifest): ManifestDiff => {\n const expected = manifest.files\n const actualFiles = walkVendorTree(vendorRoot)\n\n const modified: string[] = []\n const added: string[] = []\n\n for (const rel of actualFiles) {\n if (!(rel in expected)) {\n added.push(rel)\n continue\n }\n\n if (sha256(path.join(vendorRoot, rel)) !== expected[rel]) {\n modified.push(rel)\n }\n }\n\n const actualSet = new Set(actualFiles)\n const removed = Object.keys(expected).filter((rel) => {\n return !actualSet.has(rel)\n })\n\n return { modified, added, removed }\n}\n", "import { readdirSync } from 'node:fs'\nimport path from 'node:path'\n\nimport { isSkippedDir, isSkippedFile } from './skip-sets'\n\n/**\n * Convert a (possibly Windows) relative path to a POSIX-normalized form so the\n * manifest is byte-identical across operating systems.\n */\nconst toPosix = (relativePath: string): string => {\n return relativePath.split(path.sep).join('/')\n}\n\n/**\n * Walk a `vendor/` tree and return the relative paths of every non-skipped file,\n * POSIX-normalized and sorted byte-wise. The sort makes the output independent\n * of `readdirSync` order, which keeps generated manifests deterministic.\n *\n * Symlink handling matches the legacy scripts: only REAL directories\n * (`entry.isDirectory()`) are recursed; a symlink is treated as a leaf and its\n * relative path is emitted, to be hashed later by following it to target\n * content (`sha256`/`readFileSync`). This preserves legacy behavior exactly \u2014\n * the manifest checksum reflects target content, never the link itself.\n *\n * @example\n * walkVendorTree('/repo/vendor')\n * // => ['README.md', 'configs/eslint-config/index.js', ...]\n */\nexport const walkVendorTree = (vendorRoot: string): string[] => {\n const acc: string[] = []\n\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name)\n\n if (entry.isDirectory()) {\n if (isSkippedDir(entry.name)) {\n continue\n }\n\n walk(full)\n continue\n }\n\n if (isSkippedFile(entry.name)) {\n continue\n }\n\n acc.push(toPosix(path.relative(vendorRoot, full)))\n }\n }\n\n walk(vendorRoot)\n\n return acc.sort()\n}\n", "/**\n * Skip rules for walking a `vendor/` tree to build or verify its integrity\n * manifest. This is the SINGLE source of truth consumed by both the read path\n * (`vendor check`) and the write path (`vendor sync`/`manifest`).\n *\n * The set below is a strict superset of the legacy read script's\n * `MANIFEST_SKIP_DIRS` (`scripts/vendor-check.mjs`). It additionally skips\n * `.vitest-attachments` \u2014 a git-ignored directory (see repo `.gitignore`) that\n * therefore never appears in a committed vendor tree. Widening the read path's\n * skip set this way is deliberate and behavior-preserving: no existing manifest\n * changes, and the read and write paths share this single set so they cannot\n * diverge.\n */\n/** Root of the mirrored tree inside each repo. Single source for read + write paths. */\nexport const VENDOR_DIR = 'vendor'\n\nexport const MANIFEST_SKIP_DIRS: ReadonlySet<string> = new Set([\n 'node_modules',\n 'dist',\n '.turbo',\n '.omc',\n '__screenshots__',\n '.vitest-attachments',\n '.output',\n '.source',\n '.nitro',\n '.tanstack',\n])\n\nexport const MANIFEST_SKIP_FILES: ReadonlySet<string> = new Set(['.sync-manifest.json', '.eslintcache', 'log.txt'])\n\nexport const MANIFEST_SKIP_SUFFIXES: readonly string[] = ['.tsbuildinfo']\n\n/** Whether a directory name should be skipped when walking the vendor tree. */\nexport const isSkippedDir = (name: string): boolean => {\n return MANIFEST_SKIP_DIRS.has(name)\n}\n\n/** Whether a file name should be skipped when walking the vendor tree. */\nexport const isSkippedFile = (name: string): boolean => {\n if (MANIFEST_SKIP_FILES.has(name)) {\n return true\n }\n\n return MANIFEST_SKIP_SUFFIXES.some((suffix) => {\n return name.endsWith(suffix)\n })\n}\n", "import { z } from 'zod'\n\nimport { logger } from 'src/lib/logger'\nimport { defineMcpTool, textContent } from 'src/types'\n\nimport packageJson from '../../../package.json' with { type: 'json' }\n\n/**\n * Print the infra-kit CLI version\n */\nexport const version = async () => {\n const cliVersion = packageJson.version\n\n logger.info(cliVersion)\n\n const structuredContent = { version: cliVersion }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const versionMcpTool = defineMcpTool({\n name: 'version',\n description: 'Print the installed infra-kit CLI version',\n inputSchema: {},\n outputSchema: {\n version: z.string().describe('Installed infra-kit CLI version (from package.json)'),\n },\n handler: version,\n})\n", "/* eslint-disable sonarjs/cognitive-complexity */\nimport confirm from '@inquirer/confirm'\nimport path from 'node:path'\nimport { z } from 'zod'\nimport { $ } from 'zx'\n\nimport {\n buildCmuxWorkspaceTitle,\n createCmuxGroupFrom,\n findCmuxGroupRefByName,\n listCmuxWorkspacesByCwd,\n openCmuxWorkspaceWithLayout,\n realpathForCmuxCwd,\n} from 'src/integrations/cmux'\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { IDE_MODES, addIdeWorktreeFolders } from 'src/integrations/ide'\nimport type { IdeMode } from 'src/integrations/ide'\nimport { commandEcho, confirmOrExit } from 'src/lib/command-echo'\nimport { WORKTREES_DIR_SUFFIX } from 'src/lib/constants'\nimport { isPromptCancellation } from 'src/lib/errors/is-prompt-cancellation'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { assertManagementContext } from 'src/lib/git-guard'\nimport { getCurrentWorktrees, getMainRepoRoot, getProjectRoot } from 'src/lib/git-utils'\nimport { getInfraKitConfig, resolveConfiguredIdes } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { pickReleaseBranches } from 'src/lib/prompts/release-picker'\nimport { formatBranchName, isReleaseBranch, parseReleaseRef } from 'src/lib/release-id'\nimport {\n detectReleaseType,\n formatBranchPickerItems,\n getJiraDescriptions,\n releaseBranchLabels,\n} from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { RequiredConfirmedOptionArg } from 'src/types'\n\n// Constants\nconst FEATURE_DIR = 'feature'\nconst RELEASE_DIR = 'release'\n\ninterface WorktreeManagementArgs extends RequiredConfirmedOptionArg {\n all?: boolean\n versions?: string\n ide?: IdeMode\n /** @deprecated Alias for `ide`, kept for back-compat. Ignored when `ide` is set. */\n cursor?: IdeMode\n githubDesktop?: boolean\n cmux?: boolean\n}\n\n/**\n * Manage git worktrees for release branches\n * Creates worktrees for active release branches and removes unused ones\n */\nexport const worktreesAdd = async (options: WorktreeManagementArgs) => {\n const { confirmedCommand, all, versions, githubDesktop, cmux } = options\n // `cursor` is the deprecated alias for `ide`; `ide` wins when both are present.\n const ide = options.ide ?? options.cursor\n\n // Branch-agnostic: `git worktree add` addresses branches by name and never\n // reads HEAD, so only the worktree + clean-tree legs apply.\n await assertManagementContext({ operation: 'create worktrees' })\n\n try {\n const currentWorktrees = await getCurrentWorktrees('release')\n const projectRoot = await getProjectRoot()\n\n const worktreeDir = `${projectRoot}${WORKTREES_DIR_SUFFIX}`\n\n await ensureWorktreeDirectory(`${worktreeDir}/${RELEASE_DIR}`)\n await ensureWorktreeDirectory(`${worktreeDir}/${FEATURE_DIR}`)\n\n let selectedReleaseBranches: string[] = []\n\n if (versions) {\n selectedReleaseBranches = versions.split(',').map((v) => {\n return formatBranchName(parseReleaseRef(v.trim()))\n })\n } else {\n const releasePRsInfo = await getReleasePRsWithInfo()\n\n const releasePRsList = releasePRsInfo.map((pr) => {\n return pr.branch\n })\n\n if (releasePRsList.length === 0) {\n logger.info('\u2139\uFE0F No open release branches found')\n\n commandEcho.print()\n\n return {\n content: textContent(JSON.stringify({ createdWorktrees: [], count: 0 }, null, 2)),\n structuredContent: { createdWorktrees: [], count: 0 },\n }\n }\n\n if (all) {\n selectedReleaseBranches = releasePRsList\n } else {\n commandEcho.setInteractive()\n\n const releaseTypes = new Map<string, ReleaseType>(\n releasePRsInfo.map((pr) => {\n return [pr.branch, detectReleaseType(pr.title)]\n }),\n )\n\n const descriptions = await getJiraDescriptions()\n\n selectedReleaseBranches = await pickReleaseBranches(\n formatBranchPickerItems({ branches: releasePRsList, descriptions, types: releaseTypes }),\n { required: true },\n )\n }\n }\n\n // Track --all flag if all branches were selected (either via flag or interactively)\n if (all) {\n commandEcho.addOption('--all', true)\n } else {\n commandEcho.addOption('--versions', releaseBranchLabels(selectedReleaseBranches))\n }\n\n // Ask for confirmation\n await confirmOrExit(confirmedCommand, 'Are you sure you want to proceed with these worktree changes?')\n\n // Track --yes flag if confirmation was interactive (user confirmed)\n if (!confirmedCommand) {\n commandEcho.addOption('--yes', true)\n }\n\n const config = await getInfraKitConfig()\n\n // One attach style: every configured editor gets the worktrees added to its\n // workspace. Per-run skip is `--ide none` / `--no-ide`; no editor configured\n // means there's nothing to open.\n const ideMode: IdeMode = ide ?? (resolveConfiguredIdes(config).length > 0 ? 'workspace' : 'none')\n\n commandEcho.addOption('--ide', ideMode)\n\n const openInGithubDesktop =\n githubDesktop ??\n config.worktrees?.openInGithubDesktop ??\n (await withEscape((context) => {\n return confirm({ message: 'Open created worktrees in GitHub Desktop?' }, context)\n }))\n\n if (typeof githubDesktop === 'undefined' && config.worktrees?.openInGithubDesktop === undefined) {\n commandEcho.setInteractive()\n }\n\n if (openInGithubDesktop) {\n commandEcho.addOption('--github-desktop', true)\n } else {\n commandEcho.addOption('--no-github-desktop', true)\n }\n\n const openInCmux =\n cmux ??\n config.worktrees?.openInCmux ??\n (await withEscape((context) => {\n return confirm({ message: 'Open created worktrees in cmux?' }, context)\n }))\n\n if (typeof cmux === 'undefined' && config.worktrees?.openInCmux === undefined) {\n commandEcho.setInteractive()\n }\n\n if (openInCmux) {\n commandEcho.addOption('--cmux', true)\n } else {\n commandEcho.addOption('--no-cmux', true)\n }\n\n const { branchesToCreate } = categorizeWorktrees({\n selectedReleaseBranches,\n currentWorktrees,\n })\n\n const createdWorktrees = await createWorktrees(branchesToCreate, worktreeDir)\n\n logResults(createdWorktrees)\n\n if (ideMode === 'workspace') {\n await addIdeWorktreeFolders({ projectRoot, worktreeDir, branches: createdWorktrees })\n }\n\n if (openInGithubDesktop) {\n for (const branch of createdWorktrees) {\n await $`github ${worktreeDir}/${branch}`\n await $`sleep 5`\n }\n }\n\n if (openInCmux) {\n // Group name keys on the STABLE main-repo basename (not the worktree-local\n // `getRepoName()`), so every worktree of a repo lands in the same sidebar\n // group regardless of which checkout this runs from.\n const repoName = path.basename(await getMainRepoRoot(projectRoot))\n const openByCwd = await listCmuxWorkspacesByCwd()\n\n let groupRef = await findCmuxGroupRefByName(repoName)\n let bootstrapAttempted = false\n\n for (const branch of createdWorktrees) {\n const cwd = `${worktreeDir}/${branch}`\n\n // Skip branches whose cmux workspace is already open (matched by cwd, not\n // title), so re-running worktrees-add never duplicates an existing workspace.\n if (openByCwd.has(await realpathForCmuxCwd(cwd))) {\n continue\n }\n\n const title = buildCmuxWorkspaceTitle({ branch })\n\n try {\n if (groupRef) {\n await openCmuxWorkspaceWithLayout({ cwd, title, group: groupRef })\n } else {\n // No group yet: open ungrouped, then seed the group from this first\n // workspace via `--from` (capture-free). Attempt the seed once, so a\n // failed create doesn't spawn a group per iteration.\n const workspaceRef = await openCmuxWorkspaceWithLayout({ cwd, title })\n\n if (!bootstrapAttempted) {\n groupRef = await createCmuxGroupFrom(repoName, [workspaceRef])\n bootstrapAttempted = true\n }\n }\n } catch (error) {\n logger.warn({ error, branch }, `\u26A0\uFE0F Failed to open cmux workspace for ${branch}`)\n }\n }\n }\n\n commandEcho.print()\n\n const structuredContent = {\n createdWorktrees,\n count: createdWorktrees.length,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n } catch (error) {\n // A cancelled prompt (Ctrl-C / Esc) is a user back-out, not a failure: let it\n // reach the top-level boundary untouched so it exits cleanly, instead of being\n // logged as an error with a misleading \"branches already exist\" remediation.\n if (isPromptCancellation(error)) throw error\n\n logger.error({ error }, '\u274C Error managing worktrees')\n throw new OperationError(error, {\n operation: 'create worktrees',\n remediation: \"verify branches don't already exist as worktrees: 'git worktree list'\",\n })\n }\n}\n\n/**\n * Ensure the worktree directory exists\n */\nconst ensureWorktreeDirectory = async (worktreeDir: string): Promise<void> => {\n await $`mkdir -p ${worktreeDir}`\n}\n\ninterface CategorizeWorktreesArgs {\n selectedReleaseBranches: string[]\n currentWorktrees: string[]\n}\n\n/**\n * Categorize release worktrees into those that need to be created or removed\n */\nconst categorizeWorktrees = (args: CategorizeWorktreesArgs): { branchesToCreate: string[] } => {\n const { selectedReleaseBranches, currentWorktrees } = args\n\n const currentBranchNames = currentWorktrees.filter((branch) => {\n return isReleaseBranch(branch)\n })\n\n const branchesToCreate = selectedReleaseBranches.filter((branch) => {\n return !currentBranchNames.includes(branch)\n })\n\n return { branchesToCreate }\n}\n\n/**\n * Create worktrees for the specified branches\n */\nconst createWorktrees = async (branches: string[], worktreeDir: string): Promise<string[]> => {\n const results = await Promise.allSettled(\n branches.map(async (branch) => {\n const worktreePath = `${worktreeDir}/${branch}`\n\n await $`git worktree add ${worktreePath} ${branch}`\n await $({ cwd: worktreePath })`pnpm install`\n\n return branch\n }),\n )\n\n const created: string[] = []\n\n for (const [index, result] of results.entries()) {\n if (result.status === 'fulfilled') {\n created.push(result.value)\n } else {\n const branch = branches[index]\n const err = new OperationError(result.reason, {\n operation: `git worktree add for ${branch}`,\n remediation: 'check the branch name and that the parent dir is writable',\n })\n\n logger.error({ error: result.reason, msg: err.message })\n }\n }\n\n return created\n}\n\n/**\n * Log the results of worktree management\n */\nconst logResults = (created: string[]): void => {\n if (created.length > 0) {\n logger.info('\u2705 Created git worktrees:')\n for (const branch of created) {\n logger.info(branch)\n }\n logger.info('')\n } else {\n logger.info('\u2139\uFE0F No new git worktrees to create')\n }\n}\n\n// MCP Tool Registration\nexport const worktreesAddMcpTool = defineMcpTool({\n name: 'worktrees-add',\n description:\n 'Create local git worktrees for release branches under the worktrees directory and run \"pnpm install\" in each. Mutates the local filesystem. When invoked via MCP, pass either \"versions\" (comma-separated) or all=true \u2014 the branch picker and \"open in Cursor / GitHub Desktop / cmux\" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',\n inputSchema: {\n all: z\n .boolean()\n .optional()\n .describe(\n 'Add worktrees for every open release branch. Either \"all\" or \"versions\" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if \"versions\" is provided.',\n ),\n versions: z\n .string()\n .optional()\n .describe(\n 'Comma-separated release versions or names to target (e.g. \"1.2.5, 1.2.6\" or \"checkout-redesign, 1.2.5\"). Either \"versions\" or all=true must be provided for MCP calls. Overrides \"all\" when set.',\n ),\n ide: z\n .enum(IDE_MODES)\n .optional()\n .describe(\n 'Editor open mode for created worktrees, applied to all configured editors (Cursor and/or Zed, per the \"ide\" config). \"workspace\" (the only attach style) adds each worktree to every configured editor workspace and opens it. \"none\" skips the editor. Resolution order: this flag \u2192 \"workspace\" when at least one \"ide\" is configured \u2192 \"none\" otherwise.',\n ),\n cursor: z\n .enum(IDE_MODES)\n .optional()\n .describe('Deprecated alias for \"ide\". Prefer \"ide\". Ignored when \"ide\" is provided.'),\n githubDesktop: z\n .boolean()\n .optional()\n .describe(\n 'Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 \"worktrees.openInGithubDesktop\" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).',\n ),\n cmux: z\n .boolean()\n .optional()\n .describe(\n 'Open each created worktree in a new cmux workspace, all rooted at the worktree directory. Pane layout follows \"worktrees.cmux.layout\" (default \"two-columns\": left | right; or \"three-pane\": left split top/bottom + full-height right). Resolution order: this flag \u2192 \"worktrees.openInCmux\" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).',\n ),\n },\n outputSchema: {\n createdWorktrees: z.array(z.string()).describe('List of created git worktree branches'),\n count: z.number().describe('Number of git worktrees created'),\n },\n handler: worktreesAdd,\n})\n", "import { z } from 'zod'\n\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { getCurrentWorktrees } from 'src/lib/git-utils'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { displayLabel, formatJiraName, parseBranchName } from 'src/lib/release-id'\nimport { detectReleaseType, formatVersionLabel, getJiraDescriptions } from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\nimport { defineMcpTool, textContent } from 'src/types'\n\ninterface WorktreeInfo {\n version: string\n type: ReleaseType\n description: string | null\n}\n\n/**\n * List all release git worktrees with version, type, and Jira description\n */\nexport const worktreesList = async () => {\n // GUARD (placement is load-bearing): `git worktree list` answers in ANY repo, so without this the\n // release-branch filter renders a generic-git empty set as the infra-kit fact \"No active worktrees\n // found\" \u2014 a false statement in a stranger's repo. Must stay ABOVE `getCurrentWorktrees`.\n await getInfraKitConfig()\n\n const currentWorktrees = await getCurrentWorktrees('release')\n\n if (currentWorktrees.length === 0) {\n logger.info('\u2139\uFE0F No active worktrees found')\n\n return {\n content: textContent(JSON.stringify({ worktrees: [], count: 0 }, null, 2)),\n structuredContent: { worktrees: [], count: 0 },\n }\n }\n\n const [releasePRsInfo, jiraDescriptions] = await Promise.all([getReleasePRsWithInfo(), getJiraDescriptions()])\n\n const releaseTypes = new Map<string, ReleaseType>(\n releasePRsInfo.map((pr) => {\n return [pr.branch, detectReleaseType(pr.title)]\n }),\n )\n\n // Skip worktrees whose branch does not parse as a release id (lenient source).\n const worktrees: WorktreeInfo[] = currentWorktrees.flatMap((branch) => {\n const id = parseBranchName(branch)\n\n if (!id) return []\n\n // Human label `1.2.3` | `<name>`; Jira-descriptions map is keyed by the\n // Jira version NAME (`v1.2.3` | `<name>`) \u2014 same split as formatBranchChoices.\n const version = displayLabel(id)\n const type = releaseTypes.get(branch) || 'regular'\n const description = jiraDescriptions.get(formatJiraName(id)) || null\n\n return [{ version, type, description }]\n })\n\n // Log formatted output\n const maxVersionLength = Math.max(\n ...worktrees.map((w) => {\n return w.version.length\n }),\n )\n\n const formattedLines = worktrees.map((worktree) => {\n const label = formatVersionLabel(worktree.version, worktree.type, maxVersionLength)\n\n if (worktree.description) {\n return `${label} ${worktree.description}`\n }\n\n return label\n })\n\n // One record, no trailing newline. Two calls made pino-pretty emit a bare `INFO:` line for the\n // leading `\\n`, and the trailing one stacked a second blank line under the list \u2014 which, in the\n // session shell, collided with the blank line the transcript footer already writes above itself.\n logger.info(`\uD83C\uDF3F Active worktrees:\\n\\n${formattedLines.join('\\n')}`)\n\n const structuredContent = {\n worktrees,\n count: worktrees.length,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const worktreesListMcpTool = defineMcpTool({\n name: 'worktrees-list',\n description:\n 'List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.',\n inputSchema: {},\n outputSchema: {\n worktrees: z\n .array(\n z.object({\n version: z.string().describe('Release version'),\n type: z.enum(['regular', 'hotfix']).describe('Release type'),\n description: z.string().nullable().describe('Jira version description'),\n }),\n )\n .describe('List of all worktrees with details'),\n count: z.number().describe('Number of worktrees'),\n },\n handler: worktreesList,\n})\n", "import { z } from 'zod'\n\nimport { getReleasePRsWithInfo } from 'src/integrations/gh'\nimport { removeIdeWorktreeFolders } from 'src/integrations/ide'\nimport { commandEcho, confirmOrExit } from 'src/lib/command-echo'\nimport { WORKTREES_DIR_SUFFIX } from 'src/lib/constants'\nimport { isPromptCancellation } from 'src/lib/errors/is-prompt-cancellation'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { assertManagementContext } from 'src/lib/git-guard'\nimport { getCurrentWorktrees, getProjectRoot } from 'src/lib/git-utils'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { isMcpMode } from 'src/lib/mcp-mode'\nimport { pickReleaseBranches } from 'src/lib/prompts/release-picker'\nimport { formatBranchName, parseReleaseRef } from 'src/lib/release-id'\nimport {\n detectReleaseType,\n formatBranchPickerItems,\n getJiraDescriptions,\n releaseBranchLabels,\n} from 'src/lib/release-utils'\nimport type { ReleaseType } from 'src/lib/release-utils'\nimport { removeWorktrees } from 'src/lib/worktrees'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { RequiredConfirmedOptionArg } from 'src/types'\n\n// Constants\ninterface WorktreeManagementArgs extends RequiredConfirmedOptionArg {\n all?: boolean\n versions?: string\n}\n\n/**\n * MCP has no TTY (JSON-RPC owns stdin) and the boundary auto-confirms, so the branch picker is\n * unreachable and a bulk removal would run without any human gate. `all` is intentionally absent from\n * this tool's MCP inputSchema; guard the shared handler too so a direct/agent call can never fan out to\n * every worktree. Require MCP callers to name targets explicitly via `versions`. No-op on the CLI path.\n */\nconst assertMcpRemovalInput = (input: { all?: boolean; versions?: string }): void => {\n if (!isMcpMode()) return\n\n if (input.all) {\n throw new OperationError(undefined, {\n operation: 'remove worktrees',\n remediation: 'name targets explicitly via \"versions\"; bulk all=true removal is disabled over MCP',\n stderrExcerpt: 'all=true is not permitted for worktrees-remove over MCP',\n })\n }\n\n if (!input.versions) {\n throw new OperationError(undefined, {\n operation: 'remove worktrees',\n remediation: 'pass \"versions\" (comma-separated release versions/names); the interactive picker needs a TTY',\n stderrExcerpt: 'worktrees-remove over MCP requires \"versions\"',\n })\n }\n}\n\n/**\n * Every named target must be an active release worktree. Without this an unmatched version builds a\n * path that does not exist; `removeWorktrees` (Promise.allSettled) swallows the failure and reports a\n * no-op as success. Validate all-or-nothing BEFORE removing anything so a typo or a feature-worktree\n * name fails loudly on both the CLI `--versions` and the MCP path. The `all` and interactive-picker\n * paths select from `currentWorktrees`, so this is a no-op for them.\n */\nconst assertTargetsExist = (selected: string[], currentWorktrees: string[]): void => {\n const unmatched = selected.filter((branch) => {\n return !currentWorktrees.includes(branch)\n })\n\n if (unmatched.length > 0) {\n throw new OperationError(undefined, {\n operation: 'remove worktrees',\n remediation: `no active worktree for: ${unmatched.join(', ')}. Run 'infra-kit worktrees list' to see current worktrees`,\n stderrExcerpt: `unmatched worktree target(s): ${unmatched.join(', ')}`,\n })\n }\n}\n\n/**\n * Manage git worktrees for release branches\n * Creates worktrees for active release branches and removes unused ones\n */\nexport const worktreesRemove = async (options: WorktreeManagementArgs) => {\n const { confirmedCommand, all, versions } = options\n\n // Branch-agnostic: `git worktree remove` addresses worktrees by path and never\n // reads HEAD, so only the worktree + clean-tree legs apply.\n await assertManagementContext({ operation: 'remove worktrees' })\n\n // GUARD (placement is load-bearing): must stay ABOVE the `try` block below \u2014 its catch rewraps, and\n // getInfraKitConfig's missing-config throw is a PLAIN Error whose text buildMessage would drop.\n // Must stay BELOW assertManagementContext so a linked-worktree caller still gets the worktree advice.\n // Kept ABOVE assertMcpRemovalInput: \"not an infra-kit project\" is the more fundamental failure.\n await getInfraKitConfig()\n\n assertMcpRemovalInput({ all, versions })\n\n try {\n const currentWorktrees = await getCurrentWorktrees('release')\n\n if (currentWorktrees.length === 0) {\n logger.info('\u2139\uFE0F No active worktrees to remove')\n\n commandEcho.print()\n\n return {\n content: textContent(JSON.stringify({ removedWorktrees: [], count: 0 }, null, 2)),\n structuredContent: { removedWorktrees: [], count: 0 },\n }\n }\n\n const projectRoot = await getProjectRoot()\n\n const worktreeDir = `${projectRoot}${WORKTREES_DIR_SUFFIX}`\n\n let selectedReleaseBranches: string[] = []\n\n if (all) {\n selectedReleaseBranches = currentWorktrees\n } else if (versions) {\n selectedReleaseBranches = versions.split(',').map((v) => {\n return formatBranchName(parseReleaseRef(v.trim()))\n })\n } else {\n commandEcho.setInteractive()\n\n const [descriptions, prInfo] = await Promise.all([getJiraDescriptions(), getReleasePRsWithInfo()])\n\n const releaseTypes = new Map<string, ReleaseType>(\n prInfo.map((pr) => {\n return [pr.branch, detectReleaseType(pr.title)]\n }),\n )\n\n selectedReleaseBranches = await pickReleaseBranches(\n formatBranchPickerItems({ branches: currentWorktrees, descriptions, types: releaseTypes }),\n { required: true },\n )\n }\n\n assertTargetsExist(selectedReleaseBranches, currentWorktrees)\n\n // Track --all flag if all branches were selected (either via flag or interactively)\n const allSelected = selectedReleaseBranches.length === currentWorktrees.length\n\n if (allSelected) {\n commandEcho.addOption('--all', true)\n } else {\n commandEcho.addOption('--versions', releaseBranchLabels(selectedReleaseBranches))\n }\n\n // Ask for confirmation\n await confirmOrExit(confirmedCommand, 'Are you sure you want to proceed with these worktree changes?')\n\n // Track --yes flag if confirmation was interactive (user confirmed)\n if (!confirmedCommand) {\n commandEcho.addOption('--yes', true)\n }\n\n const removedWorktrees = await removeWorktrees({\n branches: selectedReleaseBranches,\n worktreeDir,\n pruneFolder: allSelected,\n })\n\n // `!confirmedCommand` is the interactive path (a human used the picker/confirm). Only there\n // do we let Zed's destructive `--reuse` relaunch fire; MCP/--yes runs (confirmedCommand=true)\n // and worktrees-sync never relaunch an editor window.\n await removeIdeWorktreeFolders({\n projectRoot,\n worktreeDir,\n currentWorktrees,\n removedWorktrees,\n allowEditorRelaunch: !confirmedCommand,\n })\n\n logResults(removedWorktrees)\n\n commandEcho.print()\n\n const structuredContent = {\n removedWorktrees,\n count: removedWorktrees.length,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n } catch (error) {\n // A cancelled prompt (Ctrl-C / Esc) is a user back-out, not a failure: let it\n // reach the top-level boundary untouched so it exits cleanly, instead of being\n // logged as an error with a misleading remediation.\n if (isPromptCancellation(error)) throw error\n\n // Our own guard failures (unmatched target, MCP misuse) already carry an actionable remediation;\n // surface them as-is instead of re-wrapping them with the generic message below.\n if (error instanceof OperationError) throw error\n\n logger.error({ error }, '\u274C Error managing worktrees')\n throw new OperationError(error, {\n operation: 'remove worktrees',\n remediation: \"check 'git worktree list' for the path; uncommitted changes block removal\",\n })\n }\n}\n\n/**\n * Log the results of worktree management\n */\nconst logResults = (removed: string[]): void => {\n if (removed.length > 0) {\n logger.info('\u274C Removed worktrees:')\n for (const branch of removed) {\n logger.info(branch)\n }\n logger.info('')\n } else {\n logger.info('\u2139\uFE0F No unused worktrees to remove')\n }\n}\n\n// MCP Tool Registration\nexport const worktreesRemoveMcpTool = defineMcpTool({\n name: 'worktrees-remove',\n description:\n 'Remove local git worktrees for the named release branches. Over MCP you MUST pass \"versions\" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs \"git worktree prune\".',\n requiresHumanConfirm: true,\n inputSchema: {\n versions: z\n .string()\n .describe(\n 'Comma-separated release versions or names to remove (e.g. \"1.2.5, 1.2.6\" or \"checkout-redesign, 1.2.5\"). Required: each must name an active worktree, or the call errors before removing anything.',\n ),\n confirm: z\n .boolean()\n .optional()\n .describe('Set true to execute; omit for a dry-run gate that echoes the resolved action.'),\n },\n outputSchema: {\n removedWorktrees: z.array(z.string()).describe('List of removed git worktree branches'),\n count: z.number().describe('Number of git worktrees removed'),\n },\n handler: worktreesRemove,\n})\n", "import { z } from 'zod'\nimport { $ } from 'zx'\n\nimport { closeCmuxWorkspaceByCwd } from 'src/integrations/cmux'\nimport { getReleasePRs } from 'src/integrations/gh'\nimport { removeIdeWorktreeFolders } from 'src/integrations/ide'\nimport { commandEcho, confirmOrExit } from 'src/lib/command-echo'\nimport { WORKTREES_DIR_SUFFIX } from 'src/lib/constants'\nimport { isPromptCancellation } from 'src/lib/errors/is-prompt-cancellation'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { assertManagementContext } from 'src/lib/git-guard'\nimport { getCurrentWorktrees, getProjectRoot } from 'src/lib/git-utils'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { isReleaseBranch } from 'src/lib/release-id'\nimport { defineMcpTool, textContent } from 'src/types'\nimport type { RequiredConfirmedOptionArg } from 'src/types'\n\ninterface WorktreeSyncArgs extends RequiredConfirmedOptionArg {}\n\n/**\n * Manage git worktrees for release branches.\n *\n * Creates worktrees for active release branches and removes unused ones\n */\nexport const worktreesSync = async (options: WorktreeSyncArgs) => {\n const { confirmedCommand } = options\n\n // Branch-agnostic: reconciles worktrees by name/path and never reads HEAD, so\n // only the worktree + clean-tree legs apply. Load-bearing on the MCP path,\n // which runs this unattended \u2014 a branch requirement there would refuse a\n // cleanup that has no quarrel with the caller's checkout.\n await assertManagementContext({ operation: 'sync worktrees' })\n\n // GUARD (placement is load-bearing): must stay ABOVE the `try` block below \u2014 its catch rewraps, and\n // getInfraKitConfig's missing-config throw is a PLAIN Error whose text buildMessage would drop.\n // Must stay BELOW assertManagementContext so a linked-worktree caller still gets the worktree advice.\n await getInfraKitConfig()\n\n try {\n const currentWorktrees = await getCurrentWorktrees('release')\n const projectRoot = await getProjectRoot()\n\n const worktreeDir = `${projectRoot}${WORKTREES_DIR_SUFFIX}`\n\n const releasePRsList = await getReleasePRs()\n\n // Ask for confirmation\n await confirmOrExit(confirmedCommand, 'Are you sure you want to proceed with these worktree changes?')\n\n // Track --yes flag if confirmation was interactive (user confirmed)\n if (!confirmedCommand) {\n commandEcho.addOption('--yes', true)\n }\n\n const { branchesToRemove } = categorizeWorktrees({\n releasePRsList,\n currentWorktrees,\n })\n\n const removedWorktrees = await removeWorktrees({\n branches: branchesToRemove,\n worktreeDir,\n })\n\n // Hard `false`: sync is background/stale-cleanup (predominantly the MCP path) \u2014 it must never\n // relaunch and overwrite a focused Zed window. Zed removal stays a no-op here.\n await removeIdeWorktreeFolders({\n projectRoot,\n worktreeDir,\n currentWorktrees,\n removedWorktrees,\n allowEditorRelaunch: false,\n })\n\n logResults(removedWorktrees)\n\n commandEcho.print()\n\n const structuredContent = {\n removedWorktrees,\n count: removedWorktrees.length,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n } catch (error) {\n // A cancelled prompt (Ctrl-C / Esc) is a user back-out, not a failure: let it\n // reach the top-level boundary untouched so it exits cleanly, instead of being\n // logged as an error with a misleading remediation.\n if (isPromptCancellation(error)) throw error\n\n logger.error({ error }, '\u274C Error managing worktrees')\n throw new OperationError(error, {\n operation: 'sync worktrees with remote',\n remediation: \"ensure 'gh auth status' is ok and you can reach origin\",\n })\n }\n}\n\ninterface CategorizeWorktreesArgs {\n releasePRsList: string[]\n currentWorktrees: string[]\n}\n\n/**\n * Categorize worktrees into those that need to be created or removed\n */\nconst categorizeWorktrees = (args: CategorizeWorktreesArgs): { branchesToRemove: string[] } => {\n const { releasePRsList, currentWorktrees } = args\n\n const currentBranchNames = currentWorktrees.filter((branch) => {\n return isReleaseBranch(branch)\n })\n\n const branchesToRemove = currentBranchNames.filter((branch) => {\n return !releasePRsList.includes(branch)\n })\n\n return { branchesToRemove }\n}\n\ninterface RemoveWorktreesArgs {\n branches: string[]\n worktreeDir: string\n}\n\n/**\n * Remove worktrees for the specified branches and close their cmux workspaces\n */\nconst removeWorktrees = async (args: RemoveWorktreesArgs): Promise<string[]> => {\n const { branches, worktreeDir } = args\n\n const removed: string[] = []\n\n for (const branch of branches) {\n try {\n const worktreePath = `${worktreeDir}/${branch}`\n\n // Close the cmux workspace by cwd (before `git worktree remove`, so the path\n // still exists); anchors are excluded so a group header is never closed.\n await closeCmuxWorkspaceByCwd(worktreePath)\n\n await $`git worktree remove ${worktreePath}`\n removed.push(branch)\n } catch (error) {\n const err = new OperationError(error, {\n operation: `remove stale worktree for ${branch}`,\n remediation: 'inspect the worktree dir manually; rerun with the branch checked out elsewhere',\n })\n\n logger.error({ error, branch, msg: err.message })\n }\n }\n\n return removed\n}\n\n/**\n * Log the results of worktree management\n */\nconst logResults = (removed: string[]): void => {\n if (removed.length > 0) {\n logger.info('\u274C Removed worktrees:')\n for (const branch of removed) {\n logger.info(branch)\n }\n logger.info('')\n } else {\n logger.info('\u2139\uFE0F No unused worktrees to remove')\n }\n}\n\n// MCP Tool Registration\nexport const worktreesSyncMcpTool = defineMcpTool({\n name: 'worktrees-sync',\n description:\n 'Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.',\n inputSchema: {},\n outputSchema: {\n removedWorktrees: z.array(z.string()).describe('List of removed worktree branches'),\n count: z.number().describe('Number of worktrees removed during sync'),\n },\n handler: worktreesSync,\n})\n", "import type { z } from 'zod'\n\nimport { auditMcpTool } from 'src/commands/audit'\nimport { configGetMcpTool } from 'src/commands/config-get'\nimport { devStatusMcpTool } from 'src/commands/dev-status'\nimport { doctorMcpTool } from 'src/commands/doctor'\nimport { envClearMcpTool } from 'src/commands/env-clear'\nimport { envListMcpTool } from 'src/commands/env-list'\nimport { envLoadMcpTool } from 'src/commands/env-load'\nimport { envStatusMcpTool } from 'src/commands/env-status'\nimport { envTokenListMcpTool } from 'src/commands/env-token-list'\nimport { ghMergeDevMcpTool } from 'src/commands/gh-merge-dev'\nimport { ghReleaseDeliverMcpTool } from 'src/commands/gh-release-deliver'\nimport { ghReleaseDeployAllMcpTool } from 'src/commands/gh-release-deploy-all'\nimport { ghReleaseDeploySelectedMcpTool } from 'src/commands/gh-release-deploy-selected'\nimport { ghReleaseListMcpTool } from 'src/commands/gh-release-list'\nimport { releaseCreateMcpTool } from 'src/commands/release-create'\nimport { releaseDescEditMcpTool } from 'src/commands/release-desc-edit'\nimport { reopenMcpTool } from 'src/commands/reopen'\nimport { vendorCheckMcpTool } from 'src/commands/vendor-check'\nimport { versionMcpTool } from 'src/commands/version'\nimport { worktreesAddMcpTool } from 'src/commands/worktrees-add'\nimport { worktreesListMcpTool } from 'src/commands/worktrees-list'\nimport { worktreesRemoveMcpTool } from 'src/commands/worktrees-remove'\nimport { worktreesSyncMcpTool } from 'src/commands/worktrees-sync'\nimport type { ToolsExecutionResult } from 'src/types'\n\n/**\n * Registration-facing shape of an MCP tool. The concrete `*McpTool` definitions\n * are generic over their Zod input/output shapes (and invariant), so they cannot\n * share one precise `McpTool<...>` element type in an array. This widened, non-\n * generic view exposes exactly what registration needs and every concrete tool\n * assigns to it. Matches the loose handler typing already used in tool-handler.\n */\nexport interface CatalogMcpTool {\n name: string\n description: string\n inputSchema: z.ZodRawShape\n outputSchema: z.ZodRawShape\n /**\n * Marks a destructive tool for the orthogonal MCP confirm gate in `lib/tool-handler`. Widened,\n * non-generic mirror of {@link McpTool.requiresHumanConfirm} so registration (`mcp/tools/index.ts`)\n * can forward it to `createToolHandler` without reaching into the concrete generic tool type.\n */\n requiresHumanConfirm?: boolean\n // Heterogeneous tool params; loose `any` mirrors the existing tool-handler typing.\n handler: (params: any) => Promise<ToolsExecutionResult>\n}\n\n/**\n * Single source of truth for the CLI command surface. It consolidates what used\n * to live in three hand-maintained places (the MCP `tools[]` array and the\n * three no-arg-menu name arrays) into one list, so they can no longer drift.\n *\n * It does NOT replace Commander's `.command().option()` wiring in entry/cli.ts \u2014\n * that stays the source of truth for argument parsing. This catalog only carries\n * cross-surface metadata: the canonical names, which menu group a command shows\n * in, and whether the command is exposed as an MCP tool.\n */\n\n/**\n * The menu groups, in display order \u2014 the SINGLE source of both membership and presentation. `cli.ts`\n * renders the palette by mapping over this list, so adding, renaming, or reordering a group is a\n * one-line edit here and nowhere else. (The group list used to be restated three times in `cli.ts`, and\n * the labels a fourth time in the Inquirer separators.)\n *\n * One group per CLI noun, ordered by how often it is reached for. `Develop` leads because `dev` is the\n * daily driver. `Environment` means the Doppler env commands and nothing else \u2014 it used to be a\n * 13-entry drawer holding config, vendor, and setup commands too, which made its name a lie.\n */\nexport const MENU_GROUPS = [\n { key: 'develop', label: 'Develop' },\n { key: 'release', label: 'Release Management' },\n { key: 'worktrees', label: 'Worktrees' },\n { key: 'environment', label: 'Environment' },\n { key: 'configuration', label: 'Configuration' },\n { key: 'vendor', label: 'Vendor' },\n { key: 'setup', label: 'Setup & Diagnostics' },\n] as const\n\n/** Top-level menu group for the no-arg interactive picker (null = not shown). */\nexport type MenuGroup = (typeof MENU_GROUPS)[number]['key']\n\nexport interface CommandCatalogEntry {\n /**\n * Stable flat id for the command (`release-create`), and the name its MCP tool registers under \u2014 MCP\n * tool names cannot contain a space, so the grouped path cannot serve as one.\n *\n * NOT a CLI surface: the CLI registers only the grouped form ({@link groupPath}). Flat Commander\n * commands were removed once every menu surface learned to address a command by its group path.\n */\n cliName: string\n /** Menu group, or null for subcommands not shown at the top level. */\n menuGroup: MenuGroup | null\n /** The co-located MCP tool, or null for CLI-only commands (init/config/vendor group). */\n mcpTool: CatalogMcpTool | null\n /**\n * Whether the command is registered as an MCP tool. Explicit allowlist:\n * `doctor` is deliberately UNEXPOSED (host-inspecting), so it must never become\n * agent-callable by accident.\n */\n mcpExposed: boolean\n /**\n * Whether running this command writes git/remote/consumer-repo/Doppler-env/fs-outside-cache state.\n * Drives the MCP destructive-op gate (Phase 4).\n */\n mutating: boolean\n /**\n * Canonical Commander argv for this command (grouped form, e.g. `['vendor','check']`) \u2014 the ONLY form\n * the CLI registers. Every menu surface renders `groupPath.join(' ')` and spawns/parses\n * `infra-kit <...groupPath>`, so what the palette shows is exactly what it runs and what the user can\n * retype.\n */\n groupPath: string[]\n /**\n * The command hands the terminal to a full-screen child (an `$EDITOR`) that enters the alternate\n * screen and restores it itself. The session never enters it for them \u2014 but a child killed before it\n * restores the primary buffer would leave every later frame drawn into an abandoned buffer, so the\n * session's post-child hygiene reset leaves the alternate screen defensively. Only `config-edit`.\n */\n entersAltScreen?: boolean\n /**\n * Running this from inside the session cannot mutate the parent shell's env (a child can't). The\n * transcript entry appends a notice that the change applies only after the session exits. `env-load`\n * / `env-clear`.\n */\n sessionEnvNotice?: boolean\n /**\n * A foreground process that runs until the user stops it, rather than doing a unit of work and\n * exiting. Only `dev`. It breaks BOTH of the session shell's assumptions about a child, so the two\n * consequences are deliberately carried by ONE flag \u2014 they must never be set apart:\n *\n * 1. **It produces no verdict.** Its Commander action RESOLVES seconds after boot (the process stays\n * alive on fastify/chokidar handles, not on a pending promise), so `postAction` would write a\n * session report while the server is merely *starting*. Report-presence means \"the command produced\n * a verdict\" (see `session/report.ts`), so the report is suppressed for it entirely.\n * 2. **It exits `128 + signo`, not 0.** It installs its own SIGINT handler and exits 130 on a Ctrl-C\n * \u2014 deliberately, so a supervisor sees an honest signal death. Without this flag the session would\n * read that as a failure and stamp every normal dev exit `\u2717 failed`.\n */\n longRunning?: boolean\n}\n\n/**\n * Authored in no-arg-menu display order so the interactive picker derives\n * directly from this list (see entry/cli.ts). MCP registration filters this\n * list by `mcpExposed`; MCP tool order is not contractual (clients address\n * tools by name), so the registration order need not match the array order.\n */\nexport const commandCatalog: CommandCatalogEntry[] = [\n // --- Develop (menu group) ---\n // The local dev server, and the reason most people open this menu at all \u2014 so it leads.\n //\n // It is a long-running foreground child, which the one-shot Inquirer menu could not host: that menu\n // ran the pick IN-PROCESS, so a dev server would have blocked the menu process forever. The session\n // shell spawns every pick as a separate child on the primary screen and swallows SIGINT while one\n // runs, so Ctrl-C stops only the dev server and the palette comes back. See `longRunning` for the two\n // session assumptions it still breaks (no verdict; exits 128+signo).\n //\n // Spawning the BARE `['dev']` path is deliberate: `shouldRunWizard` fires on exactly bare + TTY +\n // non-json, so a menu pick lands in the interactive wizard \u2014 the wizard IS the flag picker.\n //\n // Not an MCP tool: it never returns a result, so it cannot fit the request/response tool contract.\n {\n cliName: 'dev',\n menuGroup: 'develop',\n mcpTool: null,\n mcpExposed: false,\n mutating: true,\n groupPath: ['dev'],\n longRunning: true,\n },\n // Read-only companion to `dev`: reports what `infra-kit dev` currently has running by reading the\n // on-disk dev-context fragments (never starts a server). Top-level (`infra-kit dev-status`) per the\n // house rule \u2014 new commands go top-level with related names, not nested under a group \u2014 but carries\n // menuGroup 'develop' so it renders beside `dev` in the palette (same shape as reopen/env-status).\n {\n cliName: 'dev-status',\n menuGroup: 'develop',\n mcpTool: devStatusMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['dev-status'],\n },\n\n // --- Release Management (menu group) ---\n {\n cliName: 'merge-dev',\n menuGroup: 'release',\n mcpTool: ghMergeDevMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['release', 'merge-dev'],\n },\n {\n cliName: 'release-list',\n menuGroup: 'release',\n mcpTool: ghReleaseListMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['release', 'list'],\n },\n {\n cliName: 'release-create',\n menuGroup: 'release',\n mcpTool: releaseCreateMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['release', 'create'],\n },\n {\n cliName: 'release-desc-edit',\n menuGroup: 'release',\n mcpTool: releaseDescEditMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['release', 'desc-edit'],\n },\n {\n cliName: 'release-deploy-all',\n menuGroup: 'release',\n mcpTool: ghReleaseDeployAllMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['release', 'deploy-all'],\n },\n {\n cliName: 'release-deploy-selected',\n menuGroup: 'release',\n mcpTool: ghReleaseDeploySelectedMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['release', 'deploy-selected'],\n },\n // release-deliver does prod delivery + admin-merge \u2014 genuinely irreversible,\n // so it is CLI-only by design.\n {\n cliName: 'release-deliver',\n menuGroup: 'release',\n mcpTool: ghReleaseDeliverMcpTool,\n mcpExposed: false,\n mutating: true,\n groupPath: ['release', 'deliver'],\n },\n\n // --- Worktrees (menu group) ---\n {\n cliName: 'worktrees-add',\n menuGroup: 'worktrees',\n mcpTool: worktreesAddMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['worktrees', 'add'],\n },\n {\n cliName: 'worktrees-list',\n menuGroup: 'worktrees',\n mcpTool: worktreesListMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['worktrees', 'list'],\n },\n // `reopen` is a top-level command (`infra-kit reopen`, groupPath ['reopen']) but carries\n // menuGroup 'worktrees' so it renders alongside its kin in the palette \u2014 the same single-segment\n // top-level + non-matching-menuGroup shape as env-status/env-load (['env-status'] + 'environment').\n {\n cliName: 'reopen',\n menuGroup: 'worktrees',\n mcpTool: reopenMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['reopen'],\n },\n // worktrees-remove runs `git worktree remove` (no --force) on the named leaf worktrees. It is NOT\n // irreversible in the way release-deliver is: the release branches/commits survive, the\n // worktrees scaffold is left in place, and worktrees-add recreates a removed worktree. git also\n // refuses to remove a worktree with modified-tracked or untracked files. The residual risk \u2014\n // deletion of gitignored local state (a hydrated `.env` of Doppler secrets, node_modules/dist) \u2014 is\n // contained by the tool's own invariants rather than by withholding it: over MCP it rejects\n // all=true (no one-shot wipe) and errors on any unmatched target before removing anything. So it is\n // exposed, unlike the genuinely-irreversible release-deliver.\n {\n cliName: 'worktrees-remove',\n menuGroup: 'worktrees',\n mcpTool: worktreesRemoveMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['worktrees', 'remove'],\n },\n {\n cliName: 'worktrees-sync',\n menuGroup: 'worktrees',\n mcpTool: worktreesSyncMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['worktrees', 'sync'],\n },\n\n // --- Environment (menu group): the Doppler env commands, and ONLY those ---\n // Every menu-eligible entry must be a Commander LEAF (an action, no subcommands) so the session\n // shell's report discriminator holds. The bare `vendor`/`config` GROUPS are menuGroup:null \u2014 a bare\n // group prints help and exits non-zero, which the shell would misreport. Their useful leaves\n // (vendor-check/diff/config, config-path/edit) are surfaced in the Vendor/Configuration groups below,\n // each with a hidden flat Commander alias (see src/lib/program/program.ts) so the palette can\n // introspect + single-token dispatch.\n {\n cliName: 'env-status',\n menuGroup: 'environment',\n mcpTool: envStatusMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['env-status'],\n },\n {\n cliName: 'env-list',\n menuGroup: 'environment',\n mcpTool: envListMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['env-list'],\n },\n {\n cliName: 'env-load',\n menuGroup: 'environment',\n mcpTool: envLoadMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['env-load'],\n sessionEnvNotice: true,\n },\n {\n cliName: 'env-clear',\n menuGroup: 'environment',\n mcpTool: envClearMcpTool,\n mcpExposed: true,\n mutating: true,\n groupPath: ['env-clear'],\n sessionEnvNotice: true,\n },\n // The only env-token command that is agent-callable. It READS, and only ever emits redacted values.\n {\n cliName: 'env-token-list',\n menuGroup: 'environment',\n mcpTool: envTokenListMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['env-token-list'],\n },\n\n // --- Configuration (menu group) ---\n // Read-only merged-config introspection. Top-level (`infra-kit config-get`) per the house rule \u2014 new\n // commands go top-level with related names \u2014 but menuGroup 'configuration' renders it beside\n // `config path`/`config edit`. Exposed to agents (mutating:false); `config edit` stays CLI-only for writes.\n {\n cliName: 'config-get',\n menuGroup: 'configuration',\n mcpTool: configGetMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['config-get'],\n },\n {\n cliName: 'config-path',\n menuGroup: 'configuration',\n mcpTool: null,\n mcpExposed: false,\n mutating: false,\n groupPath: ['config', 'path'],\n },\n {\n cliName: 'config-edit',\n menuGroup: 'configuration',\n mcpTool: null,\n mcpExposed: false,\n mutating: true,\n groupPath: ['config', 'edit'],\n entersAltScreen: true,\n },\n\n // --- Vendor (menu group) ---\n {\n cliName: 'vendor-check',\n menuGroup: 'vendor',\n mcpTool: vendorCheckMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['vendor', 'check'],\n },\n {\n cliName: 'vendor-config',\n menuGroup: 'vendor',\n mcpTool: null,\n mcpExposed: false,\n mutating: true,\n groupPath: ['vendor', 'config'],\n },\n\n // --- Setup & Diagnostics (menu group) ---\n // `init`/`doctor` set the machine up and check it; `audit` checks the REPO against its config rules.\n // Both answer \"is this in a good state?\", which is why they sit together.\n { cliName: 'init', menuGroup: 'setup', mcpTool: null, mcpExposed: false, mutating: true, groupPath: ['init'] },\n {\n cliName: 'doctor',\n menuGroup: 'setup',\n mcpTool: doctorMcpTool,\n mcpExposed: false,\n mutating: true,\n groupPath: ['doctor'],\n },\n {\n cliName: 'audit',\n menuGroup: 'setup',\n mcpTool: auditMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['audit'],\n },\n {\n cliName: 'version',\n menuGroup: 'setup',\n mcpTool: versionMcpTool,\n mcpExposed: true,\n mutating: false,\n groupPath: ['version'],\n },\n\n // --- Not menu items (groups, long-running, or internal) ---\n // Bare groups: help + non-zero exit, so they never belong in the leaf-only menu.\n { cliName: 'vendor', menuGroup: null, mcpTool: null, mcpExposed: false, mutating: false, groupPath: ['vendor'] },\n { cliName: 'config', menuGroup: null, mcpTool: null, mcpExposed: false, mutating: false, groupPath: ['config'] },\n // Internal shell-startup trigger; hidden from the menu and never an MCP tool\n // (it can't apply env to a shell \u2014 only the zsh integration sources the file).\n {\n cliName: 'env-autoload',\n menuGroup: null,\n mcpTool: null,\n mcpExposed: false,\n mutating: true,\n groupPath: ['env-autoload'],\n },\n // env-token-set / env-token-remove carry NO MCP tool at all \u2014 not merely `mcpExposed: false`, so\n // there is nothing to accidentally flip on. `lib/tool-handler` injects `confirmedCommand: true` into\n // EVERY tool call, so the MCP boundary auto-confirms by construction: an agent must never be one call\n // away from WRITING a credential or DESTROYING one. Same argument that keeps `doctor --fix` CLI-only.\n // menuGroup is null because both take a required `<env>` argument the no-arg menu cannot supply.\n {\n cliName: 'env-token-set',\n menuGroup: null,\n mcpTool: null,\n mcpExposed: false,\n mutating: true,\n groupPath: ['env-token-set'],\n },\n {\n cliName: 'env-token-remove',\n menuGroup: null,\n mcpTool: null,\n mcpExposed: false,\n mutating: true,\n groupPath: ['env-token-remove'],\n },\n // The MCP boundary auto-confirms every tool, so an agent-triggered unattended global package install\n // must never be reachable there. menuGroup null keeps it off the no-arg picker too \u2014 updating the CLI\n // is a deliberate act, not something to land on by arrowing through a menu.\n {\n cliName: 'self-update',\n menuGroup: null,\n mcpTool: null,\n mcpExposed: false,\n mutating: true,\n groupPath: ['self-update'],\n },\n // Launcher for the MCP server itself; it blocks on a stdio transport, so it is neither a one-shot menu\n // command nor expressible as a request/response tool.\n { cliName: 'mcp', menuGroup: null, mcpTool: null, mcpExposed: false, mutating: false, groupPath: ['mcp'] },\n]\n\n/**\n * Mutating, MCP-exposed tools that are DELIBERATELY exempt from the destructive-op confirm gate\n * (`mcpTool.requiresHumanConfirm`) because each is low-risk / reversible. Hand-maintained: adding a\n * name here is the ONLY sanctioned way to opt a mutating exposed tool out of the gate, and the\n * default-deny test (`command-catalog.test.ts`) reds CI for any mutating+exposed tool that is neither\n * gated nor listed here. Every member carries a one-line justification so an audit reads at a glance.\n */\nexport const LOW_RISK_MUTATING_ALLOWLIST: readonly string[] = [\n // Edits a GitHub release body only \u2014 reversible by re-editing; no git/branch/deploy side effect.\n 'release-desc-edit',\n // Purely additive: creates worktrees for existing release branches; removing them is a separate op.\n 'worktrees-add',\n // Reconciles the worktree set to the live release branches; recreatable via worktrees-add.\n 'worktrees-sync',\n // Writes a load file under the infra-kit cache dir; cleared by env-clear, no remote/git effect.\n 'env-load',\n]\n\n/** The MCP tools to register: catalog entries that are exposed and carry a tool. */\nexport const getExposedMcpTools = (): CatalogMcpTool[] => {\n return commandCatalog.flatMap((entry) => {\n return entry.mcpExposed && entry.mcpTool ? [entry.mcpTool] : []\n })\n}\n\n/**\n * Catalog entries for a menu group, in catalog (display) order.\n *\n * Yields ENTRIES, not names: every menu surface addresses a command by its {@link\n * CommandCatalogEntry.groupPath} (`['release','create']`), which is both what it renders and what it\n * spawns. `cliName` is an id \u2014 the MCP tool name, which cannot hold a space \u2014 and is not a CLI surface.\n *\n * @example\n * getMenuGroupEntries('vendor').map((entry) => entry.groupPath.join(' ')) // => ['vendor check', \u2026]\n */\nexport const getMenuGroupEntries = (group: MenuGroup): CommandCatalogEntry[] => {\n return commandCatalog.filter((entry) => {\n return entry.menuGroup === group\n })\n}\n\n/**\n * True when the invoked command runs until the user stops it (see {@link CommandCatalogEntry.longRunning}).\n * Keyed by the SPACE-JOINED Commander path (`'dev'`, `'vendor check'`) so it matches what `commandPath()`\n * hands the `postAction` hook, not the flat alias.\n *\n * @example\n * isLongRunningCommand('dev') // => true (no verdict to report; exits 128+signo)\n * isLongRunningCommand('vendor check') // => false\n */\nexport const isLongRunningCommand = (commandPath: string): boolean => {\n return commandCatalog.some((entry) => {\n return entry.longRunning === true && entry.groupPath.join(' ') === commandPath\n })\n}\n", "import process from 'node:process'\n\n/**\n * Node's warning code for \"I had to guess this file's module type\".\n *\n * Emitted when Node loads a `.ts` (or extensionless-ambiguous) file whose nearest\n * `package.json` declares no `\"type\"`: it first tries to parse the source as\n * CommonJS, fails on the ESM syntax, then reparses as an ES module and warns\n * about the double parse.\n */\nconst TYPELESS_PACKAGE_JSON = 'MODULE_TYPELESS_PACKAGE_JSON'\n\n/** Read the warning `code` out of either `emitWarning` overload. */\nconst readWarningCode = (typeOrOptions: unknown, codeOrCtor: unknown): unknown => {\n // emitWarning(warning, options) \u2014 the code lives on the options object.\n if (typeof typeOrOptions === 'object' && typeOrOptions !== null) {\n return (typeOrOptions as { code?: unknown }).code\n }\n\n // emitWarning(warning, type, code, ctor) \u2014 the code is the third argument.\n return codeOrCtor\n}\n\nlet installed = false\n\n/**\n * Silence Node's `MODULE_TYPELESS_PACKAGE_JSON` warning for the rest of this\n * process, leaving every other warning untouched.\n *\n * The CLI imports config files it does not own \u2014 `infra-kit.config.ts` inside a\n * consumer's `apps/<app>/ui` \u2014 via `await import()`, relying on Node's native\n * type stripping. When that package declares no `\"type\"`, Node reparses the\n * config and prints a four-line warning naming a `package.json` that belongs to\n * the consumer, not to us.\n *\n * We swallow it rather than push `\"type\": \"module\"` onto consumers, because we\n * are the ones who chose the `.ts` config format and a published tool cannot\n * assume every package it reads a config from is ESM. (In our own repos this is\n * currently rare \u2014 79 of 80 packages carrying an `infra-kit.config.ts` already\n * declare `\"type\": \"module\"`. The lone holdout is a Docusaurus app whose\n * `babel.config.js` still needs CommonJS resolution, which is exactly the class\n * of consumer we cannot dictate to.) The double parse of a small config is\n * irrelevant; the noise is not.\n *\n * Idempotent, and safe to call before any config import. Filters at\n * `process.emitWarning` rather than replacing the `'warning'` listener, so\n * unrelated warnings keep Node's native formatting and `--trace-warnings` hint.\n * Install-once and never restored on purpose: `loadDev` is called concurrently\n * (`Promise.all` over apps), so a scoped save/restore around each `await\n * import()` would race \u2014 one import's restore would fire while another was still\n * linking, and the warning is emitted during linkage, inside that await window.\n *\n * @example\n * suppressTypelessPackageJsonWarning()\n * // no MODULE_TYPELESS_PACKAGE_JSON banner, even though apps/ui/package.json has no \"type\"\n * const config = await import(pathToFileURL('apps/ui/infra-kit.config.ts').href)\n */\nexport const suppressTypelessPackageJsonWarning = (): void => {\n if (installed) return\n\n installed = true\n\n const emitWarning = process.emitWarning.bind(process) as (...args: unknown[]) => void\n\n process.emitWarning = ((warning: string | Error, ...rest: unknown[]): void => {\n if (readWarningCode(rest[0], rest[1]) === TYPELESS_PACKAGE_JSON) return\n\n emitWarning(warning, ...rest)\n }) as typeof process.emitWarning\n}\n"],
|
|
5
|
-
"mappings": "sxBAAA,OAAOA,OAAU,YACjB,OAAOC,OAAa,eACpB,OAAS,KAAAC,MAAS,MCuBX,IAAMC,GAAgD,CAC3D,gBAAiB,CAAC,QAAS,WAAY,eAAg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WAAY,GACZ,SAAU,GACV,UAAW,CAAC,aAAa,CAC3B,EAGA,CAAE,QAAS,MAAO,UAAW,KAAM,QAAS,KAAM,WAAY,GAAO,SAAU,GAAO,UAAW,CAAC,KAAK,CAAE,CAC3G,EAqBO,IAAMC,GAAqB,IACzBC,GAAe,QAASC,GACtBA,EAAM,YAAcA,EAAM,QAAU,CAACA,EAAM,OAAO,EAAI,CAAC,CAC/D,EAaUC,GAAuBC,GAC3BH,GAAe,OAAQC,GACrBA,EAAM,YAAcE,CAC5B,EAYUC,GAAwBC,GAC5BL,GAAe,KAAMC,GACnBA,EAAM,cAAgB,IAAQA,EAAM,UAAU,KAAK,GAAG,IAAMI,CACpE,EClhBH,OAAOC,OAAa,eAUpB,IAAMC,GAAwB,+BAGxBC,GAAkB,CAACC,EAAwBC,IAE3C,OAAOD,GAAkB,UAAYA,IAAkB,KACjDA,EAAqC,KAIxCC,EAGLC,GAAY,GAkCHC,GAAqC,IAAY,CAC5D,GAAID,GAAW,OAEfA,GAAY,GAEZ,IAAME,EAAcP,GAAQ,YAAY,KAAKA,EAAO,EAEpDA,GAAQ,aAAe,CAACQ,KAA4BC,IAA0B,CACxEP,GAAgBO,EAAK,CAAC,EAAGA,EAAK,CAAC,CAAC,IAAMR,IAE1CM,EAAYC,EAAS,GAAGC,CAAI,CAC9B,EACF",
|
|
6
|
-
"names": ["path", "process", "z", "DEFAULT_RULES", "ROOT_DEFAULT_RULES", "resolvePackageConfig", "config", "baseline", "fs", "pathExists", "target", "path", "packageConfigSchema", "fs", "path", "pathToFileURL", "z", "PACKAGE_CONFIG_FILE", "readPackageJson", "packageDir", "raw", "fs", "path", "loadPackageConfig", "baseline", "DEFAULT_RULES", "configPath", "pathExists", "stat", "rawExport", "pathToFileURL", "resolvedExport", "parsed", "packageConfigSchema", "z", "resolvePackageConfig", "fs", "path", "yaml", "WORKSPACE_FILE", "listChildDirs", "dir", "fs", "entry", "path", "expandSegment", "dirs", "segment", "next", "candidate", "pathExists", "expandGlob", "projectRoot", "pattern", "discoverPackages", "raw", "patterns", "yaml", "found", "checkConfig", "packageDir", "baseline", "DEFAULT_RULES", "rules", "loadPackageConfig", "PACKAGE_CONFIG_FILE", "err", "fs", "path", "checkFiles", "packageDir", "requiredFiles", "file", "stat", "checkScripts", "scripts", "requiredScripts", "script", "value", "fs", "path", "TURBO_FILE", "checkTurbo", "packageDir", "requiredTasks", "parsed", "raw", "err", "tasks", "task", "defined", "validatePackage", "packageDir", "baseline", "DEFAULT_RULES", "pkgJson", "readPackageJson", "packageName", "path", "configCheck", "rules", "checkConfig", "checks", "checkScripts", "checkFiles", "checkTurbo", "passed", "check", "textContent", "text", "defineMcpTool", "tool", "toFailChecks", "issues", "loadErrors", "error", "issue", "checkDevPresets", "root", "presets", "getInfraKitConfig", "keyIssues", "validatePresetKeys", "checks", "apiApps", "discoverApiApps", "uiApps", "discoverUiApps", "discovered", "a", "ctx", "buildPresetProxyContext", "failChecks", "validatePresetProxy", "findPackageRoot", "start", "current", "path", "pathExists", "resolveTargets", "options", "getProjectRoot", "ROOT_DEFAULT_RULES", "discoverPackages", "dir", "process", "logResult", "result", "header", "logger", "check", "icon", "audit", "targets", "results", "target", "validatePackage", "presetResult", "checkDevPresets", "allPassed", "structuredContent", "textContent", "auditInputSchema", "z", "auditOutputSchema", "auditMcpTool", "defineMcpTool", "params", "z", "configGet", "config", "paths", "getInfraKitConfig", "getInfraKitConfigPaths", "topLevelKeys", "logger", "structuredContent", "textContent", "configGetOutputSchema", "z", "configGetMcpTool", "defineMcpTool", "fs", "path", "process", "getDevContextDir", "cwd", "asString", "value", "asNumber", "readDevContextFragments", "dir", "entries", "records", "name", "full", "mtimeMs", "raw", "stat", "parsed", "fragment", "a", "b", "z", "devStatus", "deps", "now", "isListening", "defaultIsListening", "records", "readDevContextFragments", "at", "apps", "record", "ageSeconds", "live", "active", "logger", "app", "liveness", "freshness", "structuredContent", "textContent", "devStatusOutputSchema", "z", "devStatusMcpTool", "defineMcpTool", "fs", "os", "path", "z", "$", "execFileSync", "decidePrune", "probed", "devSessionRunning", "dead", "route", "DEV_RUNNER_PATTERNS", "looksLikeDevRunner", "command", "pattern", "PS_BIN", "defaultReadCommands", "isDevSessionRunning", "readCommands", "select", "Buffer", "fs", "path", "process", "z", "$", "PROJECT_NOT_FOUND_MARKER", "CONFIG_NOT_FOUND_MARKER", "INVALID_TOKEN_MARKER", "TOKEN_SCOPE_MARKER", "classifyDopplerFailure", "stderr", "classifyDopplerAuthFailure", "buildDopplerAuthFailureMessage", "env", "DopplerAuthError", "EnvAuthError", "authKind", "message", "buildDopplerNotFoundMessage", "kind", "project", "config", "available", "lines", "label", "$", "DOPPLER_PROBE_TIMEOUT_MS", "SCOPE_KEY", "getDopplerProject", "envManagement", "getInfraKitConfig", "probeEnvToken", "childEnv", "project", "config", "prevQuiet", "$", "scopedTo", "error", "classifyProbeFailure", "stderr", "extractStderr", "classifyDopplerFailure", "classifyDopplerAuthFailure", "process", "INFRA_KIT_ENV_TOKEN_VAR", "resolveEnvToken", "env", "fromEnv", "process", "fromStore", "readTokenStore", "EnvAuthError", "buildMissingTokenMessage", "getTokenStorePath", "envTokenExists", "storePath", "tildify", "fs", "path", "yaml", "WORKFLOWS_DIR", "readWorkflowEnvOptions", "workflowFile", "projectRoot", "getProjectRoot", "parseEnvOptions", "path", "listWorkflowEnvs", "workflowsDir", "entries", "fs", "workflows", "entry", "perWorkflow", "file", "workflowPath", "parsed", "yaml", "on", "pick", "options", "option", "value", "key", "listProjectEnvs", "workflowEnvs", "listWorkflowEnvs", "store", "readTokenStore", "declared", "env", "known", "tokenOnly", "listProjectEnvNames", "entry", "fs", "$", "fs", "path", "shouldWriteWarm", "autoLoaded", "projectDir", "canonicalProjectRoot", "canonicalizeProjectRoot", "projectRoot", "fs", "writeWarmCache", "canonicalProjectDir", "contents", "dir", "getProjectWarmCacheDir", "atomicWriteFileSync", "path", "ENV_LOAD_FILE", "error", "logger", "evictStaleWarmCaches", "nowMs", "ttlSeconds", "DEFAULT_WARM_TTL_SECONDS", "root", "getWarmCacheRoot", "entries", "entry", "mtimeMs", "invalidateProjectWarmCache", "purge", "ENV_CLEAR_FILE", "parseWorktreePaths", "porcelain", "line", "purgeRepoWarmCaches", "$", "error", "logger", "removed", "worktree", "canonical", "canonicalizeProjectRoot", "dir", "getProjectWarmCacheDir", "fs", "buildAutoLoadMarkerLines", "autoLoaded", "INFRA_KIT_ENV_AUTOLOADED_VAR", "shellSingleQuote", "INFRA_KIT_ENV_CLEARED_VAR", "DOPPLER_CONFIG_KEY", "CREDENTIAL_SECRET_KEYS", "INFRA_KIT_ENV_TOKEN_VAR", "credentialFilterWarned", "warnFilteredCredentialKeys", "keys", "logger", "buildEnvLoadFileLines", "pairs", "config", "project", "projectRoot", "loadedAt", "emitted", "key", "value", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "resolveProjectRootSafe", "getProjectRoot", "writeEnvLoadFile", "beforeWrite", "projectDir", "getDopplerProject", "downloadDopplerSecrets", "fileContents", "cacheDir", "getSessionCacheDir", "envFilePath", "path", "ENV_LOAD_FILE", "fs", "atomicWriteFileSync", "canonicalProjectRoot", "canonicalizeProjectRoot", "shouldWriteWarm", "writeWarmCache", "evictStaleWarmCaches", "envLoad", "args", "selectedConfig", "envs", "listProjectEnvNames", "commandEcho", "withEscape", "context", "select", "env", "process", "result", "structuredContent", "textContent", "DOPPLER_MAX_OUTPUT_BYTES", "DOPPLER_DOWNLOAD_TIMEOUT_MS", "INHERITED_DOPPLER_VARS", "buildDopplerChildEnv", "token", "baseEnv", "childEnv", "name", "resolveEnvToken", "prevQuiet", "$", "error", "translateDopplerDownloadError", "assertDopplerOutputSize", "parseDopplerSecretsJson", "assertTokenScope", "actual", "DopplerAuthError", "stderr", "extractStderr", "kind", "classifyDopplerFailure", "classifyDopplerAuthFailure", "buildDopplerNotFoundMessage", "stdout", "bytes", "Buffer", "ENV_VAR_NAME_PATTERN", "parsed", "envLoadMcpTool", "defineMcpTool", "z", "fs", "path", "hasManagedBlock", "content", "startMarker", "endMarker", "startIdx", "endIdx", "removeManagedBlock", "before", "after", "buildManagedBlock", "startMarker", "body", "endMarker", "upsertManagedBlock", "content", "placement", "block", "present", "hasManagedBlock", "startIdx", "endIdx", "base", "removeManagedBlock", "AGENTS_MARKER_START", "AGENTS_MARKER_END", "AGENTS_VERSION_PREFIX", "AGENTS_IMPORT_START", "AGENTS_IMPORT_END", "AGENTS_FILE", "CLAUDE_FILE", "buildVersionLine", "version", "buildAgentsBody", "assertNotSymlink", "filePath", "fs", "backupFile", "stamp", "writeManaged", "nextContent", "existed", "path", "readOr", "fallback", "assertBlockPresent", "start", "end", "content", "hasManagedBlock", "migrateLegacyAgentsFile", "agentsPath", "stripped", "removeManagedBlock", "writeAgentFiles", "mainConfigPath", "getInfraKitConfigPaths", "logger", "root", "package_default", "body", "claudePath", "claudeContent", "upsertManagedBlock", "written", "file", "fs", "os", "path", "process", "fs", "path", "process", "CONFIG_KEY_DOCS", "buildUserGlobalExample", "buildUserProjectExample", "projectName", "buildVendorExample", "seeded", "exampleSiblingPath", "jsonPath", "readFileOrNull", "filePath", "fs", "seedUserProjectConfig", "paths", "configPath", "examplePath", "path", "createdConfig", "fileExists", "example", "buildUserProjectExample", "refreshedExample", "resetMergedConfigCache", "seedCreatedMessage", "result", "tildify", "ensureUserProjectConfig", "process", "getInfraKitConfigPaths", "logger", "err", "fs", "path", "pathToFileURL", "yaml", "z", "fs", "os", "path", "z", "z", "FACTORY_CONFIG_FILE", "factoryConfigSchema", "getFactoryConfigPath", "path", "os", "USER_CONFIG_DIR_NAME", "FACTORY_CONFIG_FILE", "expandTilde", "p", "loadFactoryConfig", "configPath", "raw", "fs", "data", "err", "parsed", "factoryConfigSchema", "z", "legacyYmlPath", "jsonPath", "migrateLegacyConfig", "paths", "getInfraKitConfigPaths", "layers", "infraKitConfigSchema", "path", "infraKitOverrideConfigSchema", "migrated", "layer", "ymlExists", "jsonExists", "fileExists", "logger", "tildify", "raw", "fs", "parsed", "yaml", "result", "z", "err", "resetInfraKitConfigCache", "migrateUserGlobalConfigFilename", "dir", "pairs", "renamed", "from", "to", "fromExists", "toExists", "migrateFactoryConfigToJson", "newJson", "getFactoryConfigPath", "oldTs", "oldExists", "newExists", "stat", "pathToFileURL", "wasFunction", "resolved", "factoryConfigSchema", "stripLegacyIdeMode", "ide", "changed", "stripEntry", "entry", "config", "restConfig", "key", "nextIde", "normalizeLegacyIdeStructures", "jsonPaths", "normalized", "MARKER_START", "MARKER_END", "LEGACY_PAIRED", "LEGACY_SINGLE", "init", "zshrcPath", "path", "os", "existing", "fs", "removeExistingBlock", "updated", "upsertManagedBlock", "buildShellBody", "logger", "migrateLegacyConfig", "normalizeLegacyIdeStructures", "migrateUserGlobalConfigFilename", "migrateFactoryConfigToJson", "seedUserGlobalConfig", "writeAgentFiles", "reseedUserProjectConfig", "shell", "process", "userConfigDir", "userConfigPath", "buildUserGlobalExample", "buildVendorExample", "paths", "getInfraKitConfigPaths", "result", "seedUserProjectConfig", "seedCreatedMessage", "err", "isBlockLine", "line", "content", "removeManagedBlock", "start", "end", "legacyResult", "legacyIdx", "before", "afterLines", "i", "remaining", "runCmd", "buildShellBlock", "fs", "readOverrideSummary", "filePath", "exists", "raw", "parsed", "keys", "describeOverrides", "summary", "checkCommand", "name", "command", "successMsg", "failMsg", "$", "checkZshrcInitialized", "zshrcPath", "path", "os", "fs", "content", "startIdx", "MARKER_START", "endIdx", "MARKER_END", "installedBlock", "expectedBlock", "buildShellBlock", "checkWarmCache", "root", "getProjectRoot", "canon", "canonicalizeProjectRoot", "warmFile", "getProjectWarmCacheDir", "ENV_LOAD_FILE", "ageSeconds", "ageMinutes", "ttlMinutes", "DEFAULT_WARM_TTL_SECONDS", "checkPnpmWorkspaceVirtualStore", "yamlPath", "err", "readDoctorConfig", "resetInfraKitConfigCache", "getInfraKitConfig", "checkInfraKitConfigValid", "read", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "describeEntries", "entries", "entry", "held", "resolveEntries", "environments", "resolveToken", "env", "source", "checkEnvTokensConfigured", "deps", "readStore", "readTokenStore", "resolveEnvToken", "envs", "listProjectEnvNames", "autoLoadEnv", "universe", "listing", "autoLoadEntry", "PROBE_VERDICT", "checkEnvTokenValid", "probe", "probeEnvToken", "token", "project", "result", "buildDopplerChildEnv", "verdict", "suffix", "modeOf", "target", "statPath", "stats", "checkTokenStorePerms", "fix", "storePath", "getTokenStorePath", "defaultStatPath", "chmodPath", "tildify", "projectDir", "projectsDir", "userConfigDir", "loose", "describe", "formatMode", "mode", "checkUserOverridePath", "paths", "getInfraKitConfigPaths", "exists", "summary", "readOverrideSummary", "describeOverrides", "checkLegacyUserGlobalConfig", "legacyPath", "IDE_PROBE_META", "probeIde", "provider", "meta", "checkIdeInstalled", "providers", "resolveConfiguredIdes", "ide", "probes", "missing", "RTK_REQUIRED_INDEXES", "checkRtkConfigured", "statusLines", "l", "failed", "idx", "line", "checkAgentFiles", "mainConfigPath", "claudePath", "present", "hasManagedBlock", "AGENTS_MARKER_START", "AGENTS_MARKER_END", "installDaemonCmd", "bin", "formatPortlessCommand", "trustCmd", "CA_MISMATCH_CODES", "PROBE_BUG_CODE", "checkPortlessServing", "isProxyServing", "DEFAULT_DEV_PROXY_PORT", "checkPortlessCaChain", "handshake", "routes", "caPath", "servernames", "route", "servername", "codes", "code", "checkPortlessCaTrusted", "trusted", "checkPortlessStaleRoutes", "isListening", "stale", "checkPortless", "resolveBin", "resolvePortlessBin", "defaultIsProxyServing", "handshakeChainsToCa", "caTrusted", "caFingerprintMatches", "readRoutes", "listRoutes", "defaultIsListening", "readCaPath", "installed", "serving", "chain", "pruneStalePortlessRoutes", "devRunning", "isDevSessionRunning", "probed", "prunable", "withheld", "decidePrune", "removeAlias", "createPortlessDriver", "alias", "doctor", "options", "baseChecks", "portlessChecks", "pruned", "index", "check", "checks", "structuredContent", "c", "textContent", "doctorMcpTool", "defineMcpTool", "z", "Chalk", "process", "SECTION_TOOLS", "SECTION_SHELL", "SECTION_CONFIG", "SECTION_TOKENS", "SECTION_PROXY", "PORTLESS_SERVING_NAME", "DEFAULT_DEV_PROXY_PORT", "SECTION_MEMBERS", "OTHER_SECTION", "SECTION_ORDER", "label", "SECTION_BY_NAME", "names", "name", "DOCTOR_CHECK_NAMES", "FIXABLE_NAMES", "groupChecks", "checks", "buckets", "check", "bucket", "GLYPHS", "MIN_MESSAGE_WIDTH", "wrapText", "text", "width", "words", "word", "lines", "current", "tally", "failed", "createPalette", "color", "chalk", "Chalk", "formatRollup", "counts", "total", "palette", "glyphs", "plain", "ratio", "INDENT", "ROW_INDENT", "formatSectionHeader", "section", "rollup", "gap", "formatCheckRow", "nameWidth", "glyphWidth", "plainGlyph", "plainName", "glyph", "messageColumn", "messageWidth", "first", "rest", "paint", "line", "formatSummary", "rule", "fixable", "passed", "totals", "hintText", "hint", "formatDoctorReport", "options", "unicode", "sections", "FORCE_COLOR_OFF", "LOCALE_VARS", "resolveColor", "env", "stream", "resolveUnicode", "ascii", "locale", "value", "resolveReportCapabilities", "input", "process", "printDoctorReport", "deps", "fs", "path", "process", "z", "clearProjectWarmCache", "purge", "projectRoot", "getProjectRoot", "canon", "canonicalizeProjectRoot", "invalidateProjectWarmCache", "buildEnvClearLines", "varNames", "v", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "INFRA_KIT_ENV_AUTOLOADED_VAR", "INFRA_KIT_ENV_CLEARED_VAR", "envClear", "cacheDir", "getSessionCacheDir", "envLoadPath", "path", "ENV_LOAD_FILE", "hasLoadedEnv", "fs", "parseVarNamesFromEnvFile", "unsetLines", "clearFilePath", "ENV_CLEAR_FILE", "atomicWriteFileSync", "process", "structuredContent", "textContent", "envClearMcpTool", "defineMcpTool", "z", "process", "z", "buildEnvTokenStatus", "envs", "storeTokens", "envToken", "env", "source", "ENV_TABLE_HEADERS", "formatEnvTable", "rows", "cells", "row", "widths", "header", "col", "cell", "renderRow", "values", "value", "separator", "width", "envList", "project", "getDopplerProject", "listProjectEnvs", "store", "readTokenStore", "process", "INFRA_KIT_ENV_TOKEN_VAR", "tokens", "logger", "buildResult", "line", "structuredContent", "textContent", "envListMcpTool", "defineMcpTool", "z", "path", "process", "z", "envStatus", "logger", "cacheDir", "getSessionCacheDir", "sessionId", "process", "INFRA_KIT_SESSION_VAR", "envLoadPath", "path", "ENV_LOAD_FILE", "sessionLoadedCount", "sessionTotalCount", "sessionConfig", "INFRA_KIT_ENV_CONFIG_VAR", "sessionProject", "INFRA_KIT_ENV_PROJECT_VAR", "sessionLoadedAt", "INFRA_KIT_ENV_LOADED_AT_VAR", "autoLoaded", "INFRA_KIT_ENV_AUTOLOADED_VAR", "cleared", "INFRA_KIT_ENV_CLEARED_VAR", "varNames", "parseVarNamesFromEnvFile", "v", "loadedAtDisplay", "origin", "missing", "clearedNote", "structuredContent", "textContent", "envStatusMcpTool", "defineMcpTool", "z", "process", "z", "MASK", "redactToken", "token", "buildEnvTokenRows", "environments", "storeTokens", "envToken", "env", "token", "INFRA_KIT_ENV_TOKEN_VAR", "redactToken", "BASE_COLUMNS", "formatEnvTokenTable", "rows", "checked", "header", "cells", "row", "widths", "column", "index", "cell", "envTokenList", "check", "envs", "listProjectEnvNames", "store", "readTokenStore", "process", "project", "getDopplerProject", "probe", "probeEnvToken", "buildDopplerChildEnv", "line", "logger", "missing", "structuredContent", "textContent", "envTokenListMcpTool", "defineMcpTool", "z", "z", "$", "$", "$", "$", "process", "assertJiraOk", "response", "context", "errorText", "logger", "createJiraVersion", "params", "config", "baseUrl", "token", "email", "projectId", "requestBody", "url", "credentials", "error", "getProjectVersions", "findVersionByName", "versionName", "v", "updateJiraVersion", "deliverJiraRelease", "version", "loadJiraConfig", "process", "projectIdStr", "missingVars", "errorMessage", "loadJiraConfigOptional", "DEV_REF", "getBaseBranch", "type", "prepareGitForRelease", "baseBranch", "$", "createSingleRelease", "args", "id", "jiraConfig", "description", "versionName", "formatJiraName", "result", "createJiraVersion", "jiraVersionUrl", "releaseInfo", "createReleaseBranch", "displayLabel", "getJiraDescriptions", "descriptions", "loadJiraConfigOptional", "versions", "getProjectVersions", "version", "formatVersionLabel", "maxVersionLength", "padding", "tag", "detectReleaseType", "title", "parseBranchChoices", "branches", "branch", "parseBranchName", "resolveReleaseBranch", "versionArg", "formatBranchName", "parseReleaseRef", "error", "OperationError", "releaseLabelFromBranch", "releaseBranchLabels", "deriveBranchType", "types", "formatBranchPickerItems", "label", "sortReleasePRs", "prs", "pr", "parseBranchName", "entry", "a", "b", "compareReleaseIds", "fetchAllReleasePRs", "releasePRs", "$", "hotfixPRs", "all", "seen", "loadSortedReleasePRs", "OperationError", "error", "logger", "getReleasePRs", "getReleasePRsWithInfo", "updateReleasePRBody", "args", "branch", "body", "createReleaseBranch", "id", "jiraVersionUrl", "type", "description", "prTitle", "formatPrTitle", "baseBranch", "getBaseBranch", "branchName", "formatBranchName", "prLink", "assertManagementContext", "args", "operation", "isInsideLinkedWorktree", "OperationError", "isWorkingTreeClean", "process", "PromptCancelledError", "process", "jsonOutput", "emit", "result", "write", "text", "addJsonOption", "cmd", "option", "assertInteractive", "isMcpMode", "process", "jsonOutput", "OperationError", "pickReleaseBranch", "items", "runBranchPicker", "value", "PromptCancelledError", "pickReleaseBranches", "opts", "runBranchMultiPicker", "values", "ghMergeDev", "args", "all", "confirmedCommand", "assertManagementContext", "releasePRsList", "getReleasePRsWithInfo", "pr", "detectReleaseType", "logger", "commandEcho", "textContent", "selectedReleaseBranches", "descriptions", "getJiraDescriptions", "pickReleaseBranches", "formatBranchPickerItems", "releaseBranchLabels", "confirmOrExit", "$", "error", "OperationError", "failedBranches", "branch", "mergeDev", "structuredContent", "err", "ghMergeDevMcpTool", "defineMcpTool", "z", "z", "$", "readTrimmedString", "value", "max", "formatZxError", "error", "rec", "fields", "exitCode", "stderr", "stdout", "$", "removeWorktrees", "args", "branches", "worktreeDir", "pruneFolder", "results", "branch", "worktreePath", "closeCmuxWorkspaceByCwd", "$", "removed", "index", "result", "err", "OperationError", "logger", "runStep", "operation", "remediation", "fn", "error", "logger", "formatZxError", "OperationError", "fetchPRByHead", "head", "result", "$", "fetchMergedRcPRForVersion", "id", "expectedTitle", "formatRcTitle", "pr", "fetchOpenDevToMainPR", "resolveTargetFromVersion", "version", "selectedReleaseBranch", "resolveReleaseBranch", "resolveTargetInteractively", "releasePRsInfo", "getReleasePRsWithInfo", "branches", "releaseTypes", "detectReleaseType", "commandEcho", "descriptions", "getJiraDescriptions", "pickReleaseBranch", "formatBranchPickerItems", "prInfo", "removeReleaseWorktreeIfPresent", "releaseBranch", "getCurrentWorktrees", "worktreeDir", "getProjectRoot", "WORKTREES_DIR_SUFFIX", "removeWorktrees", "mergeReleasePR", "args", "releaseType", "mergeTarget", "releasePr", "resolveRcPRNumber", "selectedLabel", "displayLabel", "existingOpen", "rcNumber", "created", "ensureRcPRMerged", "dispatchDeployWorkflow", "syncMainIntoDev", "removeDeliveredReleaseBranch", "branch", "deleteLocalBranch", "deleteRemoteBranch", "deliverJiraReleaseSafely", "jiraConfig", "loadJiraConfigOptional", "versionName", "formatJiraName", "deliverJiraRelease", "ghReleaseDeliver", "confirmedCommand", "assertManagementContext", "releasePrTitle", "releaseId", "parseBranchName", "selectedVersion", "confirmOrExit", "structuredContent", "textContent", "ghReleaseDeliverMcpTool", "defineMcpTool", "z", "confirm", "z", "$", "select", "pickEnv", "options", "operation", "OperationError", "withEscape", "context", "select", "option", "PROTECTED_ENVS", "isProtectedEnv", "env", "deployableEnvs", "options", "assertDeployable", "operation", "OperationError", "DEPLOY_ALL_WORKFLOW", "confirmDeploy", "args", "confirmedCommand", "branch", "env", "commandEcho", "answer", "withEscape", "context", "confirm", "ghReleaseDeployAll", "version", "skipTerraform", "selectedReleaseBranch", "resolveReleaseBranch", "releasePRsInfo", "getReleasePRsWithInfo", "branches", "pr", "releaseTypes", "detectReleaseType", "descriptions", "getJiraDescriptions", "pickReleaseBranch", "formatBranchPickerItems", "selectedVersion", "releaseLabelFromBranch", "envOptions", "deployableEnvs", "readWorkflowEnvOptions", "selectedEnv", "pickEnv", "assertDeployable", "shouldSkipTerraform", "logger", "structuredContent", "textContent", "$", "error", "OperationError", "ghReleaseDeployAllMcpTool", "defineMcpTool", "z", "checkbox", "confirm", "fs", "resolve", "yaml", "z", "$", "DEPLOY_SELECTED_WORKFLOW", "SKIP_TERRAFORM_INPUT", "confirmDeploy", "args", "confirmedCommand", "branch", "env", "commandEcho", "answer", "withEscape", "context", "confirm", "ghReleaseDeploySelected", "version", "services", "skipTerraform", "selectedReleaseBranch", "resolveReleaseBranch", "releasePRsInfo", "getReleasePRsWithInfo", "branches", "pr", "releaseTypes", "detectReleaseType", "descriptions", "getJiraDescriptions", "pickReleaseBranch", "formatBranchPickerItems", "selectedVersion", "releaseLabelFromBranch", "envOptions", "deployableEnvs", "readWorkflowEnvOptions", "selectedEnv", "pickEnv", "assertDeployable", "availableServices", "parseServicesFromWorkflow", "OperationError", "selectedServices", "checkbox", "svc", "invalidServices", "shouldSkipTerraform", "buildResult", "success", "structuredContent", "textContent", "logger", "$", "serviceFlags", "error", "projectRoot", "getProjectRoot", "workflowPath", "resolve", "parsed", "yaml", "fs", "inputs", "key", "value", "ghReleaseDeploySelectedMcpTool", "defineMcpTool", "z", "z", "ghReleaseList", "releases", "getReleasePRsWithInfo", "pr", "id", "parseBranchName", "displayLabel", "formatJiraName", "detectReleaseType", "jiraDescriptions", "getJiraDescriptions", "maxVersionLength", "r", "formattedLines", "release", "label", "formatVersionLabel", "description", "logger", "structuredContent", "textContent", "ghReleaseListMcpTool", "defineMcpTool", "z", "confirm", "input", "select", "process", "z", "$", "parseVersion", "versionStr", "sortVersions", "versions", "a", "b", "majA", "minA", "patchA", "majB", "minB", "patchB", "NEXT_TOKEN", "VERSION_RE", "stripBranchPrefix", "raw", "tryParse", "cleaned", "match", "semverKey", "v", "collectKnownVersions", "sources", "all", "parsed", "seen", "key", "sortVersions", "parseVersion", "NoPriorVersionsError", "computeNextVersion", "known", "type", "max", "major", "minor", "highestPatchOnMinor", "acc", "isNextToken", "token", "isReleaseType", "value", "isNamedReleaseInput", "input", "parseReleaseSpec", "spec", "firstColon", "description", "rest", "secondColon", "typeRaw", "typeLower", "entry", "formatReleaseSpec", "withDescription", "base", "resolveNamedInput", "name", "validateName", "resolveReleaseEntries", "entries", "running", "trimmed", "next", "parseReleaseRef", "explicit", "hasNextToken", "e", "extractVersionBranches", "lsRemoteStdout", "line", "tab", "parseBranchName", "id", "parseRemoteRefs", "previousQuiet", "$", "result", "fetchJiraVersionNames", "config", "loadJiraConfigOptional", "getProjectVersions", "v", "loadExistingVersions", "branchesResult", "jiraResult", "logger", "collectKnownVersions", "VERSION_PROMPT_HINT", "trySuggestNext", "known", "type", "computeNextVersion", "err", "NoPriorVersionsError", "resolveOrExit", "entries", "resolveReleaseEntries", "OperationError", "InvalidReleaseNameError", "promptForVersionInput", "running", "suggestion", "defaultHint", "versionAnswer", "withEscape", "context", "input", "versionInput", "logger", "process", "promptForNameInput", "name", "validateName", "reason", "promptForReleasesInteractive", "ensureKnown", "commandEcho", "baseKnown", "ensureRunning", "addAnother", "ordinal", "kind", "select", "resolved", "parseVersion", "description", "confirm", "formatReleaseSummary", "entry", "parts", "echoReleases", "formatReleaseSpec", "collectEntries", "inputReleases", "hasNextToken", "interactive", "assertHomogeneousReleaseType", "confirmReleases", "confirmedCommand", "summary", "confirmOrExit", "executeOne", "args", "jiraConfig", "label", "displayLabel", "prTitleLabel", "prepareGitForRelease", "result", "createSingleRelease", "error", "logFinalSummary", "total", "successCount", "failureCount", "releaseCreate", "loadJiraConfig", "loadExistingVersions", "assertManagementContext", "created", "failed", "failure", "structuredContent", "r", "textContent", "releaseCreateMcpTool", "defineMcpTool", "z", "input", "z", "buildJiraVersionUrl", "jiraConfig", "version", "buildPRBody", "jiraVersionUrl", "description", "pickReleaseBranch", "releasePRsInfo", "getReleasePRsWithInfo", "branches", "pr", "types", "detectReleaseType", "descriptions", "getJiraDescriptions", "branch", "formatBranchPickerItems", "verifyReleasePRExists", "selectedBranch", "prInfo", "OperationError", "promptDescription", "current", "hint", "trimmed", "withEscape", "context", "input", "releaseDescEdit", "args", "versionArg", "descriptionArg", "confirmedCommand", "loadJiraConfig", "resolveReleaseBranch", "commandEcho", "releaseId", "parseBranchName", "selectedVersion", "displayLabel", "versionName", "formatJiraName", "jiraVersion", "findVersionByName", "previousDescription", "newDescription", "buildResult", "changed", "structuredContent", "textContent", "logger", "confirmOrExit", "updateJiraVersion", "body", "updateReleasePRBody", "releaseDescEditMcpTool", "defineMcpTool", "z", "execFile", "path", "process", "z", "fs", "path", "addFoldersToCursorWorkspace", "args", "workspacePath", "folderPaths", "workspaceDir", "raw", "error", "parsed", "existingFolders", "existingAbsolutePaths", "entry", "added", "skipped", "folderPath", "absolutePath", "relativePath", "$", "launchCursor", "workspacePath", "fs", "path", "fs", "path", "removeFoldersFromCursorWorkspace", "args", "workspacePath", "folderPaths", "workspaceDir", "raw", "error", "parsed", "existingFolders", "targetAbsolutePaths", "folderPath", "removedAbsolutePaths", "filteredFolders", "entry", "entryAbsolutePath", "removed", "notFound", "absolutePath", "reconcileCursorWorkspaceFolders", "args", "workspacePath", "worktreeDir", "currentBranches", "workspaceDir", "path", "releaseRoot", "raw", "fs", "existingFolders", "desiredAbsolutePaths", "branch", "danglingFolderPaths", "entry", "entryAbsolutePath", "removed", "removeFoldersFromCursorWorkspace", "desiredFolderPaths", "added", "addFoldersToCursorWorkspace", "path", "resolveCursorWorkspacePath", "configValue", "projectRoot", "openCursorWorkspace", "args", "projectRoot", "worktreeDir", "currentBranches", "cursorConfig", "logger", "workspacePath", "resolveCursorWorkspacePath", "added", "removed", "reconcileCursorWorkspaceFolders", "launchCursor", "error", "$", "addFoldersToZedWorkspace", "args", "folderPaths", "folderPath", "$", "openZedWorkspace", "args", "worktreePaths", "$", "error", "logger", "$", "reuseZedWorkspace", "args", "projectRoot", "worktreeDir", "remainingBranches", "paths", "branch", "$", "logger", "error", "assertNever", "value", "addIdeWorktreeFolders", "args", "projectRoot", "worktreeDir", "branches", "config", "getInfraKitConfig", "ides", "resolveConfiguredIdes", "folderPaths", "branch", "outcomes", "ide", "logger", "workspacePath", "resolveCursorWorkspacePath", "added", "skipped", "addFoldersToCursorWorkspace", "skippedSuffix", "launchCursor", "addFoldersToZedWorkspace", "assertNever", "openIdeWorkspace", "args", "config", "getInfraKitConfig", "ides", "resolveConfiguredIdes", "projectRoot", "worktreeDir", "worktreePaths", "currentBranches", "outcomes", "ide", "outcome", "openCursorWorkspace", "openZedWorkspace", "assertNever", "ideProviderLabel", "provider", "assertNever", "removeIdeWorktreeFolders", "args", "projectRoot", "worktreeDir", "currentWorktrees", "removedWorktrees", "allowEditorRelaunch", "config", "getInfraKitConfig", "ides", "resolveConfiguredIdes", "folderPaths", "branch", "remainingBranches", "outcomes", "ide", "removeFromCursor", "removeFromZed", "assertNever", "workspacePath", "resolveCursorWorkspacePath", "removed", "removeFoldersFromCursorWorkspace", "logger", "error", "reuseZedWorkspace", "IDE_MODES", "fs", "path", "pathExists", "target", "fs", "resolveRoots", "roots", "mainRepoRoot", "getMainRepoRoot", "path", "error", "OperationError", "isScanCandidate", "child", "resolveCandidate", "root", "candidate", "hasGit", "hasConfig", "repoRoot", "readRootChildren", "discoverInfraKitProjects", "options", "byRepoRoot", "children", "project", "a", "b", "reopen", "options", "reopenAll", "reopenCurrentProject", "releaseOnly", "force", "dryRun", "getInfraKitConfig", "projectRoot", "getProjectRoot", "worktreeDir", "WORKTREES_DIR_SUFFIX", "repoName", "path", "getMainRepoRoot", "entries", "listWorktrees", "active", "selectActive", "worktreePaths", "entry", "currentBranches", "branch", "isReleaseBranch", "targets", "buildCmuxWorkspaceTitle", "result", "planReopen", "logDryRun", "commandEcho", "textContent", "ideOutcomes", "cmux", "openIdeWorkspace", "runCmux", "outcome", "logResults", "error", "OperationError", "logger", "args", "groupRef", "findCmuxGroupRefByName", "closed", "closeCmux", "opened", "skipped", "reopenCmux", "openByCwd", "listCmuxWorkspacesByCwd", "target", "safeRealpath", "closeCmuxWorkspaceByCwd", "partitionCmuxTargets", "openCwds", "toOpen", "group", "bootstrapAttempted", "openCmuxWorkspaceWithLayout", "workspaceRef", "createCmuxGroupFrom", "repo", "folder", "title", "context", "ideLabels", "provider", "ideProviderLabel", "project", "root", "discovered", "discoverInfraKitProjects", "projects", "filterProjects", "childFlags", "buildChildFlags", "results", "proj", "runRepoChild", "logReopenAll", "names", "discoveredNames", "name", "flags", "stdout", "spawnReopenChild", "message", "cwd", "selfCli", "process", "resolve", "reject", "execFile", "okCount", "failedCount", "totalOpened", "totalSkipped", "reopenMcpTool", "defineMcpTool", "z", "existsSync", "path", "process", "z", "createHash", "readFileSync", "sha256", "filePath", "readFileSync", "writeFileSync", "path", "z", "readdirSync", "path", "VENDOR_DIR", "MANIFEST_SKIP_DIRS", "MANIFEST_SKIP_FILES", "MANIFEST_SKIP_SUFFIXES", "isSkippedDir", "name", "isSkippedFile", "suffix", "toPosix", "relativePath", "path", "walkVendorTree", "vendorRoot", "acc", "walk", "dir", "entry", "readdirSync", "full", "isSkippedDir", "isSkippedFile", "MANIFEST_FILE", "CURRENT_SCHEMA_VERSION", "manifestSchema", "z", "isUnknownSchema", "manifest", "readManifest", "vendorRoot", "manifestPath", "path", "MANIFEST_FILE", "raw", "readFileSync", "parsed", "manifestSchema", "z", "compareToManifest", "vendorRoot", "manifest", "expected", "actualFiles", "walkVendorTree", "modified", "added", "rel", "sha256", "path", "actualSet", "removed", "MAX_REPORTED", "report", "label", "list", "logger", "rel", "vendorCheck", "options", "root", "getProjectRoot", "vendorRoot", "path", "VENDOR_DIR", "base", "existsSync", "structuredContent", "textContent", "MANIFEST_FILE", "manifest", "readManifest", "isUnknownSchema", "modified", "added", "removed", "compareToManifest", "drifted", "vendorCheckOutputSchema", "z", "vendorCheckMcpTool", "defineMcpTool", "process", "z", "version", "cliVersion", "package_default", "logger", "structuredContent", "textContent", "versionMcpTool", "defineMcpTool", "z", "confirm", "path", "z", "$", "FEATURE_DIR", "RELEASE_DIR", "worktreesAdd", "options", "confirmedCommand", "all", "versions", "githubDesktop", "cmux", "ide", "assertManagementContext", "currentWorktrees", "getCurrentWorktrees", "projectRoot", "getProjectRoot", "worktreeDir", "WORKTREES_DIR_SUFFIX", "ensureWorktreeDirectory", "selectedReleaseBranches", "v", "formatBranchName", "parseReleaseRef", "releasePRsInfo", "getReleasePRsWithInfo", "releasePRsList", "pr", "logger", "commandEcho", "textContent", "releaseTypes", "detectReleaseType", "descriptions", "getJiraDescriptions", "pickReleaseBranches", "formatBranchPickerItems", "releaseBranchLabels", "confirmOrExit", "config", "getInfraKitConfig", "ideMode", "resolveConfiguredIdes", "openInGithubDesktop", "withEscape", "context", "confirm", "openInCmux", "branchesToCreate", "categorizeWorktrees", "createdWorktrees", "createWorktrees", "logResults", "addIdeWorktreeFolders", "branch", "$", "repoName", "path", "getMainRepoRoot", "openByCwd", "listCmuxWorkspacesByCwd", "groupRef", "findCmuxGroupRefByName", "bootstrapAttempted", "cwd", "safeRealpath", "title", "buildCmuxWorkspaceTitle", "openCmuxWorkspaceWithLayout", "workspaceRef", "createCmuxGroupFrom", "error", "structuredContent", "isPromptCancellation", "OperationError", "args", "currentBranchNames", "isReleaseBranch", "branches", "results", "worktreePath", "created", "index", "result", "err", "worktreesAddMcpTool", "defineMcpTool", "z", "IDE_MODES", "z", "worktreesList", "getInfraKitConfig", "currentWorktrees", "getCurrentWorktrees", "logger", "textContent", "releasePRsInfo", "jiraDescriptions", "getReleasePRsWithInfo", "getJiraDescriptions", "releaseTypes", "pr", "detectReleaseType", "worktrees", "branch", "id", "parseBranchName", "version", "displayLabel", "type", "description", "formatJiraName", "maxVersionLength", "w", "formattedLines", "worktree", "label", "formatVersionLabel", "structuredContent", "worktreesListMcpTool", "defineMcpTool", "z", "z", "assertMcpRemovalInput", "input", "isMcpMode", "OperationError", "assertTargetsExist", "selected", "currentWorktrees", "unmatched", "branch", "worktreesRemove", "options", "confirmedCommand", "all", "versions", "assertManagementContext", "getInfraKitConfig", "getCurrentWorktrees", "logger", "commandEcho", "textContent", "projectRoot", "getProjectRoot", "worktreeDir", "WORKTREES_DIR_SUFFIX", "selectedReleaseBranches", "v", "formatBranchName", "parseReleaseRef", "descriptions", "prInfo", "getJiraDescriptions", "getReleasePRsWithInfo", "releaseTypes", "pr", "detectReleaseType", "pickReleaseBranches", "formatBranchPickerItems", "allSelected", "releaseBranchLabels", "confirmOrExit", "removedWorktrees", "removeWorktrees", "removeIdeWorktreeFolders", "logResults", "structuredContent", "error", "isPromptCancellation", "removed", "worktreesRemoveMcpTool", "defineMcpTool", "z", "z", "$", "worktreesSync", "options", "confirmedCommand", "assertManagementContext", "getInfraKitConfig", "currentWorktrees", "getCurrentWorktrees", "projectRoot", "getProjectRoot", "worktreeDir", "WORKTREES_DIR_SUFFIX", "releasePRsList", "getReleasePRs", "confirmOrExit", "commandEcho", "branchesToRemove", "categorizeWorktrees", "removedWorktrees", "removeWorktrees", "removeIdeWorktreeFolders", "logResults", "structuredContent", "textContent", "error", "isPromptCancellation", "logger", "OperationError", "args", "branch", "isReleaseBranch", "branches", "removed", "worktreePath", "closeCmuxWorkspaceByCwd", "$", "err", "worktreesSyncMcpTool", "defineMcpTool", "z", "MENU_GROUPS", "commandCatalog", "devStatusMcpTool", "ghMergeDevMcpTool", "ghReleaseListMcpTool", "releaseCreateMcpTool", "releaseDescEditMcpTool", "ghReleaseDeployAllMcpTool", "ghReleaseDeploySelectedMcpTool", "ghReleaseDeliverMcpTool", "worktreesAddMcpTool", "worktreesListMcpTool", "reopenMcpTool", "worktreesRemoveMcpTool", "worktreesSyncMcpTool", "envStatusMcpTool", "envListMcpTool", "envLoadMcpTool", "envClearMcpTool", "envTokenListMcpTool", "configGetMcpTool", "vendorCheckMcpTool", "doctorMcpTool", "auditMcpTool", "versionMcpTool", "getExposedMcpTools", "commandCatalog", "entry", "getMenuGroupEntries", "group", "isLongRunningCommand", "commandPath", "process", "TYPELESS_PACKAGE_JSON", "readWarningCode", "typeOrOptions", "codeOrCtor", "installed", "suppressTypelessPackageJsonWarning", "emitWarning", "warning", "rest"]
|
|
7
|
-
}
|