infra-kit 0.33.1 → 0.35.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.
Files changed (47) hide show
  1. package/dist/{boot-LC2ESPY6.js → boot-ST2534PA.js} +2 -2
  2. package/dist/boot-ST2534PA.js.map +7 -0
  3. package/dist/{chunk-SAHE3MZJ.js → chunk-55F372Z7.js} +1 -1
  4. package/dist/{chunk-SAHE3MZJ.js.map → chunk-55F372Z7.js.map} +2 -2
  5. package/dist/{chunk-33XU7ET5.js → chunk-5SGMD57Z.js} +2 -2
  6. package/dist/chunk-5SGMD57Z.js.map +7 -0
  7. package/dist/{chunk-CYVMMJNO.js → chunk-BYCCXWPB.js} +2 -2
  8. package/dist/{chunk-CYVMMJNO.js.map → chunk-BYCCXWPB.js.map} +2 -2
  9. package/dist/{chunk-I23MDR4X.js → chunk-GCOYOWGH.js} +1 -1
  10. package/dist/{chunk-I23MDR4X.js.map → chunk-GCOYOWGH.js.map} +2 -2
  11. package/dist/chunk-GDOQUC23.js +15 -0
  12. package/dist/chunk-GDOQUC23.js.map +7 -0
  13. package/dist/{chunk-XES5EOEE.js → chunk-PP44RGIU.js} +2 -2
  14. package/dist/chunk-PP44RGIU.js.map +7 -0
  15. package/dist/{chunk-7A4LVTRJ.js → chunk-QS7RKE5P.js} +2 -2
  16. package/dist/chunk-QS7RKE5P.js.map +7 -0
  17. package/dist/{chunk-AWFGP6GY.js → chunk-REDCBY4O.js} +1 -1
  18. package/dist/{chunk-AWFGP6GY.js.map → chunk-REDCBY4O.js.map} +2 -2
  19. package/dist/{chunk-JHCC4HJH.js → chunk-TFOXJRVH.js} +2 -2
  20. package/dist/{chunk-JHCC4HJH.js.map → chunk-TFOXJRVH.js.map} +1 -1
  21. package/dist/{chunk-DVXTZPQ5.js → chunk-UTQ4KTO6.js} +1 -1
  22. package/dist/{chunk-DVXTZPQ5.js.map → chunk-UTQ4KTO6.js.map} +2 -2
  23. package/dist/{chunk-TVG47UHG.js → chunk-V2ZLQPLI.js} +1 -1
  24. package/dist/{chunk-TVG47UHG.js.map → chunk-V2ZLQPLI.js.map} +2 -2
  25. package/dist/{chunk-6RCTRAEW.js → chunk-YVIJUGOB.js} +6 -6
  26. package/dist/{chunk-6RCTRAEW.js.map → chunk-YVIJUGOB.js.map} +2 -2
  27. package/dist/cli.js +147 -129
  28. package/dist/cli.js.map +4 -4
  29. package/dist/dev-server.js +5 -5
  30. package/dist/dev-server.js.map +2 -2
  31. package/dist/{dev-wizard-run-UTZIERL5.js → dev-wizard-run-5JKULZ4J.js} +2 -2
  32. package/dist/dev-wizard-run-5JKULZ4J.js.map +7 -0
  33. package/dist/{env-load-3QXHHJCM.js → env-load-HRJPWQ5X.js} +2 -2
  34. package/dist/mcp-proxy.js +1 -1
  35. package/dist/mcp-proxy.js.map +2 -2
  36. package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js → persistent-ink-dev-ui-D6ALK2P3.js} +2 -2
  37. package/dist/update-check.js +1 -1
  38. package/package.json +3 -3
  39. package/dist/boot-LC2ESPY6.js.map +0 -7
  40. package/dist/chunk-33XU7ET5.js.map +0 -7
  41. package/dist/chunk-7A4LVTRJ.js.map +0 -7
  42. package/dist/chunk-X2RBL36U.js +0 -15
  43. package/dist/chunk-X2RBL36U.js.map +0 -7
  44. package/dist/chunk-XES5EOEE.js.map +0 -7
  45. package/dist/dev-wizard-run-UTZIERL5.js.map +0 -7
  46. /package/dist/{env-load-3QXHHJCM.js.map → env-load-HRJPWQ5X.js.map} +0 -0
  47. /package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js.map → persistent-ink-dev-ui-D6ALK2P3.js.map} +0 -0
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/lib/agent-mode/agent-mode.ts", "../src/lib/json-output/json-output.ts", "../src/lib/errors/operation-error.ts", "../src/lib/git-utils/git-utils.ts", "../src/lib/release-id/release-id.ts", "../src/lib/git-utils/merge-refs.ts", "../src/lib/git-utils/scratch-worktree.ts", "../src/lib/logger/index.ts", "../src/lib/errors/structured-refusal-error.ts", "../src/lib/path-display/path-display.ts", "../src/lib/infra-kit-config/infra-kit-config.ts", "../src/lib/assert-never/assert-never.ts", "../src/lib/config-migrations/migrations/omit-key.ts", "../src/lib/config-migrations/migrations/drop-top-level-key.ts", "../src/lib/config-migrations/migrations/drop-dev-key.ts", "../src/lib/config-migrations/migrations/drop-dev-presets-key.ts", "../src/lib/config-migrations/migrations/drop-dev-proxy-key.ts", "../src/lib/config-migrations/migrations/drop-env-auto-load-key.ts", "../src/lib/config-migrations/migrations/drop-environments-key.ts", "../src/lib/config-migrations/migrations/drop-ide-key.ts", "../src/lib/config-migrations/migrations/drop-task-manager-key.ts", "../src/lib/config-migrations/registry.ts", "../src/lib/config-migrations/apply-config-migrations.ts", "../src/lib/tracked-writes/tracked-writes.ts", "../src/lib/config-migrations/migrate-config-file.ts", "../src/lib/config-migrations/auto-migrate-layer.ts"],
4
- "sourcesContent": ["/**\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 * Two 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 * - `'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 Orca\n * 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 is not the agent signal: a non-TTY stdin is also every zsh `$(\u2026)`\n * capture and CI job, and `--agent` from a terminal has a TTY \u2014 hence the declared flag plus the\n * `CLAUDECODE` \u2227 non-TTY conjunction.\n */\nimport process from 'node:process'\n\nimport { jsonOutput } from 'src/lib/json-output'\n\nexport type AgentModeSource = '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\n/**\n * True on a CI runner (every major one exports `CI`). The config loader withholds its layer-1\n * rewrite there, because a tracked file changed on an ephemeral checkout is lost with the job \u2014\n * the fix has to be committed on the branch instead. Not an agent signal: CI has no human either,\n * but `isAgentMode` keys on who is DRIVING, not where it runs.\n */\nexport const isCI = (): boolean => {\n return Boolean(process.env.CI)\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 sources. 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 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. Human/log\n * output goes to stderr (see lib/logger), so writing the structured payload to\n * 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", "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 agent 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 * (a human or a `--agent` run) with a remediation hint. Wraps an underlying\n * cause and renders a single-line, structured message so logs and the stderr\n * an agent reads 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", "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", "/**\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 // A `1.64.0@2026-10-28` spec is what `release create -r` teaches, so it is the likeliest thing to\n // be pasted here; one hint at the parser serves every ref-taking command. It REPLACES the\n // kebab-case reason rather than trailing it: that reason is noise for this input, and callers\n // that wrap the message (`resolveReleaseBranch`) cap it, which would cut the hint off.\n if (trimmed.includes('@')) {\n throw new InvalidReleaseRefError(\n `Cannot parse \"${input}\" as a release ref: the \\`@date\\` suffix belongs to \\`release create\\`; pass the version alone here and use \\`--release-date\\` on \\`release edit\\``,\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 { WORKTREES_DIR_SUFFIX, WORKTREE_SUBDIRS } from 'src/lib/constants'\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: `<projectRoot>-worktrees/merge-dev/.scratch-<runId>`, with\n * `runId` taken from `INFRA_KIT_SESSION` (this repo's per-terminal id) and falling back to the pid.\n *\n * Three properties are load-bearing: the path is outside every working tree, it is unique per run,\n * and no segment of it is `.git`.\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.\n// 2. Unique per run. A colliding path is a hard `fatal: \u2026 already exists`, so two concurrent runs\n// would fight.\n// 3. Not under `.git/`, where this used to live. `--verify` runs the repo's own suite here, and\n// Vite's default `server.fs.deny` includes `**/.git/**`: every browser-mode Vitest file failed\n// with `Access denied`, so every clean merge was reported `verify-failed`.\n//\n// `<projectRoot>-worktrees/` is safe for the same reason as `resolutionWorktreePath`: the worktree\n// is DETACHED, so `getCurrentWorktrees` never hands it to `worktrees sync` or `remove --all`.\n// The project root is derived from the common dir so a run from a linked worktree still lands\n// beside the main checkout.\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 projectRoot = path.dirname(path.resolve(root, commonDir))\n const runId = process.env.INFRA_KIT_SESSION || String(process.pid)\n\n return path.join(`${projectRoot}${WORKTREES_DIR_SUFFIX}`, WORKTREE_SUBDIRS.mergeDev, `.scratch-${runId}`)\n}\n\n/** `release/v1.2.3` \u2192 `release-v1-2-3`: one flat directory name per branch. */\nexport const branchSlug = (branch: string): string => {\n return branch.replace(/[^\\w-]+/g, '-')\n}\n\n/**\n * Where `release merge-dev --keep-conflicts` leaves a branch mid-merge for someone to resolve:\n * `<projectRoot>-worktrees/merge-dev/<branch-slug>`.\n */\n// This reverses the \"avoid `<projectRoot>-worktrees/`\" choice above, because the resolver must edit\n// files here and `.git/**` is a protected path for agent edits. Both reasons for the original choice\n// still hold: the path is outside every working tree, and the worktree is DETACHED, so\n// `getCurrentWorktrees` (which keeps only entries with a branch) never hands it to `worktrees sync`\n// or `worktrees remove --all`.\nexport const resolutionWorktreePath = (projectRoot: string, branch: string): string => {\n return path.join(`${projectRoot}${WORKTREES_DIR_SUFFIX}`, WORKTREE_SUBDIRS.mergeDev, branchSlug(branch))\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 * Ignored files go too, except `node_modules`: an install by `--verify` on one\n * branch is reused by the next instead of being reinstalled from cold, which is a\n * deliberate trade \u2014 `pnpm install` reconciles it against the next lockfile.\n */\n// Every other ignored path is build output (`dist/`, `*.tsbuildinfo`, `.turbo/`), and a leftover\n// one is read as current: a dependency's stale `dist` from one release branch failed the next\n// branch's `ts-check` with types only the first branch has, while the same tree verified fresh\n// passed. Turbo's cache is no reason to keep them \u2014 in a linked worktree it shares the main\n// checkout's `.turbo/cache`, keyed by input hash, so a restore is correct for the branch at hand.\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. `-e` still applies under `-x`, and an unanchored pattern\n // keeps every workspace package's `node_modules`, not only the root one.\n await run(() => {\n return $({ cwd, quiet: true })`git clean -fdx -e node_modules`\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", "import process from 'node:process'\nimport pino from 'pino'\nimport pretty from 'pino-pretty'\n\n/**\n * Key paths pino censors before anything reaches a destination. The load-bearing case is a handler\n * that logs its `params` object: a token-carrying key in that object would land on stderr verbatim,\n * and stderr is captured by CI logs and terminal scrollback alike.\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 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 // Sync, because reports go straight to `process.stderr` in one write beside these lines. pino-pretty's\n // default async destination buffers, so lines logged BEFORE a report landed after it in a pipe.\n sync: true,\n }),\n )\n\n return logger\n}\n\n// Singleton logger instance for CLI usage\nexport const logger = initLoggerCLI()\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 an agent: `entry/cli.ts` emits `structuredContent` under\n * `--json` and exits with `exitCode`. The message is the ordinary `OperationError` one\n * (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", "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 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 { assertNever } from 'src/lib/assert-never'\nimport { tryAutoMigrateLayer } from 'src/lib/config-migrations'\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// Orca 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 orcaLayouts = ['two-columns', 'three-pane'] as const\n\nconst orcaConfigSchema = z\n .object({\n layout: z.enum(orcaLayouts).optional(),\n })\n .strict()\n\n// worktrees prompt defaults. `.strict()` like every other leaf: a non-strict object here let zod\n// SILENTLY drop a misspelt key, turning \"open in Orca\" off with no message.\nconst worktreesConfigSchema = z\n .object({\n openInGithubDesktop: z.boolean().optional(),\n openInOrca: z.boolean().optional(),\n orca: orcaConfigSchema.optional(),\n })\n .strict()\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. `worktree`\n// (missing `s`) or `dev-proxy` would parse clean and turn the feature off with no message.\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 a human's terminal and under `--agent` alike.\n// \"cli-only\" reaches them from a terminal but not from an agent \u2014 under `--agent` (or a Claude Code\n// shell) it behaves exactly as \"disallow\", because an agent's `--yes` re-run skips every interactive\n// 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 on every checkout that still\n// carries it, so retiring a key means a registry migration, not just a deletion. \"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/**\n * A POSIX environment-variable name. Comma-free by construction, which is what keeps the derived\n * `ik-mcp` argv unambiguous.\n */\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 `infra-kit` is the `.mcp.json` key the retired\n * server sat under, and `doctor` still reads that key as the leftover registration to delete\n * (`inspectLegacyMcpRegistration`) \u2014 a proxy filed there would be advised away. The whole substring is\n * held so no proxy name reads as a copy of that entry.\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 {\n message:\n '\"infra-kit\" is reserved: it is the .mcp.json key of the retired infra-kit MCP server \u2014 pick another name',\n },\n ),\n mcpProxySchema,\n)\n\n/** A path inside the repository, resolved against its root on both the source and the target side. */\nconst repoRelativePathSchema = z\n .string()\n .min(1)\n .superRefine((value, ctx) => {\n if (value.startsWith('/') || value.startsWith('\\\\') || /^[a-z]:/i.test(value)) {\n ctx.addIssue({ code: 'custom', message: `\"${value}\" must be relative to the repository root` })\n\n return\n }\n\n const segments = value.split(/[/\\\\]/).filter((segment) => {\n return segment !== '' && segment !== '.'\n })\n\n if (segments.includes('..')) {\n ctx.addIssue({ code: 'custom', message: `\"${value}\" must not contain a \"..\" segment` })\n }\n\n // Copying or deleting inside `.git` would rewrite the target's object store and refs, not its files.\n if (segments[0] === '.git') {\n ctx.addIssue({ code: 'custom', message: `\"${value}\" must not be .git or a path inside it` })\n }\n\n // The sync rebases paths by string prefix and matches them against `git ls-files` output, which is always\n // canonical, so any other spelling of the same path silently mismatches.\n if (value.includes('\\\\')) {\n ctx.addIssue({ code: 'custom', message: `\"${value}\" must use \"/\" as the separator, not \"\\\\\"` })\n }\n\n const rawSegments = value.split('/')\n\n if (rawSegments.includes('')) {\n ctx.addIssue({ code: 'custom', message: `\"${value}\" must not have a trailing or doubled \"/\"` })\n }\n\n if (rawSegments.includes('.')) {\n ctx.addIssue({\n code: 'custom',\n message: `\"${value}\" must not contain a \".\" segment; write it from the repository root, e.g. \"vendor/configs\"`,\n })\n }\n })\n\nconst vendorModuleNameSchema = z\n .string()\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'must be kebab-case: a-z, 0-9 and inner \"-\"')\n\nconst vendorCopyEntrySchema = z\n .object({\n path: repoRelativePathSchema,\n target: repoRelativePathSchema.optional(),\n // Without a module the entry is core and reaches every target; with one, only targets that list it.\n module: vendorModuleNameSchema.optional(),\n })\n .strict()\n\n/**\n * Marks this repo as the source that `ik vendor sync` copies from. No `.default()` anywhere inside\n * it, for the same reason as `protectedEnvs`: the always-present layer 3 would inject it.\n */\nexport const vendorSourceSchema = z\n .object({\n copy: z.array(vendorCopyEntrySchema).min(1),\n // Matched against each path segment on both sides of the diff, so a slash could never match.\n exclude: z.array(z.string().regex(/^[^/\\\\]+$/, 'must be a single path segment, without \"/\"')).optional(),\n })\n .strict()\n\n/**\n * The `vendorSource` modules this repo takes on top of the core entries. Absent means every module, so a\n * target that never declared one keeps receiving the whole source set.\n */\nexport const vendorTargetSchema = z\n .object({\n modules: z.array(vendorModuleNameSchema),\n })\n .strict()\n\n/**\n * The repo root's `audit --root` rules, over `ROOT_DEFAULT_RULES`. Same vocabulary as a package's\n * `infra-kit.config.ts`, so a rule reads the same at either level; each key replaces its baseline.\n */\nconst auditRulesSchema = z\n .object({\n requiredScripts: z.array(z.string().min(1)).optional(),\n requiredFiles: z.array(z.string().min(1)).optional(),\n turbo: z\n .object({\n requiredTasks: z.array(z.string().min(1)).optional(),\n })\n .strict()\n .optional(),\n })\n .strict()\n\n/**\n * The `<repo>` label of the dev alias (`<release>.<package>.<repo>.localhost`), in place of the main\n * checkout's directory name, to keep the host short. Taken verbatim, so it must already be a DNS label.\n */\nconst aliasRepoSchema = z\n .string()\n .regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/, 'must be a DNS label: a-z, 0-9 and inner \"-\", at most 63 characters')\n\n/**\n * The environment `env-load` takes when none is named \u2014 the Doppler config name, verbatim. Meant for\n * the per-project override (`infra-kit config-set defaultEnv <name>`): each developer's personal\n * config differs, while the committed file can still carry a team-wide fallback such as `dev`. Not\n * checked against `env-list`, which is local and may be incomplete; a wrong name fails at the load.\n */\nconst defaultEnvSchema = z.string().min(1)\n\nexport const infraKitConfigObject = z\n .object({\n envManagement: envManagementSchema,\n defaultEnv: defaultEnvSchema.optional(),\n worktrees: worktreesConfigSchema.optional(),\n protectedEnvs: protectedEnvsSchema.optional(),\n mcp: mcpProxiesSchema.optional(),\n vendorSource: vendorSourceSchema.nullable().optional(),\n vendorTarget: vendorTargetSchema.optional(),\n audit: auditRulesSchema.optional(),\n aliasRepo: aliasRepoSchema.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>.<repo>.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\nexport const infraKitConfigSchema = infraKitConfigObject\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\nexport type VendorSourceConfig = z.infer<typeof vendorSourceSchema>\n\nexport type VendorTargetConfig = z.infer<typeof vendorTargetSchema>\n\n/** The root `audit` block: `audit --root` rules layered over the root baseline. */\nexport type AuditRulesConfig = z.infer<typeof auditRulesSchema>\n\n/** An Orca pane layout preset (see {@link orcaLayouts}). */\nexport type OrcaLayout = (typeof orcaLayouts)[number]\n\n/** The layout applied when `worktrees.orca.layout` is left unset. */\nexport const DEFAULT_ORCA_LAYOUT: OrcaLayout = 'two-columns'\n\n/**\n * Resolve the Orca pane layout for opened worktree workspaces, falling back to\n * {@link DEFAULT_ORCA_LAYOUT} when unconfigured. The one source of truth for\n * \"which layout should the Orca opener build.\"\n *\n * @example\n * resolveOrcaLayout({ worktrees: { orca: { layout: 'three-pane' } } }) // => 'three-pane'\n * resolveOrcaLayout({}) // => 'two-columns'\n */\nexport const resolveOrcaLayout = (config: InfraKitConfig): OrcaLayout => {\n return config.worktrees?.orca?.layout ?? DEFAULT_ORCA_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 /**\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 one process (a test suite, a `dev` session re-reading config).\n */\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 * `~/.infra-kit` \u2014 read `os.homedir()` on every call rather than at module load, because the tests\n * swap the homedir per case and a memoized value would leak one test's temp home into the next.\n *\n * @example\n * resolveUserConfigDir() // => '/Users/arthur/.infra-kit'\n */\nconst resolveUserConfigDir = (): string => {\n return path.join(os.homedir(), USER_CONFIG_DIR_NAME)\n}\n\n/**\n * The user-global config layer, `~/.infra-kit/infra-kit.json`, without going through\n * {@link getInfraKitConfigPaths}. That resolver spawns `git rev-parse` and REJECTS outside a repo,\n * but this file is the one merge layer that exists independent of any project \u2014 the setup\n * migrations address it from wherever `infra-kit setup` was run.\n *\n * @example\n * resolveUserGlobalConfigPath() // => '/Users/arthur/.infra-kit/infra-kit.json'\n */\nexport const resolveUserGlobalConfigPath = (): string => {\n return path.join(resolveUserConfigDir(), USER_GLOBAL_CONFIG_FILE)\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\n const value: InfraKitConfigPaths = {\n main: path.join(projectRoot, INFRA_KIT_CONFIG_FILE),\n userGlobal: resolveUserGlobalConfigPath(),\n userProject: path.join(resolveUserConfigDir(), 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 `worktrees`, `envManagement`)\n * replace wholesale. Results are cached per file mtimes, so repeated reads in one\n * process are free and an edit is still picked up on the next call.\n *\n * @example\n * // infra-kit.json: { \"envManagement\": { \"provider\": \"doppler\", \"config\": { \"name\": \"p\" } } }\n * // ~/.infra-kit/infra-kit.json: { \"worktrees\": { \"openInOrca\": true } }\n * const cfg = await getInfraKitConfig()\n * // => { envManagement: {...}, worktrees: { openInOrca: true } }\n * @example\n * // A reader whose stderr nobody watches: a retired key must fail as it does today, never be rewritten.\n * await getInfraKitConfig({ autoMigrate: 'off' })\n */\nexport const getInfraKitConfig = async (options: GetInfraKitConfigOptions = {}): Promise<InfraKitConfig> => {\n const autoMigrate = options.autoMigrate ?? 'write'\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, autoMigrate, mtimeMs: mtimes.main },\n {\n label: '~/.infra-kit/infra-kit.json',\n path: paths.userGlobal,\n required: false,\n autoMigrate,\n mtimeMs: mtimes.userGlobal,\n },\n {\n label: `~/.infra-kit/projects/${paths.projectName}/infra-kit.json`,\n path: paths.userProject,\n required: false,\n autoMigrate,\n mtimeMs: mtimes.userProject,\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 // No reset after an auto-migration: `mtimes` were stat'ed before `loadLayer` rewrote the file, so\n // this entry's fingerprint is already stale and the next read is exactly one guaranteed miss.\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\nexport interface GetInfraKitConfigOptions {\n /**\n * 'write' (default): a layer the strict schema refuses may be migrated and rewritten on disk.\n * 'off': never write \u2014 throw today's strict error. For callers whose stderr nobody reads.\n */\n autoMigrate?: 'write' | 'off'\n}\n\ninterface ConfigLayer {\n label: string\n path: string\n required: boolean\n autoMigrate: 'write' | 'off'\n /**\n * The mtime stat'ed BEFORE the layer is read. A migration that rewrites the file compares against\n * it so a concurrent editor's save between read and write is never clobbered; `null` when the\n * optional layer did not exist at stat time.\n */\n mtimeMs: number | null\n}\n\n/**\n * The CI wording for a required layer the strict schema refused: the checkout is ephemeral, so the\n * fix has to land on the branch rather than on this machine.\n *\n * @example\n * withSetupHint(new Error('Invalid infra-kit.json at /r/infra-kit.json: Unrecognized key: \"environments\"')).message\n * // => 'Invalid infra-kit.json at /r/infra-kit.json: Unrecognized key: \"environments\"\\nA retired key on this branch \u2014 run `infra-kit setup --skip-tools` in this checkout and commit infra-kit.json.'\n */\nexport const withSetupHint = (error: Error): Error => {\n return new Error(\n `${error.message}\\nA retired key on this branch \u2014 run \\`infra-kit setup --skip-tools\\` in this checkout and commit infra-kit.json.`,\n )\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 * A strict-schema refusal is retried once through {@link tryAutoMigrateLayer}\n * (retired keys deleted and the file rewritten) before the error is thrown.\n *\n * @example\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/missing.json', required: false, autoMigrate: 'write', mtimeMs: null })\n * // => null\n * @example\n * // /home/me/.infra-kit/infra-kit.json: '{ \"worktrees\": { \"openInOrca\": true } }'\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/home/me/.infra-kit/infra-kit.json', required: false, autoMigrate: 'write', mtimeMs: 1700000000000 })\n * // => { worktrees: { openInOrca: true } }\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 if (!layer.required && isRecord(parsedRaw)) {\n assertNoProjectLayerOnlyKeys(layer, parsedRaw)\n }\n\n const result = infraKitOverrideConfigSchema.safeParse(parsedRaw)\n\n if (result.success) {\n return result.data as Record<string, unknown>\n }\n\n const originalError = new Error(`Invalid ${layer.label} at ${layer.path}: ${z.prettifyError(result.error)}`)\n\n // The retry needs an object to migrate and the pre-read mtime as the stale-write baseline. A\n // `null` mtime here means the file did not exist when `getInfraKitConfig` stat'ed it and appeared\n // before the read above \u2014 with no baseline the rewrite could clobber whoever just created it, so\n // that race keeps the strict error.\n if (!isRecord(parsedRaw) || layer.mtimeMs === null) {\n throw originalError\n }\n\n const outcome = await tryAutoMigrateLayer({ ...layer, mtimeMs: layer.mtimeMs }, parsedRaw, raw, {\n schema: infraKitOverrideConfigSchema,\n })\n\n switch (outcome.kind) {\n case 'migrated':\n return outcome.data\n case 'ci-gated':\n throw withSetupHint(originalError)\n case 'not-applicable':\n throw originalError\n default:\n return assertNever(outcome)\n }\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: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>): 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\nconst buildVendorSourceLayerRejectionMessage = (layer: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>): string => {\n return [\n `\"vendorSource\" is not allowed in ${layer.label} (${layer.path}): only the committed project file may mark a repository as the \\`vendor sync\\` source. In the machine-wide file it would make every repository on this machine a source; in a per-project override it would make this machine disagree with every other clone.`,\n \"Move the block to the source repository's own infra-kit.json and commit it there.\",\n ].join('\\n')\n}\n\nconst buildVendorTargetLayerRejectionMessage = (layer: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>): string => {\n return [\n `\"vendorTarget\" is not allowed in ${layer.label} (${layer.path}): \\`vendor sync\\` reads it from the target repository's committed infra-kit.json only, so a per-machine copy would never be seen and would only make this clone disagree with the others.`,\n \"Move the block to the target repository's own infra-kit.json and commit it there.\",\n ].join('\\n')\n}\n\nconst buildAuditLayerRejectionMessage = (layer: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>): string => {\n return [\n `\"audit\" is not allowed in ${layer.label} (${layer.path}): the root audit gates CI, so a per-machine copy would make this machine pass or fail a different check list than CI.`,\n 'Move the block to the project infra-kit.json and commit it there.',\n ].join('\\n')\n}\n\nconst buildAliasRepoLayerRejectionMessage = (layer: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>): string => {\n return [\n `\"aliasRepo\" is not allowed in ${layer.label} (${layer.path}): the vite and Playwright helpers read it from the project infra-kit.json only, so a per-machine copy would register a dev host they never aim at.`,\n 'Move it to the project infra-kit.json and commit it there.',\n ].join('\\n')\n}\n\ntype LayerRejectionMessageBuilder = (layer: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>) => string\n\n/**\n * Keys only the committed project layer may carry. `mcp` feeds the committed `.mcp.json`, and the\n * shallow layer merge would let a per-machine block replace the project's wholesale and then be\n * derived into the shared file. `vendorSource` decides which repo is the sync source, `vendorTarget`\n * what a target takes from it. `audit` is\n * what CI enforces at the root. `aliasRepo` names the dev host, which the helpers read from the project\n * file alone.\n */\nconst PROJECT_LAYER_ONLY_KEYS: Readonly<Record<string, LayerRejectionMessageBuilder>> = {\n aliasRepo: buildAliasRepoLayerRejectionMessage,\n mcp: buildMcpLayerRejectionMessage,\n vendorSource: buildVendorSourceLayerRejectionMessage,\n vendorTarget: buildVendorTargetLayerRejectionMessage,\n audit: buildAuditLayerRejectionMessage,\n}\n\n// Refused loudly rather than silently ignored: each key's message says why a per-machine copy is\n// wrong and where the block belongs instead.\nconst assertNoProjectLayerOnlyKeys = (\n layer: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>,\n parsedRaw: Record<string, unknown>,\n): void => {\n for (const [key, buildMessage] of Object.entries(PROJECT_LAYER_ONLY_KEYS)) {\n if (key in parsedRaw) {\n throw new Error(buildMessage(layer))\n }\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: Omit<ConfigLayer, 'autoMigrate' | 'mtimeMs'>): 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", "/**\n * Exhaustiveness guard for discriminated unions. Place in the `default` branch of\n * a `switch` over a union: once every case is handled the argument narrows to\n * `never`, so adding a new variant later turns this into a compile error.\n *\n * @example\n * switch (source) {\n * case 'local': return resolveLocal()\n * case 'cloud': return resolveCloud()\n * default: return assertNever(source) // compile error if a source is unhandled\n * }\n */\nexport const assertNever = (value: never): never => {\n throw new Error(`Unexpected value: ${JSON.stringify(value)}`)\n}\n", "export const omitKey = (record: Record<string, unknown>, key: string): Record<string, unknown> => {\n return Object.fromEntries(\n Object.entries(record).filter(([entryKey]) => {\n return entryKey !== key\n }),\n )\n}\n", "import type { ConfigMigration } from '../types'\nimport { omitKey } from './omit-key'\n\n/**\n * A migration that removes one top-level key, whatever its value: the strict schema refuses the key\n * regardless, so inspecting the value would only add a way for the migration to disagree with it.\n */\nexport const dropTopLevelKey = ({ key, id, note }: { key: string; id: string; note: string }): ConfigMigration => {\n return {\n id,\n note,\n apply: (parsed) => {\n if (!(key in parsed)) return { changed: false, result: parsed }\n\n return { changed: true, result: omitKey(parsed, key) }\n },\n }\n}\n", "import { dropTopLevelKey } from './drop-top-level-key'\n\nexport const dropDevKeyMigration = dropTopLevelKey({\n key: 'dev',\n id: 'drop-dev-key',\n note: 'the unused \"dev\" key (a dev server port comes from <APP>_PORT / PORT, else the built-in default)',\n})\n", "import { dropTopLevelKey } from './drop-top-level-key'\n\nexport const dropDevPresetsKeyMigration = dropTopLevelKey({\n key: 'devServersPresets',\n id: 'drop-dev-presets-key',\n note: 'the unused \"devServersPresets\" key (run `infra-kit dev <app>` instead of a preset name)',\n})\n", "import { dropTopLevelKey } from './drop-top-level-key'\n\nexport const dropDevProxyKeyMigration = dropTopLevelKey({\n key: 'devProxy',\n id: 'drop-dev-proxy-key',\n note: 'the retired \"devProxy\" key (dev URLs are port-free https://<release>.<package>.localhost)',\n})\n", "import { dropTopLevelKey } from './drop-top-level-key'\n\nexport const dropEnvAutoLoadKeyMigration = dropTopLevelKey({\n key: 'envAutoLoad',\n id: 'drop-env-auto-load-key',\n note: 'the retired \"envAutoLoad\" key (env auto-load is gone \u2014 run `env-load -c <config>` in the terminal)',\n})\n", "import { dropTopLevelKey } from './drop-top-level-key'\n\nexport const dropEnvironmentsKeyMigration = dropTopLevelKey({\n key: 'environments',\n id: 'drop-environments-key',\n note: 'the retired \"environments\" key (deploy targets now come from each workflow\\'s workflow_dispatch options, auth from the token store)',\n})\n", "import { dropTopLevelKey } from './drop-top-level-key'\n\nexport const dropIdeKeyMigration = dropTopLevelKey({\n key: 'ide',\n id: 'drop-ide-key',\n note: 'the unused \"ide\" key (worktrees add/remove no longer edit a Cursor .code-workspace)',\n})\n", "import { dropTopLevelKey } from './drop-top-level-key'\n\nexport const dropTaskManagerKeyMigration = dropTopLevelKey({\n key: 'taskManager',\n id: 'drop-task-manager-key',\n note: 'the unused \"taskManager\" key (Jira is configured by the JIRA_BASE_URL / JIRA_PROJECT_ID env vars in Doppler)',\n})\n", "import { dropDevKeyMigration } from './migrations/drop-dev-key'\nimport { dropDevPresetsKeyMigration } from './migrations/drop-dev-presets-key'\nimport { dropDevProxyKeyMigration } from './migrations/drop-dev-proxy-key'\nimport { dropEnvAutoLoadKeyMigration } from './migrations/drop-env-auto-load-key'\nimport { dropEnvironmentsKeyMigration } from './migrations/drop-environments-key'\nimport { dropIdeKeyMigration } from './migrations/drop-ide-key'\nimport { dropTaskManagerKeyMigration } from './migrations/drop-task-manager-key'\nimport type { ConfigMigration } from './types'\n\n/**\n * Applied in this order \u2014 the order the \"removed \u2026\" notes are printed in. Each step deletes a\n * disjoint shape, so the order is not load-bearing for the result; it is fixed so the note line is\n * stable across runs.\n */\nexport const CONFIG_MIGRATIONS: readonly ConfigMigration[] = [\n dropIdeKeyMigration,\n dropEnvironmentsKeyMigration,\n dropDevProxyKeyMigration,\n dropEnvAutoLoadKeyMigration,\n dropTaskManagerKeyMigration,\n dropDevPresetsKeyMigration,\n dropDevKeyMigration,\n]\n", "import { CONFIG_MIGRATIONS } from './registry'\nimport type { MigrationResult } from './types'\n\n/**\n * Fold the registry over a parsed config. Pure: the input is never mutated, and when no step\n * changes anything the returned `result` IS the input reference, so a caller can `===` it to skip\n * a rewrite. Idempotent by construction \u2014 every step is delete-only, so a second pass finds\n * nothing to delete.\n */\nexport const applyConfigMigrations = (parsed: Record<string, unknown>): MigrationResult => {\n return CONFIG_MIGRATIONS.reduce<MigrationResult>(\n (acc, migration) => {\n const step = migration.apply(acc.result)\n\n if (!step.changed) return acc\n\n return { changed: true, result: step.result, notes: [...acc.notes, migration.note] }\n },\n { changed: false, result: parsed, notes: [] },\n )\n}\n", "/**\n * @fileoverview\n * Whether this process may rewrite files a project tracks in git (`infra-kit.json`,\n * `.claude/settings.json`, `.mcp.json`).\n *\n * Two reasons to withhold, one predicate so the writers agree: a CI checkout, where a rewrite is lost\n * with the job, and `setup --unattended`, the run the update worker starts in every project after an\n * upgrade \u2014 nobody is there to commit the hunk, and it would land on whatever branch the checkout is on.\n * A withheld write is reported with the command a human runs, never dropped silently.\n */\nimport { isCI } from 'src/lib/agent-mode'\n\n/**\n * Set by `setup --unattended`. `setup`'s own writers read this flag alone: an explicit setup in CI\n * keeps converging the tracked files, as it always has.\n *\n * Mutable holder (object so `prefer-const` holds while the flag toggles per run).\n */\nexport const trackedWrites = { withheld: false }\n\n/** The loader's gate on its silent on-read rewrite, which CI withholds too. */\nexport const trackedWritesWithheld = (): boolean => {\n return trackedWrites.withheld || isCI()\n}\n", "import { randomBytes } from 'node:crypto'\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { applyConfigMigrations } from './apply-config-migrations'\nimport type { MigrationResult } from './types'\n\n/**\n * The target was modified between the caller's read and this write. Rewriting it would clobber a\n * human's (or another process's) edit with bytes derived from a stale read; the caller retries from\n * the fresh file on its next run instead.\n */\nexport class ConfigFileChangedError extends Error {\n constructor(filePath: string) {\n super(`${filePath} changed on disk since it was read`)\n this.name = 'ConfigFileChangedError'\n }\n}\n\nexport interface WriteMigratedConfigFileOptions {\n path: string\n /** The bytes the caller read \u2014 only the indentation is taken from them. */\n raw: string\n migrated: Record<string, unknown>\n /** `mtimeMs` observed when `raw` was read; the stale-read guard compares against it. */\n expectedMtimeMs: number\n}\n\nexport interface FileMigrationResult extends MigrationResult {\n path: string\n}\n\nconst DEFAULT_INDENT = 2\n\n// The first indented line decides, so a hand-edited 4-space file is not reformatted wholesale.\nconst detectIndent = (raw: string): string | number => {\n return /^([ \\t]+)\\S/m.exec(raw)?.[1] ?? DEFAULT_INDENT\n}\n\n// Group / other permission bits and the setuid/sticky family; the file-type bits above them are not\n// chmod's business.\nconst PERMISSION_BITS = 0o7777\n\n/**\n * Serialise `migrated` over `path` \u2014 atomically, keeping the file's mode and indentation, and\n * refusing when the file moved on since it was read. Never applies the registry: the caller has\n * already done that (the loader on its retry, {@link migrateConfigFile} on the setup path), so\n * the registry runs exactly once per file whichever way in. Does not log \u2014 each caller owns its\n * own line. Throws on any fs error; callers decide.\n *\n * The rename goes over the realpath'd target, so a symlinked `~/.infra-kit/infra-kit.json`\n * (dotfiles repo) keeps its symlink and the link target is what gets replaced \u2014 `writeFile`\n * follows a link implicitly, `rename` would replace the link itself.\n */\nexport const writeMigratedConfigFile = async ({\n path: filePath,\n raw,\n migrated,\n expectedMtimeMs,\n}: WriteMigratedConfigFileOptions): Promise<void> => {\n const target = await fs.realpath(filePath)\n const dir = path.dirname(target)\n const base = path.basename(target)\n // pid + random: two racing CLIs never share a tmp name, and a reader never sees a torn file.\n const tmp = path.join(dir, `.${base}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`)\n const content = `${JSON.stringify(migrated, null, detectIndent(raw))}\\n`\n\n try {\n await fs.writeFile(tmp, content, 'utf8')\n\n // Re-stat as late as possible: the window between this check and the rename is the smallest\n // this process can make it.\n const stat = await fs.stat(target)\n\n if (stat.mtimeMs !== expectedMtimeMs) {\n throw new ConfigFileChangedError(filePath)\n }\n\n // writeFile's mode is umask-masked; chmod sets the original bits exactly (0600 stays 0600).\n await fs.chmod(tmp, stat.mode & PERMISSION_BITS)\n await fs.rename(tmp, target)\n } catch (err) {\n await fs.rm(tmp, { force: true })\n throw err\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Setup path: stat + read + {@link applyConfigMigrations} + {@link writeMigratedConfigFile}. An\n * empty (or whitespace-only) file is a no-op rather than a JSON error \u2014 an empty layer is a valid\n * \"nothing to override\". Throws on read/parse/write errors, including {@link ConfigFileChangedError}.\n */\nexport const migrateConfigFile = async (filePath: string): Promise<FileMigrationResult> => {\n const stat = await fs.stat(filePath)\n const raw = await fs.readFile(filePath, 'utf8')\n\n if (raw.trim() === '') {\n return { changed: false, result: {}, notes: [], path: filePath }\n }\n\n const parsed: unknown = JSON.parse(raw)\n\n if (!isRecord(parsed)) {\n return { changed: false, result: {}, notes: [], path: filePath }\n }\n\n const migrated = applyConfigMigrations(parsed)\n\n if (migrated.changed) {\n await writeMigratedConfigFile({ path: filePath, raw, migrated: migrated.result, expectedMtimeMs: stat.mtimeMs })\n }\n\n return { ...migrated, path: filePath }\n}\n", "import type { z } from 'zod'\n\nimport { logger } from 'src/lib/logger'\nimport { tildify } from 'src/lib/path-display'\nimport { trackedWritesWithheld } from 'src/lib/tracked-writes'\n\nimport packageJson from '../../../package.json' with { type: 'json' }\nimport { applyConfigMigrations } from './apply-config-migrations'\nimport { writeMigratedConfigFile } from './migrate-config-file'\n\n/** The slice of the loader's `ConfigLayer` the retry needs; passed in so this module never imports the loader (cycle). */\nexport interface AutoMigrateLayer {\n path: string\n /** The tracked project layer \u2014 the only one a CI checkout or an unattended setup must not rewrite. */\n required: boolean\n /** `'off'` for callers whose stderr nobody reads; they keep today's strict error instead of a rewritten file. */\n autoMigrate: 'write' | 'off'\n /** From the stat the loader already took before reading \u2014 the stale-read guard's baseline. */\n mtimeMs: number\n}\n\nexport type AutoMigrateOutcome =\n /** `data` is the second `safeParse`'s output (defaults applied), never the raw migrated object. */\n | { kind: 'migrated'; data: Record<string, unknown> }\n /** A migration WOULD fix the required layer, but CI or an unattended setup withholds the write \u2014 the caller appends its setup hint. */\n | { kind: 'ci-gated' }\n /** Policy off, nothing to migrate, still invalid afterwards, file moved, or the write failed: the caller throws its original error. */\n | { kind: 'not-applicable' }\n\n/**\n * The loader's retry after the strict schema refused a layer: migrate in memory, prove the result\n * parses, write it back, and only then hand the parsed value over \u2014 a migrated value is never\n * returned without the file on disk matching it. Ordered so the CI gate fires only when a migration\n * would actually have fixed the file (a layer with a second, real problem gets the original error\n * naming every unrecognized key, with no misleading hint).\n *\n * `warn`, not `info`, for the one stderr line: `--json` lowers the logger to `warn` and the line\n * must still land \u2014 it is the only signal that a tracked file just gained a hunk to commit.\n */\nexport const tryAutoMigrateLayer = async (\n layer: AutoMigrateLayer,\n parsedRaw: Record<string, unknown>,\n raw: string,\n { schema }: { schema: z.ZodType },\n): Promise<AutoMigrateOutcome> => {\n if (layer.autoMigrate === 'off') {\n return { kind: 'not-applicable' }\n }\n\n const migrated = applyConfigMigrations(parsedRaw)\n\n if (!migrated.changed) {\n return { kind: 'not-applicable' }\n }\n\n const second = schema.safeParse(migrated.result)\n\n if (!second.success) {\n return { kind: 'not-applicable' }\n }\n\n if (layer.required && trackedWritesWithheld()) {\n return { kind: 'ci-gated' }\n }\n\n try {\n await writeMigratedConfigFile({\n path: layer.path,\n raw,\n migrated: migrated.result,\n expectedMtimeMs: layer.mtimeMs,\n })\n } catch (err) {\n logger.debug(err, `auto-migration could not rewrite ${layer.path}`)\n\n return { kind: 'not-applicable' }\n }\n\n logger.warn(\n `Migrated ${tildify(layer.path)}: removed ${migrated.notes.join(' and ')} (retired by infra-kit ${packageJson.version})`,\n )\n\n return { kind: 'migrated', data: second.data as Record<string, unknown> }\n}\n"],
5
- "mappings": "wIAoBA,OAAOA,OAAa,eCnBpB,OAAOC,OAAa,eAcb,IAAMC,EAAa,CAAE,QAAS,EAAM,EAO9BC,GAAO,CAClBC,EACAC,EAAiCC,GAAS,CACxCL,GAAQ,OAAO,MAAMK,CAAI,CAC3B,KAEIJ,EAAW,SAAWE,GAAUA,EAAO,mBAAqB,MAC9DC,EAAM,GAAG,KAAK,UAAUD,EAAO,kBAAmB,KAAM,CAAC,CAAC;AAAA,CAAI,EAGzDA,GAIIG,GAAiBC,GAAuB,CAC5BA,EAAI,QAAQ,KAAMC,GAChCA,EAAO,OAAS,QACxB,GAGCD,EAAI,OAAO,SAAU,4EAA4E,EAGnGA,EAAI,SAAS,QAAQD,EAAa,CACpC,EDnBO,IAAMG,GAAY,CAAE,OAAQ,IAAwB,EAG9CC,EAAc,IAClBD,GAAU,SAAW,KAQjBE,GAAa,IACjBD,EAAY,GAAKE,EAAW,QASxBC,EAAO,IACX,EAAQC,GA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B,CACL,oBAAoBA,EAAM,KAAK,6CAC/B,0FACA,uEACA,0CAA0CA,EAAM,IAAI,IACpD,4DACA,iGACF,EAAE,KAAK;AAAA,CAAI",
6
- "names": ["process", "process", "jsonOutput", "emit", "result", "write", "text", "addJsonOption", "cmd", "option", "agentMode", "isAgentMode", "isHeadless", "jsonOutput", "isCI", "process", "resolveAgentModeSource", "env", "stdinIsTTY", "flag", "agentVar", "extractStderr", "cause", "seen", "current", "stderr", "stderrExcerpt", "buildMessage", "ctx", "parts", "OperationError", "path", "process", "$", "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", "$", "projectRoot", "path", "runId", "WORKTREES_DIR_SUFFIX", "WORKTREE_SUBDIRS", "branchSlug", "branch", "resolutionWorktreePath", "hasMergeInProgress", "assertPristineWorktree", "OperationError", "status", "resetScratchWorktree", "run", "fn", "withScratchWorktree", "args", "anchor", "worktreePath", "add", "firstError", "worktree", "process", "pino", "pretty", "REDACT_PATHS", "initLoggerCLI", "logLevel", "ignoreFields", "logger", "StructuredRefusalError", "OperationError", "structuredContent", "exitCode", "context", "fs", "os", "fileExists", "filePath", "tildify", "home", "fs", "os", "path", "process", "z", "assertNever", "value", "omitKey", "record", "key", "entryKey", "dropTopLevelKey", "key", "id", "note", "parsed", "omitKey", "dropDevKeyMigration", "dropTopLevelKey", "dropDevPresetsKeyMigration", "dropTopLevelKey", "dropDevProxyKeyMigration", "dropTopLevelKey", "dropEnvAutoLoadKeyMigration", "dropTopLevelKey", "dropEnvironmentsKeyMigration", "dropTopLevelKey", "dropIdeKeyMigration", "dropTopLevelKey", "dropTaskManagerKeyMigration", "dropTopLevelKey", "CONFIG_MIGRATIONS", "dropIdeKeyMigration", "dropEnvironmentsKeyMigration", "dropDevProxyKeyMigration", "dropEnvAutoLoadKeyMigration", "dropTaskManagerKeyMigration", "dropDevPresetsKeyMigration", "dropDevKeyMigration", "applyConfigMigrations", "parsed", "CONFIG_MIGRATIONS", "acc", "migration", "step", "trackedWrites", "trackedWritesWithheld", "isCI", "randomBytes", "fs", "path", "process", "ConfigFileChangedError", "filePath", "DEFAULT_INDENT", "detectIndent", "raw", "PERMISSION_BITS", "writeMigratedConfigFile", "migrated", "expectedMtimeMs", "target", "fs", "dir", "path", "base", "tmp", "process", "randomBytes", "content", "stat", "err", "isRecord", "value", "migrateConfigFile", "parsed", "applyConfigMigrations", "tryAutoMigrateLayer", "layer", "parsedRaw", "raw", "schema", "migrated", "applyConfigMigrations", "second", "trackedWritesWithheld", "writeMigratedConfigFile", "err", "logger", "tildify", "package_default", "INFRA_KIT_CONFIG_FILE", "USER_GLOBAL_CONFIG_FILE", "USER_PROJECTS_DIR", "dopplerEnvManagementSchema", "z", "envManagementSchema", "orcaLayouts", "orcaConfigSchema", "worktreesConfigSchema", "protectedEnvsSchema", "envVarName", "mcpProxySchema", "spec", "ctx", "name", "PROTECTED_CHILD_ENV_NAMES", "mcpProxiesSchema", "repoRelativePathSchema", "value", "segments", "segment", "rawSegments", "vendorModuleNameSchema", "vendorCopyEntrySchema", "vendorSourceSchema", "vendorTargetSchema", "auditRulesSchema", "aliasRepoSchema", "defaultEnvSchema", "infraKitConfigObject", "DEFAULT_DEV_PROXY_PORT", "infraKitConfigSchema", "infraKitOverrideConfigSchema", "DEFAULT_ORCA_LAYOUT", "resolveOrcaLayout", "config", "cached", "cachedPaths", "pathsCacheKey", "process", "os", "resolveUserConfigDir", "path", "USER_CONFIG_DIR_NAME", "resolveUserGlobalConfigPath", "getInfraKitConfigPaths", "key", "projectRoot", "getProjectRoot", "mainRepoRoot", "getMainRepoRoot", "projectName", "INFRA_KIT_CONFIG_FILE", "getInfraKitConfig", "options", "autoMigrate", "paths", "mainStat", "fs", "legacyYmlPath", "statIfExists", "isAgentMode", "userGlobalStat", "userProjectStat", "mtimes", "shallowEqual", "layers", "merged", "layer", "data", "loadLayer", "finalResult", "resetMergedConfigCache", "resetInfraKitConfigCache", "filePath", "readIfExists", "a", "b", "keys", "k", "withSetupHint", "error", "raw", "parsedRaw", "err", "isRecord", "buildEnvTokensRejectionMessage", "assertNoProjectLayerOnlyKeys", "result", "originalError", "outcome", "tryAutoMigrateLayer", "assertNever", "buildMcpLayerRejectionMessage", "buildVendorSourceLayerRejectionMessage", "buildVendorTargetLayerRejectionMessage", "buildAuditLayerRejectionMessage", "buildAliasRepoLayerRejectionMessage", "PROJECT_LAYER_ONLY_KEYS", "buildMessage"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/dev/proxy/portless-link.ts", "../src/dev/proxy/portless-driver.ts", "../src/lib/shell-quote/shell-quote.ts", "../src/dev/proxy/portless-node.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview\n *\n * `~/.infra-kit/portless` \u2014 a stable symlink to the portless PACKAGE directory bundled with the running\n * infra-kit, kept pointing at the current install by every process boot.\n *\n * Why it exists: `portless service install` bakes `process.execPath` and `process.argv[1]` verbatim into\n * the root launchd plist (`ProgramArguments`), and it offers no `--entry` flag to say otherwise. Under\n * pnpm 12 the script half of that pair is version-unstable \u2014 every `pnpm add -g infra-kit@x` mints a\n * fresh `global/v11/{pid}-{timestamp}/` project and removes the previous one, and the path also embeds\n * `infra-kit@<version>`. With silent auto-update on, the daemon's argv dangles after every release,\n * launchd cannot start it at the next boot, and the \"fix\" is another sudo. Node does NOT realpath\n * `argv[1]` (it keeps whatever string it was given) but DOES realpath `execPath`, so only the script half\n * can be made stable: point the plist at `<link>/dist/cli.js` and keep the link current.\n *\n * Why tmp + rename, never unlink first: `rename(2)` replaces a symlink atomically, so there is no\n * instant at which the path is absent. An unlink-then-symlink sequence has one \u2014 and a reboot inside it\n * leaves launchd with no script at all; `KeepAlive` retries the same dangling path forever, and `:443`\n * stays dark until a human runs `service install` again.\n *\n * Why the boot call must run on `version --json`: that is the exact invocation the background updater\n * spawns to verify a fresh install (`run-update-check.ts`, `readInstalledVersion`: `cwd = homedir()`,\n * `--json`, piped stdio). It is the FIRST process the new binary ever runs \u2014 and the one that re-points\n * the link after an auto-update, before any shell command does. So `bootPortlessLink` must not sit\n * behind `warnIfLocalInstall`'s `--json` guard, and it must not have an env opt-out: the link is state,\n * not advisory output.\n *\n * Every write is guarded by `isGlobalInstall`: a checkout or a project-local dependency never aims the\n * root daemon at itself (that would dangle the moment the worktree is removed). Nothing here spawns a\n * subprocess, touches stdout, or throws \u2014 the `ik-mcp` proxy calls it at boot with stdout carrying the\n * JSON-RPC transport, and the CLI calls it before Commander parses argv.\n */\nimport fs from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\nimport { isGlobalInstall, safeRealpath } from 'src/lib/install-manager'\n\nimport { formatPortlessCommand, resolvePortlessBin } from './portless-driver'\nimport type { ExistsCheck } from './portless-driver'\nimport { ensurePortlessNode, stableNodeCandidate } from './portless-node'\nimport type { EnsurePortlessNodeDeps, PortlessNodeResult } from './portless-node'\n\n/** `<home>/.infra-kit/portless` \u2014 the link path; the same `home` seam the rest of the config layer uses. */\nexport const portlessLinkPath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'portless')\n}\n\n/**\n * `<link>/dist/cli.js` when the link resolves to a portless with that file, else `null` \u2014 the path the\n * printed `service install` command (and the plist it writes) should carry. `exists` follows the\n * symlink, so a dangling link answers `null` and callers fall back to the real path.\n */\nexport const portlessLinkCliPath = (\n home: string,\n exists: (target: string) => boolean = fs.existsSync,\n): string | null => {\n const cliPath = join(portlessLinkPath(home), 'dist', 'cli.js')\n\n return exists(cliPath) ? cliPath : null\n}\n\n/** Where the link is looked up and which node to print; every seam is injectable so tests never read a real `~/.infra-kit`. */\nexport interface ServiceInstallSeams {\n home: string\n exists?: ExistsCheck\n execPath?: string\n /**\n * `~/.infra-kit/node` as a health verdict: a string is \"resolved and healthy \u2014 render through it\"\n * (doctor/setup after their node row), `null` is \"resolved and unhealthy or absent \u2014 render through\n * `execPath`, the node that provably runs\", `undefined` is \"not resolved\" and the inode-only candidate\n * is checked here instead (`dev`, which never spawns on its hot path).\n */\n stableNode?: string | null\n}\n\n/**\n * The one-time, out-of-band, ROOT command that installs the `:443` daemon. infra-kit never runs it \u2014 it\n * only ever prints it (principle 3: infra-kit probes and prints, it never elevates). `doctor`, `setup`\n * and `dev` all print it from here so no two surfaces can disagree about the path that ends up as root.\n *\n * Rendered THROUGH `~/.infra-kit/portless/dist/cli.js` whenever that link resolves: portless bakes the\n * script path it was invoked with into the plist, so the command printed here decides whether the root\n * daemon survives the next `pnpm add -g infra-kit` (the link is re-pointed on every boot; the version-\n * specific path is deleted). `bin` \u2014 the resolved `dist/cli.js`, never a bare `portless` (see\n * {@link formatPortlessCommand}) \u2014 is the fallback only, for a machine where nothing has created the\n * link yet.\n */\nexport const serviceInstallCommand = (bin: string, seams: ServiceInstallSeams): string => {\n // Resolved before the candidate check: `dev` passes `{ home }` only, and the candidate must never stat `undefined`.\n const execPath = seams.execPath ?? process.execPath\n // Written out rather than `??`-chained: a `null` verdict (\"resolved, unhealthy\") must reach `execPath`\n // directly and never fall through to a candidate check that would contradict doctor's spawn.\n const stableNode =\n seams.stableNode === undefined ? stableNodeCandidate({ home: seams.home, execPath }) : seams.stableNode\n\n return formatPortlessCommand(['service', 'install'], {\n sudo: true,\n bin: portlessLinkCliPath(seams.home, seams.exists) ?? bin,\n execPath: stableNode ?? execPath,\n })\n}\n\nexport type PortlessLinkOutcome =\n 'created' | 'repointed' | 'unchanged' | 'skipped-local' | 'skipped-unresolved' | 'failed'\n\nexport interface PortlessLinkResult {\n kind: 'link'\n outcome: PortlessLinkOutcome\n /** The portless package dir the link should point at; `null` only for `'skipped-unresolved'`. */\n target: string | null\n link: string\n}\n\n/**\n * The six fs calls the link needs, as an OBJECT seam. Named `node:fs` imports cannot be intercepted by\n * `vi.spyOn` (the binding is a live import, not a property), so the default export is the injectable\n * shape and tests hand in an in-memory fake instead of touching a real `~/.infra-kit`.\n */\nexport interface PortlessLinkFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => { isSymbolicLink: () => boolean } | undefined\n readlinkSync: (target: string) => string\n symlinkSync: (target: string, linkPath: string) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport interface EnsurePortlessLinkDeps {\n /** `resolvePortlessBin` \u2014 the bundled portless's `dist/cli.js`, or `null` when it is not installed. */\n resolveBin: () => string | null\n /** `isGlobalInstall` bound to this process \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n fs?: PortlessLinkFs\n}\n\n/** What currently sits at the link path, beyond \"a symlink to X\". */\nconst ABSENT = Symbol('absent')\nconst NOT_A_SYMLINK = Symbol('not-a-symlink')\n\nconst readCurrentLink = (link: string, linkFs: PortlessLinkFs): string | typeof ABSENT | typeof NOT_A_SYMLINK => {\n const stat = linkFs.lstatSync(link, { throwIfNoEntry: false })\n\n if (stat === undefined) return ABSENT\n if (!stat.isSymbolicLink()) return NOT_A_SYMLINK\n\n return linkFs.readlinkSync(link)\n}\n\n/**\n * Publish `target` at `link` through a pid-suffixed sibling and one `rename`, so the path never goes\n * absent (see the file header). The sibling is cleared BEFORE the symlink as well as after a failed\n * rename: a crash between the two calls leaves `.tmp-<pid>` behind forever, and pid reuse would then\n * turn a later boot's `symlinkSync` into EEXIST \u2014 a `'failed'` for a link that is fine. The name is\n * ours alone, never user data, so removing whatever sits there is safe; `ENOENT` is the normal case.\n */\nconst writeLink = (target: string, link: string, linkFs: PortlessLinkFs): void => {\n const tmp = `${link}.tmp-${process.pid}`\n\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Nothing to clear \u2014 the ordinary path.\n }\n\n linkFs.symlinkSync(target, tmp)\n\n try {\n linkFs.renameSync(tmp, link)\n } catch (error) {\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failed rename is the error worth surfacing, not the leftover sibling.\n }\n\n throw error\n }\n}\n\n/**\n * Converge `~/.infra-kit/portless` on the portless bundled with THIS install. Never throws; every\n * outcome is a value so callers can log it without a try/catch of their own.\n *\n * A non-symlink at the link path is `'failed'` and left exactly as found: this code owns a symlink, not\n * whatever a user or another tool put there, and removing a directory to make room would be the one\n * destructive action a boot hook must never take.\n *\n * @example\n * ensurePortlessLink({ resolveBin: () => '/g/node_modules/portless/dist/cli.js', isGlobal: () => true, home: '/Users/x' })\n * // => { kind: 'link', outcome: 'created', target: '/g/node_modules/portless', link: '/Users/x/.infra-kit/portless' }\n */\nexport const ensurePortlessLink = (deps: EnsurePortlessLinkDeps): PortlessLinkResult => {\n const { resolveBin, isGlobal, home, fs: linkFs = fs } = deps\n const link = portlessLinkPath(home)\n const bin = resolveBin()\n\n if (bin === null) return { kind: 'link', outcome: 'skipped-unresolved', target: null, link }\n\n const target = dirname(dirname(bin))\n\n if (!isGlobal()) return { kind: 'link', outcome: 'skipped-local', target, link }\n\n try {\n linkFs.mkdirSync(dirname(link), { recursive: true })\n\n const current = readCurrentLink(link, linkFs)\n\n if (current === target) return { kind: 'link', outcome: 'unchanged', target, link }\n if (current === NOT_A_SYMLINK) return { kind: 'link', outcome: 'failed', target, link }\n\n writeLink(target, link, linkFs)\n\n return { kind: 'link', outcome: current === ABSENT ? 'created' : 'repointed', target, link }\n } catch {\n return { kind: 'link', outcome: 'failed', target, link }\n }\n}\n\n/**\n * `(fields, message)` \u2014 the shape of `logger.debug`, so the CLI can pass it straight through. The two\n * boot results are a union on `kind`: a caller that reads `link`/`target` (the `ik-mcp` stderr line)\n * narrows first.\n */\nexport type PortlessLinkLog = (result: PortlessLinkResult | PortlessNodeResult, message: string) => void\n\n/** The link's seams and the node's, sharing ONE `isGlobal` \u2014 the two are converged together at every boot. */\nexport interface PortlessStableDeps {\n link: EnsurePortlessLinkDeps\n node: EnsurePortlessNodeDeps\n}\n\n/**\n * The real seams. Shared with `setup`, which needs the RESULTS back to report its steps, so the writers\n * can never disagree about which install is \"global\" or where the files go. `isGlobal` is memoised\n * per deps object: it costs a `realpathSync` plus the `.git` walk, and both steps ask it.\n */\nexport const realPortlessStableDeps = (): PortlessStableDeps => {\n const home = homedir()\n let global: boolean | undefined\n\n const isGlobal = (): boolean => {\n global ??= isGlobalInstall({\n selfRealPath: fs.realpathSync(fileURLToPath(import.meta.url)),\n env: process.env,\n realpath: safeRealpath,\n home,\n exists: fs.existsSync,\n })\n\n return global\n }\n\n return {\n link: { resolveBin: resolvePortlessBin, isGlobal, home },\n node: {\n isGlobal,\n home,\n execPath: process.execPath,\n version: process.version,\n arch: process.arch,\n platform: process.platform,\n },\n }\n}\n\nconst logStep = (log: PortlessLinkLog, message: string, run: () => PortlessLinkResult | PortlessNodeResult): void => {\n try {\n log(run(), message)\n } catch {\n // A file that could not be converged is `doctor`'s to report; it must never be a boot failure.\n }\n}\n\n/**\n * The process-boot entry for both bins: the link, then the node \u2014 independent state, so the node step\n * runs whatever the link reported. fs-only, no subprocess, never throws, never exits, never writes to\n * stdout; each outcome goes to `log` and nowhere else. `deps` is injectable so the \"`'failed'` is\n * logged\" contract is testable without a real disk.\n */\nexport const bootPortlessLink = (log: PortlessLinkLog, deps?: PortlessStableDeps): void => {\n const stable = deps ?? realPortlessStableDeps()\n\n logStep(log, 'portless link', () => {\n return ensurePortlessLink(stable.link)\n })\n logStep(log, 'portless node', () => {\n return ensurePortlessNode(stable.node)\n })\n}\n", "/**\n * @fileoverview\n *\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.<repo>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, an Orca pane, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\nimport { shellLine } from 'src/lib/shell-quote'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * Prints what the driver itself runs (see {@link defaultRun}): the current interpreter, by absolute path,\n * invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the command\n * works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\n// This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n// `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless\n// service install` hands the user a command that dies with `sudo: portless: command not found`. `sudo`\n// makes it strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve\n// `portless` loses it the moment the command is elevated.\n//\n// This is not merely cosmetic. portless's `service install` writes the interpreter and script path it was\n// invoked with straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n// `process.argv[1]`), so the command printed here is the command that gets installed as a ROOT SYSTEM\n// DAEMON. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as\n// root.\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + shellLine(words)\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_LABEL = 'sh.portless.proxy'\nexport const DARWIN_SERVICE_PLIST_PATH = `/Library/LaunchDaemons/${DARWIN_SERVICE_LABEL}.plist`\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n/** The systemd unit name `service install` registers on Linux \u2014 the `systemctl` argument, not a path. */\nexport const LINUX_SERVICE_UNIT_NAME = 'portless'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Trust is a separate, explicitly-validating probe (doctor's\n * CA check).\n */\n// This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was UNSOUND: portless's\n// `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n// process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n// stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n// old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n// were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n//\n// Validating the chain here would collapse two different failures \u2014 a daemon that is down, and a CA that\n// was never trusted \u2014 into one indistinguishable error, with two different fixes (a root `service install`\n// vs the sudo-free `trust`).\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.hulyo-monorepo.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>.<repo>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n isAvailable,\n isProxyServing: serving,\n probeProxy,\n isServiceInstalled,\n registerAlias,\n removeAlias,\n }\n}\n", "/**\n * Render an argv array as a line a POSIX shell runs back verbatim.\n *\n * Every surface that PRINTS a command for a human to paste has the same obligation, and `join(' ')` does\n * not meet it. The load-bearing case is `lib/dependency-install`'s refusals: a recipe we decline to run\n * is printed precisely so the human can run it, and joining\n * `['/bin/bash', '-c', 'curl -fsSL \u2026 | bash']` on spaces yields\n * `/bin/bash -c curl -fsSL \u2026 | bash` \u2014 which loses the argument boundary and runs `curl` with `-fsSL`\n * as `$0`, no URL, and the rest piped into a second shell. It fails, and it fails in a way that reads\n * like the tool's fault rather than the transcription's.\n *\n * The implementation began inside `dev/proxy/portless-driver`, which needed it first and is still a\n * caller; a second copy beside the recipes would drift from it.\n */\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set \u2014 a space, a pipe, a paren,\n * all of which appear in real recipes and real install paths \u2014 gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nexport const shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** One pasteable shell line from an argv array, each word quoted only when it needs to be. */\nexport const shellLine = (argv: readonly string[]): string => {\n return argv.map(shellQuote).join(' ')\n}\n", "/**\n * @fileoverview\n *\n * `~/.infra-kit/node` \u2014 a stable, regular-file name for the Node binary the global infra-kit runs, kept\n * current by every process boot beside `~/.infra-kit/portless` (see that module's header for the link).\n *\n * Why a HARDLINK: `portless service install` bakes `process.execPath` into the root plist, and Node\n * realpaths `execPath` (measured: a hardlink of node prints its own path from `-p process.execPath`;\n * a symlink prints the target), so no symlink in front of the binary survives into the plist. Under\n * pnpm 12 the binary lives in `global/v11/{pid}-{ts}/\u2026/node@runtime/\u2026`, a directory every `pnpm add -g`\n * re-mints \u2014 with no Node bump. A hardlink is a regular file, costs 0.3 ms and 0 bytes, and its inode\n * outlives the manager's directory, so the name cannot dangle across a re-mint + reboot the way a\n * symlink would. `copyFile(COPYFILE_FICLONE)` is a full 134 MB copy on APFS here, so it is the FALLBACK\n * only: root-owned `/usr/bin/node` under `protected_hardlinks`, a cross-volume home (macOS answers\n * `EPERM`, not `EXDEV`), exFAT/SMB/NFS (`ENOTSUP`), dataless iCloud (`EDEADLK`) \u2014 the failure set of\n * `link(2)` is not enumerable, so ANY throw takes the copy. The daemon never consults `execPath` again\n * after boot (`proxy start --foreground` spawns nothing), so that one plist word is the whole contract.\n *\n * T-1 \u2014 the hardlink SHARES an inode with the package manager's node, and macOS enforces no `ETXTBSY`:\n * a write through this name lands in the developer's real node and, on Apple Silicon, kills every\n * process mapping it by signature invalidation. Rename-only discipline is the ONLY guard: every byte\n * goes to a `node.tmp-<pid>` sibling and is published by `rename(2)`; the node path is never opened\n * for writing, never chmod'ed (that too mutates the shared inode) and never unlinked. `chmod` runs on\n * the copy branch's tmp alone \u2014 the source is executable already, this process executed it.\n *\n * Staleness is one inode compare against `process.execPath`, never a version or byte compare: after a\n * re-mint the source is a new inode with identical bytes and relinking is free. The sidecar keeps two\n * clocks \u2014 `refreshedAt` (the file) and `versionChangedAt` (the Node behind it, carried over on a\n * same-version relink) \u2014 because doctor's \"daemon predates Node \u2026\" advisory must not nag after every\n * global install. Neither is an fs timestamp: a hardlink's mtime is the source's install time.\n *\n * Same gate and contract as the link: `isGlobalInstall` is the only thing between a checkout and the\n * root daemon; nothing here spawns, writes stdout, or throws.\n */\nimport fs from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport process from 'node:process'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\n\n/** `<home>/.infra-kit/node` \u2014 the file the plist's first argv word names. */\nexport const portlessNodePath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'node')\n}\n\n/** `<node>.source.json` \u2014 what the file is (method, Node triple, source) and the two clocks. */\nexport const portlessNodeSidecar = (home: string): string => {\n return `${portlessNodePath(home)}.source.json`\n}\n\n// Hand-checked, not zod: this module is reached from the `ik-mcp` bundle, which must stay free of every\n// node_modules input (`dist-shebang.test.ts`). A sidecar is eight scalars \u2014 a validator is cheaper than\n// the dependency.\nexport interface PortlessNodeSidecar {\n method: 'hardlink' | 'copy'\n version: string\n arch: string\n platform: string\n source: string\n sourceSize?: number\n refreshedAt: string\n versionChangedAt: string\n}\n\nconst isSidecar = (value: unknown): value is PortlessNodeSidecar => {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n const strings = ['version', 'arch', 'platform', 'source', 'refreshedAt', 'versionChangedAt']\n\n return (\n (record.method === 'hardlink' || record.method === 'copy') &&\n strings.every((key) => {\n return typeof record[key] === 'string'\n }) &&\n (record.sourceSize === undefined || typeof record.sourceSize === 'number')\n )\n}\n\n/** The subset of `fs.Stats` the inode compare and the copy-path size witness need. */\nexport interface PortlessNodeStat {\n ino: number\n dev: number\n size: number\n isFile: () => boolean\n}\n\n/**\n * Every fs call the file needs, as an OBJECT seam: `vi.spyOn` cannot intercept named `node:fs` imports,\n * so tests hand in an in-memory fake and the call log \u2014 not the final state \u2014 carries the rename-only\n * contract (T-1). `copyFileSync` takes the mode so the FICLONE flag is visible in that log.\n */\nexport interface PortlessNodeFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n statSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n readFileSync: (target: string, encoding: 'utf8') => string\n writeFileSync: (target: string, data: string) => void\n readdirSync: (dir: string) => string[]\n linkSync: (existing: string, newPath: string) => void\n copyFileSync: (src: string, dest: string, mode: number) => void\n chmodSync: (target: string, mode: number) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport type PortlessNodeOutcome =\n 'created' | 'refreshed' | 'unchanged' | 'skipped-local' | 'skipped-platform' | 'failed'\n\nexport interface PortlessNodeResult {\n kind: 'node'\n outcome: PortlessNodeOutcome\n node: string\n /** The `execPath` the file was (or would have been) made from. */\n source: string\n version: string\n /** How the file relates to `source`; `null` when nothing was published and nothing converged was found. */\n method: 'hardlink' | 'copy' | null\n}\n\nexport interface EnsurePortlessNodeDeps {\n /** The SAME memoised closure the link uses \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n execPath: string\n version: string\n arch: string\n platform: NodeJS.Platform\n fs?: PortlessNodeFs\n now?: () => Date\n}\n\n// EXCL is load-bearing, not hygiene: a stale `node.tmp-<pid>` from a boot that died before its `rename`\n// can be a HARDLINK of the live node, and a reused pid would hand the copy branch that name \u2014 an\n// `O_TRUNC` open of it is the T-1 write-through. With EXCL the copy refuses (`EEXIST` \u2192 `'failed'`) and\n// the next boot's sweep clears the name.\nconst COPY_FLAGS = fs.constants.COPYFILE_FICLONE | fs.constants.COPYFILE_EXCL\nconst COPY_MODE = 0o755\n\n/** `null` when the sidecar is absent, unreadable or does not parse \u2014 every one of those forces a refresh. */\nexport const readPortlessNodeSidecar = (home: string, nodeFs: PortlessNodeFs = fs): PortlessNodeSidecar | null => {\n try {\n const parsed: unknown = JSON.parse(nodeFs.readFileSync(portlessNodeSidecar(home), 'utf8'))\n\n return isSidecar(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\nconst sameInode = (a: PortlessNodeStat, b: PortlessNodeStat): boolean => {\n return a.ino === b.ino && a.dev === b.dev\n}\n\n/**\n * `<home>/.infra-kit/node` when it is a regular file on the SAME inode as `execPath`, else `null`.\n * Inode equality is proof of runnability \u2014 the asking process IS that inode \u2014 so this needs no sidecar\n * and no spawn, which is what lets `dev` render the short `service install` line on its hot path. A\n * copy-path file is never a candidate: nothing short of running it proves it runs (doctor's job).\n */\nexport const stableNodeCandidate = (input: { home: string; execPath: string; fs?: PortlessNodeFs }): string | null => {\n const { home, execPath, fs: nodeFs = fs } = input\n const node = portlessNodePath(home)\n\n try {\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (current === undefined || exec === undefined || !current.isFile()) return null\n\n return sameInode(current, exec) ? node : null\n } catch {\n return null\n }\n}\n\ntype NodeTriple = Pick<EnsurePortlessNodeDeps, 'version' | 'arch' | 'platform'>\n\nconst describesProcess = (sidecar: PortlessNodeSidecar, deps: NodeTriple): boolean => {\n return sidecar.version === deps.version && sidecar.arch === deps.arch && sidecar.platform === deps.platform\n}\n\n/**\n * The fast path. Inode equality is the strongest signal for the FILE; the version clause is for the\n * SIDECAR: a crash between the two renames after a Node bump leaves the new inode described as the old\n * version with a pre-bump `versionChangedAt`, and without this clause that would be `'unchanged'` forever\n * (doctor printing the wrong version, the restart advisory keyed on a clock that is too old). On the copy\n * path the inode can never match, so the size is the second witness beside the version triple.\n */\nconst isConverged = (\n current: PortlessNodeStat,\n exec: PortlessNodeStat,\n sidecar: PortlessNodeSidecar,\n deps: NodeTriple,\n): boolean => {\n if (!describesProcess(sidecar, deps)) return false\n if (sameInode(current, exec)) return true\n\n return sidecar.method === 'copy' && sidecar.sourceSize === exec.size\n}\n\nconst discard = (tmp: string, nodeFs: PortlessNodeFs): void => {\n try {\n nodeFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failure that got us here is the one worth surfacing, not a leftover sibling.\n }\n}\n\n/**\n * A SIGKILL mid-copy leaves a 134 MB `node.tmp-<pid>` under a pid that may never recur; the sidecar\n * orphan is ~250 B, but one pass covers both. Only these two prefixes are ours to remove. A concurrent\n * boot's live tmp may go too \u2014 its `rename` then fails into `'failed'` and the next boot converges;\n * the published name always holds a complete file.\n */\nconst sweepOrphans = (dir: string, prefixes: string[], nodeFs: PortlessNodeFs): void => {\n let names: string[]\n\n try {\n names = nodeFs.readdirSync(dir)\n } catch {\n return\n }\n\n for (const name of names) {\n const orphan = prefixes.some((prefix) => {\n return name.startsWith(prefix)\n })\n\n if (orphan) discard(join(dir, name), nodeFs)\n }\n}\n\n/** Hardlink first; on ANY throw, the copy (see the header for why the error set is not filtered). */\nconst stageNode = (execPath: string, tmp: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n try {\n nodeFs.linkSync(execPath, tmp)\n\n return 'hardlink'\n } catch {\n nodeFs.copyFileSync(execPath, tmp, COPY_FLAGS)\n // The copy branch ONLY: on a hardlink this would chmod the manager's inode. 0755 is what the source\n // carries and what root needs to exec a file under a 0700 home \u2014 no secret lives in a node binary.\n // eslint-disable-next-line sonarjs/file-permissions -- an executable's mode, not a data file's\n nodeFs.chmodSync(tmp, COPY_MODE)\n\n return 'copy'\n }\n}\n\n/**\n * Stage under the pid-suffixed sibling, publish by ONE `rename` (T-1). The old inode stays mapped by a\n * running daemon; `rename` touches no byte of it. On any throw the sibling is removed and the old file\n * is exactly as it was.\n */\nconst publishNode = (execPath: string, node: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n const tmp = `${node}.tmp-${process.pid}`\n\n try {\n const method = stageNode(execPath, tmp, nodeFs)\n\n nodeFs.renameSync(tmp, node)\n\n return method\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\nconst publishSidecar = (sidecarPath: string, sidecar: PortlessNodeSidecar, nodeFs: PortlessNodeFs): void => {\n const tmp = `${sidecarPath}.tmp-${process.pid}`\n\n try {\n nodeFs.writeFileSync(tmp, `${JSON.stringify(sidecar, null, 2)}\\n`)\n nodeFs.renameSync(tmp, sidecarPath)\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\n/**\n * `versionChangedAt` is carried over only when the Node behind the file is the same one the previous\n * sidecar described: the triple, plus the size whenever the previous sidecar recorded one (a copy of a\n * same-version different build IS a different Node). A same-version relink after a re-mint must not\n * look like a Node bump to doctor's restart advisory. No parsable previous sidecar \u2192 `now`, which errs\n * towards one advisory too many, never too few.\n */\nconst nextSidecar = (\n previous: PortlessNodeSidecar | null,\n method: 'hardlink' | 'copy',\n exec: PortlessNodeStat,\n deps: EnsurePortlessNodeDeps,\n now: string,\n): PortlessNodeSidecar => {\n const sameNode =\n previous !== null &&\n describesProcess(previous, deps) &&\n (previous.sourceSize === undefined || previous.sourceSize === exec.size)\n\n return {\n method,\n version: deps.version,\n arch: deps.arch,\n platform: deps.platform,\n source: deps.execPath,\n ...(method === 'copy' ? { sourceSize: exec.size } : {}),\n refreshedAt: now,\n versionChangedAt: sameNode ? previous.versionChangedAt : now,\n }\n}\n\n/**\n * Converge `~/.infra-kit/node` on the Node running THIS install. Never throws; every outcome is a value.\n *\n * A symlink or directory at the path is `'failed'` and left exactly as found \u2014 this code owns a regular\n * file, and removing whatever someone else put there is the one destructive act a boot hook must never\n * take. A converged machine pays one `lstat`, one `stat` and a ~250-byte read: no write, no subprocess.\n *\n * @example\n * ensurePortlessNode({ isGlobal: () => true, home: '/Users/x', execPath: process.execPath, version: process.version, arch: process.arch, platform: process.platform })\n * // => { kind: 'node', outcome: 'created', node: '/Users/x/.infra-kit/node', source: process.execPath, version: process.version, method: 'hardlink' }\n */\nexport const ensurePortlessNode = (deps: EnsurePortlessNodeDeps): PortlessNodeResult => {\n const {\n home,\n execPath,\n version,\n fs: nodeFs = fs,\n now = () => {\n return new Date()\n },\n } = deps\n const node = portlessNodePath(home)\n const sidecarPath = portlessNodeSidecar(home)\n const result = (outcome: PortlessNodeOutcome, method: PortlessNodeResult['method']): PortlessNodeResult => {\n return { kind: 'node', outcome, node, source: execPath, version, method }\n }\n\n if (deps.platform !== 'darwin' && deps.platform !== 'linux') return result('skipped-platform', null)\n if (!deps.isGlobal()) return result('skipped-local', null)\n\n try {\n nodeFs.mkdirSync(dirname(node), { recursive: true })\n\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n\n if (current !== undefined && !current.isFile()) return result('failed', null)\n\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (exec === undefined) return result('failed', null)\n\n const previous = readPortlessNodeSidecar(home, nodeFs)\n\n if (current !== undefined && previous !== null && isConverged(current, exec, previous, deps)) {\n return result('unchanged', previous.method)\n }\n\n sweepOrphans(dirname(node), [`${basename(node)}.tmp-`, `${basename(sidecarPath)}.tmp-`], nodeFs)\n\n const method = publishNode(execPath, node, nodeFs)\n\n publishSidecar(sidecarPath, nextSidecar(previous, method, exec, deps, now().toISOString()), nodeFs)\n\n return result(current === undefined ? 'created' : 'refreshed', method)\n } catch {\n return result('failed', null)\n }\n}\n"],
5
- "mappings": "8FAgCA,OAAOA,MAAQ,UACf,OAAS,WAAAC,OAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAS,iBAAAC,OAAqB,WCP9B,OAAS,YAAAC,OAAgB,qBACzB,OAAS,cAAAC,OAAkB,cAC3B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,OAAU,YACjB,OAAOC,OAAW,aAClB,OAAOC,OAAS,WAChB,OAAS,WAAAC,OAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAOC,OAAS,WAChB,OAAS,iBAAAC,OAAqB,WAC9B,OAAS,aAAAC,OAAiB,YCrB1B,IAAMC,GAAa,mBAGbC,GAAsB,QAGfC,EAAcC,GAClBH,GAAW,KAAKG,CAAK,EAAIA,EAAQ,IAAIA,EAAM,WAAW,IAAKF,EAAmB,CAAC,IAI3EG,EAAaC,GACjBA,EAAK,IAAIH,CAAU,EAAE,KAAK,GAAG,EDctC,IAAMI,GAAgBC,GAAUC,EAAQ,EAGlCC,GAAcC,GAAuC,CACzD,IAAMC,EAAM,KAAK,MAAMC,EAAaF,EAAa,OAAO,CAAC,EACnDG,EAAM,OAAOF,EAAI,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FileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "shellLine", "argv", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "formatPortlessCommand", "args", "options", "words", "process", "shellLine", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_LABEL", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "LINUX_SERVICE_UNIT_NAME", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name", "fs", "basename", "dirname", "join", "process", "portlessNodePath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessNodeSidecar", "isSidecar", "value", "record", "strings", "key", "COPY_FLAGS", "fs", "COPY_MODE", "readPortlessNodeSidecar", "nodeFs", "parsed", "sameInode", "a", "b", "stableNodeCandidate", "input", "execPath", "node", "current", "exec", "describesProcess", "sidecar", "deps", "isConverged", "discard", "tmp", "sweepOrphans", "dir", "prefixes", "names", "name", "prefix", "stageNode", "publishNode", "process", "method", "error", "publishSidecar", "sidecarPath", "nextSidecar", "previous", "now", "sameNode", "ensurePortlessNode", "version", "result", "outcome", "dirname", "basename", "portlessLinkPath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessLinkCliPath", "exists", "fs", "cliPath", "serviceInstallCommand", "bin", "seams", "execPath", "process", "stableNode", "stableNodeCandidate", "formatPortlessCommand", "ABSENT", "NOT_A_SYMLINK", "readCurrentLink", "link", "linkFs", "stat", "writeLink", "target", "tmp", "error", "ensurePortlessLink", "deps", "resolveBin", "isGlobal", "dirname", "current", "realPortlessStableDeps", "homedir", "global", "isGlobalInstall", "fileURLToPath", "safeRealpath", "resolvePortlessBin", "logStep", "log", "message", "run", "bootPortlessLink", "stable", "ensurePortlessNode"]
7
- }