infra-kit 0.11.16 → 0.14.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-XLDVLQEG.js → boot-LC2ESPY6.js} +2 -2
- package/dist/chunk-DW2SQ2XU.js +7 -0
- package/dist/chunk-DW2SQ2XU.js.map +7 -0
- package/dist/{chunk-TT7OQ4PI.js → chunk-EAUGQ3ZU.js} +5 -5
- package/dist/{chunk-TT7OQ4PI.js.map → chunk-EAUGQ3ZU.js.map} +3 -3
- package/dist/chunk-FRBNA6VH.js +13 -0
- package/dist/chunk-FRBNA6VH.js.map +7 -0
- package/dist/chunk-MFHYIQ7B.js +2 -0
- package/dist/chunk-MFHYIQ7B.js.map +7 -0
- package/dist/chunk-UD6VVXUY.js +10 -0
- package/dist/chunk-UD6VVXUY.js.map +7 -0
- package/dist/chunk-Y3RW74TE.js +2 -0
- package/dist/chunk-Y3RW74TE.js.map +7 -0
- package/dist/cli.js +125 -122
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +24 -24
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-3DNKOVPD.js +2 -0
- package/dist/dev-wizard-run-3DNKOVPD.js.map +7 -0
- package/dist/env-load-MF26WMDL.js +2 -0
- package/dist/env-load-MF26WMDL.js.map +7 -0
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +6 -4
- package/dist/chunk-6SLDCUNI.js +0 -2
- package/dist/chunk-6SLDCUNI.js.map +0 -7
- package/dist/chunk-J7KIXQRB.js +0 -12
- package/dist/chunk-J7KIXQRB.js.map +0 -7
- package/dist/chunk-UZTYMT6R.js +0 -7
- package/dist/chunk-UZTYMT6R.js.map +0 -7
- package/dist/dev-wizard-run-QIOXS26F.js +0 -2
- package/dist/dev-wizard-run-QIOXS26F.js.map +0 -7
- /package/dist/{boot-XLDVLQEG.js.map → boot-LC2ESPY6.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
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", "../src/dev/health-probe.ts", "../src/lib/app-release/app-release.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview\n *\n * Shared supervision for the dev-server's long-lived, detached child processes\n * (`turbo watch build`, `turbo run dev`). Both are deep trees\n * (`sh \u2192 pnpm \u2192 node \u2192 turbo \u2192 \u2026`) spawned `detached` so they form their own process\n * group; teardown signals the whole GROUP (`process.kill(-pid, \u2026)`), not just the wrapper.\n *\n * Signalling turbo's group is NOT enough on its own: turbo puts every task it runs\n * (`vite`, `tsc -b`, \u2026) into a process group of its OWN, so `kill(-turboPid, \u2026)` reaches\n * turbo but never its tasks. Turbo normally forwards the signal and reaps them, but when it\n * is slower than the grace window a bare `SIGKILL` on turbo's group kills the only process\n * that knows the task groups \u2014 stranding orphaned vite servers that hold their ports until\n * the next run fails with `EADDRINUSE`.\n *\n * So teardown snapshots the descendant process groups BEFORE signalling (once turbo dies its\n * children reparent to init and can no longer be found by walking `ppid`), waits for the whole\n * set to exit, and only then force-kills whatever is left.\n *\n * The same fact \u2014 reparenting blinds the `ppid` walk \u2014 is why a snapshot taken only at teardown is not\n * enough. When turbo dies on its OWN (a crash, an OOM kill) there is no teardown to snapshot from, and\n * the tasks it never reaped are already unreachable. So the snapshot is instead kept ROLLING for the\n * child's whole life, and each group is stamped with its leader's `lstart`: a pgid is a bare integer the\n * kernel will happily recycle, and the leader's start time is the only proof that the group we are about\n * to SIGKILL is still the one we saw.\n *\n * That rolling snapshot lives in a per-child closure, which is exactly what the SECOND-SIGNAL force path\n * (`killDescendantGroupsNow`, used by both `signal-shutdown`'s force-quit and `crash-barrier`'s fatal\n * path) cannot reach on its own \u2014 it only ever does a live `ppid` walk from `process.pid`, the same walk\n * that goes blind the moment a child dies. So every supervised child's snapshot is also published to a\n * module-level `registry` (see below), letting that force path find a descendant which reparented to init\n * before ITS parent's `exit` even fired \u2014 the one case a live walk structurally cannot cover.\n */\nimport { execFile, execFileSync } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport process from 'node:process'\n\n/** Handle to a supervised child; `kill()` reaps its whole process tree and resolves when gone. */\nexport interface ManagedChild {\n kill: () => Promise<void>\n}\n\n/**\n * Grace before escalating SIGTERM \u2192 SIGKILL. Long enough for turbo to stop its tasks itself\n * (typically well under a second) and short enough that Ctrl-C still feels immediate. Escalating\n * is safe now that every task group is killed as a set, so this need not cover the worst case.\n * The happy path never waits the full window \u2014 teardown returns as soon as the groups are gone.\n */\nconst DEFAULT_GRACE_MS = 5000\n\n/** Poll interval while waiting for the doomed process groups to exit. */\nconst POLL_MS = 100\n\n/** How long to wait for the kernel to reap a group after SIGKILL before giving up on confirmation. */\nconst REAP_TIMEOUT_MS = 2000\n\n/** Absolute path to `ps` \u2014 present on both macOS and Linux, and immune to `PATH` substitution. */\nconst PS_BIN = '/bin/ps'\n\n/**\n * How often the live process table is sampled while a supervised child is alive, to keep\n * {@link ManagedChild}'s group snapshot current. See {@link superviseChild} for why a snapshot taken\n * only at kill-time is too late. Async (`execFile`, not `execFileSync`), so it never blocks the event\n * loop the in-process backends share.\n */\nconst SAMPLE_INTERVAL_MS = 1000\n\n/** `ps` columns: the `ppid` walk needs pid/ppid/pgid, and the reuse guard needs the leader's `lstart`. */\nconst PS_ARGS = ['-eo', 'pid=,ppid=,pgid=,lstart='] as const\n\n/** Cap on `ps` output; a busy machine's full process table stays far below this. */\nconst PS_MAX_BUFFER = 8 << 20\n\n/** One row of `ps -eo pid=,ppid=,pgid=,lstart=`. */\nexport interface ProcRow {\n pid: number\n ppid: number\n pgid: number\n /** The process's start time as `ps` prints it (`Mon Jul 13 13:21:14 2026`); `''` when unavailable. */\n lstart: string\n}\n\n/**\n * The subset of a {@link ProcRow} that describes the process TREE. The `ppid` walk needs nothing else,\n * so the functions that only walk take this \u2014 `lstart` is the reuse guard's concern, not the topology's.\n */\nexport type TopologyRow = Pick<ProcRow, 'pid' | 'ppid' | 'pgid'>\n\n/**\n * Parse `ps -eo pid=,ppid=,pgid=,lstart=`, skipping any line that doesn't start with three integers.\n * `lstart` is whitespace-separated and multi-token, so it is everything after the third column.\n */\nexport const parseProcRows = (raw: string): ProcRow[] => {\n return raw.split('\\n').flatMap((line) => {\n const [rawPid, rawPpid, rawPgid, ...rest] = line.trim().split(/\\s+/)\n\n if (rawPid == null || rawPpid == null || rawPgid == null) return []\n\n const pid = Number(rawPid)\n const ppid = Number(rawPpid)\n const pgid = Number(rawPgid)\n\n if (!Number.isInteger(pid) || !Number.isInteger(ppid) || !Number.isInteger(pgid)) return []\n\n return [{ pid, ppid, pgid, lstart: rest.join(' ') }]\n })\n}\n\n/**\n * A process group, stamped with its LEADER's start time at the moment the group was observed.\n *\n * The start time is the whole point. A pgid on its own is a bare integer: by the time we come to reap\n * it the kernel may have recycled it onto an unrelated process, and `kill(-pgid, \u2026)` would then destroy\n * a stranger's group. The leader's `lstart` is the identity that survives \u2014 a recycled pgid necessarily\n * has a NEWER birth time than the one recorded, so it is refused.\n */\nexport interface GroupSnapshot {\n pgid: number\n leaderStart: string\n}\n\n/** Map every process group in `rows` to its leader's start time (the leader is the pid equal to the pgid). */\nconst leaderStarts = (rows: ProcRow[]): Map<number, string> => {\n const starts = new Map<number, string>()\n\n for (const row of rows) {\n if (row.pid === row.pgid) starts.set(row.pgid, row.lstart)\n }\n\n return starts\n}\n\n/**\n * {@link collectDoomedGroups}, but each group is stamped with its leader's start time so it can be\n * validated later. Groups whose leader is not in `rows` are dropped: with no leader there is nothing to\n * stamp, so nothing could prove the group is still the one we saw, and the reuse guard must fail closed.\n *\n * @example\n * const rows = [\n * { pid: 10, ppid: 1, pgid: 10, lstart: 'Mon Jul 13 13:00:00 2026' },\n * { pid: 20, ppid: 10, pgid: 20, lstart: 'Mon Jul 13 13:00:01 2026' },\n * ]\n * snapshotGroups(10, rows) // => [{ pgid: 10, leaderStart: '\u202613:00:00\u2026' }, { pgid: 20, leaderStart: '\u202613:00:01\u2026' }]\n */\nexport const snapshotGroups = (rootPid: number, rows: ProcRow[], excludePgid?: number): GroupSnapshot[] => {\n const starts = leaderStarts(rows)\n\n return collectDoomedGroups(rootPid, rows, excludePgid).flatMap((pgid) => {\n const leaderStart = starts.get(pgid)\n\n if (leaderStart == null || leaderStart === '') return []\n\n return [{ pgid, leaderStart }]\n })\n}\n\n/**\n * pgids in `snapshot` whose leader's start time still matches `rows` \u2014 the reuse guard shared by every\n * path that reaps from a snapshot instead of a live walk: {@link reapSnapshot} (the per-child crash/kill\n * reap) and {@link collectForceReapTargets} (the force-reap path, reaping every REGISTERED child's\n * snapshot). Extracted so the two can never drift apart \u2014 a registry-sourced pgid must clear the exact\n * same check a per-child reap does before either signals it.\n */\nconst validSnapshotPgids = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n const starts = leaderStarts(rows)\n\n return snapshot.flatMap(({ pgid, leaderStart }) => {\n return starts.get(pgid) === leaderStart ? [pgid] : []\n })\n}\n\n/**\n * SIGKILL every snapshotted group whose leader is STILL the same process, and return the pgids killed.\n *\n * A group whose leader has since exited is skipped (nothing to kill, and no way to prove ownership of\n * whatever else may share the pgid). A group whose leader's start time no longer matches is a recycled\n * pgid belonging to a stranger \u2014 skipped, loudly and deliberately. This is the guard that makes reaping\n * from a stale snapshot safe, and it is why the snapshot records `lstart` at all.\n */\nexport const reapSnapshot = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n return validSnapshotPgids(snapshot, rows).flatMap((pgid) => {\n try {\n process.kill(-pgid, 'SIGKILL')\n } catch {\n // Raced us to exit (ESRCH) \u2014 nothing to kill.\n return []\n }\n\n return [pgid]\n })\n}\n\n/**\n * Distinct process groups of every transitive descendant of `rootPid`, plus `rootPid`'s own\n * group. Group `0`/`1` and `excludePgid` (our own group \u2014 a detached child can never share it,\n * but a mis-parsed row must never make us signal ourselves) are filtered out.\n *\n * @example\n * const rows = [{ pid: 10, ppid: 1, pgid: 10 }, { pid: 20, ppid: 10, pgid: 20 }]\n * collectDoomedGroups(10, rows, 5) // => [10, 20]\n */\nexport const collectDoomedGroups = (rootPid: number, rows: TopologyRow[], excludePgid?: number): number[] => {\n const childrenOf = new Map<number, TopologyRow[]>()\n\n for (const row of rows) {\n const siblings = childrenOf.get(row.ppid)\n\n if (siblings) siblings.push(row)\n else childrenOf.set(row.ppid, [row])\n }\n\n const groups = new Set<number>([rootPid])\n const seen = new Set<number>([rootPid])\n const queue = [rootPid]\n\n for (let i = 0; i < queue.length; i += 1) {\n for (const child of childrenOf.get(queue[i] ?? -1) ?? []) {\n if (seen.has(child.pid)) continue\n seen.add(child.pid)\n groups.add(child.pgid)\n queue.push(child.pid)\n }\n }\n\n return [...groups].filter((pgid) => {\n return pgid > 1 && pgid !== excludePgid\n })\n}\n\n/**\n * Snapshot the live process table; an empty list on failure degrades to group-only teardown.\n * `ps` is invoked by absolute path (not via `PATH`, unlike the `pnpm` the engines shell out to)\n * so a writable `PATH` entry can never substitute the binary we hand a kill list to.\n */\nconst snapshotProcRows = (): ProcRow[] => {\n try {\n return parseProcRows(execFileSync(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }))\n } catch {\n return []\n }\n}\n\n/**\n * {@link snapshotProcRows}, off the event loop. The rolling sampler runs on a timer for the whole life\n * of a dev session, and the in-process backends share this loop \u2014 a synchronous `ps` every second would\n * stall every request that lands during it. Resolves to `[]` on failure, degrading to the previous\n * snapshot rather than clobbering it.\n */\nconst snapshotProcRowsAsync = async (): Promise<ProcRow[]> => {\n return new Promise((resolve) => {\n execFile(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }, (error, stdout) => {\n resolve(error ? [] : parseProcRows(stdout))\n })\n })\n}\n\n/** Does `pid` currently exist and name a direct child of `parentPid`? Guards against pid reuse. */\nexport const isChildOf = (pid: number, parentPid: number, rows: TopologyRow[]): boolean => {\n return rows.some((row) => {\n return row.pid === pid && row.ppid === parentPid\n })\n}\n\n/**\n * The groups to signal for `rootPid`'s tree, excluding our own group so a mis-parsed `ps` row can\n * never make the dev-server signal itself.\n */\nconst doomedGroupsOf = (rootPid: number, rows: ProcRow[]): number[] => {\n const ownPgid = rows.find((row) => {\n return row.pid === process.pid\n })?.pgid\n\n return collectDoomedGroups(rootPid, rows, ownPgid)\n}\n\n/** Is the process group led by `pgid` still alive? (`kill(-pgid, 0)` throws ESRCH when gone.) */\nconst groupAlive = (pgid: number): boolean => {\n try {\n process.kill(-pgid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\n/** Send `signal` to every named process group, ignoring groups that already exited. */\nconst signalGroups = (pgids: number[], signal: NodeJS.Signals): void => {\n for (const pgid of pgids) {\n try {\n process.kill(-pgid, signal)\n } catch {\n // Already gone (ESRCH) \u2014 nothing to signal.\n }\n }\n}\n\n/**\n * Live accessors into every currently-supervised child's rolling {@link GroupSnapshot} list \u2014 populated by\n * {@link superviseChild} on spawn, removed only once that child's own groups are CONFIRMED gone (see\n * `deregisterAfter` inside it, not the child's bare `exit` event). This is what lets\n * {@link killDescendantGroupsNow} \u2014 the second-signal force path and the crash-barrier's fatal path \u2014\n * reach a descendant that reparented to init before ITS parent's `exit` fired: a live `ppid` walk from\n * `process.pid` cannot see such a descendant (see the module doc block for why), but a snapshot recorded\n * while the parent was still alive can.\n *\n * INVARIANT \u2014 never regress this: a registry-sourced pgid is signalled ONLY after\n * {@link validSnapshotPgids} confirms its leader's start time still matches a FRESH `ps` snapshot. An\n * ungated union would SIGKILL a recycled pgid \u2014 a hazard the live walk cannot have, since it only ever\n * names processes that are alive right now.\n */\nconst registry = new Set<() => readonly GroupSnapshot[]>()\n\n/**\n * The pgids {@link killDescendantGroupsNow} should signal: every group in the live `ppid` walk from\n * `rootPid` (unchanged semantics \u2014 see {@link doomedGroupsOf}), UNIONED with every registry-sourced\n * snapshot that survives {@link validSnapshotPgids} against the same `rows`. Live-walk pgids are not\n * lstart-gated \u2014 they carry no snapshot to validate against, and are live by construction; only the\n * registry-sourced half needs the reuse guard.\n *\n * Pulled out of `killDescendantGroupsNow` as a pure function so the union/dedupe logic can be tested\n * against a fake process table and fake registry snapshots, without spawning real processes or waiting on\n * a real `ps`.\n *\n * @example\n * // pgid 20 is unreachable from rootPid (reparented to init) but was recorded before its parent died.\n * collectForceReapTargets(1000, freshRows, [[{ pgid: 20, leaderStart: '\u2026' }]]) // => [20]\n */\nexport const collectForceReapTargets = (\n rootPid: number,\n rows: ProcRow[],\n registrySnapshots: readonly (readonly GroupSnapshot[])[],\n): number[] => {\n const live = doomedGroupsOf(rootPid, rows)\n 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", "/**\n * @fileoverview\n * Loopback liveness probes for the apps `infra-kit dev` runs: a backend's `/__health`, a UI's vite ping.\n * Shared by the dev panel's health dots and by `infra-kit e2e`, which must agree on what \"up\" means.\n */\n\n/** What a probe is aimed at. `kind` picks the endpoint AND the verdict rules \u2014 the two are not separable. */\nexport interface ProbeTarget {\n /** Stream tag (`<app>/api`, `<app>/ui`) \u2014 the key the health map and every log line agree on. */\n tag: string\n /** The port to probe: a backend's ACTUAL bound port, or a UI's runner-assigned vite port. */\n port: number\n kind: 'api' | 'ui'\n}\n\n/**\n * Something answered, but not the thing we asked for \u2014 and WHAT it answered is the whole diagnostic.\n *\n * A UI's `foreign` never paints red (see {@link ProbeOutcome}), so this line is the only thing the user\n * gets, and \"not vite's ping\" alone cannot separate the three causes it exists to tell apart: a\n * `200 text/html` means vite dropped the ping and infra-kit must ship a fix; a `502` means portless or a\n * proxy is shadowing the port; a `404` means a squatter won the free-port race. One glance, three very\n * different next moves \u2014 so the status and content-type travel with the verdict.\n */\nexport interface ForeignAnswer {\n kind: 'foreign'\n status: number\n contentType: string | null\n}\n\n/**\n * Three outcomes, not a boolean:\n * - `ok` \u2014 the endpoint PROVED it is serving (a 2xx on `/__health`; a 204 on vite's ping).\n * - `refused` \u2014 nothing answered (ECONNREFUSED, timeout, transport error).\n * - {@link ForeignAnswer} \u2014 something answered, but not the thing we asked for. For a backend that is a\n * failure (our own fastify returning non-2xx). For a UI it is NOT: a non-204 is equally consistent with a\n * squatter, with a proxy that shadows the ping, and with a future vite that dropped it \u2014 so it can never\n * be allowed to paint red, and it is the reason this is not a boolean.\n */\nexport type ProbeOutcome = 'ok' | 'refused' | ForeignAnswer\n\n/** Narrow a {@link ProbeOutcome} to the one arm that carries data. */\nexport const isForeign = (outcome: ProbeOutcome): outcome is ForeignAnswer => {\n return typeof outcome === 'object'\n}\n\n/** Build the `foreign` verdict from the response that earned it, draining its body so the socket returns. */\nconst foreignFrom = async (res: Response): Promise<ForeignAnswer> => {\n await res.body?.cancel()\n\n return { kind: 'foreign', status: res.status, contentType: res.headers.get('content-type') }\n}\n\n/**\n * The `\u25CD ?` warn. Names what answered instead of vite, because that is the whole actionable content: an\n * `html` body means vite dropped the ping (ours to fix), a 5xx means something is shadowing the port, a 404\n * means a squatter took it. The content-type is trimmed of its `; charset=\u2026` tail \u2014 it is a hint, not a\n * header dump.\n */\nexport const describeForeign = (port: number, answer: ForeignAnswer): string => {\n const type = answer.contentType?.split(';')[0]?.trim()\n const what = type == null || type === '' ? `${answer.status}` : `${answer.status} ${type}`\n\n return `port ${port} answered ${what}, not vite's ping \u2014 liveness cannot be verified`\n}\n\n/** Health-probe seam: resolve one target's liveness. Injectable so the panel stays deterministic in tests. */\nexport type HealthProbe = (target: ProbeTarget) => Promise<ProbeOutcome>\n\n/** One budget for the whole probe \u2014 BOTH hops of a UI redirect share it (see {@link probeUi}). */\nconst PROBE_TIMEOUT_MS = 1500\n\n/**\n * Vite's HMR ping. It is installed unconditionally on every dev server (no plugin, no config) and it sits\n * AHEAD of vite's `htmlFallback` middleware \u2014 which is the whole point: `htmlFallback` answers a plain\n * `GET /` with `200 index.html` even for a vite whose entry module throws, so a naive GET would report a\n * broken app as healthy. The ping cannot be forged that way; a 204 means a vite dev server is listening.\n */\nconst VITE_PING_HEADERS = { accept: 'text/x-vite-ping' } as const\n\n/**\n * Where a target is probed. Always `http://127.0.0.1:<port>`, never the `https://<alias>` the panel prints:\n * the alias adds TLS, a private CA and the portless daemon to the path, so a probe through it would report\n * the PROXY's health, not the app's. And never `localhost` \u2014 ServerlessLocalRun binds v4 loopback only,\n * while `localhost` resolves `[::1]` first on modern Node, which renders a healthy backend `\u25CF down`.\n */\nconst probeUrl = (target: ProbeTarget): string => {\n return target.kind === 'api' ? `http://127.0.0.1:${target.port}/__health` : `http://127.0.0.1:${target.port}/`\n}\n\n/** `new URL(loc, base)`, or `null` when the header is unparseable even relative to the probe URL. */\nconst resolveHop = (location: string, base: string): URL | null => {\n try {\n return new URL(location, base)\n } catch {\n return null\n }\n}\n\n/** A backend: `/__health` must answer 2xx. Anything else IS our own fastify failing, so it is not `ok`. */\nconst probeApi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { signal })\n\n if (!res.ok) return foreignFrom(res)\n // Drain: undici keeps the socket checked out until an unread body is GC'd, and this runs every 5s per app\n // for the life of the session.\n await res.body?.cancel()\n\n return 'ok'\n}\n\n/**\n * A frontend: vite's ping must answer 204.\n *\n * The redirect hop is the delicate part. Vite serves the ping from its `base`, so a UI configured with\n * `base: '/app/'` answers `/` with a 3xx whose `Location` is RELATIVE (`/app/`) \u2014 which is why the hop is\n * resolved against the probe URL rather than parsed on its own (`new URL('/app/')` throws outright). The\n * accept header is RE-SENT on the second hop: without it the redirected request falls through to vite's\n * html fallback and comes back `200 text/html` \u2014 the exact false green this probe exists to refuse.\n *\n * Exactly one hop, same-origin only. A cross-origin redirect is somebody else's server, and a second hop\n * is a loop we have no budget for; both report `foreign` \u2014 never followed, and never called alive.\n */\nconst probeUi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (res.status === 204) return 'ok'\n if (res.status < 300 || res.status >= 400) return foreignFrom(res)\n\n const location = res.headers.get('location')\n const next = location == null ? null : resolveHop(location, url)\n\n if (next == null || next.origin !== new URL(url).origin) return foreignFrom(res)\n\n await res.body?.cancel()\n\n const hop = await fetch(next, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (hop.status !== 204) return foreignFrom(hop)\n await hop.body?.cancel()\n\n return 'ok'\n}\n\n/** Default probe: per-kind, bounded, and loopback-only. A transport error or a timeout is `refused`. */\nexport const defaultHealthProbe: HealthProbe = async (target: ProbeTarget): Promise<ProbeOutcome> => {\n const url = probeUrl(target)\n // ONE signal, shared across both hops: a redirect must not double the budget a wedged server can spend.\n const signal = AbortSignal.timeout(PROBE_TIMEOUT_MS)\n\n try {\n return target.kind === 'api' ? await probeApi(url, signal) : await probeUi(url, signal)\n } catch {\n return 'refused'\n }\n}\n", "import { DEFAULT_RELEASE_SLUG, slugifyRelease } from '@slip-stream-kit/config/internal'\nimport { execFileSync } from 'node:child_process'\n\n/**\n * Slugified `<release>` for the app's git branch (resolved from the app's own dir), falling back to\n * {@link DEFAULT_RELEASE_SLUG} outside a git repo / on an empty slug. Never throws.\n *\n * A release ALWAYS resolves because it is the first DNS label of every alias, and every app is reached\n * by hostname. The fallback cannot collide the way a branch can: worktrees are what make two checkouts\n * coexist, and a worktree is by definition inside a git repo.\n */\n// Shared by the dev runner, which registers `<release>.<package>.localhost`, and `e2e`, which must name\n// that exact host \u2014 one derivation, or a test run probes an alias nobody registered.\nexport const readAppRelease = (cwd: string): string => {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, encoding: 'utf-8' }).trim()\n const slug = slugifyRelease(branch)\n\n return slug === '' ? DEFAULT_RELEASE_SLUG : slug\n } catch {\n return DEFAULT_RELEASE_SLUG\n }\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,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K,EAAI,QAAQ,IAAI,UAAU,EACrCG,EAAOR,GAAY,KAAO,KAAOD,GAAWC,EAAUG,CAAG,EAE/D,GAAIK,GAAQ,MAAQA,EAAK,SAAW,IAAI,IAAIL,CAAG,EAAE,OAAQ,OAAOG,EAAYD,CAAG,EAE/E,MAAMA,EAAI,MAAM,OAAO,EAEvB,IAAMI,EAAM,MAAM,MAAMD,EAAM,CAAE,QAASZ,GAAmB,SAAU,SAAU,OAAAQ,CAAO,CAAC,EAExF,OAAIK,EAAI,SAAW,IAAYH,EAAYG,CAAG,GAC9C,MAAMA,EAAI,MAAM,OAAO,EAEhB,KACT,EAGaC,GAAkC,MAAOZ,GAA+C,CACnG,IAAMK,EAAMN,GAASC,CAAM,EAErBM,EAAS,YAAY,QAAQ,IAAgB,EAEnD,GAAI,CACF,OAAON,EAAO,OAAS,MAAQ,MAAMI,GAASC,EAAKC,CAAM,EAAI,MAAMG,GAAQJ,EAAKC,CAAM,CACxF,MAAQ,CACN,MAAO,SACT,CACF,EC3JA,OAAS,wBAAAO,GAAsB,kBAAAC,OAAsB,mCACrD,OAAS,gBAAAC,OAAoB,qBAYtB,IAAMC,GAAkBC,GAAwB,CACrD,GAAI,CAEF,IAAMC,EAASH,GAAa,MAAO,CAAC,YAAa,eAAgB,MAAM,EAAG,CAAE,IAAAE,EAAK,SAAU,OAAQ,CAAC,EAAE,KAAK,EACrGE,EAAOL,GAAeI,CAAM,EAElC,OAAOC,IAAS,GAAKN,GAAuBM,CAC9C,MAAQ,CACN,OAAON,EACT,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", "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", "isForeign", "outcome", "foreignFrom", "res", "describeForeign", "port", "answer", "type", "what", "VITE_PING_HEADERS", "probeUrl", "target", "resolveHop", "location", "base", "probeApi", "url", "signal", "res", "foreignFrom", "probeUi", "next", "hop", "defaultHealthProbe", "
|
|
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", "/**\n * @fileoverview\n * Loopback liveness probes for the apps `infra-kit dev` runs: a backend's `/__health`, a UI's vite ping.\n * Shared by the dev panel's health dots and by `infra-kit e2e`, which must agree on what \"up\" means.\n */\n\n/** What a probe is aimed at. `kind` picks the endpoint AND the verdict rules \u2014 the two are not separable. */\nexport interface ProbeTarget {\n /** Stream tag (`<app>/api`, `<app>/ui`) \u2014 the key the health map and every log line agree on. */\n tag: string\n /** The port to probe: a backend's ACTUAL bound port, or a UI's runner-assigned vite port. */\n port: number\n kind: 'api' | 'ui'\n}\n\n/**\n * Something answered, but not the thing we asked for \u2014 and WHAT it answered is the whole diagnostic.\n *\n * A UI's `foreign` never paints red (see {@link ProbeOutcome}), so this line is the only thing the user\n * gets, and \"not vite's ping\" alone cannot separate the three causes it exists to tell apart: a\n * `200 text/html` means vite dropped the ping and infra-kit must ship a fix; a `502` means portless or a\n * proxy is shadowing the port; a `404` means a squatter won the free-port race. One glance, three very\n * different next moves \u2014 so the status and content-type travel with the verdict.\n */\nexport interface ForeignAnswer {\n kind: 'foreign'\n status: number\n contentType: string | null\n}\n\n/**\n * Three outcomes, not a boolean:\n * - `ok` \u2014 the endpoint PROVED it is serving (a 2xx on `/__health`; a 204 on vite's ping).\n * - `refused` \u2014 nothing answered (ECONNREFUSED, timeout, transport error).\n * - {@link ForeignAnswer} \u2014 something answered, but not the thing we asked for. For a backend that is a\n * failure (our own fastify returning non-2xx). For a UI it is NOT: a non-204 is equally consistent with a\n * squatter, with a proxy that shadows the ping, and with a future vite that dropped it \u2014 so it can never\n * be allowed to paint red, and it is the reason this is not a boolean.\n */\nexport type ProbeOutcome = 'ok' | 'refused' | ForeignAnswer\n\n/** Narrow a {@link ProbeOutcome} to the one arm that carries data. */\nexport const isForeign = (outcome: ProbeOutcome): outcome is ForeignAnswer => {\n return typeof outcome === 'object'\n}\n\n/** Build the `foreign` verdict from the response that earned it, draining its body so the socket returns. */\nconst foreignFrom = async (res: Response): Promise<ForeignAnswer> => {\n await res.body?.cancel()\n\n return { kind: 'foreign', status: res.status, contentType: res.headers.get('content-type') }\n}\n\n/**\n * The `\u25CD ?` warn. Names what answered instead of vite, because that is the whole actionable content: an\n * `html` body means vite dropped the ping (ours to fix), a 5xx means something is shadowing the port, a 404\n * means a squatter took it. The content-type is trimmed of its `; charset=\u2026` tail \u2014 it is a hint, not a\n * header dump.\n */\nexport const describeForeign = (port: number, answer: ForeignAnswer): string => {\n const type = answer.contentType?.split(';')[0]?.trim()\n const what = type == null || type === '' ? `${answer.status}` : `${answer.status} ${type}`\n\n return `port ${port} answered ${what}, not vite's ping \u2014 liveness cannot be verified`\n}\n\n/** Health-probe seam: resolve one target's liveness. Injectable so the panel stays deterministic in tests. */\nexport type HealthProbe = (target: ProbeTarget) => Promise<ProbeOutcome>\n\n/** One budget for the whole probe \u2014 BOTH hops of a UI redirect share it (see {@link probeUi}). */\nconst PROBE_TIMEOUT_MS = 1500\n\n/**\n * Vite's HMR ping. It is installed unconditionally on every dev server (no plugin, no config) and it sits\n * AHEAD of vite's `htmlFallback` middleware \u2014 which is the whole point: `htmlFallback` answers a plain\n * `GET /` with `200 index.html` even for a vite whose entry module throws, so a naive GET would report a\n * broken app as healthy. The ping cannot be forged that way; a 204 means a vite dev server is listening.\n */\nconst VITE_PING_HEADERS = { accept: 'text/x-vite-ping' } as const\n\n/**\n * Where a target is probed. Always `http://127.0.0.1:<port>`, never the `https://<alias>` the panel prints:\n * the alias adds TLS, a private CA and the portless daemon to the path, so a probe through it would report\n * the PROXY's health, not the app's. And never `localhost` \u2014 ServerlessLocalRun binds v4 loopback only,\n * while `localhost` resolves `[::1]` first on modern Node, which renders a healthy backend `\u25CF down`.\n */\nconst probeUrl = (target: ProbeTarget): string => {\n return target.kind === 'api' ? `http://127.0.0.1:${target.port}/__health` : `http://127.0.0.1:${target.port}/`\n}\n\n/** `new URL(loc, base)`, or `null` when the header is unparseable even relative to the probe URL. */\nconst resolveHop = (location: string, base: string): URL | null => {\n try {\n return new URL(location, base)\n } catch {\n return null\n }\n}\n\n/** A backend: `/__health` must answer 2xx. Anything else IS our own fastify failing, so it is not `ok`. */\nconst probeApi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { signal })\n\n if (!res.ok) return foreignFrom(res)\n // Drain: undici keeps the socket checked out until an unread body is GC'd, and this runs every 5s per app\n // for the life of the session.\n await res.body?.cancel()\n\n return 'ok'\n}\n\n/**\n * A frontend: vite's ping must answer 204.\n *\n * The redirect hop is the delicate part. Vite serves the ping from its `base`, so a UI configured with\n * `base: '/app/'` answers `/` with a 3xx whose `Location` is RELATIVE (`/app/`) \u2014 which is why the hop is\n * resolved against the probe URL rather than parsed on its own (`new URL('/app/')` throws outright). The\n * accept header is RE-SENT on the second hop: without it the redirected request falls through to vite's\n * html fallback and comes back `200 text/html` \u2014 the exact false green this probe exists to refuse.\n *\n * Exactly one hop, same-origin only. A cross-origin redirect is somebody else's server, and a second hop\n * is a loop we have no budget for; both report `foreign` \u2014 never followed, and never called alive.\n */\nconst probeUi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (res.status === 204) return 'ok'\n if (res.status < 300 || res.status >= 400) return foreignFrom(res)\n\n const location = res.headers.get('location')\n const next = location == null ? null : resolveHop(location, url)\n\n if (next == null || next.origin !== new URL(url).origin) return foreignFrom(res)\n\n await res.body?.cancel()\n\n const hop = await fetch(next, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (hop.status !== 204) return foreignFrom(hop)\n await hop.body?.cancel()\n\n return 'ok'\n}\n\n/** Default probe: per-kind, bounded, and loopback-only. A transport error or a timeout is `refused`. */\nexport const defaultHealthProbe: HealthProbe = async (target: ProbeTarget): Promise<ProbeOutcome> => {\n const url = probeUrl(target)\n // ONE signal, shared across both hops: a redirect must not double the budget a wedged server can spend.\n const signal = AbortSignal.timeout(PROBE_TIMEOUT_MS)\n\n try {\n return target.kind === 'api' ? await probeApi(url, signal) : await probeUi(url, signal)\n } catch {\n return 'refused'\n }\n}\n", "import { readRelease } from '@slip-stream-kit/config/internal'\n\n/**\n * Slugified `<release>` for the app's git branch (resolved from the app's own dir), falling back to\n * `DEFAULT_RELEASE_SLUG` outside a git repo / on an empty slug. Never throws.\n *\n * A release ALWAYS resolves because it is the first DNS label of every alias, and every app is reached\n * by hostname. The fallback cannot collide the way a branch can: worktrees are what make two checkouts\n * coexist, and a worktree is by definition inside a git repo. One implementation, in the config package,\n * because the vite and Playwright helpers must name the same host.\n */\nexport const readAppRelease = (cwd: string): string => {\n return readRelease(cwd)\n}\n"],
|
|
5
|
+
"mappings": "8FAiCA,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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AK,CAAE,QAASP,GAAmB,SAAU,SAAU,OAAAQ,CAAO,CAAC,EAEvF,GAAIC,EAAI,SAAW,IAAK,MAAO,KAC/B,GAAIA,EAAI,OAAS,KAAOA,EAAI,QAAU,IAAK,OAAOC,EAAYD,CAAG,EAEjE,IAAML,EAAWK,EAAI,QAAQ,IAAI,UAAU,EACrCG,EAAOR,GAAY,KAAO,KAAOD,GAAWC,EAAUG,CAAG,EAE/D,GAAIK,GAAQ,MAAQA,EAAK,SAAW,IAAI,IAAIL,CAAG,EAAE,OAAQ,OAAOG,EAAYD,CAAG,EAE/E,MAAMA,EAAI,MAAM,OAAO,EAEvB,IAAMI,EAAM,MAAM,MAAMD,EAAM,CAAE,QAASZ,GAAmB,SAAU,SAAU,OAAAQ,CAAO,CAAC,EAExF,OAAIK,EAAI,SAAW,IAAYH,EAAYG,CAAG,GAC9C,MAAMA,EAAI,MAAM,OAAO,EAEhB,KACT,EAGaC,GAAkC,MAAOZ,GAA+C,CACnG,IAAMK,EAAMN,GAASC,CAAM,EAErBM,EAAS,YAAY,QAAQ,IAAgB,EAEnD,GAAI,CACF,OAAON,EAAO,OAAS,MAAQ,MAAMI,GAASC,EAAKC,CAAM,EAAI,MAAMG,GAAQJ,EAAKC,CAAM,CACxF,MAAQ,CACN,MAAO,SACT,CACF,EC3JA,OAAS,eAAAO,OAAmB,mCAWrB,IAAMC,GAAkBC,GACtBF,GAAYE,CAAG",
|
|
6
|
+
"names": ["execFile", "execFileSync", "process", "DEFAULT_GRACE_MS", "POLL_MS", "REAP_TIMEOUT_MS", "PS_BIN", "SAMPLE_INTERVAL_MS", "PS_ARGS", "PS_MAX_BUFFER", "parseProcRows", "raw", "line", "rawPid", "rawPpid", "rawPgid", "rest", "pid", "ppid", "pgid", "leaderStarts", "rows", "starts", "row", "snapshotGroups", "rootPid", "excludePgid", "collectDoomedGroups", "leaderStart", "validSnapshotPgids", "snapshot", "reapSnapshot", "childrenOf", "siblings", "groups", "seen", "queue", "i", "child", "snapshotProcRows", "snapshotProcRowsAsync", "resolve", "error", "stdout", "isChildOf", "parentPid", "doomedGroupsOf", "ownPgid", "groupAlive", "signalGroups", "pgids", "signal", "registry", "collectForceReapTargets", "registrySnapshots", "live", "fromRegistry", "killDescendantGroupsNow", "getGroups", "sleep", "ms", "waitForExit", "timeoutMs", "deadline", "alive", "superviseChild", "graceMs", "onUnexpectedExit", "snapshotRowsOverride", "killing", "exited", "sampler", "stopSampling", "deregisterAfter", "g", "applySample", "next", "sample", "reportUnexpected", "detail", "code", "doomed", "stragglers", "late", "forced", "constants", "process", "HANDLED_SIGNALS", "SIGNAL_NUMBERS", "constants", "FALLBACK_SIGNO", "exitCodeForSignal", "signal", "TEARDOWN_DEADLINE_MS", "defaultExit", "code", "process", "defaultRegister", "handler", "defaultUnregister", "defaultSetTimer", "ms", "timer", "writeStderr", "message", "writeTeardownFailure", "error", "detail", "registerSignalShutdown", "onSignal", "exit", "register", "unregister", "forceReap", "killDescendantGroupsNow", "teardownDeadlineMs", "setTimer", "describeStall", "fileReport", "firstSignal", "cancelDeadline", "handlers", "detach", "handle", "report", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause", "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", "isForeign", "outcome", "foreignFrom", "res", "describeForeign", "port", "answer", "type", "what", "VITE_PING_HEADERS", "probeUrl", "target", "resolveHop", "location", "base", "probeApi", "url", "signal", "res", "foreignFrom", "probeUi", "next", "hop", "defaultHealthProbe", "readRelease", "readAppRelease", "cwd"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{a as ie}from"./chunk-MFAFQVTW.js";import{a as ne}from"./chunk-MFHYIQ7B.js";import{d as N,p as re,q as oe}from"./chunk-QSTGO43H.js";import Fe from"node:process";import De from"node:process";var S={enabled:!1},We=(e,t=r=>{De.stdout.write(r)})=>(S.enabled&&e&&e.structuredContent!=null&&t(`${JSON.stringify(e.structuredContent,null,2)}
|
|
2
|
+
`),e),se=e=>{e.options.some(r=>r.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(se)};var ae={source:null},w=()=>ae.source!==null,qe=()=>w()||S.enabled,_=()=>!!Fe.env.CI,Ge=({env:e,stdinIsTTY:t,flag:r})=>{if(r)return"flag";let o=e.INFRA_KIT_AGENT;return o==="1"||e.CLAUDECODE!==void 0&&!t&&o!=="0"?"env":null};var x=e=>{let t=new Set,r=e;for(;r!==null&&typeof r=="object"&&!t.has(r);){t.add(r);let{stderr:o,stderrExcerpt:n}=r;if(typeof o=="string"&&o.length>0)return o;if(typeof n=="string"&&n.length>0)return n;r=r.cause}},Be=(e,t)=>{let r=t.stderrExcerpt??x(e),o=[`failed to ${t.operation}`];return r&&o.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&o.push(`try: ${t.remediation}`),o.join(" \u2014 ")},u=class extends Error{operation;remediation;stderrExcerpt;constructor(t,r){super(Be(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation,this.stderrExcerpt=r.stderrExcerpt??x(t)}};import k from"node:path";import le from"node:process";import{$ as m}from"zx";var ze=/^v?(\d+)\.(\d+)\.(\d+)$/,Ue=/^(\d+)\.(\d+)\.(\d+)$/,He=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,I="release/",T="release/v",ce="refs/heads/",Ve="next";var ue=new Set(["dev","main","next","hotfix","regular","release"]),g=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},h=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},pe=e=>e.startsWith(ce)?e.slice(ce.length):e,de=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),L=e=>{if(e.length===0)throw new g('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new g(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!He.test(e))throw new g(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(ue.has(e))throw new g(`Release name "${e}" is reserved. Reserved names: ${[...ue].join(", ")}.`)},K=e=>{let t=pe(e.trim());if(!t.startsWith(I))return null;if(t.startsWith(T)){let o=t.slice(T.length),n=Ue.exec(o);if(n)return de(Number(n[1]),Number(n[2]),Number(n[3]))}let r=t.slice(I.length);try{L(r)}catch{return null}return{kind:"name",name:r,raw:r}},Je=e=>{let t=e.trim();if(pe(t).startsWith(I)){let n=K(t);if(!n)throw new h(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return n}let o=ze.exec(t);if(o)return de(Number(o[1]),Number(o[2]),Number(o[3]));if(t.toLowerCase()===Ve)throw new h('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');if(t.includes("@"))throw new h(`Cannot parse "${e}" as a release ref: the \`@date\` suffix belongs to \`release create\`; pass the version alone here and use \`--release-date\` on \`release edit\``);try{L(t)}catch(n){let s=n instanceof Error?n.message:String(n);throw new h(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:t,raw:t}},Xe=e=>e.kind==="version"?`${T}${e.raw}`:`${I}${e.name}`,Ye=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},Ze=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,Qe=e=>e.kind==="version"?`v${e.raw}`:e.name,et=e=>e.raw,D=e=>e==null?!1:K(e)!==null,me=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},tt=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let o=me(r?.a),n=me(r?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<t.name?-1:e.name>t.name?1:0};var fe=async e=>{let t=await m({cwd:e})`git worktree list --porcelain`,r=[],o=null;for(let n of t.stdout.split(`
|
|
3
|
+
`)){if(n.startsWith("worktree ")){o&&r.push(o),o={path:n.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}o&&(n.startsWith("branch ")?o.branch=n.slice(7).replace(/^refs\/heads\//,""):n==="detached"?o.detached=!0:n==="bare"?o.bare=!0:n==="locked"||n.startsWith("locked ")?o.locked=!0:(n==="prunable"||n.startsWith("prunable "))&&(o.prunable=!0))}return o&&r.push(o),r},rt=async e=>{let t=await fe(le.cwd()),r=o=>e==="release"?D(o):o.startsWith("feature/");return t.map(o=>o.branch).filter(o=>o!==null&&r(o))},ot=e=>{let t=x(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},nt=({hasStderr:e})=>{if(w())return"infra-kit resolves its project from the working directory; run it from inside an infra-kit project repo (or one of its git worktrees), or pass `-C <dir>` naming one";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},R=async()=>{try{return(await m({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=ot(e)??x(e);throw new u(e,{operation:`resolve the project root from ${le.cwd()}`,stderrExcerpt:t,remediation:nt({hasStderr:t!==void 0})})}},W=async e=>{let t=e??await R(),r=(await m({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),o=k.resolve(t,r);return o.includes(`${k.sep}.git${k.sep}modules${k.sep}`)?t:k.dirname(o)},ge=async()=>(await m`git rev-parse --abbrev-ref HEAD`).stdout.trim(),he=async()=>(await m`git status --porcelain`).stdout.split(`
|
|
4
|
+
`).map(t=>t.trimEnd()).filter(t=>t.trim().length>0),it=async()=>(await he()).length===0,st=async()=>{let e=await R(),[t,r]=await Promise.all([m({cwd:e})`git rev-parse --absolute-git-dir`,m({cwd:e})`git rev-parse --git-common-dir`]),o=t.stdout.trim(),n=k.resolve(e,r.stdout.trim());return o!==n};var at=async e=>(await m`git branch --list ${e}`).stdout.trim().length>0,ct=async e=>{(await m`git branch --list ${e}`).stdout.trim().length!==0&&await ge()!==e&&await m`git branch -D ${e}`},ut=async e=>{(await m`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await m`git push origin --delete ${e}`};import{$ as P}from"zx";var mt=async(e,t)=>{let r=`${t}^{commit}`;try{return(await P({cwd:e,quiet:!0})`git rev-parse --verify --quiet ${r}`).stdout.trim()||null}catch{return null}},pt=async(e,t,r)=>{try{return await P({cwd:e,quiet:!0})`git merge-base --is-ancestor ${t} ${r}`,!0}catch(o){if(o.exitCode===1)return!1;throw new u(o,{operation:`test whether ${t} is contained in ${r}`,remediation:"both refs must exist \u2014 verify them with rev-parse first"})}},dt=async(e,t)=>{let o=(await P({cwd:e,quiet:!0})`git ls-remote --heads origin ${t}`).stdout.trim().split(`
|
|
5
|
+
`)[0];return o?o.split(/\s+/)[0]??null:null},lt=async(e,t)=>{let r=t.map(o=>`${o.sha}:refs/heads/${o.branch}`);if(r.length===0)return{refspecs:r,pushed:!1};try{return await P({cwd:e,quiet:!0})`git push --atomic origin ${r}`,{refspecs:r,pushed:!0}}catch(o){return{refspecs:r,pushed:!1,stderr:o.stderr}}};import q from"node:path";import F from"node:process";import{$ as p}from"zx";var ye=async e=>{let t=e??F.cwd(),r=(await p({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),o=F.env.INFRA_KIT_SESSION||String(F.pid);return q.join(q.resolve(t,r),"infra-kit",`merge-dev-${o}`)},we=e=>e.replace(/[^\w-]+/g,"-"),ft=(e,t)=>q.join(`${e}${re}`,oe.mergeDev,we(t)),G=async e=>{try{return await p({cwd:e,quiet:!0})`git rev-parse -q --verify MERGE_HEAD`,!0}catch{return!1}},gt=async e=>{if(await G(e))throw new u(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:"a merge is still in progress in the scratch worktree",remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"});let t=(await p({cwd:e,quiet:!0})`git status --porcelain`).stdout.trim();if(t.length>0)throw new u(void 0,{operation:"reuse the scratch worktree",stderrExcerpt:`scratch worktree is dirty: ${t.split(`
|
|
6
|
+
`)[0]}`,remediation:"this is an infra-kit bug \u2014 the previous branch iteration did not clean up"})},ht=async e=>{let t=async r=>{try{await r()}catch{}};await G(e)&&await t(()=>p({cwd:e,quiet:!0})`git merge --abort`),await t(()=>p({cwd:e,quiet:!0})`git reset --hard`),await t(()=>p({cwd:e,quiet:!0})`git clean -fd`)},yt=async(e,t)=>{let{cwd:r,anchor:o="origin/dev"}=e,n=await ye(r),s=async()=>{await p({cwd:r,quiet:!0})`git worktree add --detach ${n} ${o}`};try{await s()}catch(c){try{await p({cwd:r,quiet:!0})`git worktree prune`,await s()}catch{throw new u(c,{operation:"create the scratch worktree for the merge",remediation:`remove any stale checkout at ${n}, then retry`})}}let a={path:n,remove:async()=>{try{await p({cwd:r,quiet:!0})`git worktree remove --force ${n}`}catch{}}};try{return await t(a)}finally{await a.remove()}};import wt from"node:process";import kt from"pino";import vt from"pino-pretty";var xt=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],Rt=()=>{let e=wt.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),kt({level:e,redact:xt},vt({destination:2,ignore:t.join(","),colorize:!0,sync:!0}))},B=Rt();import Q from"node:fs/promises";import Pe from"node:os";import E from"node:path";import Tt from"node:process";import{z as i}from"zod";var z=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var y=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r])=>r!==t));var v=({key:e,id:t,note:r})=>({id:t,note:r,apply:o=>e in o?{changed:!0,result:y(o,e)}:{changed:!1,result:o}});var ke=v({key:"devProxy",id:"drop-dev-proxy-key",note:'the retired "devProxy" key (dev URLs are port-free https://<release>.<package>.localhost)'});var ve=v({key:"envAutoLoad",id:"drop-env-auto-load-key",note:'the retired "envAutoLoad" key (env auto-load is gone \u2014 run `env-load -c <config>` in the terminal)'});var xe=v({key:"environments",id:"drop-environments-key",note:`the retired "environments" key (deploy targets now come from each workflow's workflow_dispatch options, auth from the token store)`});var bt=e=>{let t=e.ide;if(t===null||typeof t!="object")return{changed:!1,result:e};let r=!1,o=s=>{if(s===null||typeof s!="object"||!("config"in s))return s;let a=s.config;return a===null||typeof a!="object"||!("mode"in a)?s:(r=!0,{...s,config:y(a,"mode")})},n=Array.isArray(t)?t.map(o):o(t);return r?{changed:!0,result:{...e,ide:n}}:{changed:!1,result:e}},Re={id:"strip-legacy-ide-mode",note:'legacy "mode"',apply:bt};var Ct="zed",be=e=>e!==null&&typeof e=="object"&&e.provider===Ct,Et=e=>{let t=e.ide;if(Array.isArray(t)){let r=t.filter(o=>!be(o));return r.length===t.length?{changed:!1,result:e}:{changed:!0,result:r.length>0?{...e,ide:r}:y(e,"ide")}}return be(t)?{changed:!0,result:y(e,"ide")}:{changed:!1,result:e}},Ce={id:"strip-retired-zed-ide",note:'the retired "zed" provider',apply:Et};var U=[Re,Ce,xe,ke,ve];var b=e=>U.reduce((t,r)=>{let o=r.apply(t.result);return o.changed?{changed:!0,result:o.result,notes:[...t.notes,r.note]}:t},{changed:!1,result:e,notes:[]});import Mt from"node:fs/promises";import St from"node:os";var It=async e=>{try{return await Mt.access(e),!0}catch{return!1}},H=e=>{let t=St.homedir();return e.startsWith(t)?`~${e.slice(t.length)}`:e};import{randomBytes as Pt}from"node:crypto";import l from"node:fs/promises";import V from"node:path";import jt from"node:process";var j=class extends Error{constructor(t){super(`${t} changed on disk since it was read`),this.name="ConfigFileChangedError"}},$t=2,At=e=>/^([ \t]+)\S/m.exec(e)?.[1]??$t,Ot=4095,$=async({path:e,raw:t,migrated:r,expectedMtimeMs:o})=>{let n=await l.realpath(e),s=V.dirname(n),a=V.basename(n),c=V.join(s,`.${a}.${jt.pid}.${Pt(4).toString("hex")}.tmp`),A=`${JSON.stringify(r,null,At(t))}
|
|
7
|
+
`;try{await l.writeFile(c,A,"utf8");let d=await l.stat(n);if(d.mtimeMs!==o)throw new j(e);await l.chmod(c,d.mode&Ot),await l.rename(c,n)}catch(d){throw await l.rm(c,{force:!0}),d}},Nt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_t=async e=>{let t=await l.stat(e),r=await l.readFile(e,"utf8");if(r.trim()==="")return{changed:!1,result:{},notes:[],path:e};let o=JSON.parse(r);if(!Nt(o))return{changed:!1,result:{},notes:[],path:e};let n=b(o);return n.changed&&await $({path:e,raw:r,migrated:n.result,expectedMtimeMs:t.mtimeMs}),{...n,path:e}};var J=async(e,t,r,{schema:o})=>{if(e.autoMigrate==="off")return{kind:"not-applicable"};let n=b(t);if(!n.changed)return{kind:"not-applicable"};let s=o.safeParse(n.result);if(!s.success)return{kind:"not-applicable"};if(e.required&&_())return{kind:"ci-gated"};try{await $({path:e.path,raw:r,migrated:n.result,expectedMtimeMs:e.mtimeMs})}catch(a){return B.debug(a,`auto-migration could not rewrite ${e.path}`),{kind:"not-applicable"}}return B.warn(`Migrated ${H(e.path)}: removed ${n.notes.join(" and ")} (retired by infra-kit ${ne.version})`),{kind:"migrated",data:s.data}};var Ee="infra-kit.json";var Lt="infra-kit.json",Kt="projects",Dt=i.object({provider:i.literal("doppler"),config:i.object({name:i.string().min(1)})}),Wt=i.discriminatedUnion("provider",[Dt]),Ft=i.object({workspaceConfigPath:i.string().min(1)}).strict(),qt=i.object({provider:i.literal("cursor"),config:Ft}).strict(),Me=i.discriminatedUnion("provider",[qt]),Gt=i.union([Me,i.array(Me).min(1)]),Bt=i.object({provider:i.literal("jira"),config:i.object({baseUrl:i.string().url(),projectId:i.number().int().positive()})}),zt=i.discriminatedUnion("provider",[Bt]),Ut=["two-columns","three-pane"],Ht=i.object({layout:i.enum(Ut).optional()}).strict(),Vt=i.object({openInGithubDesktop:i.boolean().optional(),openInOrca:i.boolean().optional(),orca:Ht.optional()}).strict(),Jt=i.object({port:i.number().int().positive().optional(),prefixUrl:i.string().min(1).optional()}).strict(),Xt=i.record(i.string().min(1),Jt),Yt=i.enum(["local","cloud"]),Zt=i.object({watchDeps:i.boolean().optional(),proxy:i.record(i.string().min(1),Yt).optional()}).strict(),Qt=i.object({apps:i.record(i.string().min(1),Zt).optional(),orca:i.boolean().optional()}).strict(),er=i.record(i.string().min(1),Qt),tr=i.enum(["disallow","allow","cli-only"]),Se=i.string().regex(/^[A-Z_]\w*$/i,"must be a POSIX environment-variable name"),rr=i.object({command:i.string().min(1),args:i.array(i.string()).default([]),env:i.array(Se).min(1),unset:i.array(Se).default([])}).strict().superRefine((e,t)=>{for(let r of e.env)ie.has(r)&&t.addIssue({code:"custom",path:["env"],message:`"${r}" is process plumbing the proxy never strips or injects \u2014 it cannot be a credential name`})}),or=i.record(i.string().regex(/^[a-z][a-z0-9-]*$/,"must be lowercase letters, digits and hyphens, starting with a letter").refine(e=>!e.includes("infra-kit"),{message:'"infra-kit" is reserved: it is the .mcp.json key of the retired infra-kit MCP server \u2014 pick another name'}),rr),Ie=i.string().min(1).superRefine((e,t)=>{if(e.startsWith("/")||e.startsWith("\\")||/^[a-z]:/i.test(e)){t.addIssue({code:"custom",message:`"${e}" must be relative to the repository root`});return}let r=e.split(/[/\\]/).filter(n=>n!==""&&n!==".");r.includes("..")&&t.addIssue({code:"custom",message:`"${e}" must not contain a ".." segment`}),r[0]===".git"&&t.addIssue({code:"custom",message:`"${e}" must not be .git or a path inside it`}),e.includes("\\")&&t.addIssue({code:"custom",message:`"${e}" must use "/" as the separator, not "\\"`});let o=e.split("/");o.includes("")&&t.addIssue({code:"custom",message:`"${e}" must not have a trailing or doubled "/"`}),o.includes(".")&&t.addIssue({code:"custom",message:`"${e}" must not contain a "." segment; write it from the repository root, e.g. "vendor/configs"`})}),nr=i.object({path:Ie,target:Ie.optional()}).strict(),je=i.object({copy:i.array(nr).min(1),exclude:i.array(i.string().regex(/^[^/\\]+$/,'must be a single path segment, without "/"')).optional()}).strict(),ir=i.object({requiredScripts:i.array(i.string().min(1)).optional(),requiredFiles:i.array(i.string().min(1)).optional(),turbo:i.object({requiredTasks:i.array(i.string().min(1)).optional()}).strict().optional()}).strict(),ee=i.object({envManagement:Wt,ide:Gt.optional(),taskManager:zt.optional(),worktrees:Vt.optional(),dev:Xt.optional(),devServersPresets:er.optional(),protectedEnvs:tr.optional(),mcp:or.optional(),vendorSource:je.nullable().optional(),audit:ir.optional()}).strict(),sr=443,$e=ee.superRefine((e,t)=>{if(!Array.isArray(e.ide))return;let r=new Set;for(let o of e.ide){if(r.has(o.provider)){t.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}r.add(o.provider)}}),Z=ee.partial(),ar=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},Ae="two-columns",cr=e=>e.worktrees?.orca?.layout??Ae,f=null,C=null,Oe=()=>`${Tt.cwd()} ${Pe.homedir()}`,Ne=()=>E.join(Pe.homedir(),N),_e=()=>E.join(Ne(),Lt),Te=async()=>{let e=Oe();if(C&&C.key===e)return C.value;let t=await R(),r=await W(t),o=E.basename(r),n={main:E.join(t,Ee),userGlobal:_e(),userProject:E.join(Ne(),Kt,o,Ee),projectName:o};return C={key:e,value:n},n},ur=async(e={})=>{let t=e.autoMigrate??"write",r=Oe(),o=await Te(),n;try{n=await Q.stat(o.main)}catch{f=null;let O=o.main.replace(/\.json$/,".yml");throw await X(O)?new Error(`infra-kit.json not found at ${o.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit setup --skip-tools\` to convert it.`):new Error(w()?`infra-kit.json not found at ${o.main} \u2014 the working directory is not an infra-kit project. Run infra-kit from inside an infra-kit project repo, or pass \`-C <dir>\` naming one.`:`infra-kit.json not found at ${o.main} \u2014 this git repo is not an infra-kit project. Run \`infra-kit setup --skip-tools\` here to create it, cd into an infra-kit project repo, or check out a branch that has infra-kit.json.`)}let[s,a]=await Promise.all([X(o.userGlobal),X(o.userProject)]),c={main:Number(n.mtimeMs),userGlobal:s?Number(s.mtimeMs):null,userProject:a?Number(a.mtimeMs):null};if(f&&f.key===r&&lr(f.mtimes,c))return f.value;let A=[{label:"infra-kit.json",path:o.main,required:!0,autoMigrate:t,mtimeMs:c.main},{label:"~/.infra-kit/infra-kit.json",path:o.userGlobal,required:!1,autoMigrate:t,mtimeMs:c.userGlobal},{label:`~/.infra-kit/projects/${o.projectName}/infra-kit.json`,path:o.userProject,required:!1,autoMigrate:t,mtimeMs:c.userProject}],d={};for(let O of A){let te=await fr(O);te!==null&&(d={...d,...te})}let M=$e.safeParse(d);if(!M.success)throw new Error(`Invalid merged infra-kit config: ${i.prettifyError(M.error)}`);return f={key:r,mtimes:c,value:M.data},M.data},mr=()=>{f=null},pr=()=>{f=null,C=null},X=async e=>{try{return await Q.stat(e)}catch{return null}},dr=async e=>{try{return await Q.readFile(e,"utf-8")}catch{return null}},lr=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(o=>e[o]===t[o])},Le=e=>new Error(`${e.message}
|
|
8
|
+
A retired key on this branch \u2014 run \`infra-kit setup --skip-tools\` in this checkout and commit infra-kit.json.`),fr=async e=>{let t=await dr(e.path);if(t===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(a){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${a.message}`)}if(Y(r)&&"envTokens"in r)throw new Error(vr(e));!e.required&&Y(r)&&kr(e,r);let o=Z.safeParse(r);if(o.success)return o.data;let n=new Error(`Invalid ${e.label} at ${e.path}: ${i.prettifyError(o.error)}`);if(!Y(r)||e.mtimeMs===null)throw n;let s=await J({...e,mtimeMs:e.mtimeMs},r,t,{schema:Z});switch(s.kind){case"migrated":return s.data;case"ci-gated":throw Le(n);case"not-applicable":throw n;default:return z(s)}},gr=e=>[`"mcp" is not allowed in ${e.label} (${e.path}): it feeds the committed .mcp.json, so a per-machine copy would replace the project's servers for everyone.`,"Move the block to the project infra-kit.json and run `infra-kit setup`.","For a machine-only override of one server (e.g. a local fork), use Claude Code directly:"," claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> ... -- <command> <args>","(local scope shadows the project entry by name; `claude mcp list` will show a same-name conflict warning, which is expected)."].join(`
|
|
9
|
+
`),hr=e=>[`"vendorSource" is not allowed in ${e.label} (${e.path}): only the committed project file may mark a repository as the \`vendor sync\` source. In the machine-wide file it would make every repository on this machine a source; in a per-project override it would make this machine disagree with every other clone.`,"Move the block to the source repository's own infra-kit.json and commit it there."].join(`
|
|
10
|
+
`),yr=e=>[`"audit" is not allowed in ${e.label} (${e.path}): the root audit gates CI, so a per-machine copy would make this machine pass or fail a different check list than CI.`,"Move the block to the project infra-kit.json and commit it there."].join(`
|
|
11
|
+
`),wr={mcp:gr,vendorSource:hr,audit:yr},kr=(e,t)=>{for(let[r,o]of Object.entries(wr))if(r in t)throw new Error(o(e))},Y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vr=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
|
|
12
|
+
`);var Ke=class extends u{structuredContent;exitCode;constructor(t,r,o){super(void 0,o),this.name="StructuredRefusalError",this.structuredContent=t,this.exitCode=r}};export{S as a,We as b,se as c,ae as d,w as e,qe as f,Ge as g,x as h,u as i,g as j,L as k,K as l,Je as m,Xe as n,Ye as o,Ze as p,Qe as q,et as r,D as s,tt as t,fe as u,rt as v,R as w,W as x,ge as y,he as z,it as A,st as B,at as C,ct as D,ut as E,mt as F,pt as G,dt as H,lt as I,we as J,ft as K,G as L,gt as M,ht as N,yt as O,B as P,z as Q,It as R,H as S,j as T,$ as U,_t as V,je as W,sr as X,$e as Y,Z,ar as _,cr as $,_e as aa,Te as ba,ur as ca,mr as da,pr as ea,Ke as fa};
|
|
13
|
+
//# sourceMappingURL=chunk-FRBNA6VH.js.map
|