infra-kit 0.8.0 → 0.10.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-BL4EQMZV.js → boot-XLDVLQEG.js} +2 -2
- package/dist/boot-XLDVLQEG.js.map +7 -0
- package/dist/chunk-7AMRJ4IW.js +9 -0
- package/dist/chunk-7AMRJ4IW.js.map +7 -0
- package/dist/{chunk-HHWP3YXW.js → chunk-AWFGP6GY.js} +1 -1
- package/dist/{chunk-HHWP3YXW.js.map → chunk-AWFGP6GY.js.map} +1 -1
- package/dist/chunk-JUNJK2YC.js +3 -0
- package/dist/chunk-JUNJK2YC.js.map +7 -0
- package/dist/chunk-MOVRKV3I.js +4 -0
- package/dist/{chunk-75URROMU.js.map → chunk-MOVRKV3I.js.map} +3 -3
- package/dist/chunk-OPL7C5H6.js +10 -0
- package/dist/{chunk-AOWMCNYY.js.map → chunk-OPL7C5H6.js.map} +4 -4
- package/dist/chunk-WUTG6VMP.js +7 -0
- package/dist/chunk-WUTG6VMP.js.map +7 -0
- package/dist/{chunk-6OFUVD7F.js → chunk-YYC3QGGC.js} +2 -2
- package/dist/chunk-YYC3QGGC.js.map +7 -0
- package/dist/cli.js +457 -13
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +19 -19
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-ITRFKMTL.js +2 -0
- package/dist/dev-wizard-run-ITRFKMTL.js.map +7 -0
- package/dist/mcp-proxy.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-check.js.map +1 -1
- package/package.json +3 -7
- package/readme.md +1 -2
- package/dist/boot-BL4EQMZV.js.map +0 -7
- package/dist/chunk-5XK34MWH.js +0 -442
- package/dist/chunk-5XK34MWH.js.map +0 -7
- package/dist/chunk-6OFUVD7F.js.map +0 -7
- package/dist/chunk-75URROMU.js +0 -4
- package/dist/chunk-AEVL5XWO.js +0 -3
- package/dist/chunk-AEVL5XWO.js.map +0 -7
- package/dist/chunk-AOWMCNYY.js +0 -10
- package/dist/chunk-BVEVERTB.js +0 -7
- package/dist/chunk-BVEVERTB.js.map +0 -7
- package/dist/chunk-GCX3HDDL.js +0 -9
- package/dist/chunk-GCX3HDDL.js.map +0 -7
- package/dist/dev-wizard-run-RPZOX53B.js +0 -2
- package/dist/dev-wizard-run-RPZOX53B.js.map +0 -7
- package/dist/mcp.js +0 -3
- package/dist/mcp.js.map +0 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/dev/managed-child.ts", "../src/dev/signal-shutdown.ts", "../src/
|
|
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 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 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 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", "import process from 'node:process'\nimport { $ } from 'zx'\n\nimport type { CmuxLayoutNode } from 'src/dev/cmux-layout'\nimport { logger } from 'src/lib/logger'\n\n/** Args for {@link openCmuxDevWorkspace}: the workspace root, title, and pane layout tree. */\ninterface OpenCmuxDevWorkspaceArgs {\n cwd: string\n title: string\n layout: CmuxLayoutNode\n}\n\n/**\n * True iff the `cmux` CLI is invokable (i.e. `cmux --version` resolves). Used to\n * gate `--cmux` mode and fall back to single-process dev when cmux is absent.\n */\nexport const isCmuxAvailable = async (): Promise<boolean> => {\n try {\n await $`cmux --version`.quiet()\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Open ONE cmux workspace rooted at `cwd`, laid out per `layout` (one pane per\n * command). Runs in a `CMUX_QUIET=1` scoped env to suppress cmux's one-time compat\n * notice, then parses and returns the `workspace:<id>` ref from stdout.\n */\nexport const openCmuxDevWorkspace = async (args: OpenCmuxDevWorkspaceArgs): Promise<string> => {\n const { cwd, title, layout } = args\n const layoutJson = JSON.stringify(layout)\n\n const $cmux = $({ env: { ...process.env, CMUX_QUIET: '1' } })\n const output = (await $cmux`cmux new-workspace --name ${title} --cwd ${cwd} --focus false --layout ${layoutJson}`)\n .stdout\n\n return parseWorkspaceRef(output)\n}\n\n/**\n * Best-effort close of the cmux workspace `ref`, tearing down the workspace and\n * every pane process. Silently no-ops (debug-logged) if cmux isn't running or the\n * close fails, mirroring {@link file://./close-workspace-by-cwd.ts}.\n */\nexport const closeCmuxDevWorkspace = async (ref: string): Promise<void> => {\n try {\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, ref }, 'cmux: skipped closing dev workspace')\n }\n}\n\n/**\n * Extract the `workspace:<id>` ref from `cmux new-workspace` output (e.g.\n * `OK workspace:5`). Throws a clear error when no ref is present.\n *\n * @example\n * parseWorkspaceRef('OK workspace:5\\n') // => 'workspace:5'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in new-workspace output')\n }\n\n return match[0]\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { listCmuxWorkspacesByCwd, realpathForCmuxCwd } from './list-workspaces-by-cwd'\n\n/**\n * Best-effort close of the cmux workspace rooted at `cwd`. Resolves the workspace\n * ref via {@link listCmuxWorkspacesByCwd} (which excludes group anchors, so this\n * can never close a group header) and closes it. Silently no-ops if cmux isn't\n * running, no workspace matches the cwd, or the close fails.\n *\n * Called BEFORE `git worktree remove`, so `cwd` still exists and normalizes the\n * same way as cmux's reported `current_directory`.\n */\nexport const closeCmuxWorkspaceByCwd = async (cwd: string): Promise<void> => {\n try {\n const byCwd = await listCmuxWorkspacesByCwd()\n\n const ref = byCwd.get(await realpathForCmuxCwd(cwd))\n\n if (!ref) {\n return\n }\n\n await $`cmux workspace close ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, cwd }, 'cmux: skipped closing workspace by cwd')\n }\n}\n", "import { realpath } from 'node:fs/promises'\nimport { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxWorkspaceListEntry {\n ref: string\n current_directory: string | null\n}\n\ninterface CmuxGroupListEntry {\n anchor_workspace_ref: string | null\n}\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 the cmux-reported\n * cwd and the caller's target cwd are normalized the same way so a macOS\n * `/var`\u2192`/private/var` style symlink can't make two equal paths compare unequal\n * (the realpath-asymmetry footgun this repo has been burned by before).\n */\nconst safeRealpath = async (path: string): Promise<string> => {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n\n/**\n * Build a `realpath(cwd) \u2192 workspace ref` map of every currently-open cmux\n * workspace, keyed on its working directory. This is the dedup/close identity for\n * infra-kit's worktree workspaces.\n *\n * Two entries are deliberately excluded: workspaces with no `current_directory` (e.g.\n * `infra-kit dev` panes), and group ANCHOR workspaces, which are dropped up front via\n * `workspace-group list`'s `anchor_workspace_ref`.\n *\n * Returns an empty map if cmux isn't running or the output can't be parsed \u2014\n * callers treat \"empty\" as \"unknown, proceed as if nothing is open\".\n */\n// Why cwd is the identity: it is unique per worktree and, unlike the title, stable after the\n// repo-name title prefix was dropped \u2014 two repos can share a branch name like\n// `fix-post-script-ci-cd`, but never a worktree path.\n//\n// Why anchors must go: cmux reports a group anchor's cwd as the main-repo root, so it collides\n// with the real main-checkout workspace. Keying an anchor into the map would shadow the main\n// workspace (breaking dedup) and, worse, let close-by-cwd close the group header. Workspaces with\n// no `current_directory` carry no worktree identity at all.\nexport const listCmuxWorkspacesByCwd = async (): Promise<Map<string, string>> => {\n try {\n const [workspacesOutput, groupsOutput] = await Promise.all([\n $`cmux workspace list --json`.quiet(),\n $`cmux workspace-group list --json`.quiet(),\n ])\n\n const workspaces = (JSON.parse(workspacesOutput.stdout).workspaces ?? []) as CmuxWorkspaceListEntry[]\n const groups = (JSON.parse(groupsOutput.stdout).groups ?? []) as CmuxGroupListEntry[]\n\n const anchorRefs = new Set(\n groups\n .map((group) => {\n return group.anchor_workspace_ref\n })\n .filter((ref): ref is string => {\n return typeof ref === 'string'\n }),\n )\n\n const byCwd = new Map<string, string>()\n\n for (const workspace of workspaces) {\n if (!workspace.current_directory || anchorRefs.has(workspace.ref)) {\n continue\n }\n\n byCwd.set(await safeRealpath(workspace.current_directory), workspace.ref)\n }\n\n return byCwd\n } catch (error) {\n logger.debug({ error }, 'cmux: skipped listing workspaces by cwd')\n\n return new Map()\n }\n}\n\n/** Exported for callers that need the same normalization when looking up a target cwd. */\nexport { safeRealpath as realpathForCmuxCwd }\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxGroupListEntry {\n ref: string\n name: string\n}\n\n/**\n * Return the `workspace_group:N` ref of the sidebar group titled exactly `name`,\n * or `null` if no such group exists (or cmux is unreachable). Group names are the\n * repo name (basename of the main-repo root), so worktree workspaces for one repo\n * all resolve to the same group regardless of which worktree the command runs in.\n */\nexport const findCmuxGroupRefByName = async (name: string): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group list --json`.quiet()).stdout\n\n const groups = (JSON.parse(output).groups ?? []) as CmuxGroupListEntry[]\n\n const match = groups.find((group) => {\n return group.name === name\n })\n\n return match?.ref ?? null\n } catch (error) {\n logger.debug({ error, name }, 'cmux: skipped group lookup')\n\n return null\n }\n}\n\n/**\n * Create a pinned sidebar group named `name` seeded with EXACTLY `fromRefs`, and\n * return its ref (or `null` on failure).\n *\n * `--from` is load-bearing: `cmux workspace-group create` defaults `--from` to the\n * currently-selected/caller workspace, so omitting it silently captures an\n * unrelated workspace (and, under the `--all` fan-out, steals a sibling repo's\n * freshly-created workspace). Passing the seed refs explicitly makes creation\n * deterministic and capture-free \u2014 no snapshot/self-heal needed. The group also\n * gets a synthetic anchor workspace (its header row), matching how the user's\n * groups are already shaped.\n */\nexport const createCmuxGroupFrom = async (name: string, fromRefs: string[]): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group create --name ${name} --from ${fromRefs.join(',')}`).stdout\n\n const ref = output.match(/workspace_group:\\d+/)?.[0] ?? (await findCmuxGroupRefByName(name))\n\n if (ref) {\n await $`cmux workspace-group pin ${ref}`.quiet()\n }\n\n return ref ?? null\n } catch (error) {\n logger.warn({ error, name }, '\u26A0\uFE0F cmux: failed to create workspace group')\n\n return null\n }\n}\n", "import { $ } from 'zx'\n\nimport { getInfraKitConfig, resolveCmuxLayout } from 'src/lib/infra-kit-config'\n\ninterface OpenCmuxWorkspaceArgs {\n cwd: string\n title?: string\n /**\n * When set, the workspace is created directly inside this sidebar group\n * (`workspace_group:N` ref) via `--group`, appended at the end so existing\n * members aren't reordered. Omit to create an ungrouped workspace (e.g. the\n * first worktree of a repo, which then seeds a new group).\n */\n group?: string\n}\n\n/**\n * Opens a new cmux workspace rooted at `cwd`, with panes arranged per the\n * configured `worktrees.cmux.layout` (resolved via {@link resolveCmuxLayout},\n * default `two-columns`):\n * two-columns \u2014 left | right, both full-height (two panes)\n * three-pane \u2014 left-top / left-bottom | full-height right (three panes)\n * All panes inherit `cwd` from the workspace. Returns the created\n * `workspace:N` ref so callers can seed a group from it.\n */\nexport const openCmuxWorkspaceWithLayout = async (args: OpenCmuxWorkspaceArgs): Promise<string> => {\n const { cwd, title, group } = args\n\n const layout = resolveCmuxLayout(await getInfraKitConfig())\n\n const newWorkspaceOutput = group\n ? (await $`cmux workspace create --cwd ${cwd} --group ${group} --group-placement end`).stdout\n : (await $`cmux workspace create --cwd ${cwd}`).stdout\n\n const workspaceRef = parseWorkspaceRef(newWorkspaceOutput)\n\n const surfacesOutput = (await $`cmux list-pane-surfaces --workspace ${workspaceRef}`).stdout\n\n const leftTopRef = parseFirstSurfaceRef(surfacesOutput)\n\n // Both layouts share the vertical split into left | right columns; only the\n // legacy three-pane layout additionally splits the left column top/bottom.\n await $`cmux new-split right --workspace ${workspaceRef} --surface ${leftTopRef}`\n\n if (layout === 'three-pane') {\n await $`cmux new-split down --workspace ${workspaceRef} --surface ${leftTopRef}`\n }\n\n if (title) {\n await $`cmux workspace rename --workspace ${workspaceRef} --title ${title}`\n }\n\n return workspaceRef\n}\n\n/**\n * Extracts the first `surface:<id>` reference from the output of\n * `cmux list-pane-surfaces`. Used to locate the initial (primary) pane\n * surface so subsequent splits can be anchored relative to it.\n *\n * @example\n * const output = 'surface:12 (active)\\nsurface:13\\n'\n * parseFirstSurfaceRef(output) // => 'surface:12'\n */\nconst parseFirstSurfaceRef = (output: string): string => {\n const match = output.match(/surface:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate initial surface in list-pane-surfaces output')\n }\n\n return match[0]\n}\n\n/**\n * Extracts the `workspace:<id>` reference from the output of\n * `cmux workspace create`. The returned ref is used to target the newly\n * created workspace in follow-up `cmux` commands (splits, rename, etc.).\n *\n * @example\n * const output = 'created workspace:7\\n'\n * parseWorkspaceRef(output) // => 'workspace:7'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in workspace create output')\n }\n\n return match[0]\n}\n", "import { displayLabel, parseBranchName } from 'src/lib/release-id'\n\ninterface BuildCmuxWorkspaceTitleArgs {\n branch: string\n}\n\n/**\n * Builds the cmux workspace title for a worktree. The title is now just the\n * branch's display label \u2014 the repo name is NOT prefixed, because every worktree\n * workspace lives inside a per-repo sidebar GROUP whose header already carries the\n * repo name (e.g. group `hulyo-monorepo` \u2192 workspaces titled `1.48.0`,\n * `checkout-redesign`, `dev`). Release branches render via their release-id label\n * (`release/v1.48.0` \u2192 `1.48.0`, `release/checkout-redesign` \u2192 `checkout-redesign`);\n * non-release branches fall back to the raw branch string.\n *\n * Note: the title is NO LONGER a dedup/close key \u2014 that role moved to the\n * workspace cwd (see {@link listCmuxWorkspacesByCwd}), because dropping the repo\n * prefix makes titles collide across repos (both hulyo and travelist can have a\n * `fix-post-script-ci-cd` branch).\n */\nexport const buildCmuxWorkspaceTitle = (args: BuildCmuxWorkspaceTitleArgs): string => {\n const { branch } = args\n\n const id = parseBranchName(branch)\n\n return id ? displayLabel(id) : branch\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", "/**\n * Assembles the impure {@link PresetProxyContext} `validatePresetProxy` needs, so the STATIC\n * proxy-locality rule in `presets.ts` never has to touch the filesystem or `loadDev` itself.\n *\n * Shared by two callers that must never disagree about what \"satisfiable\" means:\n * - `infra-kit audit` (`commands/audit/preset-proxy-check.ts`) \u2014 checks every preset.\n * - `infra-kit dev <preset>` (`dev-server.ts`) \u2014 checks only the one preset about to run, BEFORE\n * any server spawns.\n */\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\n\nimport { resolvePreset } from 'src/dev/presets'\nimport type { DiscoveredParts, PresetProxyContext } from 'src/dev/presets'\nimport type { DevPresets } from 'src/lib/infra-kit-config'\n\n/** A frontend config that a preset references but that failed to load (bad/invalid config). */\nexport interface LoadError {\n app: string\n message: string\n}\n\ninterface RoutePkgLookup {\n routePkg: PresetProxyContext['routePkg']\n loadErrors: LoadError[]\n}\n\n/**\n * The set of frontend app folders any preset's proxy override actually references \u2014\n * the only configs the caller needs to load. Scoping to these keeps an unrelated\n * broken frontend config from failing (or crashing) a check it was never relevant to.\n */\nconst collectReferencedApps = (presets: DevPresets, discovered: DiscoveredParts): string[] => {\n const apps = new Set<string>()\n\n for (const preset of Object.values(presets)) {\n for (const app of Object.keys(resolvePreset(preset, discovered).proxy)) {\n apps.add(app)\n }\n }\n\n return [...apps]\n}\n\n/**\n * Load each referenced frontend's `dev.proxy.routes` into a sync `(app, route) \u2192 pkg`\n * lookup. A config that throws (schema-invalid, import error) is captured as a\n * {@link LoadError} instead of rejecting, so one bad config yields an actionable\n * result rather than crashing the whole check.\n */\nconst buildRoutePkgLookup = async (root: string, apps: string[]): Promise<RoutePkgLookup> => {\n const routesByApp: Record<string, Record<string, string>> = {}\n const loadErrors: LoadError[] = []\n\n await Promise.all(\n apps.map(async (app) => {\n try {\n const dev = await loadDev(path.join(root, 'apps', app, 'ui'))\n const routes = dev?.proxy?.routes\n\n if (!routes) return\n\n routesByApp[app] = Object.fromEntries(\n Object.entries(routes).map(([route, route_]) => {\n return [route, route_.packageName]\n }),\n )\n } catch (error) {\n loadErrors.push({ app, message: error instanceof Error ? error.message : String(error) })\n }\n }),\n )\n\n return {\n routePkg: (app, route) => {\n return routesByApp[app]?.[route]\n },\n loadErrors,\n }\n}\n\n/** Result of {@link buildPresetProxyContext}: the assembled context, plus any config that failed to load. */\nexport interface PresetProxyContextResult {\n ctx: PresetProxyContext\n loadErrors: LoadError[]\n}\n\n/**\n * Build the {@link PresetProxyContext} `validatePresetProxy` needs for `presets`: a sync\n * `(app, route) \u2192 pkg` lookup from each referenced frontend's `infra-kit.config.ts`\n * (the SAME file, through the same `loadDev`, that the vite helper resolves at runtime), plus\n * the api package name for every discovered api app.\n *\n * @example\n * const { ctx, loadErrors } = await buildPresetProxyContext('/repo', presets, discovered, apiApps)\n * const issues = validatePresetProxy(presets, ctx)\n */\nexport const buildPresetProxyContext = async (\n root: string,\n presets: DevPresets,\n discovered: DiscoveredParts,\n apiApps: { name: string; packageName: string }[],\n): Promise<PresetProxyContextResult> => {\n const { routePkg, loadErrors } = await buildRoutePkgLookup(root, collectReferencedApps(presets, discovered))\n\n return {\n ctx: {\n discovered,\n apiPkgByApp: Object.fromEntries(\n apiApps.map((a) => {\n return [a.name, a.packageName]\n }),\n ),\n routePkg,\n },\n loadErrors,\n }\n}\n"],
|
|
5
|
-
"mappings": "4EAiCA,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,EAEn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jC,CAACD,EAAOC,EAAO,WAAW,CAClC,CACH,CACF,OAASC,EAAO,CACdN,EAAW,KAAK,CAAE,IAAAL,EAAK,QAASW,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAE,CAAC,CAC1F,CACF,CAAC,CACH,EAEO,CACL,SAAU,CAACX,EAAKS,IACPL,EAAYJ,CAAG,IAAIS,CAAK,EAEjC,WAAAJ,CACF,CACF,EAkBaO,GAA0B,MACrCT,EACAP,EACAC,EACAgB,IACsC,CACtC,GAAM,CAAE,SAAAC,EAAU,WAAAT,CAAW,EAAI,MAAMH,GAAoBC,EAAMR,GAAsBC,EAASC,CAAU,CAAC,EAE3G,MAAO,CACL,IAAK,CACH,WAAAA,EACA,YAAa,OAAO,YAClBgB,EAAQ,IAAKE,GACJ,CAACA,EAAE,KAAMA,EAAE,WAAW,CAC9B,CACH,EACA,SAAAD,CACF,EACA,WAAAT,CACF,CACF",
|
|
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", "
|
|
3
|
+
"sources": ["../src/dev/managed-child.ts", "../src/dev/signal-shutdown.ts", "../src/lib/errors/is-prompt-cancellation.ts", "../src/dev/preset-proxy-context.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"],
|
|
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 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 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 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", "/**\n * Assembles the impure {@link PresetProxyContext} `validatePresetProxy` needs, so the STATIC\n * proxy-locality rule in `presets.ts` never has to touch the filesystem or `loadDev` itself.\n *\n * Shared by two callers that must never disagree about what \"satisfiable\" means:\n * - `infra-kit audit` (`commands/audit/preset-proxy-check.ts`) \u2014 checks every preset.\n * - `infra-kit dev <preset>` (`dev-server.ts`) \u2014 checks only the one preset about to run, BEFORE\n * any server spawns.\n */\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\n\nimport { resolvePreset } from 'src/dev/presets'\nimport type { DiscoveredParts, PresetProxyContext } from 'src/dev/presets'\nimport type { DevPresets } from 'src/lib/infra-kit-config'\n\n/** A frontend config that a preset references but that failed to load (bad/invalid config). */\nexport interface LoadError {\n app: string\n message: string\n}\n\ninterface RoutePkgLookup {\n routePkg: PresetProxyContext['routePkg']\n loadErrors: LoadError[]\n}\n\n/**\n * The set of frontend app folders any preset's proxy override actually references \u2014\n * the only configs the caller needs to load. Scoping to these keeps an unrelated\n * broken frontend config from failing (or crashing) a check it was never relevant to.\n */\nconst collectReferencedApps = (presets: DevPresets, discovered: DiscoveredParts): string[] => {\n const apps = new Set<string>()\n\n for (const preset of Object.values(presets)) {\n for (const app of Object.keys(resolvePreset(preset, discovered).proxy)) {\n apps.add(app)\n }\n }\n\n return [...apps]\n}\n\n/**\n * Load each referenced frontend's `dev.proxy.routes` into a sync `(app, route) \u2192 pkg`\n * lookup. A config that throws (schema-invalid, import error) is captured as a\n * {@link LoadError} instead of rejecting, so one bad config yields an actionable\n * result rather than crashing the whole check.\n */\nconst buildRoutePkgLookup = async (root: string, apps: string[]): Promise<RoutePkgLookup> => {\n const routesByApp: Record<string, Record<string, string>> = {}\n const loadErrors: LoadError[] = []\n\n await Promise.all(\n apps.map(async (app) => {\n try {\n const dev = await loadDev(path.join(root, 'apps', app, 'ui'))\n const routes = dev?.proxy?.routes\n\n if (!routes) return\n\n routesByApp[app] = Object.fromEntries(\n Object.entries(routes).map(([route, route_]) => {\n return [route, route_.packageName]\n }),\n )\n } catch (error) {\n loadErrors.push({ app, message: error instanceof Error ? error.message : String(error) })\n }\n }),\n )\n\n return {\n routePkg: (app, route) => {\n return routesByApp[app]?.[route]\n },\n loadErrors,\n }\n}\n\n/** Result of {@link buildPresetProxyContext}: the assembled context, plus any config that failed to load. */\nexport interface PresetProxyContextResult {\n ctx: PresetProxyContext\n loadErrors: LoadError[]\n}\n\n/**\n * Build the {@link PresetProxyContext} `validatePresetProxy` needs for `presets`: a sync\n * `(app, route) \u2192 pkg` lookup from each referenced frontend's `infra-kit.config.ts`\n * (the SAME file, through the same `loadDev`, that the vite helper resolves at runtime), plus\n * the api package name for every discovered api app.\n *\n * @example\n * const { ctx, loadErrors } = await buildPresetProxyContext('/repo', presets, discovered, apiApps)\n * const issues = validatePresetProxy(presets, ctx)\n */\nexport const buildPresetProxyContext = async (\n root: string,\n presets: DevPresets,\n discovered: DiscoveredParts,\n apiApps: { name: string; packageName: string }[],\n): Promise<PresetProxyContextResult> => {\n const { routePkg, loadErrors } = await buildRoutePkgLookup(root, collectReferencedApps(presets, discovered))\n\n return {\n ctx: {\n discovered,\n apiPkgByApp: Object.fromEntries(\n apiApps.map((a) => {\n return [a.name, a.packageName]\n }),\n ),\n routePkg,\n },\n loadErrors,\n }\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 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"],
|
|
5
|
+
"mappings": "8DAiCA,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,EAAM,KAAAC,EAAM,OAAQH,EAAK,KAAK,GAAG,CAAE,CAAC,CACrD,CAAC,EAiBGI,EAAgBC,GAAyC,CAC7D,IAAMC,EAAS,IAAI,IAEnB,QAAWC,KAAOF,EACZE,EAAI,MAAQA,EAAI,MAAMD,EAAO,IAAIC,EAAI,KAA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UAAY,GAEX,IAAIH,EAAU,CAClB,KAAM,+BACN,QAAS,kBAAkBE,CAAG,4BAA4BE,CAAQ,gBAAgBI,GAAa,SAAW,EAAE,GAC5G,KAAM,CAAE,IAAAN,EAAK,SAAAE,EAAU,MAAOI,GAAa,IAAK,CAClD,CAAC,CACH,EAEMI,EAAQ,MAAOC,EAAgBC,KACpB,MAAMhB,EAAiC,CACpD,WACA,QACA,aACAe,EACA,cACAC,CACF,CAAC,GAEa,MAAM,OAaTC,GAA4B,MACvCC,GAC6D,CAC7D,GAAM,CAAE,IAAAd,EAAK,MAAAe,EAAO,MAAAC,EAAO,OAAAC,EAAQ,MAAAC,EAAO,KAAAjB,EAAOT,GAAmB,CAAE,EAAIsB,EAEpEK,EAAa,CACjB,WACA,SACA,aACA,QAAQnB,CAAG,GACX,UACAe,EACA,GAAIC,EAAQ,CAAC,SAAS,EAAI,CAAC,CAC7B,EAEMI,EAAQ,MAAMrB,GAAeoB,EAAYnB,EAAKC,CAAI,EAClDoB,EAAU,CAACD,CAAK,EAEtB,OAAIH,IAAW,SACbI,EAAQ,KAAK,MAAMX,EAAMU,EAAO,YAAY,CAAC,EAEzCF,IAAU,cACZG,EAAQ,KAAK,MAAMX,EAAMU,EAAO,UAAU,CAAC,GAIxC,CAAE,QAAAC,EAAS,OAAAJ,CAAO,CAC3B,EC1IO,IAAMK,GAA0BC,GAA6C,CAClF,GAAM,CAAE,OAAAC,CAAO,EAAID,EAEbE,EAAKC,EAAgBF,CAAM,EAEjC,OAAOC,EAAKE,EAAaF,CAAE,EAAID,CACjC",
|
|
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", "loadDev", "path", "collectReferencedApps", "presets", "discovered", "apps", "preset", "app", "resolvePreset", "buildRoutePkgLookup", "root", "routesByApp", "loadErrors", "routes", "loadDev", "path", "route", "route_", "error", "buildPresetProxyContext", "apiApps", "routePkg", "a", "$", "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"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{N as g,P as x,Y as A,d as f,f as p,i as b}from"./chunk-7AMRJ4IW.js";import{s as P}from"./chunk-MOVRKV3I.js";import{a as _,b as D}from"./chunk-QWVLAZ6N.js";import h from"node:fs/promises";import l from"node:path";import{z as i}from"zod";var s=class extends Error{env;constructor(r,t=null){super(r),this.name="EnvAuthError",this.env=t}},te=e=>e instanceof s;var M="tokens.json",v=1,$=384,R=448,q=i.object({version:i.literal(v).default(v),envs:i.record(i.string().min(1),i.string().min(1))}).strict(),w=async()=>{let e=await A();return l.join(l.dirname(e.userProject),M)},E=async()=>{let e=await w(),r;try{r=await h.readFile(e,"utf-8")}catch{return null}let t;try{t=JSON.parse(r)}catch(o){throw new s(`Invalid JSON in the token store at ${x(e)}: ${o.message}
|
|
2
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let n=q.safeParse(t);if(!n.success)throw new s(`Invalid token store at ${x(e)}: ${i.prettifyError(n.error)}
|
|
3
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return n.data},y=async e=>{let r=await w(),t=l.dirname(r),n=l.dirname(t),o=l.dirname(n);for(let c of[o,n,t])await h.mkdir(c,{recursive:!0,mode:R}),await h.chmod(c,R);P(r,`${JSON.stringify(e,null,2)}
|
|
4
|
+
`,$),await h.chmod(r,$)},K=async(e,r)=>{let t=await E();await y({version:v,envs:{...t?.envs,[e]:r}})},B=async e=>{let r=await E();if(!r||!(e in r.envs))return;let t={...r.envs};delete t[e],await y({version:v,envs:t})};var J=()=>{let e="",r=[],t=!1;return{start(n){e=n,r=[],t=!1},setInteractive(){t=!0},addOption(n,o){r.push({flag:n,value:o})},formatOptions(){return r.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 r.length===0?null:{formattedOptions:this.formatOptions()}},print(){!t||r.length===0||!e||g.info(`\u{1F4DF} Equivalent command:
|
|
5
|
+
pnpm exec infra-kit ${e} ${this.formatOptions()}
|
|
6
|
+
`)},reset(){e="",r=[],t=!1}}},S=J();import{isAbsolute as I,resolve as j}from"node:path";import L from"node:process";var k=null,O=null,W=e=>{k=[...e],O=L.cwd()},z=new Set(["--yes","-y"]),U=(e,r)=>{let t=[...e];for(let[n,o]of t.entries())o==="-C"&&t[n+1]!==void 0&&!I(t[n+1])?t[n+1]=j(r,t[n+1]):o.startsWith("-C")&&o.length>2&&!o.startsWith("--")&&!I(o.slice(2))&&(t[n]=`-C${j(r,o.slice(2))}`);return t},T=()=>{if(k===null||O===null)return["--yes"];let e=U(k.slice(2),O);return e.some(t=>z.has(t))?e:[...e,"--yes"]};import N from"node:process";var a=class extends b{structuredContent;exitCode;constructor(r,t,n){super(void 0,n),this.name="StructuredRefusalError",this.structuredContent=r,this.exitCode=t}};var Y=27,G=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`,V=e=>`${e===void 0?"pass the value explicitly instead of relying on the prompt":`pass --${e}`} on the re-run`,Q=e=>{if(typeof e=="object"&&"value"in e)return e.value;let r=typeof e=="object"?e.refuse:void 0,{source:t}=f;throw new a(r===void 0?{status:"refused",agentMode:t}:{status:"argument_required",argument:r,agentMode:t},2,{operation:"interactive prompt",remediation:V(r),stderrExcerpt:G(t)})},F=async(e,r)=>{let t=new AbortController,{whenHeadless:n="refuse",...o}=r??{},c={...o,signal:t.signal};if(p())return Q(n);if(!N.stdin.isTTY)return e(c);let m=N.stdin,C=d=>{d.length===1&&d[0]===Y&&t.abort()};_();try{let d=e(c);return m.isPaused()&&m.resume(),m.on("data",C),await d}finally{m.removeListener("data",C),D()}};import X from"@inquirer/confirm";import Z from"node:process";var u=class extends Error{constructor(r="Operation cancelled by the operator"){super(r),this.name="CommandDeclinedError"}},Pe=e=>e instanceof u;var H=(e,r)=>{let{source:t}=f,n=T();throw new a({status:"confirmation_required",message:e,plan:r,rerun:n,agentMode:t},2,{operation:"confirm before running",remediation:t===null?"pass `--yes` to confirm, or drop `--json` to be prompted":`show the plan to the human, then re-run \`infra-kit ${n.join(" ")}\` to confirm`,stderrExcerpt:"confirmation required and nobody to ask"})},ee=async(e,r,t={})=>{!e&&p()&&H(r,t.plan);let n=e?!0:await F(o=>X({message:r},o),{whenHeadless:"refuse"});if(e||S.setInteractive(),!n){if(t.throwOnDecline)throw new u;g.info("Operation cancelled. Exiting..."),Z.exit(0)}};export{s as a,te as b,w as c,E as d,K as e,B as f,S as g,Pe as h,a as i,W as j,F as k,H as l,ee as m};
|
|
7
|
+
//# sourceMappingURL=chunk-WUTG6VMP.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts", "../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/errors/structured-refusal-error.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts"],
|
|
4
|
+
"sourcesContent": ["// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 it cannot heal on a 30s retry, only a human can fix it \u2014 and env\n // auto-load's sticky marker is keyed on that CLASS. Thrown as a plain Error these were classified\n // TRANSIENT, so a corrupt store went silent on the backgrounded shell-startup spawn and the user's\n // env simply stopped loading with nothing ever said. `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store. Only this\n * class earns the STICKY marker that survives the backgrounded shell-startup spawn and is replayed\n * onto the next interactive command. `DopplerAuthError extends EnvAuthError` for the subset that\n * is specifically \"Doppler refused the token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): env auto-load must tell a\n// TRANSIENT failure (network, timeout, Doppler down \u2014 heals itself, 30s backoff, stay quiet) apart\n// from a DURABLE one (never heals, and only a human can fix it). A durable failure misclassified as\n// transient is TOTAL SILENCE, forever, on the one path the whole feature exists to survive.\n//\n// That classification therefore has to travel WITH the error, not be re-derived by grepping a\n// message some other module owns \u2014 and it has to be throwable from EVERY module that can produce\n// the class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a\n// Doppler-owned base type could not be thrown there without a layering inversion and an import\n// cycle. Hence a neutral base here in `lib/errors`.\n//\n// The defect class this closes is \"a durable failure that is not type-detectable\". Adding a new\n// durable failure and forgetting to type it is exactly how this shipped silent twice.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * This is the default `isAuthFailure` of `lib/env-autoload`'s `runEnvAutoLoad`. It is deliberately\n * WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only one of the\n * durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store never reaches\n * the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n", "import { 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 * Appending is safe: no leaf uses `passThroughOptions` or `--`, and the only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv that already carries `--yes`/`-y` is returned\n * as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this function's\n * problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const args = absolutizeChangeDir(parsedArgv.slice(2), launchCwd)\n\n const alreadyConfirmed = args.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? args : [...args, '--yes']\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about 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", "import { OperationError } from './operation-error'\nimport type { OperationErrorContext } from './operation-error'\n\n/**\n * Why the command stopped, for a machine reader. `exitCode` 2 means nothing happened \u2014 re-run with\n * more; 1 means something happened and part of it failed.\n */\nexport type RefusalStatus = 'confirmation_required' | 'argument_required' | 'partial_failure' | 'refused'\n\nexport interface RefusalStructuredContent {\n status: RefusalStatus\n [k: string]: unknown\n}\n\n/**\n * A refusal that carries a payload for an agent: `entry/cli.ts` emits `structuredContent` under\n * `--json` and exits with `exitCode`. The message is the ordinary `OperationError` one\n * (operation / stderr / remediation), so the human-readable line loses nothing.\n *\n * @example\n * throw new StructuredRefusalError(\n * { status: 'argument_required', argument: 'version', agentMode: 'flag' },\n * 2,\n * { operation: 'interactive prompt', remediation: 'pass --version' },\n * )\n */\n// Extends `OperationError`, not `Error`, ON PURPOSE. Seven of the eight confirm sites sit under a\n// handler-level `catch` that passes through only `isPromptCancellation`, `isCommandDeclined` and\n// `instanceof OperationError` and REWRAPS everything else into a generic `OperationError`\n// (`release-remove.ts` near the `gh auth status` remediation, `worktrees-add.ts`, `worktrees-sync.ts`,\n// `release-create.ts`). A plain `Error` subclass would lose the payload and the exit code at exactly\n// the sites this exists for.\nexport class StructuredRefusalError extends OperationError {\n readonly structuredContent: RefusalStructuredContent\n readonly exitCode: 1 | 2\n\n constructor(structuredContent: RefusalStructuredContent, exitCode: 1 | 2, context: OperationErrorContext) {\n super(undefined, context)\n this.name = 'StructuredRefusalError'\n this.structuredContent = structuredContent\n this.exitCode = exitCode\n }\n}\n", "/**\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\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): never => {\n const { source } = agentMode\n const rerun = rerunArgv()\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n"],
|
|
5
|
+
"mappings": "kKAKA,OAAOA,MAAQ,mBACf,OAAOC,MAAU,YACjB,OAAS,KAAAC,MAAS,MCsBX,IAAMC,EAAN,cAA2B,KAAM,CAO7B,IAET,YAAYC,EAAiBC,EAAqB,KAAM,CACtD,MAAMD,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,IAAMC,CACb,CACF,EAgBaC,GAAoBC,GACxBA,aAAiBJ,EDtC1B,IAAMK,EAAmB,cAGnBC,EAAsB,EAGtBC,EAAkB,IAGlBC,EAAiB,IAqBjBC,EAAmBC,EACtB,OAAO,CACN,QAASA,EAAE,QAAQJ,CAAmB,EAAE,QAAQA,CAAmB,EACnE,KAAMI,EAAE,OAAOA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAGA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CACrD,CAAC,EACA,OAAO,EAeGC,EAAoB,SAA6B,CAC5D,IAAMC,EAAQ,MAAMC,EAAuB,EAE3C,OAAOC,EAAK,KAAKA,EAAK,QAAQF,EAAM,WAAW,EAAGP,CAAgB,CACpE,EAeaU,EAAiB,SAAwC,CACpE,IAAMC,EAAY,MAAML,EAAkB,EAEtCM,EAEJ,GAAI,CACFA,EAAM,MAAMC,EAAG,SAASF,EAAW,OAAO,CAC5C,MAAQ,CACN,OAAO,IACT,CAOA,IAAIG,EAEJ,GAAI,CAC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AChH,UAAW,yBACX,YACEA,IAAW,KACP,2DACA,uDAAuDE,EAAM,KAAK,GAAG,CAAC,gBAC5E,cAAe,yCACjB,CAAC,CACH,EAEaG,GAAgB,MAC3BC,EACAR,EACAS,EAAgC,CAAC,IACf,CACd,CAACD,GAAoBE,EAAW,GAAGX,EAAkBC,EAASS,EAAQ,IAAI,EAE9E,IAAME,EAASH,EACX,GACA,MAAMI,EACHC,GACQC,EAAQ,CAAE,QAAAd,CAAQ,EAAGa,CAAO,EAKrC,CAAE,aAAc,QAAS,CAC3B,EAMJ,GAJKL,GACHO,EAAY,eAAe,EAGzB,CAACJ,EAAQ,CACX,GAAIF,EAAQ,eACV,MAAM,IAAIO,EAGZC,EAAO,KAAK,iCAAiC,EAC7CC,EAAQ,KAAK,CAAC,CAChB,CACF",
|
|
6
|
+
"names": ["fs", "path", "z", "EnvAuthError", "message", "env", "isEnvAuthFailure", "error", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs", "createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "process", "StructuredRefusalError", "OperationError", "structuredContent", "exitCode", "context", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "source", "agentMode", "rerun", "rerunArgv", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process"]
|
|
7
|
+
}
|