infra-kit 0.7.9 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-5XK34MWH.js +442 -0
- package/dist/chunk-5XK34MWH.js.map +7 -0
- package/dist/{chunk-LDF2KOGN.js → chunk-6OFUVD7F.js} +2 -2
- package/dist/chunk-75URROMU.js +4 -0
- package/dist/chunk-75URROMU.js.map +7 -0
- package/dist/{chunk-DFZ5WUIM.js → chunk-AEVL5XWO.js} +2 -2
- package/dist/{chunk-DFZ5WUIM.js.map → chunk-AEVL5XWO.js.map} +1 -1
- package/dist/{chunk-KXQQUBGV.js → chunk-AOWMCNYY.js} +2 -2
- package/dist/chunk-BVEVERTB.js +7 -0
- package/dist/chunk-BVEVERTB.js.map +7 -0
- package/dist/chunk-GCX3HDDL.js +9 -0
- package/dist/chunk-GCX3HDDL.js.map +7 -0
- package/dist/cli.js +13 -13
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +2 -2
- package/dist/dev-server.js.map +1 -1
- package/dist/dev-wizard-run-RPZOX53B.js +2 -0
- package/dist/{dev-wizard-run-MCUYV6IN.js.map → dev-wizard-run-RPZOX53B.js.map} +1 -1
- package/dist/mcp-proxy.js +1 -1
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +4 -4
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +1 -0
- package/dist/chunk-63VNUKUS.js +0 -8
- package/dist/chunk-63VNUKUS.js.map +0 -7
- package/dist/chunk-MFNMFVI6.js +0 -443
- package/dist/chunk-MFNMFVI6.js.map +0 -7
- package/dist/chunk-NFIFWIO6.js +0 -4
- package/dist/chunk-NFIFWIO6.js.map +0 -7
- package/dist/chunk-YKCY657C.js +0 -7
- package/dist/chunk-YKCY657C.js.map +0 -7
- package/dist/dev-wizard-run-MCUYV6IN.js +0 -2
- /package/dist/{chunk-LDF2KOGN.js.map → chunk-6OFUVD7F.js.map} +0 -0
- /package/dist/{chunk-KXQQUBGV.js.map → chunk-AOWMCNYY.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts", "../src/lib/path-display/path-display.ts", "../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/errors/structured-refusal-error.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts"],
|
|
4
|
+
"sourcesContent": ["// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 it cannot heal on a 30s retry, only a human can fix it \u2014 and env\n // auto-load's sticky marker is keyed on that CLASS. Thrown as a plain Error these were classified\n // TRANSIENT, so a corrupt store went silent on the backgrounded shell-startup spawn and the user's\n // env simply stopped loading with nothing ever said. `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store. Only this\n * class earns the STICKY marker that survives the backgrounded shell-startup spawn and is replayed\n * onto the next interactive command. `DopplerAuthError extends EnvAuthError` for the subset that\n * is specifically \"Doppler refused the token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): env auto-load must tell a\n// TRANSIENT failure (network, timeout, Doppler down \u2014 heals itself, 30s backoff, stay quiet) apart\n// from a DURABLE one (never heals, and only a human can fix it). A durable failure misclassified as\n// transient is TOTAL SILENCE, forever, on the one path the whole feature exists to survive.\n//\n// That classification therefore has to travel WITH the error, not be re-derived by grepping a\n// message some other module owns \u2014 and it has to be throwable from EVERY module that can produce\n// the class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a\n// Doppler-owned base type could not be thrown there without a layering inversion and an import\n// cycle. Hence a neutral base here in `lib/errors`.\n//\n// The defect class this closes is \"a durable failure that is not type-detectable\". Adding a new\n// durable failure and forgetting to type it is exactly how this shipped silent twice.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * This is the default `isAuthFailure` of `lib/env-autoload`'s `runEnvAutoLoad`. It is deliberately\n * WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only one of the\n * durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store never reaches\n * the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\n\n/**\n * Shared path-display helpers for CLI output. Extracted from `commands/config`\n * and `commands/init/migrate-config` (which each had private copies) so config\n * surfaces print paths consistently. Keep this dependency-light (node builtins\n * only) \u2014 it is imported by several commands.\n */\n\n/**\n * Resolve whether a file is reachable, suppressing ENOENT (and any access error)\n * into a boolean. Used to render `[\u2713]`/`[ ]` existence markers.\n *\n * @example\n * await fileExists('/etc/hosts') // => true\n * await fileExists('/nope.txt') // => false\n */\nexport const fileExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath)\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Replace the user's home prefix with `~` so logged paths stay short and portable\n * across machines. Leaves non-home paths untouched.\n *\n * @example\n * // os.homedir() === '/Users/arthur'\n * tildify('/Users/arthur/.infra-kit/infra-kit.json') // => '~/.infra-kit/infra-kit.json'\n * tildify('/etc/hosts') // => '/etc/hosts'\n */\nexport const tildify = (filePath: string): string => {\n const home = os.homedir()\n\n return filePath.startsWith(home) ? `~${filePath.slice(home.length)}` : filePath\n}\n", "import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the command ran off the CLI (an MCP tool), where a `pnpm exec` line would be\n * nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * Appending is safe: no leaf uses `passThroughOptions` or `--`, and the only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv that already carries `--yes`/`-y` is returned\n * as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this function's\n * problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const args = absolutizeChangeDir(parsedArgv.slice(2), launchCwd)\n\n const alreadyConfirmed = args.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? args : [...args, '--yes']\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about an MCP schema making a field\n * required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard (and under `'mcp'` `process.stdin` IS the\n// JSON-RPC transport), so no prompt at any site can return a usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an MCP-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for MCP in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\n//\n// WORDING IS SOURCE-AWARE. \"stdin carries JSON-RPC\" is true of exactly one caller; a skill driving\n// the CLI over Bash that reads it would go looking for a server that does not exist. Only the\n// `'mcp'` source keeps that text.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === 'mcp') return 'an interactive prompt was reached under MCP, where stdin carries JSON-RPC'\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (source: AgentModeSource, argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n if (source === 'mcp') {\n return argument === undefined\n ? `${passIt} \u2014 MCP runs have no human to answer it`\n : `pass \"${argument}\" \u2014 MCP runs have no human to answer it`\n }\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(source, argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "import { OperationError } from './operation-error'\nimport type { OperationErrorContext } from './operation-error'\n\n/**\n * Why the command stopped, for a machine reader. `exitCode` 2 means nothing happened \u2014 re-run with\n * more; 1 means something happened and part of it failed.\n */\nexport type RefusalStatus = 'confirmation_required' | 'argument_required' | 'partial_failure' | 'refused'\n\nexport interface RefusalStructuredContent {\n status: RefusalStatus\n [k: string]: unknown\n}\n\n/**\n * A refusal that carries a payload for whichever agent surface is listening: `entry/cli.ts` emits\n * `structuredContent` under `--json` and exits with `exitCode`; the MCP tool handler renders it as an\n * `isError` result with the same `structuredContent`. The message is the ordinary `OperationError`\n * one (operation / stderr / remediation), so the human-readable line loses nothing.\n *\n * @example\n * throw new StructuredRefusalError(\n * { status: 'argument_required', argument: 'version', agentMode: 'flag' },\n * 2,\n * { operation: 'interactive prompt', remediation: 'pass --version' },\n * )\n */\n// Extends `OperationError`, not `Error`, ON PURPOSE. Seven of the eight confirm sites sit under a\n// handler-level `catch` that passes through only `isPromptCancellation`, `isCommandDeclined` and\n// `instanceof OperationError` and REWRAPS everything else into a generic `OperationError`\n// (`release-remove.ts` near the `gh auth status` remediation, `worktrees-add.ts`, `worktrees-sync.ts`,\n// `release-create.ts`). A plain `Error` subclass would lose the payload and the exit code at exactly\n// the sites this exists for.\nexport class StructuredRefusalError extends OperationError {\n readonly structuredContent: RefusalStructuredContent\n readonly exitCode: 1 | 2\n\n constructor(structuredContent: RefusalStructuredContent, exitCode: 1 | 2, context: OperationErrorContext) {\n super(undefined, context)\n this.name = 'StructuredRefusalError'\n this.structuredContent = structuredContent\n this.exitCode = exitCode\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their short-circuit for the MCP chokepoint and\n// every `--yes` human stays as it was.\nexport const refuseUnconfirmed = (message: string, plan?: unknown): never => {\n const { source } = agentMode\n const rerun = rerunArgv()\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n"],
|
|
5
|
+
"mappings": "2JAKA,OAAOA,MAAQ,mBACf,OAAOC,MAAU,YACjB,OAAS,KAAAC,MAAS,MCsBX,IAAMC,EAAN,cAA2B,KAAM,CAO7B,IAET,YAAYC,EAAiBC,EAAqB,KAAM,CACtD,MAAMD,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,IAAMC,CACb,CACF,EAgBaC,GAAoBC,GACxBA,aAAiBJ,EC5D1B,OAAOK,MAAQ,mBACf,OAAOC,MAAQ,UAiBR,IAAMC,EAAa,MAAOC,GAAuC,CACtE,GAAI,CACF,aAAMH,EAAG,OAAOG,CAAQ,EAEjB,EACT,MAAQ,CACN,MAAO,EACT,CACF,EAWaC,EAAWD,GAA6B,CACnD,IAAME,EAAOJ,EAAG,QAAQ,EAExB,OAAOE,EAAS,WAAWE,CAAI,EAAI,IAAIF,EAAS,MAAME,EAAK,MAAM,CAAC,GAAKF,CACzE,EFnBA,IAAMG,EAAmB,cAGnBC,EAAsB,EAGtBC,EAAkB,IAGlBC,EAAiB,IAqBjBC,EAAmBC,EACtB,OAAO,CACN,QAASA,EAAE,QAAQJ,CAAmB,EAAE,QAAQA,CAAmB,EACnE,KAAMI,EAAE,OAAOA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAGA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CACrD,CAAC,EACA,OAAO,EAeGC,EAAoB,SAA6B,CAC5D,IAAMC,EAAQ,MAAMC,EAAuB,EAE3C,OAAOC,EAAK,KAAKA,EAAK,QAAQF,EAAM,WAAW,EAAGP,CAAgB,CACpE,EAeaU,EAAiB,SAAwC,CACpE,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C3D,MAAMA,CAAO,EACb,KAAK,KAAO,sBACd,CACF,EAGaC,GAAqBC,GACzBA,aAAiBH,EDkDnB,IAAMI,EAAoB,CAACC,EAAiBC,IAA0B,CAC3E,GAAM,CAAE,OAAAC,CAAO,EAAIC,EACbC,EAAQC,EAAU,EAExB,MAAM,IAAIC,EAAuB,CAAE,OAAQ,wBAAyB,QAAAN,EAAS,KAAAC,EAAM,MAAAG,EAAO,UAAWF,CAAO,EAAG,EAAG,CAChH,UAAW,yBACX,YACEA,IAAW,KACP,2DACA,uDAAuDE,EAAM,KAAK,GAAG,CAAC,gBAC5E,cAAe,yCACjB,CAAC,CACH,EAEaG,GAAgB,MAC3BC,EACAR,EACAS,EAAgC,CAAC,IACf,CACd,CAACD,GAAoBE,EAAW,GAAGX,EAAkBC,EAASS,EAAQ,IAAI,EAE9E,IAAME,EAASH,EACX,GACA,MAAMI,EACHC,GACQC,GAAQ,CAAE,QAAAd,CAAQ,EAAGa,CAAO,EAKrC,CAAE,aAAc,QAAS,CAC3B,EAMJ,GAJKL,GACHO,EAAY,eAAe,EAGzB,CAACJ,EAAQ,CACX,GAAIF,EAAQ,eACV,MAAM,IAAIO,EAGZC,EAAO,KAAK,iCAAiC,EAC7CC,GAAQ,KAAK,CAAC,CAChB,CACF",
|
|
6
|
+
"names": ["fs", "path", "z", "EnvAuthError", "message", "env", "isEnvAuthFailure", "error", "fs", "os", "fileExists", "filePath", "tildify", "home", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs", "createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "process", "StructuredRefusalError", "OperationError", "structuredContent", "exitCode", "context", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "passIt", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "source", "agentMode", "rerun", "rerunArgv", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as V}from"./chunk-MFAFQVTW.js";import{e as $}from"./chunk-75URROMU.js";import B from"node:process";import D from"pino";import we from"pino-pretty";var q="/tmp/mcp-infra-kit.log",H=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],rr=()=>{let e=B.argv.includes("--debug")?"debug":"info",t=D({level:e,redact:H},D.destination({dest:q}));return t.info(`Logger initialized with level: ${e}. Logging to: ${q}`),t},Pe=()=>{let e=B.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),D({level:e,redact:H},we({destination:2,ignore:t.join(","),colorize:!0}))},nr=Pe();import F from"node:fs/promises";import le from"node:os";import R from"node:path";import et from"node:process";import{z as s}from"zod";import be from"node:process";var C={enabled:!1},Re=(e,t=r=>{be.stdout.write(r)})=>(C.enabled&&e&&e.structuredContent!=null&&t(`${JSON.stringify(e.structuredContent,null,2)}
|
|
2
|
+
`),e),U=e=>{e.options.some(r=>r.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(U)};var X={source:null},x=()=>X.source!==null,Se=()=>x()||C.enabled,Ee=({env:e,stdinIsTTY:t,flag:r})=>{if(r)return"flag";let n=e.INFRA_KIT_AGENT;return n==="1"||e.CLAUDECODE!==void 0&&!t&&n!=="0"?"env":null};import w from"node:path";import te from"node:process";import{$ as d}from"zx";var P=e=>{let t=new Set,r=e;for(;r!==null&&typeof r=="object"&&!t.has(r);){t.add(r);let{stderr:n,stderrExcerpt:o}=r;if(typeof n=="string"&&n.length>0)return n;if(typeof o=="string"&&o.length>0)return o;r=r.cause}},Ce=(e,t)=>{let r=t.stderrExcerpt??P(e),n=[`failed to ${t.operation}`];return r&&n.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&n.push(`try: ${t.remediation}`),n.join(" \u2014 ")},f=class extends Error{operation;remediation;stderrExcerpt;constructor(t,r){super(Ce(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation,this.stderrExcerpt=r.stderrExcerpt??P(t)}};var je=/^v?(\d+)\.(\d+)\.(\d+)$/,Ae=/^(\d+)\.(\d+)\.(\d+)$/,Ie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,j="release/",T="release/v",J="refs/heads/",$e="next";var Y=new Set(["dev","main","next","hotfix","regular","release"]),v=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},k=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},Q=e=>e.startsWith(J)?e.slice(J.length):e,ee=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),N=e=>{if(e.length===0)throw new v('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new v(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!Ie.test(e))throw new v(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(Y.has(e))throw new v(`Release name "${e}" is reserved. Reserved names: ${[...Y].join(", ")}.`)},_=e=>{let t=Q(e.trim());if(!t.startsWith(j))return null;if(t.startsWith(T)){let n=t.slice(T.length),o=Ae.exec(n);if(o)return ee(Number(o[1]),Number(o[2]),Number(o[3]))}let r=t.slice(j.length);try{N(r)}catch{return null}return{kind:"name",name:r,raw:r}},De=e=>{let t=e.trim();if(Q(t).startsWith(j)){let o=_(t);if(!o)throw new k(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return o}let n=je.exec(t);if(n)return ee(Number(n[1]),Number(n[2]),Number(n[3]));if(t.toLowerCase()===$e)throw new k('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{N(t)}catch(o){let i=o instanceof Error?o.message:String(o);throw new k(`Cannot parse "${e}" as a release ref: ${i}`)}return{kind:"name",name:t,raw:t}},Te=e=>e.kind==="version"?`${T}${e.raw}`:`${j}${e.name}`,Ne=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},_e=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,Le=e=>e.kind==="version"?`v${e.raw}`:e.name,Me=e=>e.raw,L=e=>e==null?!1:_(e)!==null,Z=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},Oe=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let n=Z(r?.a),o=Z(r?.b);return n!==null&&o!==null&&n!==o?n-o:e.name<t.name?-1:e.name>t.name?1:0};var re=async e=>{let t=await d({cwd:e})`git worktree list --porcelain`,r=[],n=null;for(let o of t.stdout.split(`
|
|
3
|
+
`)){if(o.startsWith("worktree ")){n&&r.push(n),n={path:o.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o.startsWith("branch ")?n.branch=o.slice(7).replace(/^refs\/heads\//,""):o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="locked"||o.startsWith("locked ")?n.locked=!0:(o==="prunable"||o.startsWith("prunable "))&&(n.prunable=!0))}return n&&r.push(n),r},Ke=async e=>{let t=await re(te.cwd()),r=n=>e==="release"?L(n):n.startsWith("feature/");return t.map(n=>n.branch).filter(n=>n!==null&&r(n))},We=e=>{let t=P(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},Fe=({hasStderr:e})=>{if(x())return"infra-kit resolves its project from the working directory; run it from inside an infra-kit project repo (or one of its git worktrees), or pass `-C <dir>` naming one";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},b=async()=>{try{return(await d({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=We(e)??P(e);throw new f(e,{operation:`resolve the project root from ${te.cwd()}`,stderrExcerpt:t,remediation:Fe({hasStderr:t!==void 0})})}},M=async e=>{let t=e??await b(),r=(await d({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=w.resolve(t,r);return n.includes(`${w.sep}.git${w.sep}modules${w.sep}`)?t:w.dirname(n)},ne=async()=>(await d`git rev-parse --abbrev-ref HEAD`).stdout.trim(),oe=async()=>(await d`git status --porcelain`).stdout.split(`
|
|
4
|
+
`).map(t=>t.trimEnd()).filter(t=>t.trim().length>0),Ge=async()=>(await oe()).length===0,ze=async()=>{let e=await b(),[t,r]=await Promise.all([d({cwd:e})`git rev-parse --absolute-git-dir`,d({cwd:e})`git rev-parse --git-common-dir`]),n=t.stdout.trim(),o=w.resolve(e,r.stdout.trim());return n!==o};var Ve=async e=>(await d`git branch --list ${e}`).stdout.trim().length>0,qe=async e=>{(await d`git branch --list ${e}`).stdout.trim().length!==0&&await ne()!==e&&await d`git branch -D ${e}`},Be=async e=>{(await d`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await d`git push origin --delete ${e}`};import{$ as A}from"zx";var He=async(e,t)=>{let r=`${t}^{commit}`;try{return(await A({cwd:e,quiet:!0})`git rev-parse --verify --quiet ${r}`).stdout.trim()||null}catch{return null}},Ue=async(e,t,r)=>{try{return await A({cwd:e,quiet:!0})`git merge-base --is-ancestor ${t} ${r}`,!0}catch(n){if(n.exitCode===1)return!1;throw new f(n,{operation:`test whether ${t} is contained in ${r}`,remediation:"both refs must exist \u2014 verify them with rev-parse first"})}},Xe=async(e,t)=>{let n=(await A({cwd:e,quiet:!0})`git ls-remote --heads origin ${t}`).stdout.trim().split(`
|
|
5
|
+
`)[0];return n?n.split(/\s+/)[0]??null:null},Je=async(e,t)=>{let r=t.map(n=>`${n.sha}:refs/heads/${n.branch}`);if(r.length===0)return{refspecs:r,pushed:!1};try{return await A({cwd:e,quiet:!0})`git push --atomic origin ${r}`,{refspecs:r,pushed:!0}}catch(n){return{refspecs:r,pushed:!1,stderr:n.stderr}}};import se from"node:path";import O from"node:process";import{$ as m}from"zx";var ie=async e=>{let t=e??O.cwd(),r=(await m({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=O.env.INFRA_KIT_SESSION||String(O.pid);return se.join(se.resolve(t,r),"infra-kit",`merge-dev-${n}`)},K=async e=>{try{return await m({cwd:e,quiet:!0})`git rev-parse -q --verify MERGE_HEAD`,!0}catch{return!1}},Ye=async e=>{if(await K(e))throw new f(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:"a merge is still in progress in the scratch worktree",remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"});let t=(await m({cwd:e,quiet:!0})`git status --porcelain`).stdout.trim();if(t.length>0)throw new f(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:`scratch worktree is dirty: ${t.split(`
|
|
6
|
+
`)[0]}`,remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"})},Ze=async e=>{let t=async r=>{try{await r()}catch{}};await K(e)&&await t(()=>m({cwd:e,quiet:!0})`git merge --abort`),await t(()=>m({cwd:e,quiet:!0})`git reset --hard`),await t(()=>m({cwd:e,quiet:!0})`git clean -fd`)},Qe=async(e,t)=>{let{cwd:r,anchor:n="origin/dev"}=e,o=await ie(r),i=async()=>{await m({cwd:r,quiet:!0})`git worktree add --detach ${o} ${n}`};try{await i()}catch(u){try{await m({cwd:r,quiet:!0})`git worktree prune`,await i()}catch{throw new f(u,{operation:"create the scratch worktree for the merge",remediation:`remove any stale checkout at ${o}, then retry`})}}let c={path:o,remove:async()=>{try{await m({cwd:r,quiet:!0})`git worktree remove --force ${o}`}catch{}}};try{return await t(c)}finally{await c.remove()}};var ae="infra-kit.json";var tt="infra-kit.json",rt="projects",nt=s.object({provider:s.literal("doppler"),config:s.object({name:s.string().min(1)})}),ot=s.discriminatedUnion("provider",[nt]),st=s.object({workspaceConfigPath:s.string().min(1)}),it=s.object({provider:s.literal("cursor"),config:st}),at=s.object({}),ct=s.object({provider:s.literal("zed"),config:at}),ce=s.discriminatedUnion("provider",[it,ct]),pt=s.union([ce,s.array(ce).min(1)]),ut=s.object({provider:s.literal("jira"),config:s.object({baseUrl:s.string().url(),projectId:s.number().int().positive()})}),lt=s.discriminatedUnion("provider",[ut]),dt=["two-columns","three-pane"],ft=s.object({layout:s.enum(dt).optional()}),mt=s.object({openInGithubDesktop:s.boolean().optional(),openInCmux:s.boolean().optional(),cmux:ft.optional()}),gt=s.object({port:s.number().int().positive().optional(),prefixUrl:s.string().min(1).optional()}).strict(),ht=s.record(s.string().min(1),gt),yt=s.enum(["local","cloud"]),vt=s.object({watchDeps:s.boolean().optional(),proxy:s.record(s.string().min(1),yt).optional()}).strict(),xt=s.object({apps:s.record(s.string().min(1),vt).optional(),cmux:s.boolean().optional()}).strict(),kt=s.record(s.string().min(1),xt),wt=s.object({port:s.number().int().positive().optional()}).strict(),Pt=s.object({trigger:s.enum(["shell-startup","cli-invocation"]),config:s.string().min(1)}).strict(),bt=s.enum(["disallow","allow","cli-only"]),pe=s.string().regex(/^[A-Z_]\w*$/i,"must be a POSIX environment-variable name"),Rt=s.object({command:s.string().min(1),args:s.array(s.string()).default([]),env:s.array(pe).min(1),unset:s.array(pe).default([])}).strict().superRefine((e,t)=>{for(let r of e.env)V.has(r)&&t.addIssue({code:"custom",path:["env"],message:`"${r}" is process plumbing the proxy never strips or injects \u2014 it cannot be a credential name`})}),St=s.record(s.string().regex(/^[a-z][a-z0-9-]*$/,"must be lowercase letters, digits and hyphens, starting with a letter").refine(e=>!e.includes("infra-kit"),{message:'"infra-kit" is reserved for the infra-kit MCP server itself'}),Rt),G=s.object({envManagement:ot,ide:pt.optional(),taskManager:lt.optional(),worktrees:mt.optional(),envAutoLoad:Pt.optional(),dev:ht.optional(),devServersPresets:kt.optional(),devProxy:wt.optional(),protectedEnvs:bt.optional(),mcp:St.optional()}).strict(),Et=443,de=G.superRefine((e,t)=>{if(!Array.isArray(e.ide))return;let r=new Set;for(let n of e.ide){if(r.has(n.provider)){t.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}r.add(n.provider)}}),fe=G.partial(),Ct=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},jt="two-columns",At=e=>e.worktrees?.cmux?.layout??jt,g=null,S=null,me=()=>`${et.cwd()} ${le.homedir()}`,ge=async()=>{let e=me();if(S&&S.key===e)return S.value;let t=await b(),r=await M(t),n=R.basename(r),o=R.join(le.homedir(),$),i={main:R.join(t,ae),userGlobal:R.join(o,tt),userProject:R.join(o,rt,n,ae),projectName:n};return S={key:e,value:i},i},It=async()=>{let e=me(),t=await ge(),r;try{r=await F.stat(t.main)}catch{g=null;let h=t.main.replace(/\.json$/,".yml");throw await W(h)?new Error(`infra-kit.json not found at ${t.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit setup --skip-tools\` to convert it.`):new Error(x()?`infra-kit.json not found at ${t.main} \u2014 the working directory is not an infra-kit project. Run infra-kit from inside an infra-kit project repo, or pass \`-C <dir>\` naming one.`:`infra-kit.json not found at ${t.main} \u2014 this git repo is not an infra-kit project. Run \`infra-kit setup --skip-tools\` here to create it, cd into an infra-kit project repo, or check out a branch that has infra-kit.json.`)}let[n,o]=await Promise.all([W(t.userGlobal),W(t.userProject)]),i={main:Number(r.mtimeMs),userGlobal:n?Number(n.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(g&&g.key===e&&Nt(g.mtimes,i))return g.value;let c=[{label:"infra-kit.json",path:t.main,required:!0},{label:"~/.infra-kit/infra-kit.json",path:t.userGlobal,required:!1},{label:`~/.infra-kit/projects/${t.projectName}/infra-kit.json`,path:t.userProject,required:!1}],u={};for(let h of c){let y=await _t(h);y!==null&&(u={...u,...y})}let l=de.safeParse(u);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${s.prettifyError(l.error)}`);return g={key:e,mtimes:i,value:l.data},l.data},$t=()=>{g=null},Dt=()=>{g=null,S=null},W=async e=>{try{return await F.stat(e)}catch{return null}},Tt=async e=>{try{return await F.readFile(e,"utf-8")}catch{return null}},Nt=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>e[n]===t[n])},_t=async e=>{let t=await Tt(e.path);if(t===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${o.message}`)}if(ue(r)&&"envTokens"in r)throw new Error(Mt(e));if(!e.required&&ue(r)&&"mcp"in r)throw new Error(Lt(e));let n=fe.safeParse(r);if(!n.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${s.prettifyError(n.error)}`);return n.data},Lt=e=>[`"mcp" is not allowed in ${e.label} (${e.path}): it feeds the committed .mcp.json, so a per-machine copy would replace the project's servers for everyone.`,"Move the block to the project infra-kit.json and run `infra-kit setup`.","For a machine-only override of one server (e.g. a local fork), use Claude Code directly:"," claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> ... -- <command> <args>","(local scope shadows the project entry by name; `claude mcp list` will show a same-name conflict warning, which is expected)."].join(`
|
|
7
|
+
`),ue=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Mt=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
|
|
8
|
+
`);import*as p from"node:fs";import*as a from"node:path";function Ot(e){let t=e;for(let r=0;r<10;r++){let n=a.join(t,"pnpm-workspace.yaml");if(p.existsSync(n))return t;t=a.dirname(t)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function ye(e,t){let r=a.join(e,"package.json");if(!p.existsSync(r))return t;try{let n=JSON.parse(p.readFileSync(r,"utf-8"));return typeof n.name=="string"?n.name:t}catch{return t}}function Xr(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))throw new Error(`Apps directory not found: ${t}`);let n=p.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=a.join(t,o,"api"),c=a.join(i,"serverless.yml");p.existsSync(c)&&r.push({name:o,packageName:ye(i,o),path:i})}return r}var ve=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],Kt=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function Wt(e){for(let t of ve){let r=a.join(e,t);if(p.existsSync(r))try{let n=p.readFileSync(r,"utf-8");return Kt.some(o=>n.includes(o))}catch{return!1}}return!1}function Jr(e){for(let t of ve){let r=a.join(e,t);if(p.existsSync(r))try{return p.readFileSync(r,"utf-8").includes("infraKit(")}catch{return!1}}return!1}function Ft(e){let t=a.join(e,"package.json");if(!p.existsSync(t))return!1;try{let r=JSON.parse(p.readFileSync(t,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function Yr(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))return r;let n=p.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=a.join(t,o,"ui");p.existsSync(i)&&Ft(i)&&r.push({name:o,packageName:ye(i,o),path:i,managedPort:Wt(i)})}return r}function Zr(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function Qr(e){let t=Ot(e),r=a.relative(a.join(t,"apps"),e),n=r.split(a.sep)[0];if(r===""||r.startsWith("..")||a.isAbsolute(r)||!n)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${e}). Run from an app folder or use --app=<name>.`);return n}var Gt=new Set(["api","ui"]),he=e=>{let t=a.join(e,"dist");return p.existsSync(t)&&p.statSync(t).isDirectory()?t:void 0},z=e=>p.existsSync(e)?p.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function en(e){let t=[];for(let n of z(a.join(e,"packages"))){let o=he(a.join(e,"packages",n));o!==void 0&&t.push(o)}let r=a.join(e,"apps");for(let n of z(r))for(let o of z(a.join(r,n))){if(Gt.has(o))continue;let i=a.join(r,n,o);if(!p.existsSync(a.join(i,"package.json")))continue;let c=he(i);c!==void 0&&t.push(c)}return t}function tn(e){return e.map(t=>a.join(t.path,"dist")).filter(t=>p.existsSync(t))}function rn(e,t,r){let n=a.normalize(e),o=r.find(c=>n.startsWith(a.normalize(c)));return o?{kind:"package",packageDir:o}:{kind:"app",app:t.find(c=>n.startsWith(a.normalize(c)))}}var zt={"*/api":{},"*/ui":{}},ke=e=>{let t=e.split("/"),[r,n]=t;return t.length!==2||!r?`devServersPresets: invalid target "${e}" (expected "<app>/api" or "<app>/ui")`:n!=="api"&&n!=="ui"?`devServersPresets: invalid target part "${n}" in "${e}" (expected "api" or "ui")`:null},Vt=e=>{let t=ke(e);if(t)throw new Error(t);let[r,n]=e.split("/");return{appGlob:r,part:n}},on=e=>{let t=[];for(let[r,n]of Object.entries(e))for(let o of Object.keys(n.apps??{})){let i=ke(o);i&&t.push({preset:r,key:o,message:`preset "${r}": ${i}`})}return t},qt=(e,t)=>t==="api"?e.api:e.ui,Bt=e=>[...new Set([...e.api,...e.ui])].sort(),xe=(e,t)=>`${e}/${t}`,Ht=e=>e?0:1,Ut=(e,t)=>t.watchDeps===void 0?e??{watchDeps:!0,rank:t.rank,explicitValue:!1}:!e||!e.explicitValue?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:t.rank>e.rank?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:e,Xt=(e,t,r)=>{let{app:n,part:o,watchDeps:i,isGlob:c}=r;if(!qt(t,o).includes(n)){c||e.unmatched.push(xe(n,o));return}let u=xe(n,o),l=Ut(e.targets.get(u),{watchDeps:i,rank:Ht(c)});e.targets.set(u,{app:n,part:o,...l})},Jt=(e,t)=>{let r=Object.entries(e.apps??zt),n={targets:new Map,proxy:{},unmatched:[]};for(let[c,u]of r){let{appGlob:l,part:h}=Vt(c),y=l==="*",E=y?Bt(t):[l];for(let I of E)Xt(n,t,{app:I,part:h,watchDeps:u.watchDeps,isGlob:y}),u.proxy&&(n.proxy[I]={...n.proxy[I]??{},...u.proxy})}let o=[...n.targets.values()].map(({app:c,part:u,watchDeps:l})=>({app:c,part:u,watchDeps:l})),i=[...new Set(o.filter(c=>c.part==="api").map(c=>c.app))];return{targets:o,cmux:e.cmux??!1,proxy:n.proxy,localApps:i,unmatched:n.unmatched}},sn=e=>{if(e.preset!=null)return e.preset;if(e.running.length===0)return"nothing";let t=new Set(e.running);return e.discovered.every(n=>t.has(n))?"*":[...t].sort().join(" + ")},Yt=(e,t)=>Object.keys(e).find(r=>e[r]===t),Zt=({preset:e,app:t,route:r,launchedPkgs:n,ctx:o})=>{let i=o.routePkg(t,r);if(i===void 0)return{preset:e,app:t,route:r,kind:"unknown-route",message:`preset "${e}": proxy override "${r}" on "${t}" names a route not declared in ${t}'s infra-kit.config.ts dev.proxy.routes`};if(n.has(i))return null;let c=Yt(o.apiPkgByApp,i),u=c?`add "${c}/api" to the preset`:`launch the api whose package is "${i}"`;return{preset:e,app:t,route:r,pkg:i,kind:"backend-not-launched",message:`preset "${e}": proxy override "${r}" \u2192 "local" requires backend "${i}" to run locally, but the preset does not launch it \u2014 ${u}, or set "${r}" to "cloud"`}},an=(e,t)=>{let r=[];for(let[n,o]of Object.entries(e)){let i=Jt(o,t.discovered),c=new Set(i.localApps.map(u=>t.apiPkgByApp[u]).filter(u=>u!==void 0));for(let[u,l]of Object.entries(i.proxy))for(let[h,y]of Object.entries(l)){if(y!=="local")continue;let E=Zt({preset:n,app:u,route:h,launchedPkgs:c,ctx:t});E&&r.push(E)}}return r};export{C as a,Re as b,U as c,X as d,x as e,Se as f,Ee as g,P as h,f as i,v as j,N as k,_ as l,De as m,Te as n,Ne as o,_e as p,Le as q,Me as r,L as s,Oe as t,re as u,Ke as v,b as w,M as x,ne as y,oe as z,Ge as A,ze as B,Ve as C,qe as D,Be as E,He as F,Ue as G,Xe as H,Je as I,K as J,Ye as K,Ze as L,Qe as M,q as N,rr as O,nr as P,Et as Q,de as R,fe as S,Ct as T,At as U,ge as V,It as W,$t as X,Dt as Y,Ot as Z,Xr as _,Jr as $,Yr as aa,Zr as ba,Qr as ca,en as da,tn as ea,rn as fa,ke as ga,on as ha,Jt as ia,sn as ja,an as ka};
|
|
9
|
+
//# sourceMappingURL=chunk-GCX3HDDL.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/logger/index.ts", "../src/lib/infra-kit-config/infra-kit-config.ts", "../src/lib/json-output/json-output.ts", "../src/lib/agent-mode/agent-mode.ts", "../src/lib/git-utils/git-utils.ts", "../src/lib/errors/operation-error.ts", "../src/lib/release-id/release-id.ts", "../src/lib/git-utils/merge-refs.ts", "../src/lib/git-utils/scratch-worktree.ts", "../src/dev/discovery.ts", "../src/dev/presets.ts"],
|
|
4
|
+
"sourcesContent": ["import process from 'node:process'\nimport pino from 'pino'\nimport pretty from 'pino-pretty'\n\n// eslint-disable-next-line sonarjs/publicly-writable-directories\nexport const LOG_FILE_PATH = '/tmp/mcp-infra-kit.log'\n\n/**\n * Key paths pino censors before anything reaches a destination. The load-bearing case is the MCP\n * tool-handler, which logs every tool's `params` object \u2014 twice (at entry, and again in its catch) \u2014\n * into a WORLD-READABLE `/tmp/mcp-infra-kit.log`. A token-carrying key in that object would be\n * written to a file every user on the box can read.\n *\n * The wildcard forms cover the nesting we actually produce: `{ params: { \u2026 } }` and `{ err: { \u2026 } }`\n * are both one level deep, so `*.token` catches `params.token` without enumerating every wrapper.\n *\n * LIMIT \u2014 read this before trusting it: pino's `redact` is KEY-PATH based. It cannot see a token that\n * was INTERPOLATED into a message string (`logger.info(\\`token ${t}\\`)`) \u2014 that string is opaque to\n * it and would be written verbatim. So this is a backstop, not the rule. The RULE is that a token\n * never enters a message string; everything user-facing renders it through `redactToken` first.\n */\nconst REDACT_PATHS = [\n 'token',\n '*.token',\n 'serviceToken',\n '*.serviceToken',\n 'DOPPLER_TOKEN',\n '*.DOPPLER_TOKEN',\n 'INFRA_KIT_ENV_TOKEN',\n '*.INFRA_KIT_ENV_TOKEN',\n]\n\nexport const initLoggerMcp = () => {\n const logLevel = process.argv.includes('--debug') ? 'debug' : 'info'\n\n const logger = pino({ level: logLevel, redact: REDACT_PATHS }, pino.destination({ dest: LOG_FILE_PATH }))\n\n logger.info(`Logger initialized with level: ${logLevel}. Logging to: ${LOG_FILE_PATH}`)\n\n return logger\n}\n\nexport const initLoggerCLI = () => {\n const logLevel = process.argv.includes('--debug') ? 'debug' : 'info'\n\n const ignoreFields = ['time', 'pid', 'hostname']\n\n if (logLevel === 'debug') {\n ignoreFields.push('level')\n }\n\n const logger = pino(\n { level: logLevel, redact: REDACT_PATHS },\n pretty({\n destination: 2,\n ignore: ignoreFields.join(','),\n colorize: true,\n }),\n )\n\n return logger\n}\n\n// Singleton logger instance for CLI usage\nexport const logger = initLoggerCLI()\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport { isAgentMode } from 'src/lib/agent-mode'\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\nimport { getMainRepoRoot, getProjectRoot } from 'src/lib/git-utils'\nimport { PROTECTED_CHILD_ENV_NAMES } from 'src/lib/mcp-proxy/protected-env'\n\nconst INFRA_KIT_CONFIG_FILE = 'infra-kit.json'\n\n// Re-exported for the existing consumers (the vendor factory-config loader, no import cycle \u2014 this\n// module imports no `lib/vendor` code); the definition lives in `lib/constants` so zod-free entries\n// can share it.\nexport { USER_CONFIG_DIR_NAME }\nconst USER_GLOBAL_CONFIG_FILE = 'infra-kit.json'\nconst USER_PROJECTS_DIR = 'projects'\n\n// envManagement\nconst dopplerEnvManagementSchema = z.object({\n provider: z.literal('doppler'),\n config: z.object({\n name: z.string().min(1),\n }),\n})\n\nconst envManagementSchema = z.discriminatedUnion('provider', [dopplerEnvManagementSchema])\n\n// ide\n// There is one attach style: each worktree is added to the configured editor's\n// workspace and opened (no per-window mode). Cursor needs a `.code-workspace`\n// path to reconcile its `folders` array against.\nconst cursorIdeConfigSchema = z.object({\n workspaceConfigPath: z.string().min(1),\n})\n\nconst cursorIdeSchema = z.object({\n provider: z.literal('cursor'),\n config: cursorIdeConfigSchema,\n})\n\n// Zed has no portable workspace file (no `.code-workspace`) and no folder-remove\n// CLI: a multi-worktree workspace is realized by a single `zed <root> <wt...>`\n// invocation. So `config` carries no settings \u2014 there's no path to point at.\nconst zedIdeConfigSchema = z.object({})\n\nconst zedIdeSchema = z.object({\n provider: z.literal('zed'),\n config: zedIdeConfigSchema,\n})\n\nconst ideSchema = z.discriminatedUnion('provider', [cursorIdeSchema, zedIdeSchema])\n\n// `ide` accepts a single provider (back-compat) OR an array to drive multiple\n// editors at once (e.g. Cursor + Zed). Normalized to an array everywhere via\n// `resolveConfiguredIdes`. Uniqueness-by-provider is enforced at parse time by a\n// `.superRefine` on the full config schema (see below) \u2014 not here, so the message\n// survives `z.union` error aggregation.\nconst idesSchema = z.union([ideSchema, z.array(ideSchema).min(1)])\n\n// taskManager\n//\n// PARSED BUT NEVER READ. Nothing in this CLI consumes `config.taskManager` \u2014 every Jira call builds\n// its config from the JIRA_BASE_URL / JIRA_EMAIL / JIRA_TOKEN / JIRA_PROJECT_ID environment\n// variables (see `loadJiraConfig` in integrations/jira/api.ts). Keeping it validated is deliberate:\n// `infraKitConfigObject` is `.strict()` and `getInfraKitConfig()` runs as an unconditional guard on\n// most commands, so deleting the key would make every command throw in any consumer repo whose\n// infra-kit.json declares it. The trap it sets is real \u2014 a `projectId` here looks authoritative and\n// changing it does nothing \u2014 so the consumer-facing template carries the same warning.\nconst jiraTaskManagerSchema = z.object({\n provider: z.literal('jira'),\n config: z.object({\n baseUrl: z.string().url(),\n projectId: z.number().int().positive(),\n }),\n})\n\nconst taskManagerSchema = z.discriminatedUnion('provider', [jiraTaskManagerSchema])\n\n// cmux pane layout for opened worktree workspaces. Named presets keep the config\n// typo-proof (an enum, not a free string) and let the opener switch on a single\n// value; extend the enum + the opener's switch to add a layout.\n// two-columns \u2014 left | right, both full-height (default)\n// three-pane \u2014 left split top/bottom + full-height right (legacy layout)\nconst cmuxLayouts = ['two-columns', 'three-pane'] as const\n\nconst cmuxConfigSchema = z.object({\n layout: z.enum(cmuxLayouts).optional(),\n})\n\n// worktrees prompt defaults\nconst worktreesConfigSchema = z.object({\n openInGithubDesktop: z.boolean().optional(),\n openInCmux: z.boolean().optional(),\n cmux: cmuxConfigSchema.optional(),\n})\n\n// dev-server per-app overrides. Maps an app folder name (e.g. `client`) to its\n// local dev port and/or URL prefix. Both keys optional. An app absent from the\n// map falls back to env (`{APP}_PORT` / `PORT`) then the built-in defaults, so\n// the map is intentionally NOT validated against the discovered apps here \u2014 an\n// unknown app name is simply ignored at resolve time (lib/dev), never a parse\n// error that would brick every command.\nconst devAppConfigSchema = z\n .object({\n port: z.number().int().positive().optional(),\n prefixUrl: z.string().min(1).optional(),\n })\n .strict()\n\nconst devConfigSchema = z.record(z.string().min(1), devAppConfigSchema)\n\n// devServersPresets: named local-dev sessions, declared in the per-project infra-kit.json\n// (team presets committed; personal ones layered via the user-project override).\n// Each preset names launch targets (apps/<app>/{api,ui}), optional per-backend\n// `watchDeps`, per-route proxy-source overrides, and a `cmux` layout flag; it is\n// consumed by `infra-kit dev <preset>` and resolved by src/dev/presets. Each target key\n// names exactly one workspace package (`<app>/api` or `<app>/ui`) \u2014 a bare `<app>` is a\n// folder, not a package, and is rejected. The SHAPE is strict (typos in a preset surface\n// as parse errors), but unknown app/route NAMES are intentionally NOT validated here \u2014\n// they resolve at run time against the discovered apps, so a stale preset never bricks\n// every command.\nconst proxySourceSchema = z.enum(['local', 'cloud'])\n\nconst devPresetAppSchema = z\n .object({\n // api targets only: watch the backend's dist + shared-package subdeps and restart on change.\n watchDeps: z.boolean().optional(),\n // route path (e.g. `/api`) \u2192 source, overriding that route's config.ts default for this session.\n proxy: z.record(z.string().min(1), proxySourceSchema).optional(),\n })\n .strict()\n\nconst devPresetSchema = z\n .object({\n // Launch-target key \u2014 one package: `client/ui`, `client/api`, `*/api`. Omit `apps` = all.\n apps: z.record(z.string().min(1), devPresetAppSchema).optional(),\n // Run each launched target in its own cmux pane (one workspace, N panes).\n cmux: z.boolean().optional(),\n })\n .strict()\n\nconst devPresetsSchema = z.record(z.string().min(1), devPresetSchema)\n\n// DEPRECATED (accepted and ignored). Layer-B local-dev proxy (portless).\n//\n// The proxy port is no longer negotiable: every dev URL is `https://<release>.<packageName>.localhost`\n// with NO port, and the only port that can serve a port-free HTTPS URL is 443. A configurable port would\n// put the port straight back into the URL \u2014 the exact thing this design removes.\n//\n// The key is still PARSED so it does not brick anything: `infraKitConfigObject` is `.strict()` and\n// `getInfraKitConfig` THROWS on an unknown key, so simply deleting it would hard-fail EVERY infra-kit\n// command (not just `dev`) on any machine whose config still carries it \u2014 arriving unannounced, because\n// the CLI self-updates. It is read by nothing and silently ignored. Remove one release from now.\nconst devProxyConfigSchema = z\n .object({\n port: z.number().int().positive().optional(),\n })\n .strict()\n\n// env auto-load: opt-in convenience that primes Doppler env when you work inside\n// this project / a worktree. Absent => disabled. `trigger` selects the moment\n// (pick one):\n// shell-startup \u2014 when a new shell opens inside the project\n// cli-invocation \u2014 before each `infra-kit` command (primes SUBSEQUENT commands)\n// `config` names which environment to load. It is intentionally NOT validated\n// against `environments` here: an invalid name must DISABLE the feature at\n// resolve time (lib/env-autoload), never throw inside the merged-config parse and\n// brick every command.\nconst envAutoLoadSchema = z\n .object({\n trigger: z.enum(['shell-startup', 'cli-invocation']),\n config: z.string().min(1),\n })\n .strict()\n\n// Base object shape, kept separate so `.partial()` (which only works on a plain\n// ZodObject, not the `.superRefine`-wrapped full schema) can derive the override\n// schema from it.\n//\n// `.strict()` for the same reason every leaf schema below is: this is the one config file humans\n// hand-edit, and a non-strict top level silently swallows the typo that matters most. `devServersPreset`\n// (missing `s`) or `dev-proxy` would parse clean and turn the feature off with no message. The `dev` and\n// `devServersPresets` values stay open `z.record`s \u2014 app and preset NAMES are user-chosen \u2014 so strictness\n// applies to the key set, not the contents.\n// GONE: `environments`. It answered three questions at once and was therefore wrong for two of them.\n// Where can I deploy? \u2192 each workflow's own `workflow_dispatch` `environment.options`, which GitHub\n// validates server-side (`lib/workflow-envs`). What can I authenticate to? \u2192 the token store\n// (`lib/env-tokens`). Being a third, hand-maintained copy of both, it drifted from both: hulyo declared\n// 6 envs while every hulyo workflow declared 8, and the client-side check turned that drift into a\n// REFUSAL to deploy to `stage` and `prod`.\n//\n// Deleted outright rather than accepted-and-ignored: the key is removed from every repo in the same\n// change, so nothing that is checked out on a current branch still carries it. Because this schema is\n// `.strict()`, a config that DOES still carry it (an old release branch, an unmigrated worktree) is\n// refused with `Unrecognized key: \"environments\"` \u2014 delete the key there too.\n// protectedEnvs \u2014 may THIS project reach the delivery-shaped environments listed in\n// `DEFAULT_PROTECTED_ENVS` (lib/workflow-envs/protected-envs)? The list stays in code; only the\n// decision is per-project. \"disallow\" (the default) is today's behaviour: filtered from every deploy\n// picker and refused. \"allow\" reaches them from the CLI and over MCP alike. \"cli-only\" reaches them\n// from a terminal but not from an agent \u2014 over MCP it behaves exactly as \"disallow\", because\n// `createToolHandler` injects `confirmedCommand: true`, which is the very flag that skips every\n// interactive confirmation, so there is no human keystroke on that path.\n//\n// An ENUM rather than a boolean because the VALUE extends without touching the KEY, and a key rename\n// here is expensive: `.strict()` turns the old name into a parse error that bricks every command,\n// which is why `devProxy` below is still parsed and ignored rather than deleted. \"cli-only\" is that\n// extension already spent.\n//\n// NEVER give this field a `.default()`. `infraKitOverrideConfigSchema` is `.partial()` of this object,\n// and `.partial()` makes a key optional WITHOUT stripping a `ZodDefault` \u2014 so the default is still\n// injected on absence. `loadLayer` parses EVERY layer through that schema and merges the results, and\n// layer 3 always exists (auto-seeded `{}` on each command), so a default here would parse to\n// `{ protectedEnvs: 'disallow' }` and shallow-merge OVER a layer-1 \"allow\", silently reverting the\n// setting on every machine with no error anywhere. Verified on zod 4.4.3. The fallback is applied at\n// the single read site instead \u2014 see `resolveProtectedEnvAccess`. No other field in this schema has a\n// default, so nothing here demonstrates the trap: this comment is the only warning.\nconst protectedEnvsSchema = z.enum(['disallow', 'allow', 'cli-only'])\n\n/** A POSIX environment-variable name. Comma-free by construction, which is what keeps the derived\n * `ik-mcp` argv unambiguous. */\nconst envVarName = z.string().regex(/^[A-Z_]\\w*$/i, 'must be a POSIX environment-variable name')\n\n/**\n * One stdio MCP server fronted by `ik-mcp`, the credential-agnostic proxy.\n *\n * `env` are the names the proxy reads from the `ik env-load` session file and injects inline; all of\n * them non-empty means \"credentials present\", and their ordered values are the respawn key. `unset`\n * names are forced empty in the child so a stale file-based credential can never outrank the inline\n * one. Everything else the env file holds is withheld from the child.\n */\n// The proxy is for STATELESS servers: a credential change respawns the child and discards its\n// memory. A browser-automation server would lose its open tabs on every `env-load`. Servers that\n// take credentials only as flags, via OAuth, or from their own config file are out of scope.\nconst mcpProxySchema = z\n .object({\n command: z.string().min(1),\n args: z.array(z.string()).default([]),\n env: z.array(envVarName).min(1),\n unset: z.array(envVarName).default([]),\n })\n .strict()\n .superRefine((spec, ctx) => {\n for (const name of spec.env) {\n if (PROTECTED_CHILD_ENV_NAMES.has(name)) {\n ctx.addIssue({\n code: 'custom',\n path: ['env'],\n message: `\"${name}\" is process plumbing the proxy never strips or injects \u2014 it cannot be a credential name`,\n })\n }\n }\n })\n\n/**\n * `mcp.<name>` \u2192 the proxy spec. The name is the `.mcp.json` key and the proxy's cache subdir.\n *\n * A name containing `infra-kit` is refused because `install-state.ts` recognises THE infra-kit MCP\n * server by that substring in `command args`, so `infra-kit-docs` would read as a misfiled copy of it.\n */\nconst mcpProxiesSchema = z.record(\n z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/, 'must be lowercase letters, digits and hyphens, starting with a letter')\n .refine(\n (name) => {\n return !name.includes('infra-kit')\n },\n { message: '\"infra-kit\" is reserved for the infra-kit MCP server itself' },\n ),\n mcpProxySchema,\n)\n\nexport const infraKitConfigObject = z\n .object({\n envManagement: envManagementSchema,\n ide: idesSchema.optional(),\n taskManager: taskManagerSchema.optional(),\n worktrees: worktreesConfigSchema.optional(),\n envAutoLoad: envAutoLoadSchema.optional(),\n dev: devConfigSchema.optional(),\n devServersPresets: devPresetsSchema.optional(),\n devProxy: devProxyConfigSchema.optional(),\n protectedEnvs: protectedEnvsSchema.optional(),\n mcp: mcpProxiesSchema.optional(),\n })\n .strict()\n\n/**\n * The portless proxy's listen port. `443` \u2014 the implicit HTTPS port \u2014 because that is the ONLY port that\n * can serve a port-free `https://<release>.<packageName>.localhost` URL, which is the whole point.\n *\n * It is privileged, so the daemon must already be running: `infra-kit dev` PROBES it and never elevates\n * (portless binds `:443` by re-execing through `sudo` with an inherited stdio, which a detached child can\n * never answer). One-time, out-of-band: a root `portless service install`, which `dev` and `doctor` print\n * for the user as an absolute-path command (portless is not on `PATH`; see `formatPortlessCommand`). There\n * is deliberately no unprivileged fallback \u2014 a fallback puts the port back in the URL.\n *\n * Not a constant of convenience: it is the single value that decides the scheme, and TLS on 443 is\n * portless's own default (our previous `--no-tls` was the deviation).\n */\nexport const DEFAULT_DEV_PROXY_PORT = 443\n\n// Full schema = base object + a parse-time uniqueness check on the `ide` array.\n// This runs inside the *merged* `safeParse` in getInfraKitConfig, so it's the\n// gate for the final config. (The override layers use the `.partial()` form\n// below, which drops this object-level refinement \u2014 acceptable, the merged\n// parse is authoritative.)\nexport const infraKitConfigSchema = infraKitConfigObject.superRefine((cfg, ctx) => {\n if (!Array.isArray(cfg.ide)) return\n\n const seen = new Set<string>()\n\n for (const entry of cfg.ide) {\n if (seen.has(entry.provider)) {\n ctx.addIssue({\n code: 'custom',\n message: 'each IDE provider may appear at most once',\n path: ['ide'],\n })\n\n return\n }\n\n seen.add(entry.provider)\n }\n})\n\nexport const infraKitOverrideConfigSchema = infraKitConfigObject.partial()\n\nexport type InfraKitConfig = z.infer<typeof infraKitConfigSchema>\n\n/** This project's access to the delivery-shaped environments. Absent in config means `'disallow'`. */\nexport type ProtectedEnvsSetting = z.infer<typeof protectedEnvsSchema>\n\n/** One `mcp.<name>` entry after parsing \u2014 defaults applied. */\nexport type McpProxySpec = z.infer<typeof mcpProxySchema>\nexport type McpProxies = z.infer<typeof mcpProxiesSchema>\n\n/** Resolved env auto-load config (`{ trigger, config }`), or `undefined` when off. */\nexport type EnvAutoLoadConfig = z.infer<typeof envAutoLoadSchema>\n\n/** Per-app dev-server overrides (`{ port?, prefixUrl? }`). */\nexport type DevAppConfig = z.infer<typeof devAppConfigSchema>\n\n/** The full `dev` section: a map of app folder name to its {@link DevAppConfig}. */\nexport type DevConfig = z.infer<typeof devConfigSchema>\n\n/** A proxy route's resolved source in a preset override (`'local' | 'cloud'`). */\nexport type ProxySource = z.infer<typeof proxySourceSchema>\n\n/** A single dev preset (`{ apps?, cmux? }`) from the `devServersPresets` map. */\nexport type DevPreset = z.infer<typeof devPresetSchema>\n\n/** The `devServersPresets` map: preset name \u2192 {@link DevPreset}. */\nexport type DevPresets = z.infer<typeof devPresetsSchema>\n\n/** A single resolved IDE entry (`{ provider, config }`). */\nexport type ConfiguredIde = z.infer<typeof ideSchema>\n\n/**\n * Normalize the `ide` config (single object, array, or unset) into a flat list.\n * Validation-free: assumes already-parsed input (uniqueness is enforced by the\n * schema). The one source of truth for \"which editors are configured.\"\n *\n * @example\n * resolveConfiguredIdes({ ide: { provider: 'cursor', config: {...} } }) // => [cursor]\n * resolveConfiguredIdes({ ide: [cursor, zed] }) // => [cursor, zed]\n * resolveConfiguredIdes({}) // => []\n */\nexport const resolveConfiguredIdes = (config: InfraKitConfig): ConfiguredIde[] => {\n const ide = config.ide\n\n if (!ide) return []\n\n return Array.isArray(ide) ? ide : [ide]\n}\n\n/** A cmux pane layout preset (see {@link cmuxLayouts}). */\nexport type CmuxLayout = (typeof cmuxLayouts)[number]\n\n/** The layout applied when `worktrees.cmux.layout` is left unset. */\nexport const DEFAULT_CMUX_LAYOUT: CmuxLayout = 'two-columns'\n\n/**\n * Resolve the cmux pane layout for opened worktree workspaces, falling back to\n * {@link DEFAULT_CMUX_LAYOUT} when unconfigured. The one source of truth for\n * \"which layout should the cmux opener build.\"\n *\n * @example\n * resolveCmuxLayout({ worktrees: { cmux: { layout: 'three-pane' } } }) // => 'three-pane'\n * resolveCmuxLayout({}) // => 'two-columns'\n */\nexport const resolveCmuxLayout = (config: InfraKitConfig): CmuxLayout => {\n return config.worktrees?.cmux?.layout ?? DEFAULT_CMUX_LAYOUT\n}\n\nexport interface InfraKitConfigPaths {\n /** Committed project config (required). */\n main: string\n /** User-scope global overrides applied to every project. */\n userGlobal: string\n /** User-scope per-project overrides \u2014 `<userProjectsDir>/<projectName>/infra-kit.json`. */\n userProject: string\n /** Repo basename (`path.basename(projectRoot)`) used to namespace the user-project file. */\n projectName: string\n}\n\ninterface CacheEntry {\n /** `cwd + homedir` \u2014 see {@link pathsCacheKey}. Required alongside `mtimes`: mtimes alone can\n * collide across two different repo roots (or two homedirs), which would serve one repo's config\n * to a request for another inside a long-lived process (the MCP server). */\n key: string\n mtimes: Record<keyof Omit<InfraKitConfigPaths, 'projectName'>, number | null>\n value: InfraKitConfig\n}\n\nlet cached: CacheEntry | null = null\n\ninterface PathsCacheEntry {\n key: string\n value: InfraKitConfigPaths\n}\n\n/**\n * Memo slot for {@link getInfraKitConfigPaths}. SINGLE-ENTRY, not a `Map`: the resolver's only\n * inputs are `process.cwd()` and `os.homedir()`, and production never mutates either (there is zero\n * `process.chdir` outside tests), so one key covers the whole process lifetime. A `Map` would buy\n * nothing there and could hand a chdir'ing test file a stale sibling entry; a single slot that\n * recomputes on key mismatch is strictly safer and identically fast.\n */\nlet cachedPaths: PathsCacheEntry | null = null\n\n/**\n * Cache key for {@link cachedPaths}. `homedir` is load-bearing, not decoration: the resolver reads\n * it directly, and a dozen test files swap it for a fresh `mkdtemp` home WITHOUT chdir'ing \u2014 a\n * cwd-only key would hand test B test A's already-deleted temp home.\n *\n * @example\n * pathsCacheKey() // => '/Users/arthur/projects/api /Users/arthur'\n */\nconst pathsCacheKey = (): string => {\n return `${process.cwd()} ${os.homedir()}`\n}\n\n/**\n * Resolve every file path that participates in the config merge chain. Always\n * returns paths even for files that don't yet exist, so callers can use them\n * for \"where would my override go?\" prompts.\n *\n * Memoized on `cwd + homedir` (see {@link cachedPaths}) because the two `git rev-parse` spawns below\n * run BEFORE the mtime cache in `getInfraKitConfig`, so without this every call paid for both. The\n * memo is populated on success only \u2014 `getProjectRoot` rejects outside a git repo and callers depend\n * on that rejection, so a cached rejection would be a stateful negative path. Cleared by\n * {@link resetInfraKitConfigCache}.\n *\n * Safe to memoize: this is a pure path resolver (inputs = cwd + homedir; it returns paths, never\n * file contents), so filesystem mutation cannot invalidate it.\n *\n * @example\n * const paths = await getInfraKitConfigPaths()\n * // {\n * // main: '/Users/arthur/projects/api/infra-kit.json',\n * // userGlobal: '/Users/arthur/.infra-kit/infra-kit.json',\n * // userProject: '/Users/arthur/.infra-kit/projects/api/infra-kit.json',\n * // projectName: 'api',\n * // }\n */\nexport const getInfraKitConfigPaths = async (): Promise<InfraKitConfigPaths> => {\n const key = pathsCacheKey()\n\n if (cachedPaths && cachedPaths.key === key) {\n return cachedPaths.value\n }\n\n const projectRoot = await getProjectRoot()\n // Namespace the per-project override on the MAIN repo root, not `projectRoot`.\n // Inside a linked worktree `projectRoot` is the worktree's own path, so its\n // basename is the worktree's leaf dir (e.g. `feature-x`), which would key the\n // override to a different, per-worktree file. `getMainRepoRoot` resolves the\n // shared git common dir so every worktree of a repo converges on one key. The\n // second `git rev-parse` this costs is fine \u2014 the merged config is mtime-cached.\n const mainRepoRoot = await getMainRepoRoot(projectRoot)\n const projectName = path.basename(mainRepoRoot)\n const userConfigDir = path.join(os.homedir(), USER_CONFIG_DIR_NAME)\n\n const value: InfraKitConfigPaths = {\n main: path.join(projectRoot, INFRA_KIT_CONFIG_FILE),\n userGlobal: path.join(userConfigDir, USER_GLOBAL_CONFIG_FILE),\n userProject: path.join(userConfigDir, USER_PROJECTS_DIR, projectName, INFRA_KIT_CONFIG_FILE),\n projectName,\n }\n\n // Populate only after both git calls RESOLVED \u2014 never cache a rejection.\n cachedPaths = { key, value }\n\n return value\n}\n\n/**\n * Read and validate `infra-kit.json`, with optional override layers shallow-merged\n * on top in this order (later wins):\n * 1. project `infra-kit.json` \u2014 committed source of truth\n * 2. `~/.infra-kit/infra-kit.json` \u2014 user-global defaults\n * 3. `~/.infra-kit/projects/<repo-name>/infra-kit.json` \u2014 user-scope per-project overrides\n *\n * Top-level keys (entire capability sections like `ide`, `envManagement`)\n * replace wholesale. Results are cached per file mtimes so the long-running\n * MCP server picks up edits without a restart.\n *\n * @example\n * // infra-kit.json: { \"environments\": [\"dev\"], \"envManagement\": { \"provider\": \"doppler\", \"config\": { \"name\": \"p\" } } }\n * // ~/.infra-kit/infra-kit.json: { \"ide\": { \"provider\": \"cursor\", \"config\": { \"workspaceConfigPath\": \"./ws.code-workspace\" } } }\n * const cfg = await getInfraKitConfig()\n * // => { environments: ['dev'], envManagement: {...}, ide: { provider: 'cursor', config: { workspaceConfigPath: './ws.code-workspace' } } }\n */\nexport const getInfraKitConfig = async (): Promise<InfraKitConfig> => {\n const key = pathsCacheKey()\n const paths = await getInfraKitConfigPaths()\n\n let mainStat: Awaited<ReturnType<typeof fs.stat>>\n\n try {\n mainStat = await fs.stat(paths.main)\n } catch {\n cached = null\n\n // Bridge the YAML\u2192JSON cutover: if a legacy infra-kit.yml is sitting where\n // the JSON config should be, point the user at the one-shot migration.\n const legacyYmlPath = paths.main.replace(/\\.json$/, '.yml')\n\n if (await statIfExists(legacyYmlPath)) {\n throw new Error(\n `infra-kit.json not found at ${paths.main}. A legacy infra-kit.yml exists \u2014 run \\`infra-kit setup --skip-tools\\` to convert it.`,\n )\n }\n\n throw new Error(\n isAgentMode()\n ? `infra-kit.json not found at ${paths.main} \u2014 the working directory is not an infra-kit project. Run infra-kit from inside an infra-kit project repo, or pass \\`-C <dir>\\` naming one.`\n : `infra-kit.json not found at ${paths.main} \u2014 this git repo is not an infra-kit project. Run \\`infra-kit setup --skip-tools\\` here to create it, cd into an infra-kit project repo, or check out a branch that has infra-kit.json.`,\n )\n }\n\n const [userGlobalStat, userProjectStat] = await Promise.all([\n statIfExists(paths.userGlobal),\n statIfExists(paths.userProject),\n ])\n\n const mtimes = {\n main: Number(mainStat.mtimeMs),\n userGlobal: userGlobalStat ? Number(userGlobalStat.mtimeMs) : null,\n userProject: userProjectStat ? Number(userProjectStat.mtimeMs) : null,\n }\n\n if (cached && cached.key === key && shallowEqual(cached.mtimes, mtimes)) {\n return cached.value\n }\n\n const layers: ConfigLayer[] = [\n { label: 'infra-kit.json', path: paths.main, required: true },\n { label: '~/.infra-kit/infra-kit.json', path: paths.userGlobal, required: false },\n {\n label: `~/.infra-kit/projects/${paths.projectName}/infra-kit.json`,\n path: paths.userProject,\n required: false,\n },\n ]\n\n let merged: Record<string, unknown> = {}\n\n for (const layer of layers) {\n const data = await loadLayer(layer)\n\n if (data === null) continue\n\n merged = { ...merged, ...data }\n }\n\n const finalResult = infraKitConfigSchema.safeParse(merged)\n\n if (!finalResult.success) {\n throw new Error(`Invalid merged infra-kit config: ${z.prettifyError(finalResult.error)}`)\n }\n\n cached = { key, mtimes, value: finalResult.data }\n\n return finalResult.data\n}\n\n/**\n * Drop ONLY the merged-config cache ({@link cached}), keeping the path memo ({@link cachedPaths})\n * intact. For writers of a merge layer \u2014 the config bootstrap, which creates the layer-3\n * `~/.infra-kit/projects/<repo>/infra-kit.json`.\n *\n * WHY this exists separately from {@link resetInfraKitConfigCache}: writing the layer-3 file changes\n * the MERGE RESULT (a stale merged config would miss the new layer) but it cannot change the\n * RESOLVED PATHS \u2014 those are a pure function of `cwd + homedir`, and creating a file mutates\n * neither. Blowing away the path memo there would just make the very run that creates the file\n * re-spawn both `git rev-parse` processes for nothing: 4 spawns instead of 2.\n *\n * @example\n * await fs.writeFile(paths.userProject, '{}\\n', 'utf-8')\n * resetMergedConfigCache()\n * await getInfraKitConfig() // sees the new layer-3 layer\n * await getInfraKitConfigPaths() // still served from the memo \u2014 zero extra git spawns\n */\nexport const resetMergedConfigCache = (): void => {\n cached = null\n}\n\n/**\n * For tests \u2014 drops BOTH in-memory caches: the mtime-fingerprinted merged config and the\n * `cwd + homedir`-keyed path memo ({@link cachedPaths}). The next read re-spawns `git rev-parse`\n * and re-hits disk. Production writers want the narrower {@link resetMergedConfigCache}.\n *\n * @example\n * resetInfraKitConfigCache()\n * await getInfraKitConfig() // re-resolves paths and re-reads files even if mtimes look unchanged\n */\nexport const resetInfraKitConfigCache = (): void => {\n cached = null\n cachedPaths = null\n}\n\n/**\n * `fs.stat` that returns `null` instead of throwing on ENOENT. Used so the\n * resolver can probe optional files in the merge chain without try/catch noise.\n *\n * @example\n * const stat = await statIfExists('/does/not/exist') // => null\n */\nconst statIfExists = async (filePath: string): Promise<Awaited<ReturnType<typeof fs.stat>> | null> => {\n try {\n return await fs.stat(filePath)\n } catch {\n return null\n }\n}\n\n/**\n * `fs.readFile` that returns `null` instead of throwing on ENOENT.\n *\n * @example\n * const raw = await readIfExists('/missing.json') // => null\n * const raw = await readIfExists('/exists.json') // => '{ \"environments\": [\"dev\"] }\\n'\n */\nconst readIfExists = 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 * Reference-equality comparison of every key in two flat records. Used to\n * cheaply detect whether the cached mtime fingerprint still matches.\n *\n * @example\n * shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2 }) // => true\n * shallowEqual({ a: 1 }, { a: 1, b: 2 }) // => false\n * shallowEqual({ a: 1 }, { a: 2 }) // => false\n */\nconst shallowEqual = <T extends Record<string, unknown>>(a: T, b: T): boolean => {\n const keys = Object.keys(a)\n\n if (keys.length !== Object.keys(b).length) return false\n\n return keys.every((k) => {\n return a[k] === b[k]\n })\n}\n\ninterface ConfigLayer {\n label: string\n path: string\n required: boolean\n}\n\n/**\n * Read a single layer of the merge chain: parse the JSON if the file exists\n * and validate it against the override schema. Returns `null` if an optional\n * layer is missing; throws if the layer is required, malformed, or invalid.\n * An empty/whitespace-only file is treated as `{}` (JSON.parse would throw).\n *\n * @example\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/missing.json', required: false })\n * // => null\n * @example\n * // /home/me/.infra-kit/infra-kit.json: '{ \"ide\": { \"provider\": \"cursor\", \"config\": { \"workspaceConfigPath\": \"./ws.code-workspace\" } } }'\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/home/me/.infra-kit/infra-kit.json', required: false })\n * // => { ide: { provider: 'cursor', config: { workspaceConfigPath: './ws.code-workspace' } } }\n */\nconst loadLayer = async (layer: ConfigLayer): Promise<Record<string, unknown> | null> => {\n const raw = await readIfExists(layer.path)\n\n if (raw === null) {\n if (layer.required) {\n throw new Error(`${layer.label} not found at ${layer.path}`)\n }\n\n return null\n }\n\n let parsedRaw: unknown\n\n try {\n parsedRaw = raw.trim() === '' ? {} : JSON.parse(raw)\n } catch (err) {\n throw new Error(`Invalid JSON in ${layer.label} at ${layer.path}: ${(err as Error).message}`)\n }\n\n // `envTokens` is ALREADY rejected below \u2014 the override schema keeps `.strict()`, so it lands as a\n // generic `unrecognized_keys` issue. That generic message is wrong for this one key: the user has\n // pasted a live Doppler service token into a file that may be committed, backed up by their editor,\n // or opened by `config edit`. The first instruction has to be REVOKE, not \"fix your config\". Narrow\n // by construction \u2014 every other unknown key keeps the generic error.\n if (isRecord(parsedRaw) && 'envTokens' in parsedRaw) {\n throw new Error(buildEnvTokensRejectionMessage(layer))\n }\n\n // `mcp` is the ONE key that feeds a committed artifact: `ik setup` derives `.mcp.json` entries from\n // it. The layer merge below is shallow (`{ ...merged, ...data }`), so a per-machine `mcp` would\n // replace the project's block wholesale and then be derived into the shared file \u2014 either\n // reddening `audit` on this machine alone or, worse, getting committed. Refused loudly rather than\n // silently ignored: the message names the tool that DOES own a per-machine server override.\n if (!layer.required && isRecord(parsedRaw) && 'mcp' in parsedRaw) {\n throw new Error(buildMcpLayerRejectionMessage(layer))\n }\n\n const result = infraKitOverrideConfigSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new Error(`Invalid ${layer.label} at ${layer.path}: ${z.prettifyError(result.error)}`)\n }\n\n return result.data as Record<string, unknown>\n}\n\n/**\n * Why `mcp` cannot live in this layer, and where the two things a developer might have wanted go\n * instead: the project file for a shared server, Claude Code's own local scope for a machine-only\n * override (which shadows the project entry by name and needs no infra-kit involvement).\n */\nexport const buildMcpLayerRejectionMessage = (layer: ConfigLayer): string => {\n return [\n `\"mcp\" is not allowed in ${layer.label} (${layer.path}): it feeds the committed .mcp.json, so a per-machine copy would replace the project's servers for everyone.`,\n 'Move the block to the project infra-kit.json and run `infra-kit setup`.',\n 'For a machine-only override of one server (e.g. a local fork), use Claude Code directly:',\n ' claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> ... -- <command> <args>',\n '(local scope shadows the project entry by name; `claude mcp list` will show a same-name conflict warning, which is expected).',\n ].join('\\n')\n}\n\n/**\n * Narrow parsed JSON to a plain object so a key probe is safe (JSON's top level may be an array, a\n * string, or `null`).\n *\n * @example\n * isRecord({ envTokens: {} }) // => true\n * isRecord(['envTokens']) // => false\n * isRecord(null) // => false\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * The REVOKE-first refusal for a service token found in an `infra-kit.json`. Ordered by urgency: the\n * credential is already exposed, so revoking it beats editing the file. Tokens live in a SIBLING\n * `tokens.json` (0600) that this loader never reads \u2014 see `lib/env-tokens`.\n *\n * @example\n * buildEnvTokensRejectionMessage({ label: 'infra-kit.json', path: '/r/infra-kit.json', required: true })\n * // => 'Refusing to load infra-kit.json \u2014 `envTokens` is not a config key. \u2026'\n */\nconst buildEnvTokensRejectionMessage = (layer: ConfigLayer): string => {\n return [\n `Refusing to load ${layer.label} \u2014 \\`envTokens\\` is not a config key.`,\n 'A service token in a config file can be committed, backed up by your editor, or shared.',\n ' 1. REVOKE the token in Doppler now \u2014 treat it as compromised.',\n ` 2. Remove the \\`envTokens\\` key from ${layer.path}.`,\n ' 3. Re-add it privately: `infra-kit env-token-set <env>`',\n ' (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo).',\n ].join('\\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", "/**\n * @fileoverview\n * Agent-mode flag for the CLI: \"no human is at the other end of stdin\". Anything that would read\n * keystrokes (raw `data` listeners, Ink screens, `@inquirer` prompts) must be gated off, and any\n * guard that exists because an agent needs a human's say-so keys on it.\n *\n * Three sources, and they are not interchangeable \u2014 the source is kept, not just the boolean, so a\n * refusal can word itself for the caller it actually has:\n * - `'mcp'`: this process is serving MCP and `process.stdin` IS the JSON-RPC transport. Set in\n * `createMcpServer()` (the importable, transport-free entry every MCP launch goes through), not in\n * `entry/mcp.ts`, which starts a server at module scope and so can never assert the flag was set.\n * The MCP path never runs Commander's `preAction`, so no flag or variable can reach this source.\n * - `'flag'`: the global `--agent` option. Beats every environment value, `INFRA_KIT_AGENT=0`\n * included \u2014 a skill that passes `--agent` must never be silently demoted by a variable in\n * someone's `.zshenv`.\n * - `'env'`: `INFRA_KIT_AGENT=1`, or `CLAUDECODE` set with a non-TTY stdin. The TTY qualifier is the\n * point: `CLAUDECODE=1` is inherited by every process Claude Code spawns, including the cmux and\n * Zed terminals `worktrees add` opens, and those are humans at a PTY. `INFRA_KIT_AGENT=0` suppresses\n * only that heuristic; any other value is ignored as if unset.\n *\n * `process.stdin.isTTY` alone CANNOT answer the MCP case: `commands/mcp/mcp.ts` spawns the server\n * with `stdio: 'inherit'`, so a terminal-launched `infra-kit mcp` hands the child a real TTY stdin\n * and an isTTY-keyed guard does not fire. Piped stdio (how Claude Code spawns it) only makes isTTY\n * look sufficient by coincidence.\n */\nimport { jsonOutput } from 'src/lib/json-output'\n\nexport type AgentModeSource = 'mcp' | 'flag' | 'env' | null\n\n/** Mutable holder (object so `prefer-const` holds while the source toggles per run). */\nexport const agentMode = { source: null as AgentModeSource }\n\n/** True when an agent, not a human, is driving this process \u2014 whichever source said so. */\nexport const isAgentMode = (): boolean => {\n return agentMode.source !== null\n}\n\n/**\n * True when nobody can answer a prompt: an agent is driving, or `--json` has claimed stdout for a\n * machine. Every confirm and picker site keys on this one predicate so the 20-odd sites agree; the\n * few that also care WHICH source read `agentMode.source` next to it.\n */\nexport const isHeadless = (): boolean => {\n return isAgentMode() || jsonOutput.enabled\n}\n\nexport interface ResolveAgentModeInput {\n env: NodeJS.ProcessEnv\n stdinIsTTY: boolean\n /** The global `--agent` option as Commander parsed it. */\n flag: boolean\n}\n\n/**\n * Pure precedence over the two non-MCP sources; `'mcp'` is set directly by the server and never\n * produced here. Called once per run from `program.hook('preAction')`.\n *\n * @example\n * resolveAgentModeSource({ env: { INFRA_KIT_AGENT: '0' }, stdinIsTTY: true, flag: true }) // 'flag'\n * resolveAgentModeSource({ env: { INFRA_KIT_AGENT: '1' }, stdinIsTTY: true, flag: false }) // 'env'\n * resolveAgentModeSource({ env: { CLAUDECODE: '1' }, stdinIsTTY: false, flag: false }) // 'env'\n * resolveAgentModeSource({ env: { CLAUDECODE: '1', INFRA_KIT_AGENT: '0' }, stdinIsTTY: false, flag: false }) // null\n * resolveAgentModeSource({ env: { CLAUDECODE: '1' }, stdinIsTTY: true, flag: false }) // null\n */\nexport const resolveAgentModeSource = ({ env, stdinIsTTY, flag }: ResolveAgentModeInput): AgentModeSource => {\n if (flag) return 'flag'\n\n const agentVar = env.INFRA_KIT_AGENT\n\n if (agentVar === '1') return 'env'\n\n const claudeCodeHeuristic = env.CLAUDECODE !== undefined && !stdinIsTTY && agentVar !== '0'\n\n return claudeCodeHeuristic ? 'env' : null\n}\n", "import path from 'node:path'\nimport process from 'node:process'\nimport { $ } from 'zx'\n\nimport { isAgentMode } from 'src/lib/agent-mode'\nimport { OperationError, extractStderr } from 'src/lib/errors/operation-error'\nimport { isReleaseBranch } from 'src/lib/release-id'\n\n/**\n * A single record from `git worktree list --porcelain`. The porcelain format is\n * the source of truth for worktrees: it carries the absolute `path` (which the\n * human format's `[branch]` scrape discards), and it distinguishes detached /\n * bare / prunable / locked states that the scrape collapses to `null`.\n *\n * `branch` is the short name (`release/v1.2.3`, `feature/x`) with `refs/heads/`\n * stripped, or `null` for a detached, bare, or otherwise branch-less checkout.\n */\nexport interface WorktreeEntry {\n path: string\n branch: string | null\n detached: boolean\n bare: boolean\n prunable: boolean\n locked: boolean\n}\n\n/**\n * List every git worktree of the repo containing `cwd`, parsed from\n * `git worktree list --porcelain`.\n *\n * Porcelain is a stable, documented, line-oriented format: one record per\n * worktree, records separated by a blank line, each opening with a\n * `worktree <abs-path>` line. Attribute lines (`branch`, `detached`, `bare`,\n * `locked`, `prunable`) follow. This replaces the legacy `endsWith(']')` scrape\n * of the human format, which lost the path and returned `null` for detached\n * worktrees.\n *\n * The main checkout is included in the output (as its own record), exactly as\n * git reports it.\n */\nexport const listWorktrees = async (cwd: string): Promise<WorktreeEntry[]> => {\n const output = await $({ cwd })`git worktree list --porcelain`\n\n const entries: WorktreeEntry[] = []\n let current: WorktreeEntry | null = null\n\n for (const line of output.stdout.split('\\n')) {\n if (line.startsWith('worktree ')) {\n // A new record opens; flush the previous one.\n if (current) entries.push(current)\n\n current = {\n path: line.slice('worktree '.length),\n branch: null,\n detached: false,\n bare: false,\n prunable: false,\n locked: false,\n }\n\n continue\n }\n\n if (!current) continue\n\n if (line.startsWith('branch ')) {\n current.branch = line.slice('branch '.length).replace(/^refs\\/heads\\//, '')\n } else if (line === 'detached') {\n current.detached = true\n } else if (line === 'bare') {\n current.bare = true\n } else if (line === 'locked' || line.startsWith('locked ')) {\n current.locked = true\n } else if (line === 'prunable' || line.startsWith('prunable ')) {\n current.prunable = true\n }\n }\n\n if (current) entries.push(current)\n\n return entries\n}\n\n/**\n * Get current git worktrees\n *\n * Thin wrapper over {@link listWorktrees}: harvests branch names from the\n * porcelain records and filters by release / feature shape. Detached, bare, and\n * branch-less records drop out naturally (their `branch` is `null`).\n *\n * @returns [release/v1.18.22, release/v1.18.23, release/v1.18.24] or [feature/mobile-app, feature/explore-page, feature/login-page]\n */\nexport const getCurrentWorktrees = async (type: 'release' | 'feature'): Promise<string[]> => {\n const entries = await listWorktrees(process.cwd())\n\n const matches = (branch: string): boolean => {\n return type === 'release' ? isReleaseBranch(branch) : branch.startsWith('feature/')\n }\n\n return entries\n .map((entry) => {\n return entry.branch\n })\n .filter((branch): branch is string => {\n return branch !== null && matches(branch)\n })\n}\n\n/**\n * Trim git's `not a git repository (or any of the parent directories): .git` tail \u2014 and ONLY that.\n * Returns undefined for every other failure so `OperationError` falls through to the real stderr:\n * dubious ownership, EACCES, a corrupt repo, and a missing `git` binary must each report themselves.\n */\nconst normalizeGitRootStderr = (error: unknown): string | undefined => {\n const raw = extractStderr(error)\n\n return raw && /not a git repository/i.test(raw) ? 'not a git repository' : undefined\n}\n\n/**\n * Remediation text for a failed project-root resolution.\n *\n * Channel-aware: an agent is told which action it has (`-C <dir>`, or re-running from the project\n * directory) rather than to \"cd\", which a fixed-cwd caller cannot do.\n *\n * `hasStderr` gates the stderr-referencing clause: with no stderr (missing `git`\n * binary, ENOENT) the message must not point at evidence it does not carry.\n */\nconst projectRootRemediation = ({ hasStderr }: { hasStderr: boolean }): string => {\n if (isAgentMode()) {\n return 'infra-kit resolves its project from the working directory; run it from inside an infra-kit project repo (or one of its git worktrees), or pass `-C <dir>` naming one'\n }\n\n const base = 'run infra-kit from inside an infra-kit project repo (or one of its git worktrees)'\n\n return hasStderr ? `${base}; if you are already in one, the stderr in this message is the real cause` : base\n}\n\n/**\n * Get the current project root directory\n */\nexport const getProjectRoot = async (): Promise<string> => {\n try {\n const result = await $({ quiet: true })`git rev-parse --show-toplevel`\n\n return result.stdout.trim()\n } catch (error) {\n const stderrExcerpt = normalizeGitRootStderr(error) ?? extractStderr(error)\n\n throw new OperationError(error, {\n operation: `resolve the project root from ${process.cwd()}`,\n stderrExcerpt,\n remediation: projectRootRemediation({ hasStderr: stderrExcerpt !== undefined }),\n })\n }\n}\n\n/**\n * Absolute path to the MAIN repository root \u2014 invariant across the main checkout\n * and all of its linked worktrees. A linked worktree's `--show-toplevel` is the\n * worktree's own path, but its `--git-common-dir` still points at the shared\n * `<main>/.git`, so the parent of the resolved common dir is always the main repo.\n * This is the stable identity to key per-repo state on (unlike `getProjectRoot`,\n * whose basename is the worktree's leaf directory inside a worktree).\n *\n * Submodules are the one exception: their common dir is\n * `<super>/.git/modules/<name>`, whose parent (`.../.git/modules`) is not a repo\n * root \u2014 there is no meaningful \"main repo\" to converge on \u2014 so we fall back to\n * the caller-supplied toplevel unchanged. Callers must pass a git toplevel as\n * `cwd` (e.g. the result of {@link getProjectRoot}); the fallback assumes it.\n *\n * @example\n * // main checkout: common dir '.git' \u2192 resolve \u2192 '<main>/.git' \u2192 dirname \u2192 '<main>'\n * await getMainRepoRoot('/Users/me/projects/hulyo') // => '/Users/me/projects/hulyo'\n * // linked worktree: common dir '<main>/.git' \u2192 dirname \u2192 '<main>'\n * await getMainRepoRoot('/Users/me/projects/hulyo-worktrees/feature/x') // => '/Users/me/projects/hulyo'\n */\nexport const getMainRepoRoot = async (cwd?: string): Promise<string> => {\n const root = cwd ?? (await getProjectRoot())\n const commonDir = (await $({ cwd: root, quiet: true })`git rev-parse --git-common-dir`).stdout.trim()\n const resolved = path.resolve(root, commonDir)\n\n // Submodule: common dir sits under `<super>/.git/modules/<name>` \u2014 no stable\n // main-repo root to key on, so keep the caller's own toplevel.\n if (resolved.includes(`${path.sep}.git${path.sep}modules${path.sep}`)) return root\n\n return path.dirname(resolved)\n}\n\n/**\n * Get the current git branch name (e.g. `dev`, `main`, `release/v1.2.3`).\n */\nexport const getCurrentBranch = async (): Promise<string> => {\n const result = await $`git rev-parse --abbrev-ref HEAD`\n\n return result.stdout.trim()\n}\n\n/**\n * The working tree's `git status --porcelain` lines: staged, unstaged, and untracked\n * changes, one entry per path. Empty means clean.\n *\n * The porcelain output is returned rather than reduced to a boolean because every refusal\n * built on it has to name the paths that block the operation \u2014 an operator told only\n * \"working tree has uncommitted changes\" has to run `git status` themselves to act on it.\n */\nexport const getWorkingTreeStatus = async (): Promise<string[]> => {\n const result = await $`git status --porcelain`\n\n // Only the trailing whitespace is stripped. The two leading columns are the status itself \u2014\n // ` M` is \"modified in the worktree\" and `M ` is \"modified and staged\" \u2014 so trimming the left\n // side would render the first as the second in a message whose whole job is to tell the\n // operator what is in their way.\n return result.stdout\n .split('\\n')\n .map((line) => {\n return line.trimEnd()\n })\n .filter((line) => {\n return line.trim().length > 0\n })\n}\n\n/**\n * Whether the working tree has no staged, unstaged, or untracked changes.\n */\nexport const isWorkingTreeClean = async (): Promise<boolean> => {\n return (await getWorkingTreeStatus()).length === 0\n}\n\n/**\n * Whether the current checkout is a linked git worktree rather than the main\n * repository checkout.\n *\n * A linked worktree's git dir lives under `<main>/.git/worktrees/<name>`, so it\n * differs from the shared common dir; in the main checkout the two resolve to\n * the same path. Both are anchored to the toplevel so `--git-common-dir` (which\n * git may report relative to cwd) resolves consistently.\n */\nexport const isInsideLinkedWorktree = async (): Promise<boolean> => {\n const cwd = await getProjectRoot()\n\n const [gitDirResult, commonDirResult] = await Promise.all([\n $({ cwd })`git rev-parse --absolute-git-dir`,\n $({ cwd })`git rev-parse --git-common-dir`,\n ])\n\n const gitDir = gitDirResult.stdout.trim()\n const commonDir = path.resolve(cwd, commonDirResult.stdout.trim())\n\n return gitDir !== commonDir\n}\n\n/**\n * Basename of the CURRENT worktree's toplevel \u2014 a linked worktree returns the worktree dir name,\n * not the repository. Not a repo identity; see {@link getMainRepoRoot} for the stable root.\n *\n * @deprecated It has no production caller: its last one fed `local-deploy` preflight the release\n * name instead of the project. Kept only because the test suite still imports it.\n */\nexport const getRepoName = async (): Promise<string> => {\n const projectRoot = await getProjectRoot()\n\n return path.basename(projectRoot)\n}\n\n/**\n * Check whether a local branch exists.\n *\n * `deleteLocalBranch` fails open: it silently returns without deleting when\n * the branch is the current checkout or already absent, and either way its\n * `void` return gives the caller no way to tell \"deleted\" apart from \"did\n * nothing\". A caller that must not report an unperformed deletion \u2014 such as\n * a teardown command confirming a branch is actually gone \u2014 needs this\n * independent check rather than trusting `deleteLocalBranch`'s outcome.\n */\nexport const branchExists = async (branch: string): Promise<boolean> => {\n const listed = await $`git branch --list ${branch}`\n\n return listed.stdout.trim().length > 0\n}\n\n/**\n * Delete a local branch if it exists and is not the current checkout.\n *\n * Idempotent: a no-op when the branch is absent (`git branch --list` prints\n * nothing). Uses force `-D` because a delivered release branch was\n * squash-merged \u2014 its tip is unreachable from the base, so `-d` would refuse\n * with \"not fully merged\". The delete itself still rejects if the branch is\n * checked out in another worktree; callers decide how to handle that.\n */\nexport const deleteLocalBranch = async (branch: string): Promise<void> => {\n const listed = await $`git branch --list ${branch}`\n\n if (listed.stdout.trim().length === 0) return\n\n if ((await getCurrentBranch()) === branch) return\n\n await $`git branch -D ${branch}`\n}\n\n/**\n * Delete a branch on the `origin` remote if it exists.\n *\n * Idempotent: a no-op when the branch is absent on the remote. Existence is\n * probed with `git ls-remote --heads` (empty stdout = absent) rather than\n * `--exit-code`, so a genuine network/auth failure rejects and propagates to\n * the caller instead of being silently misread as \"branch absent\".\n */\nexport const deleteRemoteBranch = async (branch: string): Promise<void> => {\n const refs = await $`git ls-remote --heads origin ${branch}`\n\n if (refs.stdout.trim().length === 0) return\n\n await $`git push origin --delete ${branch}`\n}\n", "const STDERR_EXCERPT_MAX_BYTES = 200\n\nexport interface OperationErrorContext {\n operation: string\n remediation?: string\n stderrExcerpt?: string\n}\n\n/**\n * Duck-typed read of zx's `ProcessOutput.stderr` (and similar shapes) without\n * importing zx types just for an `instanceof` check.\n *\n * @example\n * extractStderr(new Error('x')) // undefined\n * extractStderr({ stderr: 'fatal: ...' }) // 'fatal: ...'\n * extractStderr({ stderr: '' }) // undefined (empty treated as missing)\n */\nexport const extractStderr = (cause: unknown): string | undefined => {\n // Walks the `cause` chain rather than reading one level. `OperationError` renders\n // `stderrExcerpt` into its message and keeps it on the instance, but an OperationError\n // wrapped in another OperationError \u2014 which is what `executeOne` does to every per-entry\n // failure \u2014 carries no `.stderr` of its own. Reading one level there returns undefined, so\n // the inner refusal's evidence would be silently dropped from the message the operator and\n // the MCP client actually see.\n const seen = new Set<unknown>()\n let current = cause\n\n while (current !== null && typeof current === 'object' && !seen.has(current)) {\n seen.add(current)\n\n const { stderr, stderrExcerpt } = current as { stderr?: unknown; stderrExcerpt?: unknown }\n\n if (typeof stderr === 'string' && stderr.length > 0) return stderr\n if (typeof stderrExcerpt === 'string' && stderrExcerpt.length > 0) return stderrExcerpt\n\n current = (current as { cause?: unknown }).cause\n }\n\n return undefined\n}\n\n/**\n * Compose the human-and-agent-readable message body for an `OperationError`:\n * `\"failed to <operation> [\u2014 stderr: <excerpt>] [\u2014 try: <remediation>]\"`.\n * `stderrExcerpt` overrides anything duck-typed off `cause`; both are trimmed\n * and capped at {@link STDERR_EXCERPT_MAX_BYTES} so a runaway subprocess can't\n * blow up the message.\n */\nconst buildMessage = (cause: unknown, ctx: OperationErrorContext): string => {\n const stderr = ctx.stderrExcerpt ?? extractStderr(cause)\n const parts = [`failed to ${ctx.operation}`]\n\n if (stderr) parts.push(`stderr: ${stderr.slice(0, STDERR_EXCERPT_MAX_BYTES).trim()}`)\n if (ctx.remediation) parts.push(`try: ${ctx.remediation}`)\n\n return parts.join(' \u2014 ')\n}\n\n/**\n * Error type for any handler-level failure that should surface to the caller\n * (CLI user or MCP-connected agent) with a remediation hint. Wraps an\n * underlying cause and renders a single-line, structured message so logs and\n * agent tool-result text stay scannable.\n *\n * Pattern modeled on the exemplary Doppler errors in\n * `src/integrations/doppler/doppler-errors.ts`.\n *\n * @example\n * throw new OperationError(err, {\n * operation: `git worktree add for ${branch}`,\n * remediation: 'check the branch name and that the parent dir is writable',\n * })\n * @example\n * // validation failure, with no underlying cause to wrap\n * throw new OperationError(undefined, { operation: 'launch deploy-all workflow', remediation })\n */\nexport class OperationError extends Error {\n readonly operation: string\n readonly remediation?: string\n /**\n * Kept on the instance, not merely rendered into the message: this error is routinely\n * re-wrapped in another `OperationError` (see `executeOne`), and {@link extractStderr}\n * walks the `cause` chain looking for exactly this field. Without it the outer message\n * reports only its own generic remediation and the real reason disappears.\n */\n readonly stderrExcerpt?: string\n\n constructor(cause: unknown, ctx: OperationErrorContext) {\n super(buildMessage(cause, ctx), { cause })\n this.name = 'OperationError'\n this.operation = ctx.operation\n this.remediation = ctx.remediation\n this.stderrExcerpt = ctx.stderrExcerpt ?? extractStderr(cause)\n }\n}\n", "/**\n * A release identity is either a semantic version or a free-form kebab-case\n * name. `raw` is the canonical token for the id: the no-`v` semver string for\n * versions (e.g. `1.2.3`) and the name itself for named releases.\n */\nexport type ReleaseId =\n | { kind: 'version'; semver: { major: number; minor: number; patch: number }; raw: string }\n | { kind: 'name'; name: string; raw: string }\n\n/** Matches a bare or `v`-prefixed semver token, e.g. `1.2.3` or `v1.2.3`. */\nconst VERSION_RE = /^v?(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/** Matches the semver core after the `v` in a `release/v\u2026` branch. */\nconst BRANCH_SEMVER_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/** Kebab-case: lowercase alphanumeric segments joined by single hyphens. */\nconst KEBAB_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\nconst RELEASE_BRANCH_PREFIX = 'release/'\nconst VERSION_BRANCH_PREFIX = 'release/v'\nconst REFS_HEADS_PREFIX = 'refs/heads/'\n\nconst NEXT_TOKEN = 'next'\nconst MAX_NAME_LENGTH = 50\n\n/**\n * Names that would collide with branch/release semantics or read as a special\n * token. Banned regardless of kebab-case validity.\n */\nconst RESERVED_NAMES: ReadonlySet<string> = new Set(['dev', 'main', 'next', 'hotfix', 'regular', 'release'])\n\n/** Thrown by {@link validateName} when a release name is not acceptable. */\nexport class InvalidReleaseNameError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidReleaseNameError'\n }\n}\n\n/** Thrown by {@link parseReleaseRef} when a release ref cannot be parsed. */\nexport class InvalidReleaseRefError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidReleaseRefError'\n }\n}\n\nconst stripRefsHeads = (input: string): string => {\n return input.startsWith(REFS_HEADS_PREFIX) ? input.slice(REFS_HEADS_PREFIX.length) : input\n}\n\nconst makeVersion = (major: number, minor: number, patch: number): ReleaseId => {\n return {\n kind: 'version',\n semver: { major, minor, patch },\n raw: `${major}.${minor}.${patch}`,\n }\n}\n\n/**\n * Validate a release name. Throws {@link InvalidReleaseNameError} with a\n * specific message unless the name is kebab-case, at most 50 characters, and\n * not a reserved word. Semver-looking tokens (e.g. `1.2.3`) are already\n * excluded by the kebab-case rule since they contain dots.\n */\nexport const validateName = (name: string): void => {\n if (name.length === 0) {\n throw new InvalidReleaseNameError('Release name is empty. Provide a kebab-case name like \"checkout-redesign\".')\n }\n\n if (name.length > MAX_NAME_LENGTH) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is ${name.length} characters; the maximum is ${MAX_NAME_LENGTH}.`,\n )\n }\n\n if (!KEBAB_RE.test(name)) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. \"checkout-redesign\".`,\n )\n }\n\n if (RESERVED_NAMES.has(name)) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is reserved. Reserved names: ${[...RESERVED_NAMES].join(', ')}.`,\n )\n }\n}\n\n/**\n * Lenient parse of a git branch name into a {@link ReleaseId}. Tolerates a\n * leading `refs/heads/`. Returns `null` for anything that is not a valid\n * `release/v<semver>` or `release/<name>` branch. Never throws.\n *\n * Precedence is version-first: `release/v<semver>` is a version, but if the\n * segment after `release/v` is not a valid semver (e.g. `release/vnext`), the\n * whole token after `release/` is treated as a candidate name instead.\n */\nexport const parseBranchName = (branch: string): ReleaseId | null => {\n const stripped = stripRefsHeads(branch.trim())\n\n if (!stripped.startsWith(RELEASE_BRANCH_PREFIX)) return null\n\n if (stripped.startsWith(VERSION_BRANCH_PREFIX)) {\n const semverPart = stripped.slice(VERSION_BRANCH_PREFIX.length)\n const match = BRANCH_SEMVER_RE.exec(semverPart)\n\n if (match) {\n return makeVersion(Number(match[1]), Number(match[2]), Number(match[3]))\n }\n }\n\n const namePart = stripped.slice(RELEASE_BRANCH_PREFIX.length)\n\n try {\n validateName(namePart)\n } catch {\n return null\n }\n\n return { kind: 'name', name: namePart, raw: namePart }\n}\n\n/**\n * Strict parse of a release ref into a {@link ReleaseId}. Throws\n * {@link InvalidReleaseRefError} on invalid input. Precedence (order matters):\n * 1. `release/\u2026` (or `refs/heads/release/\u2026`) \u2192 delegate to parseBranchName.\n * 2. semver token (`1.2.3` / `v1.2.3`) \u2192 version.\n * 3. `next` \u2192 throws; callers must resolve `next` to a concrete version\n * via computeNextVersion before calling this.\n * 4. otherwise \u2192 validateName, returning a named release.\n */\nexport const parseReleaseRef = (input: string): ReleaseId => {\n const trimmed = input.trim()\n const branchCandidate = stripRefsHeads(trimmed)\n\n if (branchCandidate.startsWith(RELEASE_BRANCH_PREFIX)) {\n const parsed = parseBranchName(trimmed)\n\n if (!parsed) {\n throw new InvalidReleaseRefError(\n `\"${input}\" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`,\n )\n }\n\n return parsed\n }\n\n const versionMatch = VERSION_RE.exec(trimmed)\n\n if (versionMatch) {\n return makeVersion(Number(versionMatch[1]), Number(versionMatch[2]), Number(versionMatch[3]))\n }\n\n if (trimmed.toLowerCase() === NEXT_TOKEN) {\n throw new InvalidReleaseRefError(\n 'The \"next\" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.',\n )\n }\n\n try {\n validateName(trimmed)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n\n throw new InvalidReleaseRefError(`Cannot parse \"${input}\" as a release ref: ${reason}`)\n }\n\n return { kind: 'name', name: trimmed, raw: trimmed }\n}\n\n/** Render the branch name for a release id: `release/v1.2.3` | `release/<name>`. */\nexport const formatBranchName = (id: ReleaseId): string => {\n if (id.kind === 'version') return `${VERSION_BRANCH_PREFIX}${id.raw}`\n\n return `${RELEASE_BRANCH_PREFIX}${id.name}`\n}\n\n/**\n * Render a PR title: `Release v1.2.3` / `Hotfix v1.2.3` for versions,\n * `Release <name>` / `Hotfix <name>` for names.\n */\nexport const formatPrTitle = (id: ReleaseId, type: 'regular' | 'hotfix'): string => {\n const prefix = type === 'hotfix' ? 'Hotfix' : 'Release'\n\n if (id.kind === 'version') return `${prefix} v${id.raw}`\n\n return `${prefix} ${id.name}`\n}\n\n/** Render a release-candidate PR title: `Release v1.2.3 (RC)` | `Release <name> (RC)`. */\nexport const formatRcTitle = (id: ReleaseId): string => {\n if (id.kind === 'version') return `Release v${id.raw} (RC)`\n\n return `Release ${id.name} (RC)`\n}\n\n/** Render the Jira fix-version name: `v1.2.3` | `<name>`. */\nexport const formatJiraName = (id: ReleaseId): string => {\n if (id.kind === 'version') return `v${id.raw}`\n\n return id.name\n}\n\n/** Render a short human display label: `1.2.3` | `<name>`. */\nexport const displayLabel = (id: ReleaseId): string => {\n return id.raw\n}\n\n/** True iff `branch` is a valid release branch under either scheme. */\nexport const isReleaseBranch = (branch: string | null | undefined): boolean => {\n if (branch === null || branch === undefined) return false\n\n return parseBranchName(branch) !== null\n}\n\nconst toTime = (value: string | Date | undefined): number | null => {\n if (value === undefined) return null\n\n const time = value instanceof Date ? value.getTime() : new Date(value).getTime()\n\n return Number.isNaN(time) ? null : time\n}\n\n/**\n * Comparator for {@link ReleaseId} values (locked ordering):\n * - All versions sort before all names.\n * - Versions: semver ascending (major, then minor, then patch; numeric).\n * - Names: by date ascending when both dates are provided, otherwise\n * lexicographic by name. The result is stable and deterministic.\n */\nexport const compareReleaseIds = (\n a: ReleaseId,\n b: ReleaseId,\n dates?: { a?: string | Date; b?: string | Date },\n): number => {\n if (a.kind === 'version' && b.kind === 'version') {\n if (a.semver.major !== b.semver.major) return a.semver.major - b.semver.major\n if (a.semver.minor !== b.semver.minor) return a.semver.minor - b.semver.minor\n\n return a.semver.patch - b.semver.patch\n }\n\n if (a.kind === 'version') return -1\n if (b.kind === 'version') return 1\n\n const timeA = toTime(dates?.a)\n const timeB = toTime(dates?.b)\n\n if (timeA !== null && timeB !== null && timeA !== timeB) {\n return timeA - timeB\n }\n\n if (a.name < b.name) return -1\n if (a.name > b.name) return 1\n\n return 0\n}\n", "import { $ } from 'zx'\n\nimport { OperationError } from 'src/lib/errors/operation-error'\n\n/**\n * Resolve a ref to a commit sha, or `null` when it does not exist.\n *\n * Callers must run this BEFORE {@link isAncestor} on any ref that might be gone:\n * `git merge-base --is-ancestor` exits 128 on an unknown ref, which is a fatal,\n * not a boolean \u2014 so a release branch deleted on origin between the PR listing\n * and the fetch would abort the whole run instead of failing that one branch.\n */\nexport const revParseVerify = async (cwd: string, ref: string): Promise<string | null> => {\n const commitish = `${ref}^{commit}`\n\n try {\n const result = await $({ cwd, quiet: true })`git rev-parse --verify --quiet ${commitish}`\n\n return result.stdout.trim() || null\n } catch {\n return null\n }\n}\n\n/**\n * Whether `ancestor` is already contained in `descendant`.\n *\n * This is the idempotency probe for the whole command: when `origin/dev` is\n * already an ancestor of `origin/<branch>`, that branch needs no merge, no\n * checkout, and no refspec. It is also what makes a re-run after a partially\n * rejected push safe rather than duplicative.\n *\n * Exit 0 = contained, exit 1 = not. Anything else (notably 128 on an unknown\n * ref) is a programming error at the call site, so it propagates rather than\n * being flattened into `false` \u2014 a silent `false` would re-merge a branch that\n * was already done.\n */\nexport const isAncestor = async (cwd: string, ancestor: string, descendant: string): Promise<boolean> => {\n try {\n await $({ cwd, quiet: true })`git merge-base --is-ancestor ${ancestor} ${descendant}`\n\n return true\n } catch (error) {\n const exitCode = (error as { exitCode?: number }).exitCode\n\n if (exitCode === 1) return false\n\n throw new OperationError(error, {\n operation: `test whether ${ancestor} is contained in ${descendant}`,\n remediation: 'both refs must exist \u2014 verify them with rev-parse first',\n })\n }\n}\n\n/** The sha `origin` currently holds for a branch, or `null` when it has none. */\nexport const lsRemoteHead = async (cwd: string, branch: string): Promise<string | null> => {\n const result = await $({ cwd, quiet: true })`git ls-remote --heads origin ${branch}`\n const line = result.stdout.trim().split('\\n')[0]\n\n return line ? (line.split(/\\s+/)[0] ?? null) : null\n}\n\nexport interface AtomicPushRef {\n branch: string\n sha: string\n}\n\nexport interface AtomicPushResult {\n /** Refspecs exactly as handed to git \u2014 printed before the push so the transcript names what was in flight. */\n refspecs: string[]\n pushed: boolean\n /** Raw stderr on failure, for the report to quote rather than paraphrase. */\n stderr?: string\n}\n\n/**\n * Push every merge in one all-or-nothing `git push --atomic`.\n *\n * Atomicity is the whole point: a per-branch loop leaves 2^N possible outcomes\n * on a failure, and reconstructing which branches landed means inspecting every\n * remote by hand. With `--atomic`, one non-fast-forwardable ref leaves *every*\n * ref unchanged on origin.\n *\n * Deliberately never forced. No `--force`, no `--force-with-lease`, no `+`\n * refspec: each ref stays individually fast-forward-checked, so a teammate's\n * push landing between the plan and the apply loses safely \u2014 the push is\n * rejected and nothing is overwritten. A rejection here is a correct outcome,\n * not a bug to route around.\n */\nexport const pushAtomic = async (cwd: string, refs: AtomicPushRef[]): Promise<AtomicPushResult> => {\n const refspecs = refs.map((ref) => {\n return `${ref.sha}:refs/heads/${ref.branch}`\n })\n\n if (refspecs.length === 0) {\n return { refspecs, pushed: false }\n }\n\n try {\n await $({ cwd, quiet: true })`git push --atomic origin ${refspecs}`\n\n return { refspecs, pushed: true }\n } catch (error) {\n return {\n refspecs,\n pushed: false,\n stderr: (error as { stderr?: string }).stderr,\n }\n }\n}\n", "import path from 'node:path'\nimport process from 'node:process'\nimport { $ } from 'zx'\n\nimport { OperationError } from 'src/lib/errors/operation-error'\n\n/**\n * A disposable detached worktree that `gh-merge-dev` merges inside of.\n *\n * The whole point is that no checkout anyone else owns is touched: the release\n * branches this command merges into are, on this team, almost always checked out\n * in linked worktrees already, so `git switch` \u2014 the old engine \u2014 fails on the\n * ordinary case rather than the exceptional one.\n */\nexport interface ScratchWorktree {\n /** Absolute path of the scratch checkout. */\n path: string\n /** Remove the worktree registration and its directory. Never throws. */\n remove: () => Promise<void>\n}\n\n/**\n * Where the scratch worktree lives: `<git-common-dir>/infra-kit/merge-dev-<runId>`, with `runId`\n * taken from `INFRA_KIT_SESSION` (this repo's per-terminal id) and falling back to the pid.\n *\n * Two properties are load-bearing: the path is outside every working tree, and it is unique per run.\n */\n// Both are about NOT colliding with things that already exist.\n//\n// 1. Outside every working tree. An untracked directory inside the main checkout would make\n// `isWorkingTreeClean` false, and therefore `assertManagementContext` throw, for every OTHER\n// release and worktree command in this CLI \u2014 so a crashed `gh-merge-dev` would break\n// `worktrees add` and `release create` with a message naming neither of them. Under `.git/`\n// it is invisible to `git status` by construction.\n// 2. Unique per run. A colliding path is a hard `fatal: \u2026 already exists`, so two concurrent runs\n// would fight.\n//\n// It also deliberately avoids the team's `<projectRoot>-worktrees/` convention, which\n// `getCurrentWorktrees` scans for release branches.\nexport const scratchWorktreePath = async (cwd?: string): Promise<string> => {\n const root = cwd ?? process.cwd()\n const commonDir = (await $({ cwd: root, quiet: true })`git rev-parse --git-common-dir`).stdout.trim()\n const runId = process.env.INFRA_KIT_SESSION || String(process.pid)\n\n return path.join(path.resolve(root, commonDir), 'infra-kit', `merge-dev-${runId}`)\n}\n\n/** Whether a merge is in progress in `cwd`. Never throws. */\nexport const hasMergeInProgress = async (cwd: string): Promise<boolean> => {\n try {\n await $({ cwd, quiet: true })`git rev-parse -q --verify MERGE_HEAD`\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Refuse to reuse a scratch worktree that is not pristine.\n *\n * This converts a cleanup miss into a fail-fast instead of a cascade. The\n * failure it guards against is measurable: after a conflicting merge is left\n * unaborted, the next `git checkout --detach` fails with `error: you need to\n * resolve your current index first`, so branch k's conflict would be reported as\n * an error on branches k+1\u2026N \u2014 the same class of silently-wrong per-branch\n * result the new engine exists to eliminate.\n */\nexport const assertPristineWorktree = async (cwd: string): Promise<void> => {\n if (await hasMergeInProgress(cwd)) {\n throw new OperationError(undefined, {\n operation: 'reuse the scratch worktree',\n stderrExcerpt: 'a merge is still in progress in the scratch worktree',\n remediation: 'this is an infra-kit bug \u2014 the previous branch iteration did not clean up',\n })\n }\n\n const status = (await $({ cwd, quiet: true })`git status --porcelain`).stdout.trim()\n\n if (status.length > 0) {\n throw new OperationError(undefined, {\n operation: 'reuse the scratch worktree',\n stderrExcerpt: `scratch worktree is dirty: ${status.split('\\n')[0]}`,\n remediation: 'this is an infra-kit bug \u2014 the previous branch iteration did not clean up',\n })\n }\n}\n\n/**\n * Return the scratch worktree to a pristine state between branch iterations.\n * Never throws: it runs in a `finally`, and a cleanup that can throw would\n * re-create the very defect (a rejection escaping a catch/finally and killing\n * the run) that this rewrite removes.\n *\n * `clean -fd`, not `-fdx`: ignored paths survive, so a `node_modules` installed\n * by `--verify` on one branch is reused by the next instead of being reinstalled\n * from cold. That makes the `qa` verify tier non-hermetic, which is a deliberate\n * trade recorded in the plan \u2014 the cheap `install` tier is unaffected, because it\n * reads the lockfile and manifests rather than executing installed code.\n */\nexport const resetScratchWorktree = async (cwd: string): Promise<void> => {\n const run = async (fn: () => Promise<unknown>): Promise<void> => {\n try {\n await fn()\n } catch {\n // Best-effort by contract; `assertPristineWorktree` is the real gate.\n }\n }\n\n if (await hasMergeInProgress(cwd)) {\n // Guarded: an unconditional `git merge --abort` exits 128 when there is no\n // merge to abort, and this runs on paths where there often is not.\n await run(() => {\n return $({ cwd, quiet: true })`git merge --abort`\n })\n }\n\n await run(() => {\n return $({ cwd, quiet: true })`git reset --hard`\n })\n\n // `reset --hard` leaves untracked files behind, which would fail the pristine\n // assertion on the next iteration.\n await run(() => {\n return $({ cwd, quiet: true })`git clean -fd`\n })\n}\n\n/**\n * Create the scratch worktree, hand it to `fn`, and always remove it.\n *\n * Anchored on `origin/dev` rather than on the first candidate branch: a branch\n * deleted on origin between the PR listing and the fetch would make the initial\n * `add` fail, and a preflight throw there would kill the run for every *other*\n * branch too. `origin/dev` is verified by the caller immediately beforehand.\n *\n * A stale registration left by a hard kill (`fatal: \u2026 is a missing but already\n * registered worktree`) is recovered once via `git worktree prune`, because\n * otherwise the command would be broken on that machine every subsequent run.\n */\nexport const withScratchWorktree = async <T>(\n args: { cwd: string; anchor?: string },\n fn: (worktree: ScratchWorktree) => Promise<T>,\n): Promise<T> => {\n const { cwd, anchor = 'origin/dev' } = args\n const worktreePath = await scratchWorktreePath(cwd)\n\n const add = async (): Promise<void> => {\n await $({ cwd, quiet: true })`git worktree add --detach ${worktreePath} ${anchor}`\n }\n\n try {\n await add()\n } catch (firstError) {\n try {\n await $({ cwd, quiet: true })`git worktree prune`\n await add()\n } catch {\n throw new OperationError(firstError, {\n operation: 'create the scratch worktree for the merge',\n remediation: `remove any stale checkout at ${worktreePath}, then retry`,\n })\n }\n }\n\n const worktree: ScratchWorktree = {\n path: worktreePath,\n remove: async (): Promise<void> => {\n try {\n await $({ cwd, quiet: true })`git worktree remove --force ${worktreePath}`\n } catch {\n // A leftover registration is recoverable (`prune`-and-retry on the next\n // run); throwing here would mask whatever the run was actually reporting.\n }\n },\n }\n\n try {\n return await fn(worktree)\n } finally {\n await worktree.remove()\n }\n}\n", "/**\n * Filesystem discovery helpers for the dev-server.\n *\n * These functions read the filesystem (walking for the monorepo root, scanning\n * `apps/` and `packages/`) but never `chdir` and never resolve ports / prefixes \u2014\n * that stays with the pure {@link file://./ports.ts} layer. The starting directory\n * is passed in so discovery is testable against a fixture root.\n */\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n/** Bare metadata for a discovered API app (no resolved port / prefix). */\nexport interface DiscoveredApiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** Package name from package.json (e.g. sls-trvl-client), or the folder name as fallback. */\n packageName: string\n path: string\n}\n\n/** Walk up from `startDir` (max 10 levels) to the dir containing `pnpm-workspace.yaml`. */\nexport function findMonorepoRoot(startDir: string): string {\n let currentDir = startDir\n\n for (let i = 0; i < 10; i++) {\n const workspaceFile = path.join(currentDir, 'pnpm-workspace.yaml')\n\n if (fs.existsSync(workspaceFile)) {\n return currentDir\n }\n currentDir = path.dirname(currentDir)\n }\n\n throw new Error('Could not find monorepo root (pnpm-workspace.yaml)')\n}\n\n/** Read the `name` field from `<apiPath>/package.json`, falling back to `appName`. */\nexport function getPackageName(apiPath: string, appName: string): string {\n const pkgPath = path.join(apiPath, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return appName\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { name?: string }\n\n return typeof pkg.name === 'string' ? pkg.name : appName\n } catch {\n return appName\n }\n}\n\n/** Discover every `apps/<app>` that has an `api/serverless.yml` (bare metadata only). */\nexport function discoverApiApps(root: string): DiscoveredApiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredApiApp[] = []\n\n if (!fs.existsSync(appsDir)) {\n throw new Error(`Apps directory not found: ${appsDir}`)\n }\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const apiPath = path.join(appsDir, appName, 'api')\n const serverlessPath = path.join(apiPath, 'serverless.yml')\n\n if (fs.existsSync(serverlessPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(apiPath, appName),\n path: apiPath,\n })\n }\n }\n\n return apps\n}\n\n/** Bare metadata for a discovered UI app (a frontend with its own framework `dev` script). */\nexport interface DiscoveredUiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** package.json `name` \u2014 used as the exact `turbo run dev --filter` target. */\n packageName: string\n /** Absolute path to `apps/<app>/ui`. */\n path: string\n /**\n * True when this UI's vite config wires `infra-kit/vite`'s `infraKitDev()` helper \u2014 the ONLY thing\n * that makes it honor the runner-assigned `INFRA_KIT_UI_PORTS` port (which it binds with `strictPort`).\n *\n * The runner treats frameworks opaquely, so it cannot assume a pre-assigned port is the port the child\n * will bind. Without this signal it would print a confident, wrong URL for any UI that picks its own\n * port (vike, astro, a hand-rolled vite config). Unwired \u2192 the runner claims no port and the UI keeps\n * its honest \"vite prints its URL below\" reference line.\n */\n managedPort: boolean\n}\n\n/** Vite config filenames checked for the helper import, in vite's own resolution order. */\nconst VITE_CONFIG_FILES = [\n 'vite.config.ts',\n 'vite.config.mts',\n 'vite.config.cts',\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.cjs',\n]\n\n/**\n * Every module specifier that binds a UI to infra-kit's dev wiring \u2014 whether through the raw\n * `infraKitDev` helper or through the `@slip-stream-kit/vite` plugin that wraps it.\n *\n * Matched as a SUBSTRING of a config's import specifiers. This is what makes `managedPort` true, so a\n * MISSING entry is not cosmetic: the runner would stop claiming the port for every UI on that specifier,\n * and with it the hero URL. Drop the legacy entry once every consumer repo is migrated.\n */\n// A LIST, not a single literal, because the wiring moved packages twice: it used to ship from the\n// `infra-kit` CLI itself, then from `@slip-stream-kit/config` (the split that let the CLI become a global\n// install \u2014 a local `node_modules/.bin/infra-kit` would otherwise shadow the global bin, see that\n// package's readme), and the plugin form now ships from `@slip-stream-kit/vite`. Consumers migrate one\n// repo at a time, so all three specifiers are live.\n//\n// The substring match is why the config package could not be called `@infra-kit/vite`: that name\n// *contains* `infra-kit/vite`, so the legacy entry would have matched it by accident and hidden the very\n// coupling the split makes explicit. Neither `@slip-stream-kit/config/vite` nor `@slip-stream-kit/vite`\n// contains any other entry, so no entry here shadows another.\nexport const INFRA_KIT_VITE_SPECIFIERS = [\n '@slip-stream-kit/vite',\n '@slip-stream-kit/config/vite',\n 'infra-kit/vite',\n] as const\n\n/**\n * True when `<dir>`'s vite config references the `infraKitDev` helper module. A text match, not a\n * module load: the config is TypeScript the runner must not execute, and importing it would run the\n * consumer's own side effects. False negatives (a config that re-exports the helper from a shared\n * preset) cost only the reference line, never a wrong URL \u2014 the safe direction to be wrong in.\n */\nexport function usesInfraKitVite(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n const source = fs.readFileSync(configPath, 'utf-8')\n\n return INFRA_KIT_VITE_SPECIFIERS.some((specifier) => {\n return source.includes(specifier)\n })\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/**\n * True when `<dir>`'s vite config wires the `infraKit()` PLUGIN specifically \u2014 not just the raw\n * `infraKitDev()` helper it wraps (see {@link usesInfraKitVite}, which matches either). Only the\n * plugin watches `.infra-kit/dev-context` and restarts vite when the resolved proxy changes; a\n * config that calls the helper directly bakes its proxy at config load and will not react to a\n * backend recovering mid-session (see `dev-server.ts`'s boot warning for this).\n *\n * No structural signal exists to check instead: the plugin writes nothing to disk at config load,\n * so this is the same conservative text match as {@link usesInfraKitVite} \u2014 a config source read,\n * not a module load. The substring is the plugin's call syntax, `infraKit(`; it cannot false-match\n * `infraKitDev(`, whose next character after `infraKit` is `D`, not `(`. A false negative (e.g. the\n * plugin re-exported from a shared preset under a different call shape) only costs a spurious\n * warning \u2014 never a missed one \u2014 which is the safe direction here.\n */\nexport function usesInfraKitVitePlugin(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n return fs.readFileSync(configPath, 'utf-8').includes('infraKit(')\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/** True when `<dir>/package.json` declares a non-empty `scripts.dev`. */\nfunction hasDevScript(dir: string): boolean {\n const pkgPath = path.join(dir, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return false\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { scripts?: Record<string, string> }\n\n return typeof pkg.scripts?.dev === 'string' && pkg.scripts.dev.length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Discover every `apps/<app>/ui` whose package.json declares a `dev` script \u2014 the frontends\n * `infra-kit dev --ui` runs (via one delegated `turbo run dev`). Lenient: no `apps/` dir \u2192 `[]`\n * (UIs are optional), unlike {@link discoverApiApps} which requires it.\n */\nexport function discoverUiApps(root: string): DiscoveredUiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredUiApp[] = []\n\n if (!fs.existsSync(appsDir)) return apps\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const uiPath = path.join(appsDir, appName, 'ui')\n\n if (fs.existsSync(uiPath) && hasDevScript(uiPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(uiPath, appName),\n path: uiPath,\n managedPort: usesInfraKitVite(uiPath),\n })\n }\n }\n\n return apps\n}\n\n/** Normalize the `--app` include list: drop empties, and collapse an empty list to `null`. */\nexport function normalizeAppInclude(include?: string[] | null): string[] | null {\n const filtered = include?.filter(Boolean) ?? []\n\n return filtered.length > 0 ? filtered : null\n}\n\n/**\n * Infer the current app's folder name from `startDir`, so a per-app script can\n * run `infra-kit dev --self` without hardcoding its own app name. Walks up to the\n * monorepo root (via {@link findMonorepoRoot}), then takes the first path segment\n * of `startDir` relative to `<root>/apps` \u2014 e.g. `apps/config-handler/api` and\n * `apps/config-handler` both resolve to `config-handler`. Throws when `startDir`\n * isn't inside `<root>/apps/<app>/...` (repo root, or an unrelated path).\n *\n * @example\n * resolveSelfAppName('/repo/apps/config-handler/api') // => 'config-handler'\n */\nexport function resolveSelfAppName(startDir: string): string {\n const root = findMonorepoRoot(startDir)\n const relative = path.relative(path.join(root, 'apps'), startDir)\n const firstSegment = relative.split(path.sep)[0]\n const isOutsideApps = relative === '' || relative.startsWith('..') || path.isAbsolute(relative)\n\n if (isOutsideApps || !firstSegment) {\n throw new Error(\n `--self: not inside an apps/<app> directory (cwd: ${startDir}). Run from an app folder or use --app=<name>.`,\n )\n }\n\n return firstSegment\n}\n\n/** App-part directory names that are apps in their own right, never shared packages. See {@link getPackageDistDirs}. */\nconst APP_PART_DIRS = new Set(['api', 'ui'])\n\n/** `<dir>/dist` when it exists and is a directory, else `undefined`. */\nconst existingDistDir = (dir: string): string | undefined => {\n const distDir = path.join(dir, 'dist')\n\n return fs.existsSync(distDir) && fs.statSync(distDir).isDirectory() ? distDir : undefined\n}\n\n/** Immediate subdirectory names of `dir`, or `[]` when `dir` does not exist. */\nconst subdirNames = (dir: string): string[] => {\n if (!fs.existsSync(dir)) return []\n\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((d) => {\n return d.isDirectory()\n })\n .map((d) => {\n return d.name\n })\n}\n\n/**\n * Existing dist directories of every SHARED workspace package \u2014 the compiled outputs `turbo watch`\n * rewrites. Watched (alongside app dist) because editing a shared lib rewrites only the lib's `dist`,\n * never the dependent app's, so a package-dist change is the only signal that a lib was rebuilt.\n *\n * Two homes, because the pnpm workspace globs cover `packages/<pkg>` as well as `apps/<app>/<part>`:\n * - `packages/<pkg>/dist` \u2014 the obvious one.\n * - `apps/<app>/<part>/dist` where `<part>` is neither `api` nor `ui` and the dir is a real workspace\n * member (it has a `package.json`).\n *\n * `api`/`ui` parts are excluded deliberately: an api's dist is already covered by {@link getAppDistDirs},\n * and treating a frontend's dist as a shared package would bounce every backend on a UI rebuild.\n */\n// A shared library may legally live beside the app that owns it \u2014 hulyo's `@pkg/ai-mcp` is `apps/ai/mcp`,\n// and two backends depend on it. Scanning only `packages` left such a package watched by nobody: turbo\n// rebuilt its dist, the runner never saw the change, and every dependent backend kept serving stale code.\nexport function getPackageDistDirs(root: string): string[] {\n const dirs: string[] = []\n\n for (const name of subdirNames(path.join(root, 'packages'))) {\n const distDir = existingDistDir(path.join(root, 'packages', name))\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n\n const appsDir = path.join(root, 'apps')\n\n for (const app of subdirNames(appsDir)) {\n for (const part of subdirNames(path.join(appsDir, app))) {\n if (APP_PART_DIRS.has(part)) continue\n\n const partDir = path.join(appsDir, app, part)\n\n // A workspace member, not a stray build artifact directory.\n if (!fs.existsSync(path.join(partDir, 'package.json'))) continue\n\n const distDir = existingDistDir(partDir)\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n }\n\n return dirs\n}\n\n/** Existing `<app.path>/dist` directories for the given apps (order preserved). */\nexport function getAppDistDirs(apps: Array<{ path: string }>): string[] {\n return apps\n .map((app) => {\n return path.join(app.path, 'dist')\n })\n .filter((dir) => {\n return fs.existsSync(dir)\n })\n}\n\n/** How a watched dist change should be routed. */\nexport interface ChangeClassification {\n kind: 'app' | 'package'\n /** For app changes: the matched app dist dir (undefined when nothing matched). */\n app?: string\n /** For package changes: the matched `packages/<pkg>/dist` dir (the change identity used to scope restarts). */\n packageDir?: string\n}\n\n/**\n * Route a changed compiled-output path: a `packages/<pkg>/dist` change is a shared-package\n * rebuild \u2014 the matched package dist dir is returned so the caller can restart only the apps\n * whose dependency closure includes it. An `<app>/dist` change restarts only that app (the\n * matched app dist dir is returned; `undefined` when the path matches neither). Package matches\n * take precedence.\n */\nexport function classifyDistChange(\n changedPath: string,\n appDistDirs: string[],\n packageDistDirs: string[],\n): ChangeClassification {\n const normalized = path.normalize(changedPath)\n\n const matchedPackageDir = packageDistDirs.find((dir) => {\n return normalized.startsWith(path.normalize(dir))\n })\n\n if (matchedPackageDir) {\n return { kind: 'package', packageDir: matchedPackageDir }\n }\n\n const matchedDir = appDistDirs.find((dir) => {\n return normalized.startsWith(path.normalize(dir))\n })\n\n return { kind: 'app', app: matchedDir }\n}\n", "/**\n * Pure resolution of a named dev preset into a concrete run plan.\n *\n * A preset (declared under `devServersPresets` in the per-project infra-kit.json) names\n * launch targets (`client/api`, `client/ui`, with `*` allowed in the app position), optional\n * per-target `watchDeps` (api + ui), per-route proxy-source overrides, and a `cmux` layout\n * flag. This module turns that declarative shape into a flat {@link ResolvedPreset}\n * the runner consumes. Side-effect free: the discovered app parts are passed in\n * (never read from disk here), so resolution is fully unit-testable.\n *\n * Every target key names exactly one workspace package \u2014 the app folder plus the part\n * (`apps/<app>/api` or `apps/<app>/ui`). A bare `<app>` is not a package and is rejected.\n */\nimport type { DevPreset, DevPresets, ProxySource } from 'src/lib/infra-kit-config'\n\n/** The two launchable halves of an `apps/<app>` folder. */\nexport type AppPart = 'api' | 'ui'\n\n/** One concrete thing to launch: a single part of a single app. */\nexport interface ResolvedTarget {\n /** App folder name (e.g. `client`). */\n app: string\n /** Which half of the app to launch. */\n part: AppPart\n /**\n * Participate in dependency-closure watching (uniform for api + ui): react to a change in\n * this target's own workspace-dependency closure. Default `true` (opt-in participation).\n * Resolution is specificity-ordered: an explicit value on a more-specific key (a concrete\n * app, or an explicit `/part`) wins over a `*` glob; at equal specificity an explicit\n * `false` wins over `true` (order-independent opt-out). See {@link resolveWatch}.\n */\n watchDeps: boolean\n}\n\n/** Which apps have an `api` / `ui` part on disk \u2014 the resolver's view of discovery. */\nexport interface DiscoveredParts {\n /** App names that have `apps/<app>/api`. */\n api: string[]\n /** App names that have `apps/<app>/ui`. */\n ui: string[]\n}\n\n/** A fully-resolved preset: the flat run plan derived from its declarative shape. */\nexport interface ResolvedPreset {\n /** Every (app, part) to launch, de-duplicated. */\n targets: ResolvedTarget[]\n /** Run each target in its own cmux pane. */\n cmux: boolean\n /**\n * app \u2192 (route path \u2192 source) overrides, as DECLARED by the preset.\n *\n * Not an input to proxy resolution, and never has been: the vite helper derives a route's source from\n * the dev-context fragments the runner writes, so a route is local iff its backend is actually up. This\n * map is the declared INTENT, and it has two readers:\n * - `validatePresetProxy` \u2014 the STATIC check, run by `infra-kit audit` and the bare-invocation wizard.\n * Note it does NOT run on the `infra-kit dev <preset>` path, so it cannot be relied on to have\n * caught anything by the time a run starts;\n * - `local-pairing.ts` \u2014 the RUNTIME check, which folds a `local` pin into the set of packages the run\n * intended to serve locally, and refuses when one of them is not actually up.\n */\n proxy: Record<string, Record<string, ProxySource>>\n /** Apps whose `api` part is launched \u2014 their backends are local (derived). */\n localApps: string[]\n /** Concretely-named `<app>/<part>` targets that matched no discovered app/part (for a warning). */\n unmatched: string[]\n}\n\n/** The target keys resolution falls back to when a preset omits `apps`: every discovered package. */\nconst ALL_TARGETS_KEYS: NonNullable<DevPreset['apps']> = { '*/api': {}, '*/ui': {} }\n\n/** A preset target key that does not name an `<app>/<part>` package. */\nexport interface PresetKeyIssue {\n /** Preset name the bad key is under. */\n preset: string\n /** The offending key, verbatim. */\n key: string\n /** Human-readable, actionable explanation (already prefixed with the preset name). */\n message: string\n}\n\ninterface ParsedKey {\n /** App name or `*` (all discovered apps). */\n appGlob: string\n /** The single part the key selects. */\n part: AppPart\n}\n\n/**\n * Explain why `key` is not a valid target, or null when it parses. Keys name one workspace\n * package, so the `/api`|`/ui` part is mandatory \u2014 a bare `client` names a folder, not a package.\n */\nexport const explainTargetKey = (key: string): string | null => {\n const segments = key.split('/')\n const [appGlob, part] = segments\n\n if (segments.length !== 2 || !appGlob) {\n return `devServersPresets: invalid target \"${key}\" (expected \"<app>/api\" or \"<app>/ui\")`\n }\n\n if (part !== 'api' && part !== 'ui') {\n return `devServersPresets: invalid target part \"${part}\" in \"${key}\" (expected \"api\" or \"ui\")`\n }\n\n return null\n}\n\n/**\n * Parse a preset target key into an app glob + its part. Throws when the key is not an\n * `<app>/<part>` package identity (see {@link explainTargetKey}).\n *\n * A `*` app glob is legal (`*` plus a part), and expands to every discovered app.\n *\n * @example\n * parseTargetKey('client/api') // => { appGlob: 'client', part: 'api' }\n */\nexport const parseTargetKey = (key: string): ParsedKey => {\n const error = explainTargetKey(key)\n\n if (error) {\n throw new Error(error)\n }\n\n const [appGlob, part] = key.split('/') as [string, AppPart]\n\n return { appGlob, part }\n}\n\n/** Every `preset \u2192 invalid target key` in the map, with the reason (empty when all keys parse). */\nexport const validatePresetKeys = (presets: DevPresets): PresetKeyIssue[] => {\n const issues: PresetKeyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n for (const key of Object.keys(def.apps ?? {})) {\n const error = explainTargetKey(key)\n\n if (error) {\n issues.push({ preset, key, message: `preset \"${preset}\": ${error}` })\n }\n }\n }\n\n return issues\n}\n\n/** App names that have `part` on disk, per the discovery result. */\nconst appsWithPart = (discovered: DiscoveredParts, part: AppPart): string[] => {\n return part === 'api' ? discovered.api : discovered.ui\n}\n\n/** Every discovered app name (union of api + ui halves), sorted for deterministic output. */\nconst allApps = (discovered: DiscoveredParts): string[] => {\n return [...new Set([...discovered.api, ...discovered.ui])].sort()\n}\n\n/** Stable `app/part` identity key for de-duplicating targets across preset keys. */\nconst targetId = (app: string, part: AppPart): string => {\n return `${app}/${part}`\n}\n\n/** A resolved target plus the provenance the merge needs to order later keys by specificity. */\ninterface ResolvedTargetInternal extends ResolvedTarget {\n /** Specificity rank of the key that set `watchDeps` (see {@link keyRank}) \u2014 a higher rank wins. */\n rank: number\n /** Whether `watchDeps` came from an explicit preset value (vs the participate-default). */\n explicitValue: boolean\n}\n\ninterface ResolveState {\n targets: Map<string, ResolvedTargetInternal>\n proxy: Record<string, Record<string, ProxySource>>\n unmatched: string[]\n}\n\n/**\n * Specificity rank of a preset key, higher = more specific. Every key names a part, so the\n * only axis left is the app: a concrete `client/api` (1) beats a `*` glob key (0).\n */\nconst keyRank = (isGlob: boolean): number => {\n return isGlob ? 0 : 1\n}\n\n/**\n * Merge a preset key's `watchDeps` into any prior resolution for the same target. A key that\n * omits `watchDeps` never clobbers a prior explicit value (and, absent any explicit value,\n * seeds the participate-default `true`). A more-specific key ({@link keyRank}) wins in either\n * direction, so a `*` glob cannot override a concrete `client/api` and vice-versa. Two explicit\n * keys can never tie: each target is named by at most one key per rank (one glob, one concrete),\n * so the merge is order-independent.\n */\nconst resolveWatch = (\n prior: ResolvedTargetInternal | undefined,\n next: { watchDeps: boolean | undefined; rank: number },\n): { watchDeps: boolean; rank: number; explicitValue: boolean } => {\n // This key configured nothing \u2192 keep the prior resolution, or seed the participate-default.\n if (next.watchDeps === undefined) {\n return prior ?? { watchDeps: true, rank: next.rank, explicitValue: false }\n }\n\n // No prior explicit value (fresh, or only a default) \u2192 this explicit value takes it.\n if (!prior || !prior.explicitValue) {\n return { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true }\n }\n\n // Two explicit values: the more-specific key wins, in either direction.\n return next.rank > prior.rank ? { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true } : prior\n}\n\n/**\n * Fold one (app, part) into the accumulator: record a target when the part exists,\n * merge `watchDeps` with any prior target of the same identity by specificity\n * ({@link resolveWatch}), and flag a named-but-missing package as unmatched\n * (glob-expanded misses are silent).\n */\nconst addTarget = (\n state: ResolveState,\n discovered: DiscoveredParts,\n spec: { app: string; part: AppPart; watchDeps: boolean | undefined; isGlob: boolean },\n): void => {\n const { app, part, watchDeps, isGlob } = spec\n\n if (!appsWithPart(discovered, part).includes(app)) {\n // A glob expands over discovery, so its misses are expected; a concretely-named\n // `<app>/<part>` that can't be found is a mistake worth surfacing.\n if (!isGlob) {\n state.unmatched.push(targetId(app, part))\n }\n\n return\n }\n\n const id = targetId(app, part)\n const merged = resolveWatch(state.targets.get(id), { watchDeps, rank: keyRank(isGlob) })\n\n state.targets.set(id, { app, part, ...merged })\n}\n\n/**\n * Resolve a preset against the discovered app parts. Expands `*` app globs,\n * de-duplicates targets, derives the local-backend set from the launched `api`\n * targets, and collects per-app proxy overrides. Unknown app/route names are\n * tolerated (a missing named target lands in `unmatched`, not an exception) so a\n * stale preset degrades gracefully \u2014 but a key that is not an `<app>/<part>`\n * package identity throws, since it can't be resolved at all.\n *\n * @example\n * resolvePreset(\n * { apps: { 'client/ui': {}, 'client/api': { watchDeps: false } } },\n * { api: ['client'], ui: ['client'] },\n * )\n * // => { targets: [{ app: 'client', part: 'ui', watchDeps: true }, // default participate\n * // { app: 'client', part: 'api', watchDeps: false }], // explicit opt-out\n * // cmux: false, proxy: {}, localApps: ['client'], unmatched: [] }\n */\nexport const resolvePreset = (preset: DevPreset, discovered: DiscoveredParts): ResolvedPreset => {\n const entries = Object.entries(preset.apps ?? ALL_TARGETS_KEYS)\n const state: ResolveState = { targets: new Map(), proxy: {}, unmatched: [] }\n\n for (const [key, cfg] of entries) {\n const { appGlob, part } = parseTargetKey(key)\n const isGlob = appGlob === '*'\n const apps = isGlob ? allApps(discovered) : [appGlob]\n\n for (const app of apps) {\n addTarget(state, discovered, { app, part, watchDeps: cfg.watchDeps, isGlob })\n\n if (cfg.proxy) {\n state.proxy[app] = { ...(state.proxy[app] ?? {}), ...cfg.proxy }\n }\n }\n }\n\n const targets: ResolvedTarget[] = [...state.targets.values()].map(({ app, part, watchDeps }) => {\n return { app, part, watchDeps }\n })\n const localApps = [\n ...new Set(\n targets\n .filter((t) => {\n return t.part === 'api'\n })\n .map((t) => {\n return t.app\n }),\n ),\n ]\n\n return { targets, cmux: preset.cmux ?? false, proxy: state.proxy, localApps, unmatched: state.unmatched }\n}\n\n/** What the run launched, as passed to {@link deriveTargetLabel}. */\nexport interface TargetLabelInput {\n /** Named preset (`infra-kit dev <preset>`) \u2014 its name is the label when present. */\n preset?: string\n /** The `<app>/<part>` package keys actually being launched, after preset resolution and `--app`. */\n running: string[]\n /** Every `<app>/<part>` package key discovered in the monorepo. */\n discovered: string[]\n}\n\n/**\n * The header's target label. A named preset labels itself; otherwise the label is the set of\n * `<app>/<part>` packages actually launching, collapsing to `*` when that set is everything\n * discovered. Never a bare app name: `client` is not a target anywhere in this system (see\n * {@link parseTargetKey}) and would hide which half of the app is running \u2014 the whole point of\n * the wizard's part-level selection.\n *\n * @example\n * deriveTargetLabel({ running: ['client/ui', 'client/api'], discovered: ['client/api', 'client/ui', 'seo/ui'] })\n * // => 'client/api + client/ui'\n * deriveTargetLabel({ running: ['client/api'], discovered: ['client/api'] }) // => '*'\n * deriveTargetLabel({ preset: 'full', running: ['client/api'], discovered: ['client/api', 'seo/ui'] }) // => 'full'\n */\nexport const deriveTargetLabel = (input: TargetLabelInput): string => {\n if (input.preset != null) {\n return input.preset\n }\n if (input.running.length === 0) {\n return 'nothing'\n }\n\n const running = new Set(input.running)\n const isEverything = input.discovered.every((key) => {\n return running.has(key)\n })\n\n return isEverything ? '*' : [...running].sort().join(' + ')\n}\n\n/** A devServersPresets proxy-locality violation surfaced by the audit. */\nexport interface PresetProxyIssue {\n /** Preset name the violation is in. */\n preset: string\n /** Frontend app folder the override is under (e.g. `client`). */\n app: string\n /** Route path forced to a source (e.g. `/api`). */\n route: string\n /** Backend pkg the route maps to; undefined when the route is not declared in the frontend config. */\n pkg?: string\n /** `unknown-route` = route absent from the frontend config; `backend-not-launched` = local target not launched. */\n kind: 'unknown-route' | 'backend-not-launched'\n /** Human-readable, actionable explanation. */\n message: string\n}\n\n/**\n * Cross-file lookups the proxy validator needs, kept injectable so the rule stays\n * filesystem-free (and unit-testable). The impure side (audit) builds these from\n * discovery + each frontend's loaded `infra-kit.config.ts`.\n */\nexport interface PresetProxyContext {\n /** Discovered app parts, for resolving each preset's launch set. */\n discovered: DiscoveredParts\n /** App folder name \u2192 its `apps/<app>/api` package name. */\n apiPkgByApp: Record<string, string>\n /** (frontend app folder, route path) \u2192 backend pkg from that frontend's config; undefined when the route is absent. */\n routePkg: (app: string, route: string) => string | undefined\n}\n\ninterface CheckLocalRouteArgs {\n preset: string\n app: string\n route: string\n launchedPkgs: ReadonlySet<string>\n ctx: PresetProxyContext\n}\n\n/** App folder whose `api` package is `pkg` (for the remediation hint), or undefined. */\nconst ownerApp = (apiPkgByApp: Record<string, string>, pkg: string): string | undefined => {\n return Object.keys(apiPkgByApp).find((app) => {\n return apiPkgByApp[app] === pkg\n })\n}\n\n/**\n * Validate one `route \u2192 'local'` override: the route must be declared in the\n * frontend config, and the backend pkg it maps to must be in the preset's launched\n * set. Returns the issue, or null when the override is satisfiable.\n */\nconst checkLocalRoute = ({ preset, app, route, launchedPkgs, ctx }: CheckLocalRouteArgs): PresetProxyIssue | null => {\n const pkg = ctx.routePkg(app, route)\n\n if (pkg === undefined) {\n return {\n preset,\n app,\n route,\n kind: 'unknown-route',\n message: `preset \"${preset}\": proxy override \"${route}\" on \"${app}\" names a route not declared in ${app}'s infra-kit.config.ts dev.proxy.routes`,\n }\n }\n\n if (launchedPkgs.has(pkg)) {\n return null\n }\n\n const owner = ownerApp(ctx.apiPkgByApp, pkg)\n const hint = owner ? `add \"${owner}/api\" to the preset` : `launch the api whose package is \"${pkg}\"`\n\n return {\n preset,\n app,\n route,\n pkg,\n kind: 'backend-not-launched',\n message: `preset \"${preset}\": proxy override \"${route}\" \u2192 \"local\" requires backend \"${pkg}\" to run locally, but the preset does not launch it \u2014 ${hint}, or set \"${route}\" to \"cloud\"`,\n }\n}\n\n/**\n * Audit every preset's per-route proxy overrides: a route pinned to `local` is only\n * valid when the backend package it resolves to (per the frontend's\n * `infra-kit.config.ts`) is actually launched by that same preset. Catches the\n * `{ \"client/ui\": { \"proxy\": { \"/api\": \"local\" } } }` case where no local backend\n * is running to serve `/api`. `cloud` overrides are always satisfiable and skipped.\n *\n * @example\n * validatePresetProxy(\n * { 'client-remote': { apps: { 'client/ui': { proxy: { '/api': 'local' } } } } },\n * { discovered: { api: ['client'], ui: ['client'] }, apiPkgByApp: { client: 'backend-api' },\n * routePkg: () => 'backend-api' },\n * )\n * // => [{ preset: 'client-remote', app: 'client', route: '/api', pkg: 'backend-api',\n * // kind: 'backend-not-launched', message: '\u2026' }]\n */\nexport const validatePresetProxy = (presets: DevPresets, ctx: PresetProxyContext): PresetProxyIssue[] => {\n const issues: PresetProxyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n const resolved = resolvePreset(def, ctx.discovered)\n const launchedPkgs = new Set(\n resolved.localApps\n .map((app) => {\n return ctx.apiPkgByApp[app]\n })\n .filter((pkg): pkg is string => {\n return pkg !== undefined\n }),\n )\n\n for (const [app, routes] of Object.entries(resolved.proxy)) {\n for (const [route, source] of Object.entries(routes)) {\n if (source !== 'local') {\n continue\n }\n\n const issue = checkLocalRoute({ preset, app, route, launchedPkgs, ctx })\n\n if (issue) {\n issues.push(issue)\n }\n }\n }\n }\n\n return issues\n}\n"],
|
|
5
|
+
"mappings": "gFAAA,OAAOA,MAAa,eACpB,OAAOC,MAAU,OACjB,OAAOC,OAAY,cAGZ,IAAMC,EAAgB,yBAgBvBC,EAAe,CACnB,QACA,UACA,eACA,iBACA,gBACA,kBACA,sBACA,uBACF,EAEaC,GAAgB,IAAM,CACjC,IAAMC,EAAWN,EAAQ,KAAK,SAAS,SAAS,EAAI,QAAU,OAExDO,EAASN,EAAK,CAAE,MAAOK,EAAU,OAAQF,CAAa,EAAGH,EAAK,YAAY,CAAE,KAAME,CAAc,CAAC,CAAC,EAExG,OAAAI,EAAO,KAAK,kCAAkCD,CAAQ,iBAAiBH,CAAa,EAAE,EAE/EI,CACT,EAEaC,GAAgB,IAAM,CACjC,IAAMF,EAAWN,EAAQ,KAAK,SAAS,SAAS,EAAI,QAAU,OAExDS,EAAe,CAAC,OAAQ,MAAO,UAAU,EAE/C,OAAIH,IAAa,SACfG,EAAa,KAAK,OAAO,EAGZR,EACb,CAAE,MAAOK,EAAU,OAAQF,CAAa,EACxCF,GAAO,CACL,YAAa,EACb,OAAQO,EAAa,KAAK,GAAG,EAC7B,SAAU,EACZ,CAAC,CACH,CAGF,EAGaF,GAASC,GAAc,EChEpC,OAAOE,MAAQ,mBACf,OAAOC,OAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,OAAa,eACpB,OAAS,KAAAC,MAAS,MCHlB,OAAOC,OAAa,eAcb,IAAMC,EAAa,CAAE,QAAS,EAAM,EAO9BC,GAAO,CAClBC,EACAC,EAAiCC,GAAS,CACxCL,GAAQ,OAAO,MAAMK,CAAI,CAC3B,KAEIJ,EAAW,SAAWE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,QAAQA,CAAK,sBAAwB,oCAAoCL,CAAG,IAEjG,MAAO,CACL,OAAA9B,EACA,IAAAM,EACA,MAAA0B,EACA,IAAAF,EACA,KAAM,uBACN,QAAS,WAAW9B,CAAM,sBAAsBgC,CAAK,sCAAiCF,CAAG,8DAAyDM,CAAI,aAAaJ,CAAK,cAC1K,CACF,EAkBaK,GAAsB,CAACvC,EAAqBoC,IAAgD,CACvG,IAAMnC,EAA6B,CAAC,EAEpC,OAAW,CAACC,EAAQC,CAAG,IAAK,OAAO,QAAQH,CAAO,EAAG,CACnD,IAAMwC,EAAWpB,GAAcjB,EAAKiC,EAAI,UAAU,EAC5CD,EAAe,IAAI,IACvBK,EAAS,UACN,IAAKhC,GACG4B,EAAI,YAAY5B,CAAG,CAC3B,EACA,OAAQwB,GACAA,IAAQ,MAChB,CACL,EAEA,OAAW,CAACxB,EAAKiC,CAAM,IAAK,OAAO,QAAQD,EAAS,KAAK,EACvD,OAAW,CAACN,EAAOQ,CAAM,IAAK,OAAO,QAAQD,CAAM,EAAG,CACpD,GAAIC,IAAW,QACb,SAGF,IAAMC,EAAQV,GAAgB,CAAE,OAAA/B,EAAQ,IAAAM,EAAK,MAAA0B,EAAO,aAAAC,EAAc,IAAAC,CAAI,CAAC,EAEnEO,GACF1C,EAAO,KAAK0C,CAAK,CAErB,CAEJ,CAEA,OAAO1C,CACT",
|
|
6
|
+
"names": ["process", "pino", "pretty", "LOG_FILE_PATH", "REDACT_PATHS", "initLoggerMcp", "logLevel", "logger", "initLoggerCLI", "ignoreFields", "fs", "os", "path", "process", "z", "process", "jsonOutput", "emit", "result", "write", "text", "addJsonOption", "cmd", "option", "agentMode", "isAgentMode", "isHeadless", "jsonOutput", "resolveAgentModeSource", "env", "stdinIsTTY", "flag", "agentVar", "path", "process", "$", "extractStderr", "cause", "seen", "current", "stderr", "stderrExcerpt", "buildMessage", "ctx", "parts", "OperationError", "VERSION_RE", "BRANCH_SEMVER_RE", "KEBAB_RE", "RELEASE_BRANCH_PREFIX", "VERSION_BRANCH_PREFIX", "REFS_HEADS_PREFIX", "NEXT_TOKEN", "RESERVED_NAMES", "InvalidReleaseNameError", "message", "InvalidReleaseRefError", "stripRefsHeads", "input", "REFS_HEADS_PREFIX", "makeVersion", "major", "minor", "patch", "validateName", "name", "KEBAB_RE", "parseBranchName", "branch", "stripped", "RELEASE_BRANCH_PREFIX", "VERSION_BRANCH_PREFIX", "semverPart", "match", "BRANCH_SEMVER_RE", "namePart", "parseReleaseRef", "trimmed", "parsed", "versionMatch", "VERSION_RE", "NEXT_TOKEN", "err", "reason", "formatBranchName", "id", "formatPrTitle", "type", "prefix", "formatRcTitle", "formatJiraName", "displayLabel", "isReleaseBranch", "toTime", "value", "time", "compareReleaseIds", "a", "b", "dates", "timeA", "timeB", "listWorktrees", "cwd", "output", "$", "entries", "current", "line", "getCurrentWorktrees", "type", "process", "matches", "branch", "isReleaseBranch", "entry", "normalizeGitRootStderr", "error", "raw", "extractStderr", "projectRootRemediation", "hasStderr", "isAgentMode", "base", "getProjectRoot", "stderrExcerpt", "OperationError", "getMainRepoRoot", "root", "commonDir", "resolved", "path", "getCurrentBranch", "getWorkingTreeStatus", "isWorkingTreeClean", "isInsideLinkedWorktree", "gitDirResult", "commonDirResult", "gitDir", "branchExists", "branch", "$", "deleteLocalBranch", "getCurrentBranch", "deleteRemoteBranch", "$", "revParseVerify", "cwd", "ref", "commitish", "$", "isAncestor", "ancestor", "descendant", "error", "OperationError", "lsRemoteHead", "branch", "line", "pushAtomic", "refs", "refspecs", "path", "process", "$", "scratchWorktreePath", "cwd", "root", "process", "commonDir", "$", "runId", "path", "hasMergeInProgress", "assertPristineWorktree", "OperationError", "status", "resetScratchWorktree", "run", "fn", "withScratchWorktree", "args", "anchor", "worktreePath", "add", "firstError", "worktree", "INFRA_KIT_CONFIG_FILE", "USER_GLOBAL_CONFIG_FILE", "USER_PROJECTS_DIR", "dopplerEnvManagementSchema", "z", "envManagementSchema", "cursorIdeConfigSchema", "cursorIdeSchema", "zedIdeConfigSchema", "zedIdeSchema", "ideSchema", "idesSchema", "jiraTaskManagerSchema", "taskManagerSchema", "cmuxLayouts", "cmuxConfigSchema", "worktreesConfigSchema", "devAppConfigSchema", "devConfigSchema", "proxySourceSchema", "devPresetAppSchema", "devPresetSchema", "devPresetsSchema", "devProxyConfigSchema", "envAutoLoadSchema", "protectedEnvsSchema", "envVarName", "mcpProxySchema", "spec", "ctx", "name", "PROTECTED_CHILD_ENV_NAMES", "mcpProxiesSchema", "infraKitConfigObject", "DEFAULT_DEV_PROXY_PORT", "infraKitConfigSchema", "cfg", "seen", "entry", "infraKitOverrideConfigSchema", "resolveConfiguredIdes", "config", "ide", "DEFAULT_CMUX_LAYOUT", "resolveCmuxLayout", "cached", "cachedPaths", "pathsCacheKey", "process", "os", "getInfraKitConfigPaths", "key", "projectRoot", "getProjectRoot", "mainRepoRoot", "getMainRepoRoot", "projectName", "path", "userConfigDir", "USER_CONFIG_DIR_NAME", "value", "INFRA_KIT_CONFIG_FILE", "getInfraKitConfig", "paths", "mainStat", "fs", "legacyYmlPath", "statIfExists", "isAgentMode", "userGlobalStat", "userProjectStat", "mtimes", "shallowEqual", "layers", "merged", "layer", "data", "loadLayer", "finalResult", "resetMergedConfigCache", "resetInfraKitConfigCache", "filePath", "readIfExists", "a", "b", "keys", "k", "raw", "parsedRaw", "err", "isRecord", "buildEnvTokensRejectionMessage", "buildMcpLayerRejectionMessage", "result", "fs", "path", "findMonorepoRoot", "startDir", "currentDir", "i", "workspaceFile", "getPackageName", "apiPath", "appName", "pkgPath", "pkg", "discoverApiApps", "root", "appsDir", "apps", "appDirs", "dirent", "serverlessPath", "VITE_CONFIG_FILES", "INFRA_KIT_VITE_SPECIFIERS", "usesInfraKitVite", "dir", "file", "configPath", "source", "specifier", "usesInfraKitVitePlugin", "hasDevScript", "discoverUiApps", "uiPath", "normalizeAppInclude", "include", "filtered", "resolveSelfAppName", "relative", "firstSegment", "APP_PART_DIRS", "existingDistDir", "distDir", "subdirNames", "d", "getPackageDistDirs", "dirs", "name", "app", "part", "partDir", "getAppDistDirs", "classifyDistChange", "changedPath", "appDistDirs", "packageDistDirs", "normalized", "matchedPackageDir", "ALL_TARGETS_KEYS", "explainTargetKey", "key", "segments", "appGlob", "part", "parseTargetKey", "error", "validatePresetKeys", "presets", "issues", "preset", "def", "appsWithPart", "discovered", "allApps", "targetId", "app", "keyRank", "isGlob", "resolveWatch", "prior", "next", "addTarget", "state", "spec", "watchDeps", "id", "merged", "resolvePreset", "entries", "cfg", "apps", "targets", "localApps", "t", "deriveTargetLabel", "input", "running", "ownerApp", "apiPkgByApp", "pkg", "checkLocalRoute", "route", "launchedPkgs", "ctx", "owner", "hint", "validatePresetProxy", "resolved", "routes", "source", "issue"]
|
|
7
|
+
}
|