infra-kit 0.34.0 → 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.
- package/dist/{boot-LC2ESPY6.js → boot-ST2534PA.js} +2 -2
- package/dist/boot-ST2534PA.js.map +7 -0
- package/dist/{chunk-SAHE3MZJ.js → chunk-55F372Z7.js} +1 -1
- package/dist/{chunk-SAHE3MZJ.js.map → chunk-55F372Z7.js.map} +2 -2
- package/dist/{chunk-5ZBDB3U7.js → chunk-5SGMD57Z.js} +2 -2
- package/dist/chunk-5SGMD57Z.js.map +7 -0
- package/dist/{chunk-MWGE43QS.js → chunk-BYCCXWPB.js} +2 -2
- package/dist/{chunk-MWGE43QS.js.map → chunk-BYCCXWPB.js.map} +2 -2
- package/dist/{chunk-I23MDR4X.js → chunk-GCOYOWGH.js} +1 -1
- package/dist/{chunk-I23MDR4X.js.map → chunk-GCOYOWGH.js.map} +2 -2
- package/dist/chunk-GDOQUC23.js +15 -0
- package/dist/chunk-GDOQUC23.js.map +7 -0
- package/dist/{chunk-XES5EOEE.js → chunk-PP44RGIU.js} +2 -2
- package/dist/chunk-PP44RGIU.js.map +7 -0
- package/dist/{chunk-7A4LVTRJ.js → chunk-QS7RKE5P.js} +2 -2
- package/dist/chunk-QS7RKE5P.js.map +7 -0
- package/dist/{chunk-AWFGP6GY.js → chunk-REDCBY4O.js} +1 -1
- package/dist/{chunk-AWFGP6GY.js.map → chunk-REDCBY4O.js.map} +2 -2
- package/dist/{chunk-U7VGROH3.js → chunk-TFOXJRVH.js} +2 -2
- package/dist/{chunk-U7VGROH3.js.map → chunk-TFOXJRVH.js.map} +1 -1
- package/dist/{chunk-DVXTZPQ5.js → chunk-UTQ4KTO6.js} +1 -1
- package/dist/{chunk-DVXTZPQ5.js.map → chunk-UTQ4KTO6.js.map} +2 -2
- package/dist/{chunk-TVG47UHG.js → chunk-V2ZLQPLI.js} +1 -1
- package/dist/{chunk-TVG47UHG.js.map → chunk-V2ZLQPLI.js.map} +2 -2
- package/dist/{chunk-QCTAEXMN.js → chunk-YVIJUGOB.js} +6 -6
- package/dist/{chunk-QCTAEXMN.js.map → chunk-YVIJUGOB.js.map} +2 -2
- package/dist/cli.js +145 -127
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +5 -5
- package/dist/dev-server.js.map +2 -2
- package/dist/{dev-wizard-run-452R76HN.js → dev-wizard-run-5JKULZ4J.js} +2 -2
- package/dist/dev-wizard-run-5JKULZ4J.js.map +7 -0
- package/dist/{env-load-IXDGWGPV.js → env-load-HRJPWQ5X.js} +2 -2
- package/dist/mcp-proxy.js +1 -1
- package/dist/mcp-proxy.js.map +2 -2
- package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js → persistent-ink-dev-ui-D6ALK2P3.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/dist/boot-LC2ESPY6.js.map +0 -7
- package/dist/chunk-467ZSXYU.js +0 -15
- package/dist/chunk-467ZSXYU.js.map +0 -7
- package/dist/chunk-5ZBDB3U7.js.map +0 -7
- package/dist/chunk-7A4LVTRJ.js.map +0 -7
- package/dist/chunk-XES5EOEE.js.map +0 -7
- package/dist/dev-wizard-run-452R76HN.js.map +0 -7
- /package/dist/{env-load-IXDGWGPV.js.map → env-load-HRJPWQ5X.js.map} +0 -0
- /package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js.map → persistent-ink-dev-ui-D6ALK2P3.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/dev/managed-child.ts", "../src/dev/signal-shutdown.ts", "../src/lib/errors/is-prompt-cancellation.ts", "../src/integrations/orca/run-orca.ts", "../src/integrations/orca/availability.ts", "../src/integrations/orca/realpath-for-orca-cwd.ts", "../src/integrations/orca/ensure-repo.ts", "../src/integrations/orca/is-worktree-listed.ts", "../src/integrations/orca/caller-inside-target.ts", "../src/integrations/orca/list-terminals-by-cwd.ts", "../src/integrations/orca/close-worktree-terminals.ts", "../src/integrations/orca/open-worktree-terminals.ts", "../src/integrations/orca/terminal-title.ts", "../src/dev/health-probe.ts", "../src/lib/app-release/app-release.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview\n *\n * Shared supervision for the dev-server's long-lived, detached child processes\n * (`turbo watch build`, `turbo run dev`). Both are deep trees\n * (`sh \u2192 pnpm \u2192 node \u2192 turbo \u2192 \u2026`) spawned `detached` so they form their own process\n * group; teardown signals the whole GROUP (`process.kill(-pid, \u2026)`), not just the wrapper.\n *\n * Signalling turbo's group is NOT enough on its own: turbo puts every task it runs\n * (`vite`, `tsc -b`, \u2026) into a process group of its OWN, so `kill(-turboPid, \u2026)` reaches\n * turbo but never its tasks. Turbo normally forwards the signal and reaps them, but when it\n * is slower than the grace window a bare `SIGKILL` on turbo's group kills the only process\n * that knows the task groups \u2014 stranding orphaned vite servers that hold their ports until\n * the next run fails with `EADDRINUSE`.\n *\n * So teardown snapshots the descendant process groups BEFORE signalling (once turbo dies its\n * children reparent to init and can no longer be found by walking `ppid`), waits for the whole\n * set to exit, and only then force-kills whatever is left.\n *\n * The same fact \u2014 reparenting blinds the `ppid` walk \u2014 is why a snapshot taken only at teardown is not\n * enough. When turbo dies on its OWN (a crash, an OOM kill) there is no teardown to snapshot from, and\n * the tasks it never reaped are already unreachable. So the snapshot is instead kept ROLLING for the\n * child's whole life, and each group is stamped with its leader's `lstart`: a pgid is a bare integer the\n * kernel will happily recycle, and the leader's start time is the only proof that the group we are about\n * to SIGKILL is still the one we saw.\n *\n * That rolling snapshot lives in a per-child closure, which is exactly what the SECOND-SIGNAL force path\n * (`killDescendantGroupsNow`, used by both `signal-shutdown`'s force-quit and `crash-barrier`'s fatal\n * path) cannot reach on its own \u2014 it only ever does a live `ppid` walk from `process.pid`, the same walk\n * that goes blind the moment a child dies. So every supervised child's snapshot is also published to a\n * module-level `registry` (see below), letting that force path find a descendant which reparented to init\n * before ITS parent's `exit` even fired \u2014 the one case a live walk structurally cannot cover.\n */\nimport { execFile, execFileSync } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport process from 'node:process'\n\n/** Handle to a supervised child; `kill()` reaps its whole process tree and resolves when gone. */\nexport interface ManagedChild {\n kill: () => Promise<void>\n}\n\n/**\n * Grace before escalating SIGTERM \u2192 SIGKILL. Long enough for turbo to stop its tasks itself\n * (typically well under a second) and short enough that Ctrl-C still feels immediate. Escalating\n * is safe now that every task group is killed as a set, so this need not cover the worst case.\n * The happy path never waits the full window \u2014 teardown returns as soon as the groups are gone.\n */\nconst DEFAULT_GRACE_MS = 5000\n\n/** Poll interval while waiting for the doomed process groups to exit. */\nconst POLL_MS = 100\n\n/** How long to wait for the kernel to reap a group after SIGKILL before giving up on confirmation. */\nconst REAP_TIMEOUT_MS = 2000\n\n/** Absolute path to `ps` \u2014 present on both macOS and Linux, and immune to `PATH` substitution. */\nconst PS_BIN = '/bin/ps'\n\n/**\n * How often the live process table is sampled while a supervised child is alive, to keep\n * {@link ManagedChild}'s group snapshot current. See {@link superviseChild} for why a snapshot taken\n * only at kill-time is too late. Async (`execFile`, not `execFileSync`), so it never blocks the event\n * loop the in-process backends share.\n */\nconst SAMPLE_INTERVAL_MS = 1000\n\n/** `ps` columns: the `ppid` walk needs pid/ppid/pgid, and the reuse guard needs the leader's `lstart`. */\nconst PS_ARGS = ['-eo', 'pid=,ppid=,pgid=,lstart='] as const\n\n/** Cap on `ps` output; a busy machine's full process table stays far below this. */\nconst PS_MAX_BUFFER = 8 << 20\n\n/** One row of `ps -eo pid=,ppid=,pgid=,lstart=`. */\nexport interface ProcRow {\n pid: number\n ppid: number\n pgid: number\n /** The process's start time as `ps` prints it (`Mon Jul 13 13:21:14 2026`); `''` when unavailable. */\n lstart: string\n}\n\n/**\n * The subset of a {@link ProcRow} that describes the process TREE. The `ppid` walk needs nothing else,\n * so the functions that only walk take this \u2014 `lstart` is the reuse guard's concern, not the topology's.\n */\nexport type TopologyRow = Pick<ProcRow, 'pid' | 'ppid' | 'pgid'>\n\n/**\n * Parse `ps -eo pid=,ppid=,pgid=,lstart=`, skipping any line that doesn't start with three integers.\n * `lstart` is whitespace-separated and multi-token, so it is everything after the third column.\n */\nexport const parseProcRows = (raw: string): ProcRow[] => {\n return raw.split('\\n').flatMap((line) => {\n const [rawPid, rawPpid, rawPgid, ...rest] = line.trim().split(/\\s+/)\n\n if (rawPid == null || rawPpid == null || rawPgid == null) return []\n\n const pid = Number(rawPid)\n const ppid = Number(rawPpid)\n const pgid = Number(rawPgid)\n\n if (!Number.isInteger(pid) || !Number.isInteger(ppid) || !Number.isInteger(pgid)) return []\n\n return [{ pid, ppid, pgid, lstart: rest.join(' ') }]\n })\n}\n\n/**\n * A process group, stamped with its LEADER's start time at the moment the group was observed.\n *\n * The start time is the whole point. A pgid on its own is a bare integer: by the time we come to reap\n * it the kernel may have recycled it onto an unrelated process, and `kill(-pgid, \u2026)` would then destroy\n * a stranger's group. The leader's `lstart` is the identity that survives \u2014 a recycled pgid necessarily\n * has a NEWER birth time than the one recorded, so it is refused.\n */\nexport interface GroupSnapshot {\n pgid: number\n leaderStart: string\n}\n\n/** Map every process group in `rows` to its leader's start time (the leader is the pid equal to the pgid). */\nconst leaderStarts = (rows: ProcRow[]): Map<number, string> => {\n const starts = new Map<number, string>()\n\n for (const row of rows) {\n if (row.pid === row.pgid) starts.set(row.pgid, row.lstart)\n }\n\n return starts\n}\n\n/**\n * {@link collectDoomedGroups}, but each group is stamped with its leader's start time so it can be\n * validated later. Groups whose leader is not in `rows` are dropped: with no leader there is nothing to\n * stamp, so nothing could prove the group is still the one we saw, and the reuse guard must fail closed.\n *\n * @example\n * const rows = [\n * { pid: 10, ppid: 1, pgid: 10, lstart: 'Mon Jul 13 13:00:00 2026' },\n * { pid: 20, ppid: 10, pgid: 20, lstart: 'Mon Jul 13 13:00:01 2026' },\n * ]\n * snapshotGroups(10, rows) // => [{ pgid: 10, leaderStart: '\u202613:00:00\u2026' }, { pgid: 20, leaderStart: '\u202613:00:01\u2026' }]\n */\nexport const snapshotGroups = (rootPid: number, rows: ProcRow[], excludePgid?: number): GroupSnapshot[] => {\n const starts = leaderStarts(rows)\n\n return collectDoomedGroups(rootPid, rows, excludePgid).flatMap((pgid) => {\n const leaderStart = starts.get(pgid)\n\n if (leaderStart == null || leaderStart === '') return []\n\n return [{ pgid, leaderStart }]\n })\n}\n\n/**\n * pgids in `snapshot` whose leader's start time still matches `rows` \u2014 the reuse guard shared by every\n * path that reaps from a snapshot instead of a live walk: {@link reapSnapshot} (the per-child crash/kill\n * reap) and {@link collectForceReapTargets} (the force-reap path, reaping every REGISTERED child's\n * snapshot). Extracted so the two can never drift apart \u2014 a registry-sourced pgid must clear the exact\n * same check a per-child reap does before either signals it.\n */\nconst validSnapshotPgids = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n const starts = leaderStarts(rows)\n\n return snapshot.flatMap(({ pgid, leaderStart }) => {\n return starts.get(pgid) === leaderStart ? [pgid] : []\n })\n}\n\n/**\n * SIGKILL every snapshotted group whose leader is STILL the same process, and return the pgids killed.\n *\n * A group whose leader has since exited is skipped (nothing to kill, and no way to prove ownership of\n * whatever else may share the pgid). A group whose leader's start time no longer matches is a recycled\n * pgid belonging to a stranger \u2014 skipped, loudly and deliberately. This is the guard that makes reaping\n * from a stale snapshot safe, and it is why the snapshot records `lstart` at all.\n */\nexport const reapSnapshot = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n return validSnapshotPgids(snapshot, rows).flatMap((pgid) => {\n try {\n process.kill(-pgid, 'SIGKILL')\n } catch {\n // Raced us to exit (ESRCH) \u2014 nothing to kill.\n return []\n }\n\n return [pgid]\n })\n}\n\n/**\n * Distinct process groups of every transitive descendant of `rootPid`, plus `rootPid`'s own\n * group. Group `0`/`1` and `excludePgid` (our own group \u2014 a detached child can never share it,\n * but a mis-parsed row must never make us signal ourselves) are filtered out.\n *\n * @example\n * const rows = [{ pid: 10, ppid: 1, pgid: 10 }, { pid: 20, ppid: 10, pgid: 20 }]\n * collectDoomedGroups(10, rows, 5) // => [10, 20]\n */\nexport const collectDoomedGroups = (rootPid: number, rows: TopologyRow[], excludePgid?: number): number[] => {\n const childrenOf = new Map<number, TopologyRow[]>()\n\n for (const row of rows) {\n const siblings = childrenOf.get(row.ppid)\n\n if (siblings) siblings.push(row)\n else childrenOf.set(row.ppid, [row])\n }\n\n const groups = new Set<number>([rootPid])\n const seen = new Set<number>([rootPid])\n const queue = [rootPid]\n\n for (let i = 0; i < queue.length; i += 1) {\n for (const child of childrenOf.get(queue[i] ?? -1) ?? []) {\n if (seen.has(child.pid)) continue\n seen.add(child.pid)\n groups.add(child.pgid)\n queue.push(child.pid)\n }\n }\n\n return [...groups].filter((pgid) => {\n return pgid > 1 && pgid !== excludePgid\n })\n}\n\n/**\n * Snapshot the live process table; an empty list on failure degrades to group-only teardown.\n * `ps` is invoked by absolute path (not via `PATH`, unlike the `pnpm` the engines shell out to)\n * so a writable `PATH` entry can never substitute the binary we hand a kill list to.\n */\nconst snapshotProcRows = (): ProcRow[] => {\n try {\n return parseProcRows(execFileSync(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }))\n } catch {\n return []\n }\n}\n\n/**\n * {@link snapshotProcRows}, off the event loop. The rolling sampler runs on a timer for the whole life\n * of a dev session, and the in-process backends share this loop \u2014 a synchronous `ps` every second would\n * stall every request that lands during it. Resolves to `[]` on failure, degrading to the previous\n * snapshot rather than clobbering it.\n */\nconst snapshotProcRowsAsync = async (): Promise<ProcRow[]> => {\n return new Promise((resolve) => {\n execFile(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }, (error, stdout) => {\n resolve(error ? [] : parseProcRows(stdout))\n })\n })\n}\n\n/** Does `pid` currently exist and name a direct child of `parentPid`? Guards against pid reuse. */\nexport const isChildOf = (pid: number, parentPid: number, rows: TopologyRow[]): boolean => {\n return rows.some((row) => {\n return row.pid === pid && row.ppid === parentPid\n })\n}\n\n/**\n * The groups to signal for `rootPid`'s tree, excluding our own group so a mis-parsed `ps` row can\n * never make the dev-server signal itself.\n */\nconst doomedGroupsOf = (rootPid: number, rows: ProcRow[]): number[] => {\n const ownPgid = rows.find((row) => {\n return row.pid === process.pid\n })?.pgid\n\n return collectDoomedGroups(rootPid, rows, ownPgid)\n}\n\n/** Is the process group led by `pgid` still alive? (`kill(-pgid, 0)` throws ESRCH when gone.) */\nconst groupAlive = (pgid: number): boolean => {\n try {\n process.kill(-pgid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\n/** Send `signal` to every named process group, ignoring groups that already exited. */\nconst signalGroups = (pgids: number[], signal: NodeJS.Signals): void => {\n for (const pgid of pgids) {\n try {\n process.kill(-pgid, signal)\n } catch {\n // Already gone (ESRCH) \u2014 nothing to signal.\n }\n }\n}\n\n/**\n * Live accessors into every currently-supervised child's rolling {@link GroupSnapshot} list \u2014 populated by\n * {@link superviseChild} on spawn, removed only once that child's own groups are CONFIRMED gone (see\n * `deregisterAfter` inside it, not the child's bare `exit` event). This is what lets\n * {@link killDescendantGroupsNow} \u2014 the second-signal force path and the crash-barrier's fatal path \u2014\n * reach a descendant that reparented to init before ITS parent's `exit` fired: a live `ppid` walk from\n * `process.pid` cannot see such a descendant (see the module doc block for why), but a snapshot recorded\n * while the parent was still alive can.\n *\n * INVARIANT \u2014 never regress this: a registry-sourced pgid is signalled ONLY after\n * {@link validSnapshotPgids} confirms its leader's start time still matches a FRESH `ps` snapshot. An\n * ungated union would SIGKILL a recycled pgid \u2014 a hazard the live walk cannot have, since it only ever\n * names processes that are alive right now.\n */\nconst registry = new Set<() => readonly GroupSnapshot[]>()\n\n/**\n * The pgids {@link killDescendantGroupsNow} should signal: every group in the live `ppid` walk from\n * `rootPid` (unchanged semantics \u2014 see {@link doomedGroupsOf}), UNIONED with every registry-sourced\n * snapshot that survives {@link validSnapshotPgids} against the same `rows`. Live-walk pgids are not\n * lstart-gated \u2014 they carry no snapshot to validate against, and are live by construction; only the\n * registry-sourced half needs the reuse guard.\n *\n * Pulled out of `killDescendantGroupsNow` as a pure function so the union/dedupe logic can be tested\n * against a fake process table and fake registry snapshots, without spawning real processes or waiting on\n * a real `ps`.\n *\n * @example\n * // pgid 20 is unreachable from rootPid (reparented to init) but was recorded before its parent died.\n * collectForceReapTargets(1000, freshRows, [[{ pgid: 20, leaderStart: '\u2026' }]]) // => [20]\n */\nexport const collectForceReapTargets = (\n rootPid: number,\n rows: ProcRow[],\n registrySnapshots: readonly (readonly GroupSnapshot[])[],\n): number[] => {\n const live = doomedGroupsOf(rootPid, rows)\n\n const fromRegistry = registrySnapshots.flatMap((snapshot) => {\n return validSnapshotPgids(snapshot, rows)\n })\n\n return [...new Set([...live, ...fromRegistry])]\n}\n\n/**\n * SIGKILL every process group descended from this process, right now \u2014 plus every REGISTERED\n * supervised-child snapshot that still validates, so a group that reparented to init before its parent's\n * `exit` fired is not left behind just because the live `ppid` walk can no longer see it.\n *\n * The force-quit path (a second Ctrl-C) abandons the graceful teardown, but it must not abandon the\n * CHILDREN: they hold the dev ports, and the next start would 502 against their stale portless\n * aliases. So this is the blunt counterpart to {@link superviseChild}'s teardown \u2014 no SIGTERM grace,\n * no escalation, no waiting for the kernel to reap. Straight to SIGKILL.\n *\n * Synchronous by contract: the caller exits the process on the very next line, so anything deferred\n * to a later tick would never run. Cost is one `ps` (tens of ms) plus a `kill` per group; that is the\n * whole latency budget a user who just hit Ctrl-C twice is willing to spend.\n */\nexport const killDescendantGroupsNow = (): void => {\n const rows = snapshotProcRows()\n\n const registrySnapshots = [...registry].map((getGroups) => {\n return getGroups()\n })\n\n signalGroups(collectForceReapTargets(process.pid, rows, registrySnapshots), 'SIGKILL')\n}\n\n/** Resolve after `ms`, used to pace the teardown polling loop. */\nconst sleep = async (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/** Poll `pgids` until every group has exited or `timeoutMs` elapses; returns the survivors. */\nconst waitForExit = async (pgids: number[], timeoutMs: number): Promise<number[]> => {\n const deadline = Date.now() + timeoutMs\n let alive = pgids\n\n while (alive.length > 0 && Date.now() < deadline) {\n alive = alive.filter(groupAlive)\n if (alive.length === 0) break\n await sleep(POLL_MS)\n }\n\n return alive\n}\n\n/**\n * Called when a supervised child dies on its OWN \u2014 a natural `exit` or a spawn `error` that was\n * NOT initiated by {@link ManagedChild.kill}. `detail` is a short human description of the cause.\n * The runner uses it to surface a silently-dead `turbo watch`/`turbo run dev` engine (which stops\n * rebuilds/HMR with no other signal) instead of leaving the session looking healthy.\n */\nexport type UnexpectedExitHandler = (detail: string) => void\n\n/**\n * Wrap a detached child: `unref()` it (so it never keeps the loop alive) and return a handle\n * whose `kill()` reaps the child AND every process group turbo spawned beneath it.\n *\n * Snapshot first, signal second: after turbo exits its tasks reparent to init, so the `ppid`\n * walk that finds them must run while turbo is still alive. Then SIGTERM every doomed group,\n * poll until all are gone, and SIGKILL the survivors. Resolves once nothing is left.\n *\n * `onUnexpectedExit` (optional) fires when the child dies WITHOUT `kill()` having been called \u2014\n * the \"engine died silently\" case; the exit our own teardown causes never reaches it.\n */\n// The snapshot-first order covers the ORDERLY death, where we choose the moment and can walk the tree\n// first. It does not cover turbo CRASHING, because reparenting happens at termination \u2014 strictly before\n// Node hands us the `exit` event \u2014 so by then the walk is already blind. A rolling snapshot (see `sample`)\n// is therefore kept for the child's whole life, and both the crash path and a `kill()` on an already-dead\n// child reap from it, validating each group against its leader's start time so a recycled pgid is never\n// killed.\n//\n// A `killing` latch, set at the top of `kill()` before any signal goes out, is what suppresses\n// `onUnexpectedExit` for our own teardown, so it reports only genuine crashes.\n//\n// The `error` listener is load-bearing beyond reporting: a ChildProcess that emits `error` (e.g. `pnpm`\n// ENOENT) with no listener throws as an uncaught exception and would take the whole dev session down.\nexport function superviseChild(\n child: ChildProcess,\n graceMs: number = DEFAULT_GRACE_MS,\n onUnexpectedExit?: UnexpectedExitHandler,\n /**\n * Test-only seam: overrides the `ps` snapshot used by this child's own reap ATTEMPTS (the crash-time\n * reap in the `exit` handler, and `kill()`'s reaps) \u2014 never the rolling sampler, which always uses the\n * real one. Defaults to the real synchronous `ps` call for every production caller. Lets a test simulate\n * a transient `ps` failure (an empty read) without needing to race the real one.\n */\n snapshotRowsOverride: () => ProcRow[] = snapshotProcRows,\n): ManagedChild {\n // Don't keep the parent event loop alive on the child; the runner owns lifecycle via kill().\n child.unref()\n\n // Latched by kill() before it signals, so the child's own teardown exit is not misreported as a crash.\n let killing = false\n // Set by the `exit` listener, so a sampler callback still in flight cannot clobber the final snapshot.\n let exited = false\n /** Last known process groups beneath this child, refreshed while it is alive. See the sampler below. */\n let groups: GroupSnapshot[] = []\n let sampler: NodeJS.Timeout | null = null\n\n /** Live accessor registered in {@link registry} for the whole life of this child \u2014 see `deregisterAfter`. */\n const getGroups = (): readonly GroupSnapshot[] => {\n return groups\n }\n\n registry.add(getGroups)\n\n const stopSampling = (): void => {\n if (sampler) clearInterval(sampler)\n sampler = null\n }\n\n /**\n * Drop this child's accessor from {@link registry} once every group it ever recorded is CONFIRMED gone\n * \u2014 never merely because `exit` fired or a reap attempt ran. A reap attempt can fail to kill anything\n * for a legitimate reason (a stale/empty `ps` read) while the descendant is still very much alive, and\n * removing the entry THEN would strand it: nothing else remembers those pgids once this closure is gone.\n * Bounded by `REAP_TIMEOUT_MS` so a group this genuinely cannot reap (a foreign process now holding a\n * recycled pgid) does not pin a dead entry in the registry forever.\n */\n const deregisterAfter = async (): Promise<void> => {\n await waitForExit(\n groups.map((g) => {\n return g.pgid\n }),\n REAP_TIMEOUT_MS,\n )\n registry.delete(getGroups)\n }\n\n /**\n * Turn a fresh `ps` read into an updated {@link groups}. An empty result is discarded rather than\n * stored: `ps` failing, or racing the child's own death, must degrade to the previous snapshot, never\n * erase it. Shared by the synchronous first sample below and the async rolling {@link sample}, so the\n * two can never compute the group set differently.\n */\n const applySample = (rows: ProcRow[]): void => {\n const pid = child.pid\n\n if (pid == null || exited || killing || rows.length === 0) return\n\n const ownPgid = rows.find((row) => {\n return row.pid === process.pid\n })?.pgid\n\n const next = snapshotGroups(pid, rows, ownPgid)\n\n if (next.length > 0) groups = next\n }\n\n /**\n * Refresh {@link groups} while the child is alive.\n *\n * This is what makes a crash survivable. Reaping walks `ppid` from the child \u2014 but a process that\n * dies has ALREADY reparented its children to init by the time Node delivers `exit`, so a walk\n * started from the corpse finds only the corpse's own group. Verified: while turbo is alive the walk\n * yields `[turbo, vite]`; inside the `exit` handler it yields `[turbo]`, and vite (`ppid=1`, still\n * running, still holding its port) is unreachable forever. There is no window to race \u2014 the only way\n * to know vite's group after turbo dies is to have written it down BEFORE turbo died.\n *\n * Async (`snapshotProcRowsAsync`) so the rolling tick never blocks the event loop the in-process\n * backends share \u2014 see the FIRST sample below for why that leaves a narrow window this function alone\n * cannot close.\n */\n const sample = async (): Promise<void> => {\n if (child.pid == null || exited || killing) return\n\n applySample(await snapshotProcRowsAsync())\n }\n\n // Synchronous, not `void sample()`: a child that crashes within `sample()`'s first async `ps` round\n // trip (tens of ms) would otherwise have no snapshot recorded at all, and the `exit` handler's\n // `reapSnapshot(groups, \u2026)` would run against an empty `groups` and reap nothing \u2014 the exact\n // spawn\u2192first-snapshot window W11 closes. One small `ps` exec, before this function ever returns,\n // costs the same one-time block on the shared event loop that `killDescendantGroupsNow`'s synchronous\n // `ps` call already spends on every force-quit \u2014 paid once per spawn instead of once per Ctrl-C.\n applySample(snapshotProcRows())\n\n sampler = setInterval(() => {\n void sample()\n }, SAMPLE_INTERVAL_MS)\n // The timer must never be the reason the process stays alive \u2014 it outlives nothing.\n sampler.unref()\n\n const reportUnexpected = (detail: string): void => {\n if (killing) return\n onUnexpectedExit?.(detail)\n }\n\n child.on('exit', (code, signal) => {\n exited = true\n stopSampling()\n\n // The child died WITHOUT us killing it \u2014 a turbo crash, or an OOM kill. Turbo puts each of its\n // tasks in a process group of its OWN, and a turbo that dies this way reaps none of them, so\n // `vite`/`tsc` survive holding their ports. Nothing can find them by walking (see `sample`), and\n // the `kill()` below would bail on an already-exited child. Reaping from the snapshot here is the\n // only thing standing between a crashed engine and a permanently orphaned dev server.\n //\n // `deregisterAfter` (not a bare delete) \u2014 this reap attempt reading a stale/empty `ps` snapshot must\n // not be mistaken for the descendants actually being gone; the registry entry is the only remaining\n // record of them until a later confirmation (or force-reap) proves they are.\n if (!killing) {\n reapSnapshot(groups, snapshotRowsOverride())\n void deregisterAfter()\n }\n\n reportUnexpected(`exited unexpectedly (code=${code ?? 'null'}, signal=${signal ?? 'null'})`)\n })\n child.on('error', (error: Error) => {\n reportUnexpected(`failed to spawn: ${error.message}`)\n })\n\n return {\n kill: async (): Promise<void> => {\n // Latch FIRST: the child WILL emit `exit` during the reap below, and that exit is ours, not a crash.\n killing = true\n stopSampling()\n\n const pid = child.pid\n\n if (pid == null) {\n // Never spawned a real pid \u2014 nothing was ever tracked, so nothing to confirm.\n registry.delete(getGroups)\n\n return\n }\n\n // Once the child is reaped the OS may recycle `pid` onto an unrelated process, and `kill(-pid, \u2026)`\n // would then destroy a stranger's group \u2014 so an exited child is never walked. It is not simply\n // skipped either: a turbo that CRASHED left its task groups running, and this is the Ctrl-C that\n // has to clear them. The snapshot is the only surviving handle on those groups, and `reapSnapshot`\n // re-validates each one against its leader's start time, so a recycled pgid is refused.\n if (child.exitCode !== null || child.signalCode !== null) {\n reapSnapshot(groups, snapshotRowsOverride())\n await deregisterAfter()\n\n return\n }\n\n const rows = snapshotRowsOverride()\n\n // The cheap check above misses a child reaped just now, so confirm `pid` is still ours: a\n // detached child keeps us as its parent, so a foreign `ppid` means the pid was recycled.\n // Skipped when `ps` failed (empty `rows`) \u2014 then only the guard above stands. The registry entry is\n // deliberately left alone here: this state is genuinely ambiguous (did the pid really get\n // recycled, or did `ps` just fail?), and the safe default is to let a later reap re-decide with a\n // fresh read, not to guess by dropping the one record we have.\n if (rows.length > 0 && !isChildOf(pid, process.pid, rows)) return\n\n const doomed = doomedGroupsOf(pid, rows)\n\n // Negative pid \u2192 the whole group (detached made the child a group leader). Turbo forwards\n // this to its tasks; the extra task groups are signalled directly in case it doesn't.\n signalGroups(doomed, 'SIGTERM')\n\n const stragglers = await waitForExit(doomed, graceMs)\n\n if (stragglers.length === 0) {\n // Every doomed group (this child's own, plus every task group the live walk found) exited\n // within grace \u2014 confirmed by the `waitForExit` above, so no further wait is needed here.\n registry.delete(getGroups)\n\n return\n }\n\n // Re-snapshot before forcing: turbo is still alive (that's why we're here), so its tree is\n // still walkable, and `turbo watch build` may have started a task AFTER the first snapshot.\n // Union with the known stragglers, whose groups may already have left turbo's subtree.\n const late = doomedGroupsOf(pid, snapshotRowsOverride())\n const forced = [...new Set([...stragglers, ...late])].filter(groupAlive)\n\n // Killing turbo's group alone would orphan exactly these, so they are killed as a set.\n signalGroups(forced, 'SIGKILL')\n\n // A SIGKILLed leader lingers as an unreaped zombie for a few ms, and `kill(pgid, 0)` still\n // succeeds against it. Wait for the kernel to finish so callers that exit the process\n // immediately after `kill()` resolves aren't racing the teardown they just awaited.\n await waitForExit(forced, REAP_TIMEOUT_MS)\n registry.delete(getGroups)\n },\n }\n}\n", "/**\n * @fileoverview\n *\n * Signal-driven graceful shutdown, shared by every long-lived dev entry point.\n *\n * Three invariants:\n *\n * 1. Only a REPEAT OF THE SAME SIGNAL is an escape hatch. It is tempting to treat any second\n * signal as \"the user pressed Ctrl-C again, get out now\" \u2014 that was the old rule, and it\n * silently orphaned every child. A process manager in front of us relays its own signal after\n * the TTY's, so ONE Ctrl-C under `pnpm exec` arrives as SIGINT *then* SIGTERM:\n *\n * $ pnpm exec node -e \"process.on('SIGINT',\u2026); process.on('SIGTERM',\u2026)\"\n * ^C GOT SIGINT\n * GOT SIGTERM <- pnpm relaying, NOT a second keypress\n *\n * Under the old rule that relay force-quit the teardown a few hundred ms in and abandoned the\n * turbo/vite children (which sit in their own process groups). Keying the escape on the FIRST\n * signal's type fixes it without losing the hatch: a real second Ctrl-C re-sends SIGINT, and a\n * supervisor escalating SIGTERM -> SIGTERM still force-quits. `npm`/`yarn` relay the same way,\n * so this must live here, in the library, not in one consumer's `dev` script.\n * 2. Force-quitting must still not orphan. Even a genuine double Ctrl-C leaves children holding\n * ports (the next start then 502s), so the force path SIGKILLs the descendant process groups\n * before exiting. Bounded and synchronous \u2014 no grace, no escalation, no waiting for reaping.\n * 3. A signal-terminated process must not report exit code 0. The old handlers ran\n * `finally { process.exit(0) }`, which also swallowed a rejecting teardown without a word.\n * Here the rejection goes to stderr and the code stays `128 + signo` \u2014 even on a failed\n * teardown, because the process genuinely WAS signal-terminated, no conventional code means\n * \"signal-terminated but cleanup failed\", and inventing one would break the SIGTERM -> 143\n * contract supervisors rely on. The failure is surfaced by logging, not by the code.\n */\nimport { constants } from 'node:os'\nimport process from 'node:process'\n\nimport { killDescendantGroupsNow } from 'src/dev/managed-child'\n\n/**\n * The signals a resident dev process tears down on.\n *\n * SIGHUP is here for invariant 2: the terminal going away (window closed, ssh dropped) is delivered to\n * the foreground process group, so `dev` gets it \u2014 but its turbo/vite children DON'T, because they sit\n * in their own detached process groups. Without a handler, `dev` takes SIGHUP's default kill, never runs\n * `killDescendantGroupsNow`, and leaves the whole tree alive holding the dev ports; the next start then\n * 502s. Closing a terminal is the single most common way to walk away from a dev server, so this is the\n * likeliest orphan path, not an exotic one.\n */\nconst HANDLED_SIGNALS: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']\n\n/**\n * `os.constants.signals` typed for lookup by an arbitrary {@link NodeJS.Signals}. The platform\n * table omits signals that do not exist on the host, so the index is genuinely partial.\n */\nconst SIGNAL_NUMBERS: Partial<Record<NodeJS.Signals, number>> = constants.signals\n\n/** Fallback signal number when the host table lacks the signal: SIGINT, yielding the usual 130. */\nconst FALLBACK_SIGNO = 2\n\n/**\n * The POSIX exit code for a process terminated by `signal`: `128 + signo`.\n *\n * A shell reports SIGINT as 130 and SIGTERM as 143. Exiting 0 after a signal tells a supervisor\n * the process stopped voluntarily, which is a lie.\n *\n * @example\n * exitCodeForSignal('SIGINT') // 130\n * exitCodeForSignal('SIGTERM') // 143\n */\nexport const exitCodeForSignal = (signal: NodeJS.Signals): number => {\n return 128 + (SIGNAL_NUMBERS[signal] ?? FALLBACK_SIGNO)\n}\n\n/**\n * Seams for {@link registerSignalShutdown}. Each exists because the real implementation is\n * untestable in-process: `process.exit` kills the test runner, and delivering a real POSIX\n * signal to the runner is unsafe and flaky.\n */\nexport interface SignalShutdownDeps {\n /** The context-specific teardown. May reject; the rejection is logged, never swallowed. */\n onSignal: (signal: NodeJS.Signals) => Promise<void>\n /**\n * Terminate the process. Typed as returning `void`, not `never`, so a test can pass a plain\n * recording fake: a `never` fake would have to throw a sentinel, and that throw would reject the\n * in-flight teardown promise. Nothing meaningful runs after a call, so a returning fake is safe.\n */\n exit?: (code: number) => void\n /** Subscribe `handler` to `signal`. Defaults to `process.on`. */\n register?: (signal: NodeJS.Signals, handler: () => void) => void\n /**\n * Unsubscribe `handler` from `signal`. Defaults to `process.off`. Called once the teardown this module\n * owns is over \u2014 graceful completion, the force-quit escape, or the deadline \u2014 so a process whose\n * `exit` seam does not actually terminate (a test, or a caller with its own reasons to keep running)\n * is not left with a dangling SIGINT/SIGTERM/SIGHUP handler from a session that already ended.\n */\n unregister?: (signal: NodeJS.Signals, handler: () => void) => void\n /**\n * Reap surviving descendant process groups on the force-quit path, where the normal teardown is\n * abandoned mid-flight. Synchronous by contract: the process exits on the next line, so anything\n * deferred to a later tick would never run. Defaults to {@link killDescendantGroupsNow}.\n */\n forceReap?: () => void\n /** How long a teardown may run before it is force-quit. See {@link TEARDOWN_DEADLINE_MS}. */\n teardownDeadlineMs?: number\n /**\n * Timer seam, returning its own cancel. Defaults to `setTimeout`/`clearTimeout`; a test injects a fake\n * so the deadline is fired deliberately rather than waited out.\n */\n setTimer?: (handler: () => void, ms: number) => () => void\n /**\n * Name the teardown step still in flight when the deadline trips \u2014 the CLI entry wires this to\n * `runner.shutdownStage`.\n *\n * This module holds NO reference to the runner and so cannot read a stage on its own. Without the seam\n * the deadline degrades into a plain force-quit and the incident's central question (\"`shutdown()`\n * demonstrably ran \u2014 so where did it wedge?\") survives the fix meant to answer it.\n */\n describeStall?: () => string\n /**\n * File the deadline report where it can still be read. The entry routes it into the per-service log sink:\n * on the path this deadline exists for, the terminal is exactly what is gone, so stderr is not a channel.\n * Defaults to a no-op \u2014 library code has no sink to file into.\n */\n fileReport?: (text: string) => void\n}\n\n/**\n * How long a teardown may run before the process force-quits: 20 s, well past a healthy reap (a turbo tree\n * escalates SIGTERM\u2192SIGKILL per child, seconds at worst) and far short of \"forever\".\n *\n * This module used to argue that NO deadline should be armed: *\"any value safe enough not to preempt a\n * legitimate teardown would fire later than a user's second Ctrl-C, and a supervisor sends its own SIGKILL\n * on its own grace.\"* That reasoning quietly ASSUMES A HUMAN IS PRESENT to press Ctrl-C twice \u2014 and the\n * incident that put this here is precisely the case where there is none: the terminal is gone, the operator\n * is not watching, and no supervisor sits above an interactive `ik dev`. Five processes took SIGHUP, ran\n * `shutdown()`, wedged, and spun for five hours writing 455 GB. The escape hatch the old design leaned on\n * cannot be pressed by anyone who has already walked away.\n */\nconst TEARDOWN_DEADLINE_MS = 20_000\n\nconst defaultExit = (code: number): void => {\n process.exit(code)\n}\n\nconst defaultRegister = (signal: NodeJS.Signals, handler: () => void): void => {\n process.on(signal, handler)\n}\n\nconst defaultUnregister = (signal: NodeJS.Signals, handler: () => void): void => {\n process.off(signal, handler)\n}\n\nconst defaultSetTimer = (handler: () => void, ms: number): (() => void) => {\n const timer = setTimeout(handler, ms)\n\n // `unref` so the deadline itself never HOLDS the process open: if the loop empties, the teardown is done\n // and Node exits on its own. A wedged teardown always has live handles (children, listening servers), so\n // the timer phase is still reached \u2014 the probe proved the fault storm does not starve it either.\n timer.unref()\n\n return (): void => {\n clearTimeout(timer)\n }\n}\n\n/**\n * Write to stderr, swallowing a failed write.\n *\n * `stderr.write` can throw (EPIPE, when the parent closed the pipe). Every caller here is on the\n * exit path, and failing to REPORT something must never break that path \u2014 the process still has to\n * die with the right code. A lost message is recoverable; a process that survives its own SIGINT\n * is not.\n */\nconst writeStderr = (message: string): void => {\n try {\n process.stderr.write(message)\n } catch {\n // stderr is gone; there is nowhere left to report to.\n }\n}\n\n/** Report a rejected teardown \u2014 message AND stack, so a wedge is never silent. */\nconst writeTeardownFailure = (signal: NodeJS.Signals, error: unknown): void => {\n const detail = error instanceof Error ? `${error.message}\\n${error.stack ?? '(no stack)'}` : String(error)\n\n writeStderr(`\\n\u2717 Teardown failed while handling ${signal}: ${detail}\\n`)\n}\n\n/**\n * Wire SIGINT/SIGTERM to `onSignal`, then exit `128 + signo`.\n *\n * The first signal runs the teardown. While it is in flight, a signal of a DIFFERENT type is a\n * relay from the process manager above us (`pnpm exec` turns one Ctrl-C into SIGINT + SIGTERM) and\n * is ignored, so the teardown survives to reap its children. A repeat of the FIRST signal is the\n * real escape hatch: it force-quits without touching `onSignal` again, SIGKILLing the descendant\n * groups on the way out so nothing is left holding a port.\n *\n * A {@link TEARDOWN_DEADLINE_MS} deadline IS armed \u2014 read its doc block before removing it.\n *\n * Returns a `detach` function that drops the SIGINT/SIGTERM/SIGHUP listeners this call installed. Every\n * exit path already calls it before exiting, so a real process never needs it.\n *\n * @example\n * registerSignalShutdown({\n * onSignal: async (signal) => {\n * process.stdout.write(`Received ${signal}, shutting down...`)\n * await runner.shutdown()\n * },\n * describeStall: () => runner.shutdownStage,\n * })\n */\n// On the deadline: this module used to explain at length why one should NOT be armed. That explanation\n// assumed a human at the keyboard to press Ctrl-C a second time; the incident it now guards against is the\n// case where nobody is there. Mechanically it depends on `terminal-liveness`: with a fault storm live,\n// teardown competes with ~100k blocking `writeSync` calls per second, and a deadline shipped into a\n// machine that cannot honour it is decoration. The storm is cut at its source first; this is what stops\n// the wedge that follows.\n//\n// On `detach`: it exists for a caller whose `exit` seam does NOT terminate the process (every test in this\n// suite), so a session that already ended does not leave dangling handlers behind for the next one in the\n// same process. In a real process `exit` terminates first.\nexport const registerSignalShutdown = ({\n onSignal,\n exit = defaultExit,\n register = defaultRegister,\n unregister = defaultUnregister,\n forceReap = killDescendantGroupsNow,\n teardownDeadlineMs = TEARDOWN_DEADLINE_MS,\n setTimer = defaultSetTimer,\n describeStall = () => {\n return 'unknown'\n },\n fileReport = () => {},\n}: SignalShutdownDeps): (() => void) => {\n /** The signal that opened the teardown \u2014 `null` until the first one lands. */\n let firstSignal: NodeJS.Signals | null = null\n /** Cancels the armed deadline \u2014 on a completed teardown, and on the second-signal escape. */\n let cancelDeadline: (() => void) | null = null\n /** Every handler this call installed, so `detach` can drop exactly those and nothing else. */\n const handlers = new Map<NodeJS.Signals, () => void>()\n\n /**\n * Drop every listener this call installed. Runs at the end of EVERY exit path below (graceful\n * completion, the second-signal escape, and the deadline) \u2014 not just the happy one \u2014 so a caller whose\n * `exit` seam does not actually terminate the process (a test, or a future non-terminating consumer)\n * is never left holding SIGINT/SIGTERM/SIGHUP handlers from a session that already ended. Idempotent:\n * a second call finds an empty map and does nothing.\n */\n const detach = (): void => {\n for (const [signal, handler] of handlers) {\n unregister(signal, handler)\n }\n handlers.clear()\n }\n\n const handle = (signal: NodeJS.Signals): void => {\n if (firstSignal !== null) {\n // A DIFFERENT signal while tearing down is the process manager in front of us relaying its\n // own (pnpm/npm turn one Ctrl-C into SIGINT + SIGTERM), never a second keypress. Ignoring it\n // is what lets the teardown finish and reap the children. Only a repeat of the signal that\n // STARTED the teardown is the user (or a supervisor) genuinely asking again.\n if (signal !== firstSignal) return\n\n writeStderr(`\\n\u26A0 Received ${signal} again \u2014 force-quitting.\\n`)\n cancelDeadline?.()\n // Abandoning the teardown must still not abandon the children: they hold the dev ports, and\n // the next start would 502 against their stale portless aliases.\n forceReap()\n detach()\n exit(exitCodeForSignal(signal))\n\n return\n }\n\n firstSignal = signal\n\n // The human's escape hatch, armed for the case where there is no human. Same destination as a second\n // Ctrl-C \u2014 reap the descendant groups, exit `128 + signo` \u2014 but it also NAMES the step that wedged, and\n // files that name where it can still be read once the terminal is gone.\n cancelDeadline = setTimer(() => {\n const report = `\\n\u26A0 Teardown deadline exceeded at stage=${describeStall()} after ${teardownDeadlineMs}ms \u2014 force-quitting.\\n`\n\n writeStderr(report)\n fileReport(report)\n forceReap()\n detach()\n exit(exitCodeForSignal(signal))\n }, teardownDeadlineMs)\n\n void (async (): Promise<void> => {\n try {\n await onSignal(signal)\n } catch (error) {\n writeTeardownFailure(signal, error)\n } finally {\n // `finally`, so the exit survives anything the catch body might later throw: a process must\n // never outlive its own signal. Not the old `finally { process.exit(0) }` bug \u2014 that one\n // exited zero without logging; this logs first, then exits the honest code.\n cancelDeadline?.()\n detach()\n exit(exitCodeForSignal(signal))\n }\n })()\n }\n\n for (const signal of HANDLED_SIGNALS) {\n const handler = (): void => {\n return handle(signal)\n }\n\n handlers.set(signal, handler)\n register(signal, handler)\n }\n\n return detach\n}\n", "/**\n * Names of the error classes thrown when an interactive prompt ends without a\n * value. From `@inquirer/core`: `ExitPromptError` (Ctrl-C \u2014 and ONLY Ctrl-C:\n * inquirer binds no escape key, so it raises this from readline's SIGINT) and\n * `AbortPromptError` (the prompt was aborted via an `AbortSignal`, which is how\n * Esc arrives \u2014 see lib/prompts/escapable-context). From our own Ink pickers:\n * `PromptCancelledError` (see ./prompt-cancelled-error), which is registered here\n * rather than impersonating an inquirer class name. All are intentional\n * cancellations, not failures.\n */\nconst CANCELLATION_ERROR_NAMES = new Set(['ExitPromptError', 'AbortPromptError', 'PromptCancelledError'])\n\nconst hasCancellationName = (value: unknown): boolean => {\n return value instanceof Error && CANCELLATION_ERROR_NAMES.has(value.name)\n}\n\n/**\n * True when `error` represents a user (or signal) cancellation of an interactive\n * prompt \u2014 Ctrl-C anywhere, or Esc, which reaches an `@inquirer` prompt as an\n * abort and an Ink picker as a `PromptCancelledError`. Matched by `name` rather\n * than `instanceof` so it stays correct\n * even when pnpm dedupes more than one copy of `@inquirer/core` into the tree\n * (an `instanceof` check fails across realms/duplicate classes).\n *\n * Also unwraps one level of `cause`, so a cancellation re-wrapped in an\n * {@link ./operation-error.OperationError} is still recognised at the top-level\n * error boundary.\n *\n * @example\n * try {\n * await checkbox({ message: 'Select release branches', choices })\n * } catch (err) {\n * if (isPromptCancellation(err)) process.exit(0) // clean back-out, not an error\n * throw err\n * }\n */\nexport const isPromptCancellation = (error: unknown): boolean => {\n if (hasCancellationName(error)) return true\n\n const cause = (error as { cause?: unknown } | null | undefined)?.cause\n\n return hasCancellationName(cause)\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\n/**\n * The only place that spawns `orca`. Everything the driver knows about the CLI is\n * encoded here:\n *\n * - infra-kit owns git; Orca owns windows. The `orca worktree` subcommand's\n * `create` and `rm` verbs are forbidden in this codebase \u2014 `rm` also deletes the\n * local branch, and `create` picks paths/branch names infra-kit's worktree\n * layout does not control (docs/orca-migration-plan.md \u00A71, principle 1).\n * - The JSON envelope is the contract, never the exit code: `ok:false` came back\n * with exit 0 on 1.4.203 and exit 1 on 1.4.204, and the app auto-updates\n * unattended (docs/orca-cli-findings.md, \"Additional facts\").\n */\n\nexport interface OrcaErrorPayload {\n code: string\n message: string\n data?: unknown\n}\n\ninterface OrcaEnvelope<T> {\n ok: boolean\n result?: T\n error?: OrcaErrorPayload\n}\n\n/** Orca answered with `{ ok: false, error }`. */\nexport class OrcaError extends Error {\n readonly code: string\n readonly data: unknown\n\n constructor(payload: OrcaErrorPayload) {\n super(payload.message)\n this.name = 'OrcaError'\n this.code = payload.code\n this.data = payload.data\n }\n}\n\n/** Orca ran but stdout was not an envelope \u2014 a crash, a `--help` fallback, or a CLI too old for `--json`. */\nexport class OrcaMalformedError extends Error {\n readonly exitCode: number | null\n readonly stderrTail: string\n\n constructor(exitCode: number | null, stderrTail: string) {\n super(`orca: stdout is not a JSON envelope (exit ${exitCode ?? 'signal'})`)\n this.name = 'OrcaMalformedError'\n this.exitCode = exitCode\n this.stderrTail = stderrTail\n }\n}\n\n/** The `orca` binary is not on PATH (spawn ENOENT, or the shell's exit 127). */\nexport class OrcaAbsentError extends Error {\n constructor() {\n super('orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI')\n this.name = 'OrcaAbsentError'\n }\n}\n\nconst STDERR_TAIL_CHARS = 400\nconst SHELL_COMMAND_NOT_FOUND = 127\n\ninterface SpawnOutput {\n exitCode: number | null\n stdout: string\n stderr: string\n}\n\nconst isEnoent = (error: unknown): boolean => {\n return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'ENOENT'\n}\n\nconst spawnOrca = async (argv: string[]): Promise<SpawnOutput> => {\n try {\n // zx runs through a shell, so a missing binary normally surfaces as exit 127 rather than a\n // rejection; the catch covers the shell-less spawn failure shape.\n return await $({ nothrow: true, quiet: true })`orca ${argv} --json`\n } catch (error) {\n if (isEnoent(error)) {\n throw new OrcaAbsentError()\n }\n\n throw error\n }\n}\n\nconst parseEnvelope = <T>(stdout: string): OrcaEnvelope<T> | null => {\n try {\n const parsed: unknown = JSON.parse(stdout)\n\n if (typeof parsed === 'object' && parsed !== null && typeof (parsed as { ok?: unknown }).ok === 'boolean') {\n return parsed as OrcaEnvelope<T>\n }\n\n return null\n } catch {\n return null\n }\n}\n\n/**\n * Run one `orca` command and return its `result`. Throws {@link OrcaError} on an\n * `ok:false` envelope, {@link OrcaMalformedError} when stdout is not an envelope,\n * and {@link OrcaAbsentError} when the binary is missing \u2014 regardless of exit code.\n */\nexport const runOrca = async <T>(argv: string[]): Promise<T> => {\n const output = await spawnOrca(argv)\n const envelope = parseEnvelope<T>(output.stdout)\n\n logger.debug({ argv, ok: envelope?.ok, code: envelope?.error?.code, exitCode: output.exitCode }, 'orca')\n\n if (!envelope) {\n if (output.exitCode === SHELL_COMMAND_NOT_FOUND) {\n throw new OrcaAbsentError()\n }\n\n throw new OrcaMalformedError(output.exitCode, output.stderr.slice(-STDERR_TAIL_CHARS))\n }\n\n if (!envelope.ok) {\n throw new OrcaError(envelope.error ?? { code: 'unknown', message: 'orca: ok:false without an error payload' })\n }\n\n return envelope.result as T\n}\n", "import { logger } from 'src/lib/logger'\n\nimport { OrcaAbsentError, runOrca } from './run-orca'\n\nexport type OrcaProbe = 'absent' | 'unreachable' | 'ready'\n\ninterface OrcaStatus {\n app?: { running?: boolean }\n runtime?: { reachable?: boolean; appVersion?: string }\n}\n\n/**\n * Three-state readiness probe behind every fallback branch and doctor's Orca row.\n * `ready` needs both halves: a headless `orca serve` runtime is reachable but has\n * no UI to adopt a tab, so it reads as `unreachable`. `runtime.appVersion` is the\n * only trustworthy version source (`ORCA_APP_VERSION` is spawn-time stale).\n */\nexport const probeOrca = async (): Promise<OrcaProbe> => {\n try {\n const status = await runOrca<OrcaStatus>(['status'])\n\n logger.debug({ appVersion: status.runtime?.appVersion }, 'orca: status')\n\n return status.app?.running === true && status.runtime?.reachable === true ? 'ready' : 'unreachable'\n } catch (error) {\n if (error instanceof OrcaAbsentError) {\n return 'absent'\n }\n\n logger.debug({ error }, 'orca: status probe failed')\n\n return 'unreachable'\n }\n}\n", "import { realpath } from 'node:fs/promises'\n\n/**\n * Resolve `path` through the filesystem, falling back to the input when it can't\n * be resolved (e.g. the directory was already removed). Both Orca-reported paths\n * and the caller's target are normalized the same way so a macOS\n * `/var`\u2192`/private/var` symlink can't make two equal paths compare unequal.\n *\n * Selectors are NOT built from this \u2014 they take the path as `git worktree list`\n * reports it; realpath is for equality only.\n */\nexport const realpathForOrcaCwd = async (path: string): Promise<string> => {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n", "import { realpathForOrcaCwd } from './realpath-for-orca-cwd'\nimport { runOrca } from './run-orca'\n\nexport type OrcaRepoVisibility = 'show' | 'hide'\n\ninterface OrcaRepoRow {\n path: string\n externalWorktreeVisibility?: OrcaRepoVisibility\n}\n\ninterface OrcaRepoListResult {\n repos?: OrcaRepoRow[]\n}\n\ninterface OrcaRepoAddResult {\n repo?: OrcaRepoRow\n}\n\nexport interface OrcaRepoLookup {\n registered: boolean\n visibility?: OrcaRepoVisibility\n}\n\n/**\n * Whether Orca knows the repo at `mainRepoRoot`, and whether its external\n * worktrees (infra-kit's `<repo>-worktrees/*`) are shown in the sidebar. Split\n * from {@link addOrcaRepo} so a caller can put \"will register <repo> in Orca\" in\n * its confirm preview before mutating \u2014 `repo add` carries hook policy defaults.\n */\nexport const findOrcaRepo = async (mainRepoRoot: string): Promise<OrcaRepoLookup> => {\n const [{ repos = [] }, wanted] = await Promise.all([\n runOrca<OrcaRepoListResult>(['repo', 'list']),\n realpathForOrcaCwd(mainRepoRoot),\n ])\n\n for (const repo of repos) {\n if ((await realpathForOrcaCwd(repo.path)) === wanted) {\n return { registered: true, visibility: repo.externalWorktreeVisibility }\n }\n }\n\n return { registered: false }\n}\n\n/** Registers the repo; the returned visibility is `hide` for a fresh row (measured). */\nexport const addOrcaRepo = async (mainRepoRoot: string): Promise<{ visibility?: OrcaRepoVisibility }> => {\n const { repo } = await runOrca<OrcaRepoAddResult>(['repo', 'add', '--path', mainRepoRoot])\n\n return { visibility: repo?.externalWorktreeVisibility }\n}\n", "import { realpathForOrcaCwd } from './realpath-for-orca-cwd'\nimport { runOrca } from './run-orca'\n\ninterface OrcaWorktreeListResult {\n worktrees?: Array<{ path: string }>\n}\n\nconst WORKTREE_LIST_LIMIT = '500'\n\n/**\n * Whether the sidebar shows the worktree at `cwd`. Distinct from \"the selector\n * resolves it\": a hidden external worktree still answers `terminal create` with a\n * tab nobody can see (docs/orca-cli-findings.md, gate outcome), so callers use\n * this to report `orcaHidden` instead of a silent success.\n */\nexport const isOrcaWorktreeListed = async (mainRepoRoot: string, cwd: string): Promise<boolean> => {\n const [{ worktrees = [] }, wanted] = await Promise.all([\n runOrca<OrcaWorktreeListResult>([\n 'worktree',\n 'list',\n '--repo',\n `path:${mainRepoRoot}`,\n '--limit',\n WORKTREE_LIST_LIMIT,\n ]),\n realpathForOrcaCwd(cwd),\n ])\n\n for (const worktree of worktrees) {\n if ((await realpathForOrcaCwd(worktree.path)) === wanted) {\n return true\n }\n }\n\n return false\n}\n", "import process from 'node:process'\n\nimport { realpathForOrcaCwd } from './realpath-for-orca-cwd'\n\nconst WORKTREE_ID_SEPARATOR = '::'\n\n/**\n * The path half of `ORCA_WORKTREE_ID` (`<repoId>::<abs path>`), or `null` when the\n * caller is not inside an Orca terminal. The id is per-terminal env \u2014 `cd` and\n * `-C` never change it \u2014 which is exactly why it identifies the terminal a\n * removal would destroy, and why \"re-run from elsewhere\" is the only remediation.\n */\nconst orcaCallerWorktreePath = (env: NodeJS.ProcessEnv): string | null => {\n const id = env.ORCA_WORKTREE_ID\n\n if (!id) {\n return null\n }\n\n const separatorAt = id.indexOf(WORKTREE_ID_SEPARATOR)\n\n if (separatorAt < 0) {\n return null\n }\n\n const path = id.slice(separatorAt + WORKTREE_ID_SEPARATOR.length)\n\n return path.length > 0 ? path : null\n}\n\n/**\n * The first of `paths` that is the caller's own Orca worktree, or `null`. Runs in\n * the command preflight of `worktrees remove` / `release-remove` \u2014 before the\n * confirm prompt and before any git call \u2014 because closing that worktree's\n * terminals would kill the shell running infra-kit.\n */\nexport const orcaCallerInsideTargets = async (\n paths: string[],\n env: NodeJS.ProcessEnv = process.env,\n): Promise<string | null> => {\n const callerPath = orcaCallerWorktreePath(env)\n\n if (callerPath === null) {\n return null\n }\n\n const caller = await realpathForOrcaCwd(callerPath)\n\n for (const path of paths) {\n if ((await realpathForOrcaCwd(path)) === caller) {\n return path\n }\n }\n\n return null\n}\n", "import { logger } from 'src/lib/logger'\n\nimport { OrcaError, runOrca } from './run-orca'\n\nexport interface OrcaTerminal {\n handle: string\n title: string\n tabId: string\n connected: boolean\n orphaned: boolean\n}\n\ninterface OrcaTerminalListResult {\n terminals?: OrcaTerminal[]\n truncated?: boolean\n}\n\nconst TERMINAL_LIST_LIMIT = '200'\n\n/**\n * The terminals Orca has open in the worktree at `cwd`. A `selector_not_found`\n * is \"nothing open\" (probe semantics \u2014 the row may not exist yet, or was pruned);\n * any other Orca failure propagates. `truncated` is surfaced, not resolved: a\n * truncated list still proves the worktree is open.\n */\nexport const listOrcaTerminals = async (cwd: string): Promise<{ terminals: OrcaTerminal[]; truncated: boolean }> => {\n try {\n const result = await runOrca<OrcaTerminalListResult>([\n 'terminal',\n 'list',\n '--worktree',\n `path:${cwd}`,\n '--limit',\n TERMINAL_LIST_LIMIT,\n ])\n\n const truncated = result.truncated === true\n\n if (truncated) {\n logger.debug({ cwd, limit: TERMINAL_LIST_LIMIT }, 'orca: terminal list truncated')\n }\n\n return { terminals: result.terminals ?? [], truncated }\n } catch (error) {\n if (error instanceof OrcaError && error.code === 'selector_not_found') {\n return { terminals: [], truncated: false }\n }\n\n throw error\n }\n}\n", "import { logger } from 'src/lib/logger'\n\nimport type { OrcaProbe } from './availability'\nimport { listOrcaTerminals } from './list-terminals-by-cwd'\nimport { OrcaAbsentError, OrcaError, OrcaMalformedError, runOrca } from './run-orca'\n\nexport type CloseOrcaWorktreeTerminalsOutcome =\n | { closed: true; count: number }\n | { closed: false; skipped: 'absent' | 'unreachable' | 'not_found' }\n | { closed: false; error: OrcaError }\n\ntype RetireOutcome = 'retired' | 'not_found'\n\n/**\n * `--all` refuses (`terminal_close_incomplete`) while any terminal is live and\n * on an empty row only retires the tab surfaces and resume records \u2014 so it runs\n * LAST, after every handle was closed one by one, and its refusal is not a\n * failure (docs/orca-cli-findings.md \u00A73.4).\n */\nconst retireSurfaces = async (cwd: string): Promise<RetireOutcome> => {\n try {\n await runOrca(['terminal', 'close', '--worktree', `path:${cwd}`, '--all'])\n\n return 'retired'\n } catch (error) {\n if (error instanceof OrcaError && error.code === 'selector_not_found') {\n return 'not_found'\n }\n\n if (error instanceof OrcaError && error.code === 'terminal_close_incomplete') {\n logger.debug({ cwd, error }, 'orca: surfaces not retired')\n\n return 'retired'\n }\n\n throw error\n }\n}\n\nconst closeEach = async (cwd: string): Promise<CloseOrcaWorktreeTerminalsOutcome> => {\n const { terminals } = await listOrcaTerminals(cwd)\n\n // Sequential on purpose: the tab is torn down pane by pane and Orca serializes these anyway.\n for (const terminal of terminals) {\n await runOrca(['terminal', 'close', '--terminal', terminal.handle])\n }\n\n const retired = await retireSurfaces(cwd)\n\n if (terminals.length === 0 && retired === 'not_found') {\n return { closed: false, skipped: 'not_found' }\n }\n\n return { closed: true, count: terminals.length }\n}\n\nconst asOutcome = (cwd: string, error: unknown): CloseOrcaWorktreeTerminalsOutcome => {\n if (error instanceof OrcaAbsentError) {\n return { closed: false, skipped: 'absent' }\n }\n\n if (error instanceof OrcaError) {\n return { closed: false, error }\n }\n\n if (error instanceof OrcaMalformedError) {\n return {\n closed: false,\n error: new OrcaError({\n code: 'orca_malformed_output',\n message: error.message,\n data: { exitCode: error.exitCode, stderrTail: error.stderrTail },\n }),\n }\n }\n\n logger.debug({ cwd, error }, 'orca: close failed outside the Orca contract')\n\n return {\n closed: false,\n error: new OrcaError({\n code: 'orca_close_failed',\n message: error instanceof Error ? error.message : String(error),\n }),\n }\n}\n\n/**\n * Tears down every Orca terminal of the worktree at `cwd` \u2014 called right before\n * `git worktree remove`, and nowhere else (a closed GUI is never a precondition\n * for anything that survives). Never throws: the caller decides whether an error\n * outcome blocks git, and a probe that is not `ready` skips without spawning.\n * The Orca-side row is pruned by Orca itself once the directory is gone.\n */\nexport const closeOrcaWorktreeTerminals = async (\n cwd: string,\n probe: OrcaProbe,\n): Promise<CloseOrcaWorktreeTerminalsOutcome> => {\n if (probe !== 'ready') {\n return { closed: false, skipped: probe }\n }\n\n try {\n return await closeEach(cwd)\n } catch (error) {\n return asOutcome(cwd, error)\n }\n}\n", "import { setTimeout as sleep } from 'node:timers/promises'\n\nimport { OrcaError, runOrca } from './run-orca'\n\nexport type OrcaPanes = 'two-columns' | 'three-pane'\nexport type OrcaOpenedLayout = 'full' | 'single-pane'\n\n/**\n * Shared per batch (one `worktrees add --all`): a fresh worktree\n * that `git worktree add` created milliseconds ago may not be selectable yet, so\n * `terminal create` is retried on `selector_not_found`. The cause of an\n * exhaustion (Orca not scanning the repo) is per-repo, so after the first one the\n * remaining targets attempt once \u2014 worst case `1 \u00D7 budget + (N\u22121) \u00D7 0`.\n */\nexport interface OrcaOpenPoll {\n attempts: number\n delayMs: number\n exhausted: boolean\n}\n\nconst DEFAULT_POLL_ATTEMPTS = 3\nconst DEFAULT_POLL_DELAY_MS = 300\n\nexport const createOrcaOpenPoll = (\n overrides: Partial<Pick<OrcaOpenPoll, 'attempts' | 'delayMs'>> = {},\n): OrcaOpenPoll => {\n return {\n attempts: overrides.attempts ?? DEFAULT_POLL_ATTEMPTS,\n delayMs: overrides.delayMs ?? DEFAULT_POLL_DELAY_MS,\n exhausted: false,\n }\n}\n\ninterface OpenOrcaWorktreeTerminalsArgs {\n cwd: string\n title: string\n /**\n * `--focus` steals the window; callers pass `false` on every multi-branch\n * `worktrees add` fan-out. It must also stay `false` on a row the sidebar hides \u2014\n * there `--focus` times out after ~10 s (docs/orca-cli-findings.md, axis 1).\n */\n focus: boolean\n layout: OrcaOpenedLayout\n /** The configured pane preset; only consulted when `layout` is `full`. */\n panes: OrcaPanes\n poll?: OrcaOpenPoll\n}\n\nexport interface OrcaTerminalCreateResult {\n terminal: { handle: string }\n}\n\nexport interface OrcaTerminalSplitResult {\n split: { handle: string }\n}\n\ntype CreateOutcome = { created: OrcaTerminalCreateResult } | { notSelectable: OrcaError }\n\nconst tryCreate = async (argv: string[]): Promise<CreateOutcome> => {\n try {\n return { created: await runOrca<OrcaTerminalCreateResult>(argv) }\n } catch (error) {\n if (error instanceof OrcaError && error.code === 'selector_not_found') {\n return { notSelectable: error }\n }\n\n throw error\n }\n}\n\nconst createWithPoll = async (argv: string[], cwd: string, poll: OrcaOpenPoll): Promise<string> => {\n const attempts = poll.exhausted ? 1 : poll.attempts\n\n const schedule = Array.from({ length: attempts }, (_, index) => {\n return index + 1\n })\n\n let lastRefusal: OrcaError | undefined\n\n for (const attempt of schedule) {\n const outcome = await tryCreate(argv)\n\n if ('created' in outcome) {\n return outcome.created.terminal.handle\n }\n\n lastRefusal = outcome.notSelectable\n\n if (attempt < attempts) {\n await sleep(poll.delayMs)\n }\n }\n\n poll.exhausted = true\n\n throw new OrcaError({\n code: 'orca_worktree_not_selectable',\n message: `orca: worktree ${cwd} is not selectable after ${attempts} attempt(s): ${lastRefusal?.message ?? ''}`,\n data: { cwd, attempts, cause: lastRefusal?.data },\n })\n}\n\nconst split = async (handle: string, direction: 'horizontal' | 'vertical'): Promise<string> => {\n const result = await runOrca<OrcaTerminalSplitResult>([\n 'terminal',\n 'split',\n '--terminal',\n handle,\n '--direction',\n direction,\n ])\n\n return result.split.handle\n}\n\n/**\n * Opens terminals for the worktree at `cwd` in one Orca tab and returns their\n * handles (`handles[0]` is the tab's first pane). `full` lays out the preset:\n * `horizontal` on `h0` puts a pane to the RIGHT, and `three-pane` adds a\n * `vertical` split on the same `h0` for the pane BELOW it (measured tree:\n * `horizontal(vertical(h0, h2), h1)`).\n *\n * A background (non-`--focus`) handle is splittable in the same tab, so no\n * layout depends on focus.\n */\nexport const openOrcaWorktreeTerminals = async (\n args: OpenOrcaWorktreeTerminalsArgs,\n): Promise<{ handles: string[]; layout: OrcaOpenedLayout }> => {\n const { cwd, title, focus, layout, panes, poll = createOrcaOpenPoll() } = args\n\n const createArgv = [\n 'terminal',\n 'create',\n '--worktree',\n `path:${cwd}`,\n '--title',\n title,\n ...(focus ? ['--focus'] : []),\n ]\n\n const first = await createWithPoll(createArgv, cwd, poll)\n const handles = [first]\n\n if (layout === 'full') {\n handles.push(await split(first, 'horizontal'))\n\n if (panes === 'three-pane') {\n handles.push(await split(first, 'vertical'))\n }\n }\n\n return { handles, layout }\n}\n", "import { displayLabel, parseBranchName } from 'src/lib/release-id'\n\ninterface BuildOrcaTerminalTitleArgs {\n branch: string\n}\n\n/**\n * The Orca TAB title for a worktree's terminals \u2014 release branches render via\n * their release-id label (`release/v1.48.0` \u2192 `1.48.0`), anything else is the raw\n * branch. It labels the tab only: the sidebar row keeps Orca's automatic branch\n * name, and titles are never an ownership key because Orca programs rewrite the\n * per-terminal title at runtime (`\u2733 Claude Code`).\n */\nexport const buildOrcaTerminalTitle = (args: BuildOrcaTerminalTitleArgs): string => {\n const { branch } = args\n\n const id = parseBranchName(branch)\n\n return id ? displayLabel(id) : branch\n}\n", "/**\n * @fileoverview\n * Loopback liveness probes for the apps `infra-kit dev` runs: a backend's `/__health`, a UI's vite ping.\n * Shared by the dev panel's health dots and by `infra-kit e2e`, which must agree on what \"up\" means.\n */\n\n/** What a probe is aimed at. `kind` picks the endpoint AND the verdict rules \u2014 the two are not separable. */\nexport interface ProbeTarget {\n /** Stream tag (`<app>/api`, `<app>/ui`) \u2014 the key the health map and every log line agree on. */\n tag: string\n /** The port to probe: a backend's ACTUAL bound port, or a UI's runner-assigned vite port. */\n port: number\n kind: 'api' | 'ui'\n}\n\n/**\n * Something answered, but not the thing we asked for \u2014 and WHAT it answered is the whole diagnostic.\n *\n * A UI's `foreign` never paints red (see {@link ProbeOutcome}), so this line is the only thing the user\n * gets, and \"not vite's ping\" alone cannot separate the three causes it exists to tell apart: a\n * `200 text/html` means vite dropped the ping and infra-kit must ship a fix; a `502` means portless or a\n * proxy is shadowing the port; a `404` means a squatter won the free-port race. One glance, three very\n * different next moves \u2014 so the status and content-type travel with the verdict.\n */\nexport interface ForeignAnswer {\n kind: 'foreign'\n status: number\n contentType: string | null\n}\n\n/**\n * Three outcomes, not a boolean:\n * - `ok` \u2014 the endpoint PROVED it is serving (a 2xx on `/__health`; a 204 on vite's ping).\n * - `refused` \u2014 nothing answered (ECONNREFUSED, timeout, transport error).\n * - {@link ForeignAnswer} \u2014 something answered, but not the thing we asked for. For a backend that is a\n * failure (our own fastify returning non-2xx). For a UI it is NOT: a non-204 is equally consistent with a\n * squatter, with a proxy that shadows the ping, and with a future vite that dropped it \u2014 so it can never\n * be allowed to paint red, and it is the reason this is not a boolean.\n */\nexport type ProbeOutcome = 'ok' | 'refused' | ForeignAnswer\n\n/** Narrow a {@link ProbeOutcome} to the one arm that carries data. */\nexport const isForeign = (outcome: ProbeOutcome): outcome is ForeignAnswer => {\n return typeof outcome === 'object'\n}\n\n/** Build the `foreign` verdict from the response that earned it, draining its body so the socket returns. */\nconst foreignFrom = async (res: Response): Promise<ForeignAnswer> => {\n await res.body?.cancel()\n\n return { kind: 'foreign', status: res.status, contentType: res.headers.get('content-type') }\n}\n\n/**\n * The `\u25CD ?` warn. Names what answered instead of vite, because that is the whole actionable content: an\n * `html` body means vite dropped the ping (ours to fix), a 5xx means something is shadowing the port, a 404\n * means a squatter took it. The content-type is trimmed of its `; charset=\u2026` tail \u2014 it is a hint, not a\n * header dump.\n */\nexport const describeForeign = (port: number, answer: ForeignAnswer): string => {\n const type = answer.contentType?.split(';')[0]?.trim()\n const what = type == null || type === '' ? `${answer.status}` : `${answer.status} ${type}`\n\n return `port ${port} answered ${what}, not vite's ping \u2014 liveness cannot be verified`\n}\n\n/** Health-probe seam: resolve one target's liveness. Injectable so the panel stays deterministic in tests. */\nexport type HealthProbe = (target: ProbeTarget) => Promise<ProbeOutcome>\n\n/** One budget for the whole probe \u2014 BOTH hops of a UI redirect share it (see {@link probeUi}). */\nconst PROBE_TIMEOUT_MS = 1500\n\n/**\n * Vite's HMR ping. It is installed unconditionally on every dev server (no plugin, no config) and it sits\n * AHEAD of vite's `htmlFallback` middleware \u2014 which is the whole point: `htmlFallback` answers a plain\n * `GET /` with `200 index.html` even for a vite whose entry module throws, so a naive GET would report a\n * broken app as healthy. The ping cannot be forged that way; a 204 means a vite dev server is listening.\n */\nconst VITE_PING_HEADERS = { accept: 'text/x-vite-ping' } as const\n\n/**\n * Where a target is probed. Always `http://127.0.0.1:<port>`, never the `https://<alias>` the panel prints:\n * the alias adds TLS, a private CA and the portless daemon to the path, so a probe through it would report\n * the PROXY's health, not the app's. And never `localhost` \u2014 ServerlessLocalRun binds v4 loopback only,\n * while `localhost` resolves `[::1]` first on modern Node, which renders a healthy backend `\u25CF down`.\n */\nconst probeUrl = (target: ProbeTarget): string => {\n return target.kind === 'api' ? `http://127.0.0.1:${target.port}/__health` : `http://127.0.0.1:${target.port}/`\n}\n\n/** `new URL(loc, base)`, or `null` when the header is unparseable even relative to the probe URL. */\nconst resolveHop = (location: string, base: string): URL | null => {\n try {\n return new URL(location, base)\n } catch {\n return null\n }\n}\n\n/** A backend: `/__health` must answer 2xx. Anything else IS our own fastify failing, so it is not `ok`. */\nconst probeApi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { signal })\n\n if (!res.ok) return foreignFrom(res)\n // Drain: undici keeps the socket checked out until an unread body is GC'd, and this runs every 5s per app\n // for the life of the session.\n await res.body?.cancel()\n\n return 'ok'\n}\n\n/**\n * A frontend: vite's ping must answer 204.\n *\n * The redirect hop is the delicate part. Vite serves the ping from its `base`, so a UI configured with\n * `base: '/app/'` answers `/` with a 3xx whose `Location` is RELATIVE (`/app/`) \u2014 which is why the hop is\n * resolved against the probe URL rather than parsed on its own (`new URL('/app/')` throws outright). The\n * accept header is RE-SENT on the second hop: without it the redirected request falls through to vite's\n * html fallback and comes back `200 text/html` \u2014 the exact false green this probe exists to refuse.\n *\n * Exactly one hop, same-origin only. A cross-origin redirect is somebody else's server, and a second hop\n * is a loop we have no budget for; both report `foreign` \u2014 never followed, and never called alive.\n */\nconst probeUi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (res.status === 204) return 'ok'\n if (res.status < 300 || res.status >= 400) return foreignFrom(res)\n\n const location = res.headers.get('location')\n const next = location == null ? null : resolveHop(location, url)\n\n if (next == null || next.origin !== new URL(url).origin) return foreignFrom(res)\n\n await res.body?.cancel()\n\n const hop = await fetch(next, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (hop.status !== 204) return foreignFrom(hop)\n await hop.body?.cancel()\n\n return 'ok'\n}\n\n/** Default probe: per-kind, bounded, and loopback-only. A transport error or a timeout is `refused`. */\nexport const defaultHealthProbe: HealthProbe = async (target: ProbeTarget): Promise<ProbeOutcome> => {\n const url = probeUrl(target)\n // ONE signal, shared across both hops: a redirect must not double the budget a wedged server can spend.\n const signal = AbortSignal.timeout(PROBE_TIMEOUT_MS)\n\n try {\n return target.kind === 'api' ? await probeApi(url, signal) : await probeUi(url, signal)\n } catch {\n return 'refused'\n }\n}\n", "import { readRelease } from '@slip-stream-kit/config/internal'\n\n/**\n * Slugified `<release>` for the app's git branch (resolved from the app's own dir), falling back to\n * `DEFAULT_RELEASE_SLUG` outside a git repo / on an empty slug. Never throws.\n *\n * A release ALWAYS resolves because it is the first DNS label of every alias, and every app is reached\n * by hostname. The fallback cannot collide the way a branch can: worktrees are what make two checkouts\n * coexist, and a worktree is by definition inside a git repo. One implementation, in the config package,\n * because the vite and Playwright helpers must name the same host.\n */\nexport const readAppRelease = (cwd: string): string => {\n return readRelease(cwd)\n}\n"],
|
|
5
|
+
"mappings": "sDAiCA,OAAS,YAAAA,GAAU,gBAAAC,OAAoB,qBAEvC,OAAOC,MAAa,eAapB,IAAMC,GAAmB,IAGnBC,GAAU,IAGVC,EAAkB,IAGlBC,EAAS,UAQTC,GAAqB,IAGrBC,EAAU,CAAC,MAAO,0BAA0B,EAG5CC,EAAgB,GAAK,GAqBdC,EAAiBC,GACrBA,EAAI,MAAM;AAAA,CAAI,EAAE,QAASC,GAAS,CACvC,GAAM,CAACC,EAAQC,EAASC,EAAS,GAAGC,CAAI,EAAIJ,EAAK,KAAK,EAAE,MAAM,KAAK,EAEnE,GAAIC,GAAU,MAAQC,GAAW,MAAQC,GAAW,KAAM,MAAO,CAAC,EAElE,IAAME,EAAM,OAAOJ,CAAM,EACnBK,EAAO,OAAOJ,CAAO,EACrBK,EAAO,OAAOJ,CAAO,EAE3B,MAAI,CAAC,OAAO,UAAUE,CAAG,GAAK,CAAC,OAAO,UAAUC,CAAI,GAAK,CAAC,OAAO,UAAUC,CAAI,EAAU,CAAC,EAEnF,CAAC,CAAE,IAAAF,EAAK,KAAAC,EAA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AE/E,MAAMA,EAAI,MAAM,OAAO,EAEvB,IAAMI,EAAM,MAAM,MAAMD,EAAM,CAAE,QAASZ,GAAmB,SAAU,SAAU,OAAAQ,CAAO,CAAC,EAExF,OAAIK,EAAI,SAAW,IAAYH,EAAYG,CAAG,GAC9C,MAAMA,EAAI,MAAM,OAAO,EAEhB,KACT,EAGaC,GAAkC,MAAOZ,GAA+C,CACnG,IAAMK,EAAMN,GAASC,CAAM,EAErBM,EAAS,YAAY,QAAQ,IAAgB,EAEnD,GAAI,CACF,OAAON,EAAO,OAAS,MAAQ,MAAMI,GAASC,EAAKC,CAAM,EAAI,MAAMG,GAAQJ,EAAKC,CAAM,CACxF,MAAQ,CACN,MAAO,SACT,CACF,EC3JA,OAAS,eAAAO,OAAmB,mCAWrB,IAAMC,GAAkBC,GACtBF,GAAYE,CAAG",
|
|
6
|
+
"names": ["execFile", "execFileSync", "process", "DEFAULT_GRACE_MS", "POLL_MS", "REAP_TIMEOUT_MS", "PS_BIN", "SAMPLE_INTERVAL_MS", "PS_ARGS", "PS_MAX_BUFFER", "parseProcRows", "raw", "line", "rawPid", "rawPpid", "rawPgid", "rest", "pid", "ppid", "pgid", "leaderStarts", "rows", "starts", "row", "snapshotGroups", "rootPid", "excludePgid", "collectDoomedGroups", "leaderStart", "validSnapshotPgids", "snapshot", "reapSnapshot", "childrenOf", "siblings", "groups", "seen", "queue", "i", "child", "snapshotProcRows", "snapshotProcRowsAsync", "resolve", "error", "stdout", "isChildOf", "parentPid", "doomedGroupsOf", "ownPgid", "groupAlive", "signalGroups", "pgids", "signal", "registry", "collectForceReapTargets", "registrySnapshots", "live", "fromRegistry", "killDescendantGroupsNow", "getGroups", "sleep", "ms", "waitForExit", "timeoutMs", "deadline", "alive", "superviseChild", "graceMs", "onUnexpectedExit", "snapshotRowsOverride", "killing", "exited", "sampler", "stopSampling", "deregisterAfter", "g", "applySample", "next", "sample", "reportUnexpected", "detail", "code", "doomed", "stragglers", "late", "forced", "constants", "process", "HANDLED_SIGNALS", "SIGNAL_NUMBERS", "constants", "FALLBACK_SIGNO", "exitCodeForSignal", "signal", "TEARDOWN_DEADLINE_MS", "defaultExit", "code", "process", "defaultRegister", "handler", "defaultUnregister", "defaultSetTimer", "ms", "timer", "writeStderr", "message", "writeTeardownFailure", "error", "detail", "registerSignalShutdown", "onSignal", "exit", "register", "unregister", "forceReap", "killDescendantGroupsNow", "teardownDeadlineMs", "setTimer", "describeStall", "fileReport", "firstSignal", "cancelDeadline", "handlers", "detach", "handle", "report", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause", "$", "OrcaError", "payload", "OrcaMalformedError", "exitCode", "stderrTail", "OrcaAbsentError", "STDERR_TAIL_CHARS", "SHELL_COMMAND_NOT_FOUND", "isEnoent", "error", "spawnOrca", "argv", "$", "parseEnvelope", "stdout", "parsed", "runOrca", "output", "envelope", "logger", "probeOrca", "status", "runOrca", "logger", "error", "OrcaAbsentError", "realpath", "realpathForOrcaCwd", "path", "findOrcaRepo", "mainRepoRoot", "repos", "wanted", "runOrca", "realpathForOrcaCwd", "repo", "addOrcaRepo", "WORKTREE_LIST_LIMIT", "isOrcaWorktreeListed", "mainRepoRoot", "cwd", "worktrees", "wanted", "runOrca", "realpathForOrcaCwd", "worktree", "process", "WORKTREE_ID_SEPARATOR", "orcaCallerWorktreePath", "env", "id", "separatorAt", "path", "orcaCallerInsideTargets", "paths", "process", "callerPath", "caller", "realpathForOrcaCwd", "TERMINAL_LIST_LIMIT", "listOrcaTerminals", "cwd", "result", "runOrca", "truncated", "logger", "error", "OrcaError", "retireSurfaces", "cwd", "runOrca", "error", "OrcaError", "logger", "closeEach", "terminals", "listOrcaTerminals", "terminal", "retired", "asOutcome", "OrcaAbsentError", "OrcaMalformedError", "closeOrcaWorktreeTerminals", "probe", "sleep", "DEFAULT_POLL_ATTEMPTS", "DEFAULT_POLL_DELAY_MS", "createOrcaOpenPoll", "overrides", "tryCreate", "argv", "runOrca", "error", "OrcaError", "createWithPoll", "cwd", "poll", "attempts", "schedule", "_", "index", "lastRefusal", "attempt", "outcome", "sleep", "split", "handle", "direction", "openOrcaWorktreeTerminals", "args", "title", "focus", "layout", "panes", "createArgv", "first", "handles", "buildOrcaTerminalTitle", "args", "branch", "id", "parseBranchName", "displayLabel", "isForeign", "outcome", "foreignFrom", "res", "describeForeign", "port", "answer", "type", "what", "VITE_PING_HEADERS", "probeUrl", "target", "resolveHop", "location", "base", "probeApi", "url", "signal", "res", "foreignFrom", "probeUi", "next", "hop", "defaultHealthProbe", "readRelease", "readAppRelease", "cwd"]
|
|
7
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{P as v,S as w,d as g,
|
|
1
|
+
import{P as v,S as w,X as x,d as g,ea as $,f as h}from"./chunk-GDOQUC23.js";import{p as D}from"./chunk-GCOYOWGH.js";import{a as j,b as I}from"./chunk-QWVLAZ6N.js";var H=()=>{let e="",t=[],r=!1;return{start(n){e=n,t=[],r=!1},setInteractive(){r=!0},addOption(n,o){t.push({flag:n,value:o})},formatOptions(){return t.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ")},snapshot(){return t.length===0?null:{formattedOptions:this.formatOptions()}},print(){!r||t.length===0||!e||v.info(`\u{1F4DF} Equivalent command:
|
|
2
2
|
pnpm exec infra-kit ${e} ${this.formatOptions()}
|
|
3
3
|
`)},reset(){e="",t=[],r=!1}}},T=H();import{isAbsolute as _,resolve as N}from"node:path";import K from"node:process";var k=null,S=null,q=e=>{k=[...e],S=K.cwd()},B=new Set(["--yes","-y"]),J=(e,t)=>{let r=[...e];for(let[n,o]of r.entries())o==="-C"&&r[n+1]!==void 0&&!_(r[n+1])?r[n+1]=N(t,r[n+1]):o.startsWith("-C")&&o.length>2&&!o.startsWith("--")&&!_(o.slice(2))&&(r[n]=`-C${N(t,o.slice(2))}`);return r},O=()=>{if(k===null||S===null)return["--yes"];let e=k.slice(2),t=e.indexOf("--"),r=t===-1?e.length:t,n=J(e.slice(0,r),S),o=e.slice(r);return n.some(s=>B.has(s))?[...n,...o]:[...n,"--yes",...o]};import M from"node:process";var L=27,W=e=>e===null?"an interactive prompt was reached under --json, which never prompts":`an interactive prompt was reached in agent mode (${e==="flag"?"--agent":"INFRA_KIT_AGENT / CLAUDECODE"}), where there is no human to answer it`,z=e=>`${e===void 0?"pass the value explicitly instead of relying on the prompt":`pass --${e}`} on the re-run`,U=e=>{if(typeof e=="object"&&"value"in e)return e.value;let t=typeof e=="object"?e.refuse:void 0,{source:r}=g;throw new x(t===void 0?{status:"refused",agentMode:r}:{status:"argument_required",argument:t,agentMode:r},2,{operation:"interactive prompt",remediation:z(t),stderrExcerpt:W(r)})},R=async(e,t)=>{let r=new AbortController,{whenHeadless:n="refuse",...o}=t??{},a={...o,signal:r.signal};if(h())return U(n);if(!M.stdin.isTTY)return e(a);let s=M.stdin,m=c=>{c.length===1&&c[0]===L&&r.abort()};j();try{let c=e(a);return s.isPaused()&&s.resume(),s.on("data",m),await c}finally{s.removeListener("data",m),I()}};import Y from"@inquirer/confirm";import G from"node:process";var d=class extends Error{constructor(t="Operation cancelled by the operator"){super(t),this.name="CommandDeclinedError"}},pe=e=>e instanceof d;var F=(e,t,r=O())=>{let{source:n}=g;throw new x({status:"confirmation_required",message:e,plan:t,rerun:r,agentMode:n},2,{operation:"confirm before running",remediation:n===null?"pass `--yes` to confirm, or drop `--json` to be prompted":`show the plan to the human, then re-run \`infra-kit ${r.join(" ")}\` to confirm`,stderrExcerpt:"confirmation required and nobody to ask"})},V=async(e,t,r={})=>{!e&&h()&&F(t,r.plan,r.rerun);let n=e?!0:await R(o=>Y({message:t},o),{whenHeadless:"refuse"});if(e||T.setInteractive(),!n){if(r.throwOnDecline)throw new d;v.info("Operation cancelled. Exiting..."),G.exit(0)}};import l from"node:fs/promises";import i from"node:path";import{z as u}from"zod";var f=class extends Error{env;constructor(t,r=null){super(t),this.name="EnvAuthError",this.env=r}};var Q="tokens.json",E=1,P=384,p=448,X=u.object({version:u.literal(E).default(E),envs:u.record(u.string().min(1),u.string().min(1))}).strict(),y=async()=>{let e=await $();return i.join(i.dirname(e.userProject),Q)},C=async()=>{let e=await y(),t;try{t=await l.readFile(e,"utf-8")}catch{return null}let r;try{r=JSON.parse(t)}catch(o){throw new f(`Invalid JSON in the token store at ${w(e)}: ${o.message}
|
|
4
4
|
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let n=X.safeParse(r);if(!n.success)throw new f(`Invalid token store at ${w(e)}: ${u.prettifyError(n.error)}
|
|
5
5
|
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return n.data},b=async e=>{let t=await y(),r=i.dirname(t),n=i.dirname(r),o=i.dirname(n);for(let a of[o,n,r])await l.mkdir(a,{recursive:!0,mode:p}),await l.chmod(a,p);D(t,`${JSON.stringify(e,null,2)}
|
|
6
6
|
`,P),await l.chmod(t,P)},Z=async()=>{let e=await y().catch(()=>null);if(e===null)return null;let t=i.dirname(e),r=i.dirname(t),o=[[i.dirname(r),p],[r,p],[t,p],[e,P]];if(!await l.stat(e).then(()=>!0,()=>!1))return null;let s=[];for(let[m,c]of o){let A=(await l.stat(m)).mode&511;A!==c&&(await l.chmod(m,c),s.push(`${w(m)} was 0${A.toString(8)}`))}return s};var ee=async e=>{let t=await C();await b({version:E,envs:{...t?.envs,...e}})},te=async e=>{let t=await C();if(!t||!(e in t.envs))return;let r={...t.envs};delete r[e],await b({version:E,envs:r})};export{T as a,pe as b,q as c,O as d,R as e,F as f,V as g,f as h,y as i,C as j,Z as k,ee as l,te as m};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-BYCCXWPB.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts", "../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts"],
|
|
4
|
-
"sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the handler was called off the CLI (a test, an in-process caller), where a\n * `pnpm exec` line would be nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be\n * worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * `--yes` goes before the first `--`: `e2e` hands everything after it to Playwright, so a `--yes`\n * there never reaches Commander and the confirm fires again. The only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv whose options already carry `--yes`/`-y` is\n * returned as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this\n * function's problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const userArgs = parsedArgv.slice(2)\n const separator = userArgs.indexOf('--')\n const optionsEnd = separator === -1 ? userArgs.length : separator\n const options = absolutizeChangeDir(userArgs.slice(0, optionsEnd), launchCwd)\n const passThrough = userArgs.slice(optionsEnd)\n\n const alreadyConfirmed = options.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? [...options, ...passThrough] : [...options, '--yes', ...passThrough]\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about the retired server's schema making a\n * field required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard, so no prompt at any site can return a\n// usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an agent-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for agents in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (`--yes`, the argv a `confirmation_required`\n * refusal hands back) the prompt is skipped and execution proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path: headless\n * callers refuse above it, so a `--json` document is never cut short by it.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n /**\n * The argv that confirms, when it must carry more than this run's own argv plus `--yes` \u2014 e.g.\n * the content hash the human is approving. Defaults to `rerunArgv()`.\n */\n rerun?: string[]\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their `--yes` short-circuit stays as it was for\n// agent and human alike.\nexport const refuseUnconfirmed = (message: string, plan?: unknown, rerun: string[] = rerunArgv()): never => {\n const { source } = agentMode\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan, options.rerun)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n", "// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 only a human can fix it \u2014 and downstream callers classify on that\n // CLASS (see EnvAuthError's doc). `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Re-assert the store's 0600 / 0700 modes without rewriting it, for a store something other than\n * {@link writeTokenStore} touched (an editor's save-and-rename, a `cp -r`, a synced dotfiles dir).\n * Returns the paths it changed, or `null` when there is no store to protect.\n *\n * @example\n * await tightenTokenStoreModes() // => ['~/.infra-kit/projects/api/tokens.json was 0644']\n */\nexport const tightenTokenStoreModes = async (): Promise<string[] | null> => {\n // Outside a git repo there is no project, so no store either.\n const storePath = await getTokenStorePath().catch(() => {\n return null\n })\n\n if (storePath === null) return null\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n const chain: Array<[target: string, mode: number]> = [\n [userConfigDir, TOKEN_DIR_MODE],\n [projectsDir, TOKEN_DIR_MODE],\n [projectDir, TOKEN_DIR_MODE],\n [storePath, TOKEN_FILE_MODE],\n ]\n\n const exists = await fs.stat(storePath).then(\n () => {\n return true\n },\n () => {\n return false\n },\n )\n\n if (!exists) return null\n\n const tightened: string[] = []\n\n for (const [target, mode] of chain) {\n const actual = (await fs.stat(target)).mode & 0o777\n\n if (actual === mode) continue\n\n await fs.chmod(target, mode)\n tightened.push(`${tildify(target)} was 0${actual.toString(8)}`)\n }\n\n return tightened\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n await setTokens({ [env]: token })\n}\n\n/**\n * Add or replace several environments' tokens in ONE read-modify-write, so a bulk import never leaves\n * the store half-written between two of its entries.\n *\n * @example\n * await setTokens({ dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' })\n * // tokens.json => { version: 1, envs: { \u2026existing, dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' } }\n */\nexport const setTokens = async (tokens: Record<string, string>): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, ...tokens },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store.\n * `DopplerAuthError extends EnvAuthError` for the subset that is specifically \"Doppler refused the\n * token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): every consumer of the auth\n// channel needs to classify a failure by its CLASS, not by re-deriving the answer from a message\n// some other module owns \u2014 and it has to be throwable from EVERY module that can produce the\n// class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned\n// base type could not be thrown there without a layering inversion and an import cycle. Hence a\n// neutral base here in `lib/errors`.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * Deliberately WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only\n * one of the durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store\n * never reaches the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the handler was called off the CLI (a test, an in-process caller), where a\n * `pnpm exec` line would be nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be\n * worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * `--yes` goes before the first `--`: `e2e` hands everything after it to Playwright, so a `--yes`\n * there never reaches Commander and the confirm fires again. The only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv whose options already carry `--yes`/`-y` is\n * returned as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this\n * function's problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const userArgs = parsedArgv.slice(2)\n const separator = userArgs.indexOf('--')\n const optionsEnd = separator === -1 ? userArgs.length : separator\n const options = absolutizeChangeDir(userArgs.slice(0, optionsEnd), launchCwd)\n const passThrough = userArgs.slice(optionsEnd)\n\n const alreadyConfirmed = options.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? [...options, ...passThrough] : [...options, '--yes', ...passThrough]\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about the retired server's schema making a\n * field required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard, so no prompt at any site can return a\n// usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an agent-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for agents in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (`--yes`, the argv a `confirmation_required`\n * refusal hands back) the prompt is skipped and execution proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path: headless\n * callers refuse above it, so a `--json` document is never cut short by it.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n /**\n * The argv that confirms, when it must carry more than this run's own argv plus `--yes` \u2014 e.g.\n * the content hash the human is approving. Defaults to `rerunArgv()`.\n */\n rerun?: string[]\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their `--yes` short-circuit stays as it was for\n// agent and human alike.\nexport const refuseUnconfirmed = (message: string, plan?: unknown, rerun: string[] = rerunArgv()): never => {\n const { source } = agentMode\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan, options.rerun)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n", "// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 only a human can fix it \u2014 and downstream callers classify on that\n // CLASS (see EnvAuthError's doc). `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Re-assert the store's 0600 / 0700 modes without rewriting it, for a store something other than\n * {@link writeTokenStore} touched (an editor's save-and-rename, a `cp -r`, a synced dotfiles dir).\n * Returns the paths it changed, or `null` when there is no store to protect.\n *\n * @example\n * await tightenTokenStoreModes() // => ['~/.infra-kit/projects/api/tokens.json was 0644']\n */\nexport const tightenTokenStoreModes = async (): Promise<string[] | null> => {\n // Outside a git repo there is no project, so no store either.\n const storePath = await getTokenStorePath().catch(() => {\n return null\n })\n\n if (storePath === null) return null\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n const chain: Array<[target: string, mode: number]> = [\n [userConfigDir, TOKEN_DIR_MODE],\n [projectsDir, TOKEN_DIR_MODE],\n [projectDir, TOKEN_DIR_MODE],\n [storePath, TOKEN_FILE_MODE],\n ]\n\n const exists = await fs.stat(storePath).then(\n () => {\n return true\n },\n () => {\n return false\n },\n )\n\n if (!exists) return null\n\n const tightened: string[] = []\n\n for (const [target, mode] of chain) {\n const actual = (await fs.stat(target)).mode & 0o777\n\n if (actual === mode) continue\n\n await fs.chmod(target, mode)\n tightened.push(`${tildify(target)} was 0${actual.toString(8)}`)\n }\n\n return tightened\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n await setTokens({ [env]: token })\n}\n\n/**\n * Add or replace several environments' tokens in ONE read-modify-write, so a bulk import never leaves\n * the store half-written between two of its entries.\n *\n * @example\n * await setTokens({ dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' })\n * // tokens.json => { version: 1, envs: { \u2026existing, dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' } }\n */\nexport const setTokens = async (tokens: Record<string, string>): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, ...tokens },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store.\n * `DopplerAuthError extends EnvAuthError` for the subset that is specifically \"Doppler refused the\n * token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): every consumer of the auth\n// channel needs to classify a failure by its CLASS, not by re-deriving the answer from a message\n// some other module owns \u2014 and it has to be throwable from EVERY module that can produce the\n// class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned\n// base type could not be thrown there without a layering inversion and an import cycle. Hence a\n// neutral base here in `lib/errors`.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * Deliberately WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only\n * one of the durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store\n * never reaches the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n"],
|
|
5
|
+
"mappings": "mKAOA,IAAMA,EAAoB,IAAM,CAC9B,IAAIC,EAAU,GACVC,EAA2B,CAAC,EAC5BC,EAAgB,GAEpB,MAAO,CAWL,MAAMC,EAAoB,CACxBH,EAAUG,EACVF,EAAU,CAAC,EACXC,EAAgB,EAClB,EAMA,gBAAuB,CACrBA,EAAgB,EAClB,EAQA,UAAUE,EAAcC,EAA0C,CAChEJ,EAAQ,KAAK,CAAE,KAAAG,EAAM,MAAAC,CAAM,CAAC,CAC9B,EAKA,eAAwB,CACtB,OAAOJ,EACJ,IAAKK,GACA,OAAOA,EAAI,OAAU,UAChBA,EAAI,MAAQA,EAAI,KAAO,GAG5B,MAAM,QAAQA,EAAI,KAAK,EAClB,GAAGA,EAAI,IAAI,KAAKA,EAAI,MAAM,KAAK,IAAI,CAAC,IAGtC,GAAGA,EAAI,IAAI,KAAKA,EAAI,KAAK,GACjC,EACA,OAAO,OAAO,EACd,KAAK,GAAG,CACb,EAOA,UAAgD,CAC9C,OAAIL,EAAQ,SAAW,EACd,KAGF,CAAE,iBAAkB,KAAK,cAAc,CAAE,CAClD,EAUA,OAAc,CACR,CAACC,GAAiBD,EAAQ,SAAW,GAAK,CAACD,GAI/CO,EAAO,KAAK;AAAA,sBAAgDP,CAAO,IAAI,KAAK,cAAc,CAAC;AAAA,CAAI,CACjG,EAKA,OAAc,CACZA,EAAU,GACVC,EAAU,CAAC,EACXC,EAAgB,EAClB,CACF,CACF,EAGaM,EAAcT,EAAkB,EC5G7C,OAAS,cAAAU,EAAY,WAAAC,MAAe,YACpC,OAAOC,MAAa,eASpB,IAAIC,EAAuC,KACvCC,EAA2B,KAOlBC,EAAiBC,GAAkC,CAC9DH,EAAa,CAAC,GAAGG,CAAI,EACrBF,EAAYF,EAAQ,IAAI,C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,CACnD,CAHoBlB,EAAK,QAAQa,CAAW,EAG5BnB,CAAc,EAC9B,CAACmB,EAAanB,CAAc,EAC5B,CAACkB,EAAYlB,CAAc,EAC3B,CAACQ,EAAWT,CAAe,CAC7B,EAWA,GAAI,CATW,MAAMW,EAAG,KAAKF,CAAS,EAAE,KACtC,IACS,GAET,IACS,EAEX,EAEa,OAAO,KAEpB,IAAMiB,EAAsB,CAAC,EAE7B,OAAW,CAACC,EAAQC,CAAI,IAAKH,EAAO,CAClC,IAAMI,GAAU,MAAMlB,EAAG,KAAKgB,CAAM,GAAG,KAAO,IAE1CE,IAAWD,IAEf,MAAMjB,EAAG,MAAMgB,EAAQC,CAAI,EAC3BF,EAAU,KAAK,GAAGX,EAAQY,CAAM,CAAC,SAASE,EAAO,SAAS,CAAC,CAAC,EAAE,EAChE,CAEA,OAAOH,CACT,EAsBO,IAAMI,GAAY,MAAOC,GAAkD,CAChF,IAAMC,EAAW,MAAMC,EAAe,EAEtC,MAAMC,EAAgB,CACpB,QAASC,EACT,KAAM,CAAE,GAAGH,GAAU,KAAM,GAAGD,CAAO,CACvC,CAAC,CACH,EAYaK,GAAc,MAAOC,GAA+B,CAC/D,IAAML,EAAW,MAAMC,EAAe,EAEtC,GAAI,CAACD,GAAY,EAAEK,KAAOL,EAAS,MAAO,OAE1C,IAAMM,EAAO,CAAE,GAAGN,EAAS,IAAK,EAEhC,OAAOM,EAAKD,CAAG,EAEf,MAAMH,EAAgB,CACpB,QAASC,EACT,KAAAG,CACF,CAAC,CACH",
|
|
6
6
|
"names": ["createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "userArgs", "separator", "optionsEnd", "options", "passThrough", "process", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "rerun", "rerunArgv", "source", "agentMode", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process", "fs", "path", "z", "EnvAuthError", "message", "env", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "tightenTokenStoreModes", "chain", "tightened", "target", "mode", "actual", "setTokens", "tokens", "existing", "readTokenStore", "writeTokenStore", "TOKEN_STORE_VERSION", "removeToken", "env", "envs"]
|
|
7
7
|
}
|
|
@@ -2,4 +2,4 @@ import _ from"node:fs";import V from"node:os";import E from"node:path";import p
|
|
|
2
2
|
`).map(o=>o.endsWith("\r")?o.slice(0,-1):o),s=0,i=!1;for(;s<n.length;){let o=n[s];if(i){i=a(o,i),s+=1;continue}let I=T.exec(o);if(!I){let c=D.exec(o);c&&r?.(c[1]),i=a(o,!1),s+=1;continue}let g=I[1],R=o.slice(I[0].length);if(!R.startsWith("'")){e({name:g,value:R}),i=a(o,!1),s+=1;continue}let u=[R],N=a(R,!1);for(;N&&s+1<n.length;){s+=1;let c=n[s];u.push(c),N=a(c,!0)}e({name:g,value:L(u.join(`
|
|
3
3
|
`))}),i=N,s+=1}},y=t=>{let e=[];return F(l(t),({name:r})=>{e.push(r)}),e},W=t=>{let e={};return F(l(t),({name:r,value:n})=>{e[r]=n}),e},w=t=>{let e=[];return F(l(t),()=>{},r=>{e.push(r)}),e},m=()=>{let t=p.env.XDG_CACHE_HOME,e=t&&t.length>0?t:E.join(V.homedir(),".cache");return E.join(e,"infra-kit")},P=()=>{let t=p.env[A];if(!t)throw new Error(`${A} is not set. Run \`infra-kit setup --skip-tools\` then \`source ~/.zshrc\`.`);return E.join(m(),t)},U=(t,e,r)=>{let n=`${t}.tmp.${p.pid}`;_.writeFileSync(n,e,{mode:r});try{_.renameSync(n,t)}catch(s){throw _.rmSync(n,{force:!0}),s}},b="-worktrees",G=(t,e)=>{let r;try{r=_.readFileSync(t,"utf-8")}catch{return!0}let n=J(e);return r.split(`
|
|
4
4
|
`).filter(Boolean).some(s=>n===s||n.startsWith(`${s}${E.sep}`))},J=t=>{try{return _.realpathSync(t)}catch{return E.resolve(t)}},$={release:"release",feature:"feature",mergeDev:"merge-dev"};export{h as a,O as b,S as c,A as d,f as e,d as f,v as g,x as h,K as i,C as j,y as k,W as l,w as m,m as n,P as o,U as p,b as q,G as r,$ as s};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-GCOYOWGH.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/lib/constants/constants.ts"],
|
|
4
|
-
"sourcesContent": ["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nexport const ENV_LOAD_FILE = 'env-load.sh'\nexport const ENV_CLEAR_FILE = 'env-clear.sh'\n/**\n * Sidecar of `env-load.sh`: the directories, one per line, the loaded env belongs to. The session is\n * per terminal, not per repo, so without it a shell or agent in repo A sourced repo B's env.\n */\nexport const ENV_LOAD_ROOT_FILE = 'env-load.root'\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * Directory under the user's home that holds all machine-local infra-kit config:\n * the runtime `infra-kit.json` merge layer, per-project overrides, the factory\n * registry (`vendor.json`), and the `portless` package link. Single source of\n * truth for `.infra-kit`.\n *\n * Defined HERE, not in `lib/infra-kit-config`, because that module pulls in zod\n * and the `ik-mcp` proxy bundle must stay Node-builtins-only (guarded in\n * `entry/__tests__/dist-shebang.test.ts`); `lib/infra-kit-config` re-exports it\n * for its existing consumers.\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\n/**\n * The active environment/config NAME (e.g. `dev`, `arthur`), exported plainly so\n * non-shell consumers can read it from `process.env`. Notably `infra-kit/vite`'s\n * `infraKitDev()` reads this to interpolate the `<env>` placeholder in cloud proxy\n * targets. Mirrors {@link INFRA_KIT_ENV_CONFIG_VAR} (same value) but is the stable,\n * purpose-named handle for tooling rather than the shell session-metadata var.\n */\nexport const INFRA_KIT_ENV_VAR = 'INFRA_KIT_ENV'\nexport const INFRA_KIT_ENV_CONFIG_VAR = 'INFRA_KIT_ENV_CONFIG'\nexport const INFRA_KIT_ENV_PROJECT_VAR = 'INFRA_KIT_ENV_PROJECT'\n/**\n * Absolute project root (git top-level) the loaded env belongs to, so a shell can\n * tell whose secrets it is carrying after a `cd` into another project.\n */\nexport const INFRA_KIT_ENV_PROJECT_ROOT_VAR = 'INFRA_KIT_ENV_PROJECT_ROOT'\nexport const INFRA_KIT_ENV_LOADED_AT_VAR = 'INFRA_KIT_ENV_LOADED_AT'\n\n/**\n * Matches a line of the form `KEY=...` where KEY is an env-var identifier\n * (letter or underscore, then word chars). Capture group 1 is the name. Shared\n * between env-load (validation, var counting) and parseVarNamesFromEnvFile.\n */\nexport const ENV_VAR_LINE_PATTERN = /^([A-Z_]\\w*)=/i\n\n/**\n * The `unset NAME` line env-clear.sh is made of. Anchored at both ends so a value that merely\n * starts with the word is not a match.\n */\nconst UNSET_LINE_PATTERN = /^unset ([A-Z_]\\w*)$/i\n\n/**\n * Track whether a physical line leaves us inside an open single-quoted value,\n * mirroring how `shellSingleQuote` emits values (`'\u2026'`, with literal quotes as\n * `'\\''`). Outside a quote a backslash escapes the next char; inside a quote a\n * `'` closes it. Lets the parser skip the continuation lines of a multiline value.\n */\nconst advanceSingleQuoteState = (line: string, startInQuote: boolean): boolean => {\n let inQuote = startInQuote\n\n for (let i = 0; i < line.length; i++) {\n if (!inQuote && line[i] === '\\\\') {\n i++\n continue\n }\n\n if (line[i] === \"'\") {\n inQuote = !inQuote\n }\n }\n\n return inQuote\n}\n\n/** One `KEY=value` assignment recovered from an env file, value already unescaped. */\nexport interface EnvAssignment {\n name: string\n value: string\n}\n\n/**\n * Undo {@link shellSingleQuote}: drop the wrapping quotes, then turn each `'\\''`\n * back into a literal `'`. Order matters \u2014 unescaping first would let an embedded\n * `'\\''` be mistaken for the closing quote.\n */\nconst decodeSingleQuoted = (raw: string): string => {\n const withoutOpen = raw.startsWith(\"'\") ? raw.slice(1) : raw\n const body = withoutOpen.endsWith(\"'\") ? withoutOpen.slice(0, -1) : withoutOpen\n\n return body.split(\"'\\\\''\").join(\"'\")\n}\n\n/** File contents, or '' when the path is absent, a directory, or unreadable. */\nconst readEnvFileContent = (filePath: string): string => {\n try {\n return fs.readFileSync(filePath, 'utf-8')\n } catch {\n return ''\n }\n}\n\n/**\n * Walk every assignment in an env-load.sh body, skipping the continuation lines of\n * multiline values. {@link parseVarNamesFromEnvFile}, {@link parseVarsFromEnvFile}\n * and {@link parseUnsetNamesFromEnvFile} all go through here, so they can never\n * disagree about where a value ends \u2014 an `unset X` inside a quoted value is a\n * continuation line to every one of them.\n */\nconst forEachAssignment = (\n content: string,\n visit: (assignment: EnvAssignment) => void,\n visitUnset?: (name: string) => void,\n): void => {\n // A trailing CR is stripped per line: a CRLF file would otherwise hand back values\n // ending in '\\r' \u2014 a token that looks right in a diff and fails every request.\n const lines = content.split('\\n').map((line) => {\n return line.endsWith('\\r') ? line.slice(0, -1) : line\n })\n let index = 0\n let inQuote = false\n\n while (index < lines.length) {\n const line = lines[index]!\n\n // Only a line that starts OUTSIDE a quoted value can be a real assignment;\n // continuation lines of a multiline secret value are skipped.\n if (inQuote) {\n inQuote = advanceSingleQuoteState(line, inQuote)\n index += 1\n continue\n }\n\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (!match) {\n const unset = UNSET_LINE_PATTERN.exec(line)\n\n if (unset) visitUnset?.(unset[1]!)\n\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const name = match[1]!\n const rest = line.slice(match[0].length)\n\n // An unquoted value cannot span lines (`CONNECTION_STRING=host=db;user=admin`).\n if (!rest.startsWith(\"'\")) {\n visit({ name, value: rest })\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const parts = [rest]\n let open = advanceSingleQuoteState(rest, false)\n\n while (open && index + 1 < lines.length) {\n index += 1\n const continuation = lines[index]!\n\n parts.push(continuation)\n open = advanceSingleQuoteState(continuation, true)\n }\n\n visit({ name, value: decodeSingleQuoted(parts.join('\\n')) })\n inQuote = open\n index += 1\n }\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(readEnvFileContent(filePath), ({ name }) => {\n names.push(name)\n })\n\n return names\n}\n\n/**\n * Same walk as {@link parseVarNamesFromEnvFile}, but keeping the values. Later\n * assignments win, matching what `source`ing the file would do.\n */\nexport const parseVarsFromEnvFile = (filePath: string): Record<string, string> => {\n const vars: Record<string, string> = {}\n\n forEachAssignment(readEnvFileContent(filePath), ({ name, value }) => {\n vars[name] = value\n })\n\n return vars\n}\n\n/**\n * The names the file `unset`s \u2014 everything env-clear.sh does. Absent file \u2192 `[]`, like\n * its siblings.\n */\nexport const parseUnsetNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(\n readEnvFileContent(filePath),\n () => {},\n (name) => {\n names.push(name)\n },\n )\n\n return names\n}\n\n/**\n * Root cache dir for infra-kit across all sessions. Resolved from\n * $XDG_CACHE_HOME when set, falling back to ~/.cache/infra-kit. Keep in sync\n * with the shell block emitted by `infra-kit setup` (src/commands/init/init.ts).\n */\nexport const getCacheRoot = (): string => {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), '.cache')\n\n return path.join(base, 'infra-kit')\n}\n\nexport const getSessionCacheDir = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n if (!session) {\n throw new Error(\n `${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit setup --skip-tools\\` then \\`source ~/.zshrc\\`.`,\n )\n }\n\n return path.join(getCacheRoot(), session)\n}\n\n/**\n * Write content atomically: write to a pid-suffixed temp file in the same\n * directory, then rename. fs.renameSync is atomic on a single filesystem, so\n * concurrent writers can't produce a half-written secret file.\n */\nexport const atomicWriteFileSync = (filePath: string, content: string, mode: number): void => {\n const tmpPath = `${filePath}.tmp.${process.pid}`\n\n fs.writeFileSync(tmpPath, content, { mode })\n\n try {\n fs.renameSync(tmpPath, filePath)\n } catch (error) {\n fs.rmSync(tmpPath, { force: true })\n throw error\n }\n}\n\nexport const WORKTREES_DIR_SUFFIX = '-worktrees'\n\n/**\n * Whether `cwd` is one of the directories in an {@link ENV_LOAD_ROOT_FILE}, or under one. Mirrors the\n * `~/.zshenv` check in `init.ts`, symlinks resolved on both sides. No sidecar is in scope everywhere:\n * that is an `env-load.sh` written before the sidecar existed, and it stays usable until the next load.\n */\nexport const isInEnvLoadScope = (rootFile: string, cwd: string): boolean => {\n let content: string\n\n try {\n content = fs.readFileSync(rootFile, 'utf-8')\n } catch {\n return true\n }\n\n const realCwd = safeRealpath(cwd)\n\n return content\n .split('\\n')\n .filter(Boolean)\n .some((root) => {\n return realCwd === root || realCwd.startsWith(`${root}${path.sep}`)\n })\n}\n\nconst safeRealpath = (target: string): string => {\n try {\n return fs.realpathSync(target)\n } catch {\n return path.resolve(target)\n }\n}\n\n/**\n * Canonical `<repo>-worktrees` subdirectory names, shared by every command that lays worktrees\n * out under it (`init`'s scaffold, `worktrees add`) or reasons about that layout (`worktrees\n * sync`/`remove`, `gh merge-dev`'s scratch checkout) \u2014 one literal each, not re-typed per site.\n */\nexport const WORKTREE_SUBDIRS = { release: 'release', feature: 'feature', mergeDev: 'merge-dev' } as const\n"],
|
|
5
|
-
"mappings": "AAAA,OAAOA,MAAQ,UACf,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAEb,IAAMC,EAAgB,cAChBC,EAAiB,eAKjBC,EAAqB,gBAErBC,EAAwB,oBAYxBC,EAAuB,aAQvBC,EAAoB,gBACpBC,EAA2B,uBAC3BC,EAA4B,wBAK5BC,EAAiC,6BACjCC,EAA8B,0BAO9BC,EAAuB,iBAM9BC,EAAqB,uBAQrBC,EAA0B,CAACC,EAAcC,IAAmC,CAChF,IAAIC,EAAUD,EAEd,QAASE,EAAI,EAAGA,EAAIH,EAAK,OAAQG,IAAK,CACpC,GAAI,CAACD,GAAWF,EAAKG,CAAC,IAAM,KAAM,CAChCA,IACA,QACF,CAEIH,EAAKG,CAAC,IAAM,MACdD,EAAU,CAACA,EAEf,CAEA,OAAOA,CACT,EAaME,EAAsBC,GAAwB,CAClD,IAAMC,EAAcD,EAAI,WAAW,GAAG,EAAIA,EAAI,MAAM,CAAC,EAAIA,EAGzD,OAFaC,EAAY,SAAS,GAAG,EAAIA,EAAY,MAAM,EAAG,EAAE,EAAIA,GAExD,MAAM,OAAO,EAAE,KAAK,GAAG,CACrC,EAGMC,EAAsBC,GAA6B,CACvD,GAAI,CACF,OAAOzB,EAAG,aAAayB,EAAU,OAAO,CAC1C,MAAQ,CACN,MAAO,EACT,CACF,EASMC,EAAoB,CACxBC,EACAC,EACAC,IACS,CAGT,IAAMC,EAAQH,EAAQ,MAAM;AAAA,CAAI,EAAE,IAAKV,GAC9BA,EAAK,SAAS,IAAI,EAAIA,EAAK,MAAM,EAAG,EAAE,EAAIA,CAClD,
|
|
4
|
+
"sourcesContent": ["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nexport const ENV_LOAD_FILE = 'env-load.sh'\nexport const ENV_CLEAR_FILE = 'env-clear.sh'\n/**\n * Sidecar of `env-load.sh`: the directories, one per line, the loaded env belongs to. The session is\n * per terminal, not per repo, so without it a shell or agent in repo A sourced repo B's env.\n */\nexport const ENV_LOAD_ROOT_FILE = 'env-load.root'\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * Directory under the user's home that holds all machine-local infra-kit config:\n * the runtime `infra-kit.json` merge layer, per-project overrides, the factory\n * registry (`vendor.json`), and the `portless` package link. Single source of\n * truth for `.infra-kit`.\n *\n * Defined HERE, not in `lib/infra-kit-config`, because that module pulls in zod\n * and the `ik-mcp` proxy bundle must stay Node-builtins-only (guarded in\n * `entry/__tests__/dist-shebang.test.ts`); `lib/infra-kit-config` re-exports it\n * for its existing consumers.\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\n/**\n * The active environment/config NAME (e.g. `dev`, `arthur`), exported plainly so\n * non-shell consumers can read it from `process.env`. Notably `infra-kit/vite`'s\n * `infraKitDev()` reads this to interpolate the `<env>` placeholder in cloud proxy\n * targets. Mirrors {@link INFRA_KIT_ENV_CONFIG_VAR} (same value) but is the stable,\n * purpose-named handle for tooling rather than the shell session-metadata var.\n */\nexport const INFRA_KIT_ENV_VAR = 'INFRA_KIT_ENV'\nexport const INFRA_KIT_ENV_CONFIG_VAR = 'INFRA_KIT_ENV_CONFIG'\nexport const INFRA_KIT_ENV_PROJECT_VAR = 'INFRA_KIT_ENV_PROJECT'\n/**\n * Absolute project root (git top-level) the loaded env belongs to, so a shell can\n * tell whose secrets it is carrying after a `cd` into another project.\n */\nexport const INFRA_KIT_ENV_PROJECT_ROOT_VAR = 'INFRA_KIT_ENV_PROJECT_ROOT'\nexport const INFRA_KIT_ENV_LOADED_AT_VAR = 'INFRA_KIT_ENV_LOADED_AT'\n\n/**\n * Matches a line of the form `KEY=...` where KEY is an env-var identifier\n * (letter or underscore, then word chars). Capture group 1 is the name. Shared\n * between env-load (validation, var counting) and parseVarNamesFromEnvFile.\n */\nexport const ENV_VAR_LINE_PATTERN = /^([A-Z_]\\w*)=/i\n\n/**\n * The `unset NAME` line env-clear.sh is made of. Anchored at both ends so a value that merely\n * starts with the word is not a match.\n */\nconst UNSET_LINE_PATTERN = /^unset ([A-Z_]\\w*)$/i\n\n/**\n * Track whether a physical line leaves us inside an open single-quoted value,\n * mirroring how `shellSingleQuote` emits values (`'\u2026'`, with literal quotes as\n * `'\\''`). Outside a quote a backslash escapes the next char; inside a quote a\n * `'` closes it. Lets the parser skip the continuation lines of a multiline value.\n */\nconst advanceSingleQuoteState = (line: string, startInQuote: boolean): boolean => {\n let inQuote = startInQuote\n\n for (let i = 0; i < line.length; i++) {\n if (!inQuote && line[i] === '\\\\') {\n i++\n continue\n }\n\n if (line[i] === \"'\") {\n inQuote = !inQuote\n }\n }\n\n return inQuote\n}\n\n/** One `KEY=value` assignment recovered from an env file, value already unescaped. */\nexport interface EnvAssignment {\n name: string\n value: string\n}\n\n/**\n * Undo {@link shellSingleQuote}: drop the wrapping quotes, then turn each `'\\''`\n * back into a literal `'`. Order matters \u2014 unescaping first would let an embedded\n * `'\\''` be mistaken for the closing quote.\n */\nconst decodeSingleQuoted = (raw: string): string => {\n const withoutOpen = raw.startsWith(\"'\") ? raw.slice(1) : raw\n const body = withoutOpen.endsWith(\"'\") ? withoutOpen.slice(0, -1) : withoutOpen\n\n return body.split(\"'\\\\''\").join(\"'\")\n}\n\n/** File contents, or '' when the path is absent, a directory, or unreadable. */\nconst readEnvFileContent = (filePath: string): string => {\n try {\n return fs.readFileSync(filePath, 'utf-8')\n } catch {\n return ''\n }\n}\n\n/**\n * Walk every assignment in an env-load.sh body, skipping the continuation lines of\n * multiline values. {@link parseVarNamesFromEnvFile}, {@link parseVarsFromEnvFile}\n * and {@link parseUnsetNamesFromEnvFile} all go through here, so they can never\n * disagree about where a value ends \u2014 an `unset X` inside a quoted value is a\n * continuation line to every one of them.\n */\nconst forEachAssignment = (\n content: string,\n visit: (assignment: EnvAssignment) => void,\n visitUnset?: (name: string) => void,\n): void => {\n // A trailing CR is stripped per line: a CRLF file would otherwise hand back values\n // ending in '\\r' \u2014 a token that looks right in a diff and fails every request.\n const lines = content.split('\\n').map((line) => {\n return line.endsWith('\\r') ? line.slice(0, -1) : line\n })\n\n let index = 0\n let inQuote = false\n\n while (index < lines.length) {\n const line = lines[index]!\n\n // Only a line that starts OUTSIDE a quoted value can be a real assignment;\n // continuation lines of a multiline secret value are skipped.\n if (inQuote) {\n inQuote = advanceSingleQuoteState(line, inQuote)\n index += 1\n continue\n }\n\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (!match) {\n const unset = UNSET_LINE_PATTERN.exec(line)\n\n if (unset) visitUnset?.(unset[1]!)\n\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const name = match[1]!\n const rest = line.slice(match[0].length)\n\n // An unquoted value cannot span lines (`CONNECTION_STRING=host=db;user=admin`).\n if (!rest.startsWith(\"'\")) {\n visit({ name, value: rest })\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const parts = [rest]\n let open = advanceSingleQuoteState(rest, false)\n\n while (open && index + 1 < lines.length) {\n index += 1\n const continuation = lines[index]!\n\n parts.push(continuation)\n open = advanceSingleQuoteState(continuation, true)\n }\n\n visit({ name, value: decodeSingleQuoted(parts.join('\\n')) })\n inQuote = open\n index += 1\n }\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(readEnvFileContent(filePath), ({ name }) => {\n names.push(name)\n })\n\n return names\n}\n\n/**\n * Same walk as {@link parseVarNamesFromEnvFile}, but keeping the values. Later\n * assignments win, matching what `source`ing the file would do.\n */\nexport const parseVarsFromEnvFile = (filePath: string): Record<string, string> => {\n const vars: Record<string, string> = {}\n\n forEachAssignment(readEnvFileContent(filePath), ({ name, value }) => {\n vars[name] = value\n })\n\n return vars\n}\n\n/**\n * The names the file `unset`s \u2014 everything env-clear.sh does. Absent file \u2192 `[]`, like\n * its siblings.\n */\nexport const parseUnsetNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(\n readEnvFileContent(filePath),\n () => {},\n (name) => {\n names.push(name)\n },\n )\n\n return names\n}\n\n/**\n * Root cache dir for infra-kit across all sessions. Resolved from\n * $XDG_CACHE_HOME when set, falling back to ~/.cache/infra-kit. Keep in sync\n * with the shell block emitted by `infra-kit setup` (src/commands/init/init.ts).\n */\nexport const getCacheRoot = (): string => {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), '.cache')\n\n return path.join(base, 'infra-kit')\n}\n\nexport const getSessionCacheDir = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n if (!session) {\n throw new Error(\n `${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit setup --skip-tools\\` then \\`source ~/.zshrc\\`.`,\n )\n }\n\n return path.join(getCacheRoot(), session)\n}\n\n/**\n * Write content atomically: write to a pid-suffixed temp file in the same\n * directory, then rename. fs.renameSync is atomic on a single filesystem, so\n * concurrent writers can't produce a half-written secret file.\n */\nexport const atomicWriteFileSync = (filePath: string, content: string, mode: number): void => {\n const tmpPath = `${filePath}.tmp.${process.pid}`\n\n fs.writeFileSync(tmpPath, content, { mode })\n\n try {\n fs.renameSync(tmpPath, filePath)\n } catch (error) {\n fs.rmSync(tmpPath, { force: true })\n throw error\n }\n}\n\nexport const WORKTREES_DIR_SUFFIX = '-worktrees'\n\n/**\n * Whether `cwd` is one of the directories in an {@link ENV_LOAD_ROOT_FILE}, or under one. Mirrors the\n * `~/.zshenv` check in `init.ts`, symlinks resolved on both sides. No sidecar is in scope everywhere:\n * that is an `env-load.sh` written before the sidecar existed, and it stays usable until the next load.\n */\nexport const isInEnvLoadScope = (rootFile: string, cwd: string): boolean => {\n let content: string\n\n try {\n content = fs.readFileSync(rootFile, 'utf-8')\n } catch {\n return true\n }\n\n const realCwd = safeRealpath(cwd)\n\n return content\n .split('\\n')\n .filter(Boolean)\n .some((root) => {\n return realCwd === root || realCwd.startsWith(`${root}${path.sep}`)\n })\n}\n\nconst safeRealpath = (target: string): string => {\n try {\n return fs.realpathSync(target)\n } catch {\n return path.resolve(target)\n }\n}\n\n/**\n * Canonical `<repo>-worktrees` subdirectory names, shared by every command that lays worktrees\n * out under it (`init`'s scaffold, `worktrees add`) or reasons about that layout (`worktrees\n * sync`/`remove`, `gh merge-dev`'s scratch checkout) \u2014 one literal each, not re-typed per site.\n */\nexport const WORKTREE_SUBDIRS = { release: 'release', feature: 'feature', mergeDev: 'merge-dev' } as const\n"],
|
|
5
|
+
"mappings": "AAAA,OAAOA,MAAQ,UACf,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAEb,IAAMC,EAAgB,cAChBC,EAAiB,eAKjBC,EAAqB,gBAErBC,EAAwB,oBAYxBC,EAAuB,aAQvBC,EAAoB,gBACpBC,EAA2B,uBAC3BC,EAA4B,wBAK5BC,EAAiC,6BACjCC,EAA8B,0BAO9BC,EAAuB,iBAM9BC,EAAqB,uBAQrBC,EAA0B,CAACC,EAAcC,IAAmC,CAChF,IAAIC,EAAUD,EAEd,QAASE,EAAI,EAAGA,EAAIH,EAAK,OAAQG,IAAK,CACpC,GAAI,CAACD,GAAWF,EAAKG,CAAC,IAAM,KAAM,CAChCA,IACA,QACF,CAEIH,EAAKG,CAAC,IAAM,MACdD,EAAU,CAACA,EAEf,CAEA,OAAOA,CACT,EAaME,EAAsBC,GAAwB,CAClD,IAAMC,EAAcD,EAAI,WAAW,GAAG,EAAIA,EAAI,MAAM,CAAC,EAAIA,EAGzD,OAFaC,EAAY,SAAS,GAAG,EAAIA,EAAY,MAAM,EAAG,EAAE,EAAIA,GAExD,MAAM,OAAO,EAAE,KAAK,GAAG,CACrC,EAGMC,EAAsBC,GAA6B,CACvD,GAAI,CACF,OAAOzB,EAAG,aAAayB,EAAU,OAAO,CAC1C,MAAQ,CACN,MA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9B,EAEJ,GAAI,CACFA,EAAU3B,EAAG,aAAawD,EAAU,OAAO,CAC7C,MAAQ,CACN,MAAO,EACT,CAEA,IAAME,EAAUC,EAAaF,CAAG,EAEhC,OAAO9B,EACJ,MAAM;AAAA,CAAI,EACV,OAAO,OAAO,EACd,KAAMiC,GACEF,IAAYE,GAAQF,EAAQ,WAAW,GAAGE,CAAI,GAAG1D,EAAK,GAAG,EAAE,CACnE,CACL,EAEMyD,EAAgBE,GAA2B,CAC/C,GAAI,CACF,OAAO7D,EAAG,aAAa6D,CAAM,CAC/B,MAAQ,CACN,OAAO3D,EAAK,QAAQ2D,CAAM,CAC5B,CACF,EAOaC,EAAmB,CAAE,QAAS,UAAW,QAAS,UAAW,SAAU,WAAY",
|
|
6
6
|
"names": ["fs", "os", "path", "process", "ENV_LOAD_FILE", "ENV_CLEAR_FILE", "ENV_LOAD_ROOT_FILE", "INFRA_KIT_SESSION_VAR", "USER_CONFIG_DIR_NAME", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "ENV_VAR_LINE_PATTERN", "UNSET_LINE_PATTERN", "advanceSingleQuoteState", "line", "startInQuote", "inQuote", "i", "decodeSingleQuoted", "raw", "withoutOpen", "readEnvFileContent", "filePath", "forEachAssignment", "content", "visit", "visitUnset", "lines", "index", "match", "unset", "name", "rest", "parts", "open", "continuation", "parseVarNamesFromEnvFile", "names", "parseVarsFromEnvFile", "vars", "value", "parseUnsetNamesFromEnvFile", "getCacheRoot", "xdg", "base", "getSessionCacheDir", "session", "atomicWriteFileSync", "mode", "tmpPath", "error", "WORKTREES_DIR_SUFFIX", "isInEnvLoadScope", "rootFile", "cwd", "realCwd", "safeRealpath", "root", "target", "WORKTREE_SUBDIRS"]
|
|
7
7
|
}
|