{
  "version": 3,
  "sources": ["../src/client/host-probe.ts", "../src/client/append-system.ts", "../src/client/safe-kill.ts", "../src/client/lifecycle.ts", "../src/client/host-registry.ts", "../src/client/client-lifecycle.ts", "../src/client/cookie-mint.ts", "../src/client/host-health.ts", "../src/client/host-port.ts", "../src/client/host-launch.ts"],
  "sourcesContent": [
    "/**\n * Host liveness probes used by the lifecycle manager before it hands an\n * authority to the client carrier.\n *\n * Two distinct questions:\n *\n * - `probeHostHttp` — \"is this authority OUR dsh host?\" A `GET /` carrying\n *   the cookie minted from this home's grant must answer with a web-app\n *   response (2xx/3xx). A live process that merely holds the TCP port (a\n *   foreign home's host, a test server, a wedge that lost its connection\n *   service) answers 401/404/5xx and must NOT be adopted: adopting it makes\n *   the carrier reconnect forever against an authority it can never\n *   authenticate.\n *\n * - `probeHostMux` — \"is the client mux actually serving?\" The carrier's\n *   readiness gate is the validated `$events` ready item, so the lifecycle\n *   uses the same handshake (upgrade + open `$events` + first item) before\n *   returning from a cold boot. Without it, readiness can resolve on a bare\n *   TCP listener and the first carrier attempt is rejected while the HTTP\n *   stack is still mounting — the `[connection] connection lost, retry #n`\n *   burst this module exists to eliminate.\n *\n * Both probes are bounded and never throw: the caller decides what a false\n * result means (stale lock vs. boot failure).\n */\n\nimport { randomUUID } from \"node:crypto\"\nimport WS from \"ws\"\nimport { openEventsStreamFrame, parseMuxFrame } from \"./mux-frame.ts\"\n\n/** Default bound for one probe. */\nexport const DEFAULT_HOST_PROBE_TIMEOUT_MS = 2_000\n\n/** Minimal socket seam the probe drives; defaults to a real `ws` socket.\n * Tests inject a fake that reproduces ws's async CONNECTING-close error. */\nexport type HostProbeSocketFactory = () => WS\n\n/** Extra surface a real `ws` socket exposes for bounded teardown. The ambient\n * `ws.d.ts` declares only the transport's minimal slice, so the probe names the\n * teardown methods it relies on locally (no `any` / suppression needed). */\ninterface TeardownSocket extends WS {\n  removeAllListeners(): this\n  terminate(): void\n}\n\nexport interface HostProbeOptions {\n  /** `host:port` (scheme omitted) exactly as the host binds it. */\n  authority: string\n  /** Full `Cookie` header value minted for this authority. */\n  cookieHeader: string\n  /** Bound for the whole probe; defaults to 2s. */\n  timeoutMs?: number\n  /** Injectable socket factory (tests). Default: real `ws` to the mux path. */\n  socketFactory?: HostProbeSocketFactory\n}\n\nfunction validAuthority(authority: string): boolean {\n  return typeof authority === \"string\" && authority.length > 0 && !/[\\r\\n/]/.test(authority)\n}\n\n/**\n * Raw HTTP status of the authenticated `GET /` probe, or `null` when the\n * authority is malformed or the request could not complete (timeout / TCP\n * refused / fetch threw). Exposed so callers that decide health themselves\n * (e.g. `host-health.ts`) can compose TCP + status without duplicating the\n * cookie/authority/timeout plumbing. Never throws.\n */\nexport async function probeHostHttpStatus(options: HostProbeOptions): Promise<number | null> {\n  if (!validAuthority(options.authority)) return null\n  const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS\n  try {\n    const response = await fetch(`http://${options.authority}/`, {\n      headers: { cookie: options.cookieHeader },\n      signal: AbortSignal.timeout(timeoutMs),\n    })\n    // The body is irrelevant; drop it so the socket is released promptly.\n    try {\n      await response.body?.cancel()\n    } catch {\n      /* already consumed/closed */\n    }\n    return response.status\n  } catch {\n    return null\n  }\n}\n\n/**\n * Authenticated liveness: `GET /` with the owner cookie must reach the web\n * app. Any 2xx/3xx counts; 401/403 (cookie not accepted), 404 (something\n * else holds the port) and 5xx (broken host) all mean \"not usable\".\n */\nexport async function probeHostHttp(options: HostProbeOptions): Promise<boolean> {\n  const status = await probeHostHttpStatus(options)\n  return status !== null && status >= 200 && status < 400\n}\n\n/**\n * Full client-generation handshake: upgraded mux WebSocket + `$events` open\n * frame + the validated ready item. This is exactly what the carrier's\n * `createEventsPumpSource` gates on, so a true result guarantees the first\n * carrier attempt has something to attach to.\n */\nexport async function probeHostMux(options: HostProbeOptions): Promise<boolean> {\n  if (!validAuthority(options.authority)) return false\n  const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS\n  const makeSocket: HostProbeSocketFactory =\n    options.socketFactory ??\n    (() => new WS(`ws://${options.authority}/api/remote.mux`, { headers: { cookie: options.cookieHeader } }))\n  return await new Promise<boolean>((resolve) => {\n    let settled = false\n    let socket: WS | undefined\n    const timer = setTimeout(() => done(false), timeoutMs)\n    function done(ok: boolean): void {\n      if (settled) return\n      settled = true\n      clearTimeout(timer)\n      try {\n        const teardown = socket as TeardownSocket | undefined\n        teardown?.removeAllListeners()\n        // Closing a still-CONNECTING socket makes `ws` emit 'error' (\"closed\n        // before established\") ASYNCHRONOUSLY, after removeAllListeners() has\n        // removed the probe's own listeners — keep a noop handler attached so\n        // it can never surface as an uncaught exception (events-source.ts and\n        // remote-stream.ts fixed the identical race the same way). Every\n        // settlement path funnels through done(), so all of them are covered.\n        socket?.on(\"error\", () => {})\n        teardown?.terminate()\n      } catch {\n        /* already gone */\n      }\n      resolve(ok)\n    }\n    try {\n      socket = makeSocket()\n    } catch {\n      done(false)\n      return\n    }\n    socket.on(\"open\", () => {\n      try {\n        socket?.send(JSON.stringify(openEventsStreamFrame(randomUUID())))\n      } catch {\n        done(false)\n      }\n    })\n    socket.on(\"message\", (data) => {\n      try {\n        const frame = parseMuxFrame(String(data))\n        if (frame.type !== \"item\") {\n          done(false)\n          return\n        }\n        const value = frame.value as { type?: unknown } | undefined\n        done(value?.type === \"ready\")\n      } catch {\n        done(false)\n      }\n    })\n    socket.on(\"unexpected-response\", (_request, response) => {\n      try {\n        ;(response as { resume(): void }).resume()\n      } catch {\n        /* already drained */\n      }\n      done(false)\n    })\n    socket.on(\"error\", () => done(false))\n    socket.on(\"close\", () => done(false))\n  })\n}\n",
    "/**\n * Append-system (ported from dsh-tui-pi's APPEND_SYSTEM.md, P2 gap closure).\n *\n * tui-pi semantics: `$DSH_HOME/APPEND_SYSTEM.md` is appended to the system\n * prompt of every TUI-created main agent (subagents excluded). The opentui\n * host exposes no wire to register a system-prompt section, so the delivery\n * channel here is an agentPreset: the client maintains one `@deepseek-ai/\n * dsh-agent-preset` row in the opentui profile's `cordis.patch.yml` whose\n * composition is the shipped `standard` preset verbatim with the persona row\n * carrying `{ suffix: <APPEND_SYSTEM.md> }`. The preset scope shadows only\n * the persona sections, so the session face is standard's plus the suffix —\n * additive by construction. `session/create` rides that preset when the host\n * roster composes it (remote-host-session.ts).\n *\n * File-driven persona: the suffix is a `!!js` expression the HOST evaluates\n * at boot — a guarded `readFileSync` of `$DSH_HOME/APPEND_SYSTEM.md` (probe\n * 2026-11-15, host 0.2.2-rc.3: `process.getBuiltinModule('node:module')\n * .createRequire(baseUrl)` and `baseUrl` are both reachable from user-patch\n * `!!js` rows; missing file resolves to '' and the empty section is dropped\n * by the prompt renderer). The patch block is therefore content-independent:\n * it is written once and never resynced, and persona edits follow the file\n * on the next host boot.\n *\n * Boot-time seeding (tui-pi parity): a missing APPEND_SYSTEM.md is seeded\n * from the embedded template; an existing file is user-owned — zero writes.\n */\n\nimport { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\n\n/** The preset id the client rides on `session/create` (unique vs the shipped roster: standard/ptc/minimal/cordis). */\nexport const APPEND_SYSTEM_PRESET_ID = \"opentui-append-system\"\n/** The patch row id carrying the preset declaration (unique vs profile patch row ids). */\nexport const APPEND_SYSTEM_ROW_ID = `preset-${APPEND_SYSTEM_PRESET_ID}`\n/** The managed-block marker comment: its presence marks OUR lines; resync never touches other lines. */\nexport const APPEND_SYSTEM_MARKER = \"# dsh-opentui:append-system\"\n\n/** Default harness home: `$DSH_HOME` or `~/.dsh` (tui-pi parity; an empty DSH_HOME falls back, host-side parity). */\nexport function defaultDshHome(): string {\n\treturn process.env.DSH_HOME || join(homedir(), \".dsh\")\n}\n\n/** The user-editable append file (`$DSH_HOME/APPEND_SYSTEM.md`). */\nexport function appendSystemPath(home: string = defaultDshHome()): string {\n\treturn join(home, \"APPEND_SYSTEM.md\")\n}\n\n/**\n * The seed template for a missing APPEND_SYSTEM.md — neutral scaffolding\n * (the tui-pi template is the original user's personal orchestrator identity,\n * not shippable content) carrying the one iron rule tui-pi maintained. The\n * todo-lifecycle section is deliberately absent: the opentui host clears\n * todos every turn (loop.ts), so tui-pi's pinned-list problem does not exist\n * here.\n */\nexport const APPEND_SYSTEM_TEMPLATE = `# APPEND_SYSTEM.md — standing system-prompt additions\n\nThe content of this file is appended to the system prompt of every main\nsession the dsh-opentui client creates (ported from dsh-tui-pi).\n\nThe file is user-owned: the client seeds it once and never rewrites it.\nEdits apply to sessions created after the next client start; clearing or\ndeleting this file switches the append off (it is not re-seeded).\n\n## Vocabulary\n\n- \"subagent\" means the registered subagents only; never invent or use\n  unregistered subagents.\n\n## Additions\n\nWrite your persistent instructions below this line.\n`\n\n/**\n * The persona suffix the host evaluates at boot: guarded read of\n * `$DSH_HOME/APPEND_SYSTEM.md`, '' when missing/unreadable. One line, no\n * double quotes (survives YAML double-quoted scalars), no backslashes.\n */\nexport const APPEND_SYSTEM_SUFFIX_EXPR =\n\t`((req, path) => { try { const text = req('node:fs').readFileSync(path.join(process.env.DSH_HOME || ((process.env.HOME || '') + '/.dsh'), 'APPEND_SYSTEM.md'), 'utf8'); return text.length > 65536 ? text.slice(0, 65536) + String.fromCharCode(10) + '[append-system: truncated at 64KiB]' : text } catch { return '' } })(process.getBuiltinModule('node:module').createRequire(baseUrl), process.getBuiltinModule('node:path'))`\n\n/**\n * The managed patch block. The plugin list is the shipped `standard` preset\n * verbatim (dsh-web-app presets/standard.patch.yml — the effective default\n * this profile's sessions compose from) except the persona row, whose prefix\n * is copied verbatim and whose suffix is the APPEND_SYSTEM.md read. Copying\n * the whole composition is what makes the preset additive: a persona-only\n * preset would shadow standard's skill/plan/compaction/delegation rows and\n * shrink the session face (agents-mount gate).\n */\nexport function appendSystemPresetBlock(): string {\n\treturn `${APPEND_SYSTEM_MARKER} — managed block (client-owned; the client appends it once and never rewrites other lines).\n${APPEND_SYSTEM_MARKER} persona suffix = $DSH_HOME/APPEND_SYSTEM.md, evaluated by the host at boot (!!js guarded read; empty file => empty section => dropped).\n- insert:\n    - id: ${APPEND_SYSTEM_ROW_ID}\n      name: '@deepseek-ai/dsh-agent-preset'\n      config:\n        id: ${APPEND_SYSTEM_PRESET_ID}\n        name: Standard + Append\n        description: The shipped standard preset plus the user's APPEND_SYSTEM.md appended to the system prompt.\n        order: 5\n        plugins:\n          - id: persona\n            name: '@deepseek-ai/dsh-persona'\n            config:\n              prefix: You are a coding agent powered by the {{model}} model.\n              suffix: !!js \"${APPEND_SYSTEM_SUFFIX_EXPR}\"\n          - id: agent-instructions\n            name: '@deepseek-ai/dsh-agent-instructions'\n            config:\n              maxBytes: 65536\n          - id: time-context\n            name: '@deepseek-ai/dsh-time-context'\n          - id: tool-bash\n            name: '@deepseek-ai/dsh-tool-bash'\n            disabled: !!js process.platform === 'win32'\n          - id: tool-pwsh\n            name: '@deepseek-ai/dsh-tool-pwsh'\n            disabled: !!js process.platform !== 'win32'\n          - id: tool-fs\n            name: '@deepseek-ai/dsh-tool-fs'\n            config:\n              # Set false to drop the apply_patch tool beside edit.\n              applyPatch: false\n          - id: tool-fs-search\n            name: '@deepseek-ai/dsh-tool-fs-search'\n            config:\n              sampleOverCapGlobResults: false\n          - id: tool-jobs\n            name: '@deepseek-ai/dsh-tool-jobs'\n          - id: tool-schedule\n            name: '@deepseek-ai/dsh-tool-schedule'\n          - id: skill-filesystem\n            name: '@deepseek-ai/dsh-skill-filesystem'\n            config:\n              customSkillDirs:\n                - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills')\n          - id: tool-skill\n            name: '@deepseek-ai/dsh-tool-skill'\n          - id: command-goal\n            name: '@deepseek-ai/dsh-command-goal'\n          - id: tool-goal\n            name: '@deepseek-ai/dsh-tool-goal'\n          - id: planning\n            name: cordis:group\n            group: true\n            isolate:\n              planMode: true\n            config:\n              - id: plan-mode\n                name: '@deepseek-ai/dsh-plan-mode'\n                config:\n                  section: |\n                    You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.\n\n                    Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.\n\n                    The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed to keep the tool catalog unchanged. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode.\n\n                    Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out.\n\n                    Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions.\n\n                    When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask \"should I proceed?\" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation.\n          - id: compaction\n            name: cordis:group\n            group: true\n            isolate:\n              compaction: true\n              toolResultPruner: true\n            config:\n              - id: compaction-basic\n                name: '@deepseek-ai/dsh-compaction-basic'\n              - id: command-compact\n                name: '@deepseek-ai/dsh-command-compact'\n              - id: tool-result-pruner\n                name: '@deepseek-ai/dsh-compaction-tool-result-pruner'\n                config:\n                  thresholdChars: 8192\n                  headChars: 4096\n                  tailChars: 1024\n          - id: delegation\n            name: cordis:group\n            group: true\n            isolate:\n              workflowEngine: true\n            config:\n              - id: tool-subagent-control\n                name: '@deepseek-ai/dsh-tool-subagent-control'\n                config:\n                  interrupt: false\n              - id: tool-subagent\n                name: '@deepseek-ai/dsh-tool-subagent'\n                config:\n                  provider: spawn\n                  toolName: subagent\n                  modelSelection: true\n                  modelDiscovery: true\n              - id: tool-subagent-fork\n                name: '@deepseek-ai/dsh-tool-subagent'\n                config:\n                  provider: fork\n                  toolName: subagent_fork\n              - id: workflow-ptc\n                name: '@deepseek-ai/dsh-workflow-ptc'\n                config:\n                  provider: spawn\n              - id: tool-workflow\n                name: '@deepseek-ai/dsh-tool-workflow'\n          - id: tool-ask-user\n            name: '@deepseek-ai/dsh-tool-ask-user'\n          - id: tool-todo\n            name: '@deepseek-ai/dsh-tool-todo'\n            config:\n              allowParallelInProgress: true\n          - id: tool-web\n            name: '@deepseek-ai/dsh-tool-web'\n            config:\n              fetch: true\n              searchTimeoutMs: 60000\n          - id: present\n            name: '@deepseek-ai/dsh-tool-present'\n          - id: tool-office\n            name: '@deepseek-ai/dsh-tool-office'\n          - id: tool-plugin-manager\n            name: '@deepseek-ai/dsh-plugin-manager/tools'\n            disabled: !!js \"!ctx.get('profileContext')\"\n          - id: tool-plugin-market\n            name: '@deepseek-ai/dsh-plugin-market/tools'\n            disabled: true\n`\n}\n\n/**\n * Read the append file for prompt assembly. Missing/unreadable => ''\n * (tui-pi parity: the empty section is dropped by the renderer).\n */\nexport function readAppendSystem(path: string = appendSystemPath()): string {\n\ttry {\n\t\treturn readFileSync(path, \"utf8\")\n\t} catch {\n\t\treturn \"\"\n\t}\n}\n\n/** Atomic write: temp file in the same directory, then rename (tui-pi parity). */\nfunction writeAtomically(path: string, content: string, mode: number): void {\n\tmkdirSync(join(path, \"..\"), { recursive: true })\n\tconst tmp = `${path}.${process.pid}.tmp`\n\ttry {\n\t\twriteFileSync(tmp, content, { mode })\n\t\trenameSync(tmp, path)\n\t} catch (error) {\n\t\ttry {\n\t\t\tunlinkSync(tmp)\n\t\t} catch {\n\t\t\t/* sweep is best-effort */\n\t\t}\n\t\tthrow error\n\t}\n}\n\n/**\n * Seed the append file — FIRST PROVISIONING ONLY: a missing file is seeded\n * solely when the managed preset block is absent too. After provisioning,\n * deleting the file is how the user switches the append OFF (an empty persona\n * suffix renders no section), and this function must not resurrect it (the\n * block's presence answers \"provisioned\"). An existing file — even an empty\n * one — is user-owned: zero writes. Atomic; throws on write failure (the\n * caller degrades to booting without the feature, never fails the boot).\n * @param path - target file (injectable for tests). Whether the install is\n *   already provisioned (managed block present => deleted file stays deleted)\n *   is the CALLER's judgment — see {@link provisionAppendSystem}.\n */\nexport function ensureAppendSystemFile(path: string = appendSystemPath()): \"seeded\" | \"kept\" {\n\ttry {\n\t\treadFileSync(path, \"utf8\")\n\t\treturn \"kept\"\n\t} catch {\n\t\twriteAtomically(path, APPEND_SYSTEM_TEMPLATE, 0o644)\n\t\ttry {\n\t\t\tchmodSync(path, 0o644)\n\t\t} catch {\n\t\t\t/* best-effort mode normalization */\n\t\t}\n\t\treturn \"seeded\"\n\t}\n}\n\n/** Outcome of one profile-patch sync pass. */\nexport type AppendPresetSyncResult =\n\t| { status: \"added\" }\n\t| { status: \"present\" }\n\t| { status: \"collision\"; detail: string }\n\t| { status: \"skipped\"; detail: string }\n\n/**\n * The profile patch file the client maintains (`~/.dsh/profiles/<profile>/cordis.patch.yml`).\n */\nexport function profilePatchPath(home: string, profile: string): string {\n\treturn join(home, \"profiles\", profile, \"cordis.patch.yml\")\n}\n\n/**\n * The [start, end) line span of OUR managed block: from the first marker\n * comment through our single top-level `- insert:` entry — the span ends at\n * the NEXT top-level patch row (`^- `) after our insert line, or EOF. Lines\n * outside the span are the user's (or other tools') — this module never\n * rewrites them.\n */\nfunction managedSpan(lines: readonly string[]): [number, number] | undefined {\n\tconst start = lines.findIndex((line) => line.startsWith(APPEND_SYSTEM_MARKER))\n\tif (start < 0) return undefined\n\tlet end = lines.length\n\tlet seenOwnInsert = false\n\tfor (let i = start + 1; i < lines.length; i++) {\n\t\tif (/^- /.test(lines[i])) {\n\t\t\t// The first top-level row after the marker is our own `- insert:`.\n\t\t\tif (!seenOwnInsert) {\n\t\t\t\tseenOwnInsert = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tend = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn [start, end]\n}\n\n/**\n * One boot-time provisioning pass (the lifecycle entry point): maintain the\n * managed preset row, then seed the append file only when the install is not\n * yet provisioned (no managed block) AND the file is missing — afterwards a\n * deleted file means OFF and stays deleted. Returns both outcomes for the\n * caller's structured logging; write failures propagate.\n */\nexport function provisionAppendSystem(home: string, profile: string): { patch: AppendPresetSyncResult; file: \"seeded\" | \"kept\" } {\n\t// Provisioning is judged on the PRE-sync patch state: the block this pass\n\t// just added must not count (a fresh install seeds the file in the same\n\t// breath), while a block that already existed means the user may have\n\t// deleted the file to switch OFF — never re-seed over that.\n\tlet preText: string | undefined\n\ttry {\n\t\tpreText = readFileSync(profilePatchPath(home, profile), \"utf8\")\n\t} catch {\n\t\tpreText = undefined // no patch file: nothing provisioned, seeding stays eligible\n\t}\n\tconst patch = syncAppendSystemPreset(home, profile)\n\tif (preText !== undefined && managedSpan(preText.split(\"\\n\")) !== undefined) {\n\t\treturn { patch, file: \"kept\" } // provisioned install: deleted file stays deleted (delete = off)\n\t}\n\treturn { patch, file: ensureAppendSystemFile(appendSystemPath(home)) }\n}\n\n/**\n * Maintain the append-system preset row in the profile patch (conservative\n * line-level editing — the file is user-owned YAML, no parse-and-reserialize):\n *\n * - the ids appear OUTSIDE our block (a preset/row the user declared or a\n *   future host ships with the same id) => `collision`, zero writes;\n * - otherwise: block present => `present`, untouched (the block is content-\n *   independent in file-driven mode; there is nothing to resync); block\n *   absent => append at EOF (`added`);\n * - patch file or profile dir missing => `skipped` (the host owns that\n *   layout; enrichment must not create profile plumbing).\n *\n * The write is atomic (tmp + rename) and preserves the file mode (0600 for a\n * fresh file, matching the host's config-editor convention).\n */\nexport function syncAppendSystemPreset(home: string, profile: string): AppendPresetSyncResult {\n\tconst path = profilePatchPath(home, profile)\n\tlet before: string\n\ttry {\n\t\tbefore = readFileSync(path, \"utf8\")\n\t} catch {\n\t\treturn { status: \"skipped\", detail: `no profile patch at ${path}` }\n\t}\n\tconst lines = before.split(\"\\n\")\n\tconst span = managedSpan(lines)\n\tconst outside = (needle: string): string | undefined => {\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tif (span !== undefined && i >= span[0] && i < span[1]) continue\n\t\t\tif (lines[i].includes(needle)) return `line ${i + 1}: ${lines[i].trim()}`\n\t\t}\n\t\treturn undefined\n\t}\n\tfor (const needle of [APPEND_SYSTEM_PRESET_ID, APPEND_SYSTEM_ROW_ID]) {\n\t\tconst hit = outside(needle)\n\t\tif (hit !== undefined) {\n\t\t\treturn { status: \"collision\", detail: `${needle} already declared (${hit})` }\n\t\t}\n\t}\n\tif (span !== undefined) return { status: \"present\" }\n\t// Append at EOF: the patch is a YAML sequence; a new top-level entry is\n\t// safe at the end (the last layer wins per id, and we collide-checked).\n\tconst separator = before.length === 0 || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\"\n\tconst next = `${before}${separator}${appendSystemPresetBlock()}`\n\twriteAtomically(path, next, 0o600)\n\treturn { status: \"added\" }\n}\n",
    "/**\n * Three-evidence safe process stop — the ONE module allowed to signal a host\n * (ADR-0009 decision 8; DESIGN-redesign §6).\n *\n * A process may only be signalled when ALL of these agree:\n *   1. the pid recorded in the v2 registry (`registryPid`) equals the pid we\n *      are about to signal;\n *   2. its `ps` cmdline contains `--profile <expected>` AND no other `--profile`;\n *   3. its environment carries `DSH_OPENTUI_SERVER=1`.\n *\n * Evidence 3 is OPTIONAL when the env is genuinely unreadable (DESIGN §6):\n * on some platforms `ps eww` cannot expose a detached process's environment.\n * In that case only the two hard evidences (registry pid + exact\n * `--profile <expected>` cmdline) are required, and a fallback log is emitted.\n * A bare \"dsh\" substring match remains explicitly forbidden in ALL cases.\n * Every signal goes\n * through {@link ProcessKillHooks.kill}, which is injectable so unit tests\n * never signal a real process. No other module in the T3b path calls\n * `process.kill` on a host pid directly.\n *\n * Default signal sequence for a confirmed host: SIGTERM (let the host flush /\n * persist), wait a grace window, then SIGKILL only if the pid is still alive.\n */\n\nimport { spawnSync } from 'node:child_process'\n\n/** Env marking a process as THIS launcher's Host service (ADR-0009 decision 1). */\nexport const SERVER_ENV_NAME = 'DSH_OPENTUI_SERVER'\nexport const SERVER_ENV_VALUE = '1'\n/** The one product profile whose host may be signalled. */\nexport const HOST_PROFILE = 'opentui'\n/** Default wait after SIGTERM before escalating to SIGKILL. */\nexport const DEFAULT_TERM_GRACE_MS = 5_000\n/** Default wait after SIGKILL to confirm the pid is gone. */\nexport const DEFAULT_KILL_GRACE_MS = 2_000\n/** Poll cadence while waiting for a pid to exit. */\nexport const DEFAULT_EXIT_POLL_MS = 50\n\n/** The three-evidence process-identification seam, fully injectable. */\nexport interface ProcessKillHooks {\n  /** Full cmdline of `pid`, or null when the process is gone / unreadable. */\n  cmdline(pid: number): string | null\n  /** True when `pid`'s environment contains `DSH_OPENTUI_SERVER=1`. */\n  hasServerEnv(pid: number): boolean\n  /** Send a signal to `pid` (no-op on ESRCH is fine). */\n  kill(pid: number, signal: NodeJS.Signals): void\n  /** Pid liveness probe (defaults to `process.kill(pid, 0)`). */\n  pidAlive?(pid: number): boolean\n  /**\n   * Whether `pid`'s environment can be READ AT ALL (distinct from \"readable\n   * but lacks the marker\"). When this returns false, `evidencesAgree` waives\n   * evidence 3 and requires only registry pid + exact cmdline. Hooks that omit\n   * it keep the strict three-evidence rule (backward compatible).\n   */\n  envReadable?(pid: number): boolean\n  /** Called once when the two-evidence fallback is used (logging seam). */\n  onEnvFallback?(pid: number): void\n}\n\n/** Read a pid's process state via `ps -o stat=`; null when ps is unavailable. */\nfunction psStat(pid: number): string | null {\n  try {\n    const result = spawnSync('ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' })\n    if (result.error || result.status !== 0) return null\n    return (result.stdout ?? '').trim() || null\n  } catch {\n    return null\n  }\n}\n\n/** True when a `ps -o stat=` row denotes a zombie (Z / Z+ / Z<...>). */\nfunction statIsZombie(stat: string): boolean {\n  return stat.startsWith('Z')\n}\n\nexport function defaultPidAlive(pid: number): boolean {\n  try {\n    process.kill(pid, 0)\n  } catch (err) {\n    return (err as NodeJS.ErrnoException).code === 'EPERM'\n  }\n  // kill(0) succeeds for a zombie the parent has not reaped yet. Confirm via\n  // ps; when ps is unavailable keep the kill(0) verdict (no semantic change).\n  const stat = psStat(pid)\n  if (stat !== null && statIsZombie(stat)) return false\n  return true\n}\n\n/** Default three-evidence hooks via `ps` (portable enough for darwin/linux). */\nexport const psKillHooks: ProcessKillHooks = {\n  cmdline(pid) {\n    try {\n      return spawnSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' }).stdout?.trim() || null\n    } catch {\n      return null\n    }\n  },\n  hasServerEnv(pid) {\n    try {\n      const out = spawnSync('ps', ['eww', '-p', String(pid), '-o', 'command='], { encoding: 'utf8' }).stdout ?? ''\n      return out.includes(`${SERVER_ENV_NAME}=${SERVER_ENV_VALUE}`)\n    } catch {\n      return false\n    }\n  },\n  envReadable(pid) {\n    try {\n      const result = spawnSync('ps', ['eww', '-p', String(pid), '-o', 'command='], { encoding: 'utf8' })\n      if (result.error || (result.status !== null && result.status !== 0)) return false\n      const out = (result.stdout ?? '').trim()\n      // A zombie's command degrades to `<defunct>` and carries no readable env.\n      if (!out || out.includes('<defunct>')) return false\n      const stat = psStat(pid)\n      if (stat !== null && statIsZombie(stat)) return false\n      // A non-empty `ps eww` row means the env was readable, even if the\n      // marker itself is absent (that case must still refuse to signal).\n      return true\n    } catch {\n      return false\n    }\n  },\n  onEnvFallback(pid) {\n    console.warn(\n      `[safe-kill] ${SERVER_ENV_NAME} env unreadable for pid ${pid}; ` +\n        `using registry + cmdline two-evidence fallback (no \"dsh\" match)`,\n    )\n  },\n  kill(pid, signal) {\n    try {\n      process.kill(pid, signal)\n    } catch {\n      /* already gone */\n    }\n  },\n}\n\n/**\n * True when the ADR-0009 decision-8 evidences agree. Evidences 1 (registry\n * pid) and 2 (exact `--profile <expectedProfile>` cmdline, no other profile)\n * are always required. Evidence 3 (the env marker) is waived ONLY when the env is\n * genuinely unreadable (`hooks.envReadable(pid) === false`, e.g. `ps eww` is\n * unavailable) — in that case a fallback log is emitted. When the env is\n * readable but lacks the marker, this still refuses to signal. This is the\n * sole gate before any host signal and never falls back to a \"dsh\" substring\n * or port guess.\n */\nexport function evidencesAgree(\n  pid: number,\n  registryPid: number,\n  hooks: ProcessKillHooks,\n  expectedProfile: string = HOST_PROFILE,\n): boolean {\n  if (!Number.isInteger(pid) || pid <= 0) return false\n  if (registryPid !== pid) return false // (1) registry pid\n  const cmd = hooks.cmdline(pid)\n  if (!cmd) return false\n  // (2) exactly one --profile, compared by equality (never a substring match).\n  const profiles = [...cmd.matchAll(/--profile[= ]+([^\\s]+)/g)].map((m) => m[1])\n  if (profiles.length === 0 || profiles.some((p) => p !== expectedProfile)) return false\n  // (3) env marker — required when readable, optional when unreadable.\n  if (hooks.hasServerEnv(pid)) return true\n  if (hooks.envReadable && !hooks.envReadable(pid)) {\n    hooks.onEnvFallback?.(pid)\n    return true\n  }\n  return false\n}\n\nexport interface SafeStopOptions {\n  /** The pid we intend to signal. */\n  pid: number\n  /** The pid recorded in the registry (evidence 1). */\n  registryPid: number\n  hooks: ProcessKillHooks\n  /** Profile this host belongs to; must equal the cmdline profile (default `HOST_PROFILE`). */\n  profile?: string\n  termGraceMs?: number\n  killGraceMs?: number\n  sleep?: (ms: number) => Promise<void>\n  pidAlive?: (pid: number) => boolean\n  /** Injectable clock for wait deadlines (defaults to `Date.now`). */\n  now?: () => number\n}\n\nexport interface SafeStopResult {\n  /** Whether any signal was sent (false when evidence failed). */\n  attempted: boolean\n  /** Whether the three evidences agreed. */\n  evidencesOk: boolean\n  /** Signals actually sent, in order. */\n  signals: NodeJS.Signals[]\n  /** Whether the pid was confirmed gone at the end. */\n  stopped: boolean\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\nasync function waitGone(\n  pid: number,\n  budgetMs: number,\n  alive: (pid: number) => boolean,\n  sleep: (ms: number) => Promise<void>,\n  now: () => number,\n): Promise<boolean> {\n  if (!alive(pid)) return true\n  const deadline = now() + budgetMs\n  // Bound by BOTH the clock and an iteration cap: an injected clock that does\n  // not advance (or a sleep that does not move it) must never spin forever.\n  const maxIterations = Math.max(1, Math.ceil(budgetMs / DEFAULT_EXIT_POLL_MS) + 8)\n  for (let i = 0; i < maxIterations && now() < deadline; i++) {\n    await sleep(DEFAULT_EXIT_POLL_MS)\n    if (!alive(pid)) return true\n  }\n  return !alive(pid)\n}\n\n/**\n * Confirm the three evidences, then SIGTERM → grace → SIGKILL a host. When any\n * evidence is missing this is a strict no-op (no signal at all). All I/O is\n * injectable; tests drive it with fake hooks / clock / sleep.\n */\nexport async function safeStopHost(options: SafeStopOptions): Promise<SafeStopResult> {\n  const {\n    pid,\n    registryPid,\n    hooks,\n    profile = HOST_PROFILE,\n    termGraceMs = DEFAULT_TERM_GRACE_MS,\n    killGraceMs = DEFAULT_KILL_GRACE_MS,\n    sleep = defaultSleep,\n    pidAlive = hooks.pidAlive ?? defaultPidAlive,\n    now = Date.now,\n  } = options\n\n  if (!evidencesAgree(pid, registryPid, hooks, profile)) {\n    return { attempted: false, evidencesOk: false, signals: [], stopped: !pidAlive(pid) }\n  }\n\n  const signals: NodeJS.Signals[] = []\n  hooks.kill(pid, 'SIGTERM')\n  signals.push('SIGTERM')\n  if (await waitGone(pid, termGraceMs, pidAlive, sleep, now)) {\n    return { attempted: true, evidencesOk: true, signals, stopped: true }\n  }\n\n  hooks.kill(pid, 'SIGKILL')\n  signals.push('SIGKILL')\n  const stopped = await waitGone(pid, killGraceMs, pidAlive, sleep, now)\n  return { attempted: true, evidencesOk: true, signals, stopped }\n}\n",
    "// Client-mode host lifecycle manager (ADR-0005 decision 5; audit bucket (e)).\n//\n// `ensureHost` manages ONE resident `dsh` host per profile per machine:\n//\n//   const host = await ensureHost({ profile: 'opentui', idleExitSec: 5 })\n//   host.authority    // '127.0.0.1:45931' — where the host listens\n//   host.cookieHeader // minted Cookie header for /api + /connect auth\n//   host.pid          // host child process id (or adopted pid)\n//   host.port / host.url / host.token\n//   host.adopted      // true when a host spawned by another (dead) client was taken over\n//   host.refCount     // live users of this host from this process\n//   host.retain()     // +1 (join; cancels a pending idle-exit)\n//   host.release()    // -1; reaching 0 arms the idle-exit timer\n//   await host.dispose() // SIGTERM (+SIGKILL escalation) now, remove lockfile\n//\n// Idempotency: a second `ensureHost` for the same profile + dshHome joins the\n// live host (refcount +1, pending idle-exit cancelled) instead of re-booting.\n//\n// Single-instance lock: `$DSH_HOME/opentui-host.<profile>.json` holds\n// { pid, port, authority, startedAt, profile }. A lock whose pid is dead or\n// whose listener is gone is stale and taken over (replaced by a fresh boot).\n// A lock whose pid lives and whose port listens is adopted ONLY after an\n// authenticated probe (`GET /` with the cookie minted from this home) proves\n// the process is OUR host: a foreign home / rotated grant answers 401 and\n// would otherwise leave the carrier reconnecting forever. The foreign pid is\n// never signalled; only the stale lock is removed.\n// A fresh lock is adopted (no spawn) — that is the crashed-client recovery\n// path. Unexpected child death clears the lock; the next `ensureHost`\n// respawns, capped at MAX_RAPID_RESPAWNS spawn attempts inside\n// RESPAWN_WINDOW_MS after which HostRespawnLoopError surfaces instead of\n// looping.\n//\n// Cold-boot mutual exclusion: before spawning, the booter claims the\n// lockfile as a `booting: true` placeholder (atomic create-if-absent —\n// exactly one cold boot wins per profile across processes). Another client\n// that finds a fresh booting lock WAITS for it to flip into a real lock and\n// then adopts it (join); it takes over (removes the placeholder and boots\n// itself) when the booting pid dies or the join budget\n// (`readinessTimeoutMs + BOOT_JOIN_MARGIN_MS`) lapses. The real lock is only\n// written after readiness + mint and only while the claim is still intact —\n// a superseded booter kills its own child (HostBootSupersededError) instead\n// of clobbering the winner's lock.\n//\n// Adoption bumps the lockfile (fresh startedAt/mtime): the detached idle\n// reaper (scripts/idle-reaper.mjs) treats a lockfile generation change since\n// its own start as a live adopter, so a client that adopted at the grace edge\n// and is still minting its cookie (no ESTABLISHED connection yet) is not\n// reaped underneath.\n//\n// Idle exit (ADR-0005 decision 5): when the refcount reaches 0 a timer of\n// `idleExitSec` seconds (default 5, overridable with\n// DSH_OPENTUI_HOST_IDLE_MS; `0` = never exit, resident) SIGTERMs the child\n// and cleans the lockfile; an `ensureHost` inside the grace window cancels the\n// timer and re-attaches. Because the in-process timer is unref()ed and dies\n// with the client, a clean quit also hands the window to the detached reaper\n// (scripts/idle-reaper.mjs), which owns it after this process is gone.\n//\n// Readiness: the `dsh web: http://127.0.0.1:<port>/?token=...` stdout line\n// (verified against the shipped CLI; it prints only after the loader and the\n// connection service are mounted) or an HTTP-responds fallback, within\n// `readinessTimeoutMs` (default 30s) — a typed HostBootTimeoutError on miss.\n// The HTTP fallback is deliberately stronger than a TCP accept: a bound\n// socket that does not answer HTTP rejects the carrier's first mux upgrade.\n// After a fallback boot (and the cookie mint) the lifecycle also performs the\n// full `$events` handshake, so a returned host is always mux-serving. Boot\n// errors quote the child's output tail (last 12 lines) in their message.\n// The child is spawned detached with a bind-probed free port, so it survives\n// this process and is adopted by the next client via the lockfile.\n//\n// Auth: `mintOwnerCookie({ home, authority, maxAgeMs? }): string` from\n// ./cookie-mint.ts (owned by the transport/cookie agent; contract frozen).\n// It resolves lazily at runtime so this file works before that module lands;\n// tests inject a fake via `mintCookie`. A missing module at runtime throws\n// MintUnavailableError. First-boot mint races (\"credentials grant not yet\n// written\") are retried for 15s before surfacing.\n//\n// Known v1 limit (per ADR-0005 decision 5): the refcount is per\n// manager-process. A client process that dies while holding the host leaves\n// it resident; the next client adopts it through the lockfile, and a clean\n// owner exit with refcount 0 shuts it down.\n\nimport { spawn } from 'node:child_process'\nimport { existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { connect as netConnect, Server, type AddressInfo } from 'node:net'\nimport { join } from 'node:path'\nimport { probeHostHttp, probeHostMux } from './host-probe.ts'\nimport { provisionAppendSystem } from './append-system.ts'\nimport { defaultPidAlive } from './safe-kill.ts'\n\nexport const DEFAULT_PROFILE = 'opentui'\n/** Idle-exit window: the resident host exits this long after the LAST client\n * disconnects, unless a client re-attaches inside the window. 5s is the\n * product default; `0` = never exit (resident). Override per process with\n * `DSH_OPENTUI_HOST_IDLE_MS` (milliseconds), or per call with\n * `ensureHost({ idleExitSec })`. */\nexport const DEFAULT_IDLE_EXIT_MS = 5_000\nexport const DEFAULT_IDLE_EXIT_SEC = DEFAULT_IDLE_EXIT_MS / 1000\n/** Env override for the idle-exit window, in milliseconds (`0` = resident;\n * an empty or unparsable value falls back to the default). */\nexport const ENV_IDLE_EXIT_MS = 'DSH_OPENTUI_HOST_IDLE_MS'\nexport const DEFAULT_READINESS_TIMEOUT_MS = 30_000\n/** Env override for the host-start readiness budget, in milliseconds. */\nexport const ENV_BOOT_TIMEOUT_MS = 'DSH_OPENTUI_BOOT_TIMEOUT_MS'\n/** Env override for the post-mint mux-readiness budget, in milliseconds. */\nexport const ENV_MUX_TIMEOUT_MS = 'DSH_OPENTUI_MUX_TIMEOUT_MS'\n/** Default mux-readiness budget (the former SERVE_PROBE_BUDGET_MS constant). */\nexport const DEFAULT_SERVE_PROBE_BUDGET_MS = 20_000\n/** Env override for the first-connection budget, in milliseconds (transport). */\nexport const ENV_CONNECT_TIMEOUT_MS = 'DSH_OPENTUI_CONNECT_TIMEOUT_MS'\n/** Default first-connection budget (mirrors transport.ts's former constant). */\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 30_000\n\n/** Resolve the idle window (ms) for this process: explicit seconds option >\n * `DSH_OPENTUI_HOST_IDLE_MS` > `DEFAULT_IDLE_EXIT_MS`. Negative values are\n * clamped to 0 (resident); sub-millisecond values round to the nearest ms. */\nexport function resolveIdleExitMs(explicitSec?: number): number {\n  if (explicitSec !== undefined && Number.isFinite(explicitSec)) {\n    return Math.max(0, Math.round(explicitSec * 1000))\n  }\n  const raw = process.env[ENV_IDLE_EXIT_MS]\n  if (raw !== undefined && raw.trim() !== '') {\n    const parsed = Number(raw)\n    if (Number.isFinite(parsed)) return Math.max(0, Math.round(parsed))\n  }\n  return DEFAULT_IDLE_EXIT_MS\n}\n\n/** Same window in seconds (the `ensureHost`/`release()` unit). */\nexport function resolveIdleExitSec(explicitSec?: number): number {\n  return resolveIdleExitMs(explicitSec) / 1000\n}\n\n/** A usable millisecond budget: finite, integer and strictly positive. */\nfunction validBudgetMs(value: number): boolean {\n  return Number.isFinite(value) && Number.isInteger(value) && value > 0\n}\n\n/** Resolve a millisecond budget: explicit option > env > default. Non-finite,\n * non-integer and non-positive values are ignored (never thrown), falling\n * through to the next source — the same shape as resolveIdleExitMs. An env\n * value must be a plain decimal integer: `Number()` alone would also accept\n * hex/octal (`0x1D`), exponent (`30e2`) and numeric separators (`1_000`),\n * which are not valid spellings of a millisecond budget here. */\nfunction resolveBudgetMs(explicitMs: number | undefined, envName: string, defaultMs: number): number {\n  if (explicitMs !== undefined && validBudgetMs(explicitMs)) return explicitMs\n  const raw = process.env[envName]\n  if (raw !== undefined && /^\\d+$/.test(raw)) {\n    const parsed = Number(raw)\n    if (validBudgetMs(parsed)) return parsed\n  }\n  return defaultMs\n}\n\n/** Host-start readiness budget: explicit > DSH_OPENTUI_BOOT_TIMEOUT_MS > 30s. */\nexport function resolveBootTimeoutMs(explicitMs?: number): number {\n  return resolveBudgetMs(explicitMs, ENV_BOOT_TIMEOUT_MS, DEFAULT_READINESS_TIMEOUT_MS)\n}\n\n/** Post-mint mux-readiness budget: explicit > DSH_OPENTUI_MUX_TIMEOUT_MS > 20s. */\nexport function resolveMuxTimeoutMs(explicitMs?: number): number {\n  return resolveBudgetMs(explicitMs, ENV_MUX_TIMEOUT_MS, DEFAULT_SERVE_PROBE_BUDGET_MS)\n}\n\n/** First-connection budget: explicit > DSH_OPENTUI_CONNECT_TIMEOUT_MS > 30s.\n * Lives here next to the other two so all three env contracts stay in sync;\n * transport.ts imports it for its connectBudgetMs. */\nexport function resolveConnectTimeoutMs(explicitMs?: number): number {\n  return resolveBudgetMs(explicitMs, ENV_CONNECT_TIMEOUT_MS, DEFAULT_CONNECT_TIMEOUT_MS)\n}\n/** How long a lock whose pid is alive but not yet listening gets to come up\n * before we declare the lock stale (covers a cold host mid-boot). */\nexport const DEFAULT_STALE_PROBE_MS = 8_000\n/** Join budget over the readiness budget for a foreign booting placeholder:\n * covers the post-readiness cookie mint (MINT_RETRY_BUDGET_MS = 15s) that\n * still precedes the real lock write, plus slack. */\nconst BOOT_JOIN_MARGIN_MS = 20_000\n/** Poll cadence while waiting out a foreign booting placeholder. */\nconst BOOT_JOIN_POLL_MS = 200\nconst RESPAWN_WINDOW_MS = 15_000\nconst MAX_RAPID_RESPAWNS = 3\nconst LISTEN_PROBE_TIMEOUT_MS = 750\nconst LISTEN_POLL_MS = 200\n/** Bound for one authenticated adoption probe (a live host answers in ms). */\nconst ADOPT_PROBE_TIMEOUT_MS = 2_000\n/** Cadence for the post-boot mux-readiness poll (listener-fallback boots). */\nconst SERVE_PROBE_POLL_MS = 250\n/** Lines of child output quoted in surfaced error messages. */\nconst ERROR_TAIL_LINES = 12\nconst KILL_GRACE_MS = 5_000\nconst KILL_ESCALATE_MS = 2_000\nconst OUTPUT_TAIL_CAP = 8_000\n/** The host's readiness line (empirical, shipped dsh CLI):\n * `dsh web: http://127.0.0.1:<port>/?token=...` */\nconst URL_LINE = /dsh web: (https?:\\/\\/\\S+)/\n\n// ---------------------------------------------------------------------------\n// Errors — all typed, all carrying `code`.\n// ---------------------------------------------------------------------------\n\nexport class HostLifecycleError extends Error {\n  readonly code: string\n  constructor(code: string, message: string) {\n    super(message)\n    this.name = new.target.name\n    this.code = code\n  }\n}\n\n/** Last `ERROR_TAIL_LINES` lines of captured child output, for error text. */\nfunction errorTail(outputTail: string): string {\n  const lines = outputTail.split(/\\r?\\n/).filter((line) => line.length > 0)\n  if (lines.length === 0) return ''\n  return `\\n--- dsh host output (last ${Math.min(lines.length, ERROR_TAIL_LINES)} lines) ---\\n${lines\n    .slice(-ERROR_TAIL_LINES)\n    .join('\\n')}`\n}\n\nexport class HostBootTimeoutError extends HostLifecycleError {\n  constructor(readonly budgetMs: number, readonly outputTail: string) {\n    super('host-boot-timeout', `dsh host did not become ready within ${budgetMs}ms${errorTail(outputTail)}`)\n  }\n}\n\nexport class HostDiedError extends HostLifecycleError {\n  constructor(\n    readonly exitCode: number | null,\n    readonly signal: string | null,\n    readonly outputTail: string,\n  ) {\n    super(\n      'host-died',\n      `dsh host exited before readiness (code=${exitCode ?? 'null'}, signal=${signal ?? 'null'})${errorTail(outputTail)}`,\n    )\n  }\n}\n\n/** The listener came up but the client mux never served a ready item — the\n * host is wedged or died just after binding (a patch/plugin failure). The\n * child's output tail is quoted so the failure is diagnosable from the TUI\n * error line alone. */\nexport class HostNotServingError extends HostLifecycleError {\n  constructor(readonly outputTail: string, readonly budgetMs: number = DEFAULT_SERVE_PROBE_BUDGET_MS) {\n    super(\n      'host-not-serving',\n      `dsh host is listening but never served the client mux (${budgetMs}ms budget)${errorTail(outputTail)}`,\n    )\n  }\n}\n\nexport class HostSpawnError extends HostLifecycleError {\n  constructor(readonly cause: Error) {\n    super('host-spawn-failed', `failed to start dsh host: ${cause.message}`)\n    this.name = new.target.name\n  }\n}\n\nexport class HostRespawnLoopError extends HostLifecycleError {\n  constructor(readonly attempts: number, readonly windowMs: number) {\n    super(\n      'host-respawn-loop',\n      `dsh host failed ${attempts} rapid spawn attempts within ${windowMs}ms — giving up instead of looping`,\n    )\n  }\n}\n\nexport class HostBootSupersededError extends HostLifecycleError {\n  constructor() {\n    super(\n      'host-boot-superseded',\n      'another client took over this boot while it was coming up — our child was shut down; retry ensureHost to join the winner',\n    )\n  }\n}\n\nexport class ProfileMissingError extends HostLifecycleError {\n  constructor(readonly profile: string, readonly profileDir: string) {\n    super(\n      'profile-missing',\n      `profile '${profile}' is not provisioned (${profileDir} missing) — run scripts/provision-opentui-profile.mjs or: dsh ${profile} --from-default-profile web --dump-config`,\n    )\n  }\n}\n\nexport class MintUnavailableError extends HostLifecycleError {\n  constructor() {\n    super(\n      'mint-unavailable',\n      'mintOwnerCookie is unavailable: ./cookie-mint.ts not found and no mintCookie injected',\n    )\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Injectable seams + public contract.\n// ---------------------------------------------------------------------------\n\n/** Minimal shape of the spawned child the manager needs (structurally\n * satisfied by node's ChildProcess; faked in tests). */\nexport interface HostChildProcess {\n  pid: number\n  exitCode: number | null\n  stdout: { on(event: 'data', listener: (chunk: unknown) => void): unknown }\n  stderr: { on(event: 'data', listener: (chunk: unknown) => void): unknown }\n  on(event: 'exit', listener: (code: number | null, signal: string | null) => void): unknown\n  on(event: 'error', listener: (err: Error) => void): unknown\n  kill(signal?: string): boolean\n  unref?(): void\n}\n\nexport type SpawnDsh = (\n  argv: string[],\n  options: { cwd: string; env: NodeJS.ProcessEnv },\n) => HostChildProcess\n\n/** Frozen contract with ./cookie-mint.ts (parallel agent owns the real file). */\nexport type MintOwnerCookie = (opts: {\n  home: string\n  authority: string\n  maxAgeMs?: number\n}) => string\n\nexport interface EnsureHostOptions {\n  /** Host profile to run. Fixed product profile per ADR-0005 decision 3. */\n  profile?: string\n  /** Idle seconds after the last release before the host is SIGTERMed.\n   * Default 60. `0` = never exit (resident). */\n  idleExitSec?: number\n  /** dsh home dir. Default $DSH_HOME or ~/.dsh. */\n  dshHome?: string\n  /** Injectable spawn runner (tests). Default: real `dsh` from PATH. */\n  spawnDsh?: SpawnDsh\n  /** Injectable cookie mint (tests). Default: ./cookie-mint.ts import. */\n  mintCookie?: MintOwnerCookie\n  /** Readiness budget. Default 30_000 (or DSH_OPENTUI_BOOT_TIMEOUT_MS). */\n  readinessTimeoutMs?: number\n  /** Post-mint mux-readiness budget for listener-fallback boots.\n   * Default 20_000 (or DSH_OPENTUI_MUX_TIMEOUT_MS). */\n  serveProbeBudgetMs?: number\n  /** Max wait for a concurrently-booting host (another process holding the\n   * `booting` placeholder) to finish, when this client cold-boots behind it.\n   * Default `readinessTimeoutMs + 20s` (readiness + mint budget + slack). */\n  bootJoinTimeoutMs?: number\n  /** Grace window for a locked-but-not-listening pid (default 8_000). */\n  staleProbeMs?: number\n  /** Cookie max age forwarded to mintOwnerCookie. */\n  maxAgeMs?: number\n  /** v2 host-launch seam (ADR-0009). Called by `ensureV2Host` to claim/attach\n   * the singleton host through the v2 registry. Default: the real\n   * `host-launch.ts ensureHost` (dynamically imported to avoid the registry↔\n   * lifecycle import cycle). Tests inject a fake that writes a v2 record. */\n  launchHost?: (deps: V2LaunchDeps) => Promise<V2LaunchResult>\n  /** Child cwd for the v2 launcher (default `process.cwd()`). */\n  cwd?: string\n}\n\n/** Minimal deps the v2 launcher needs from the client. */\nexport interface V2LaunchDeps {\n  home: string\n  profile: string\n  cwd: string\n}\n\n/** The subset of host-launch's `HostLaunchResult` the v2 adapter consumes. */\nexport interface V2LaunchResult {\n  port: number\n  adopted: boolean\n  spawned: boolean\n  hostPid?: number\n}\n\nexport interface HostHandle {\n  readonly profile: string\n  readonly dshHome: string\n  readonly pid: number\n  readonly port: number\n  /** '127.0.0.1:<port>' — audience for the minted cookie. */\n  readonly authority: string\n  /** Minted Cookie header value; send as `Cookie: <cookieHeader>`. */\n  readonly cookieHeader: string\n  /** The printed `dsh web:` URL, or null when readiness came from the probe. */\n  readonly url: string | null\n  /** Launch token parsed out of the URL, or null. */\n  readonly token: string | null\n  /** Child stdout/stderr tail captured by this process ('' when adopted). */\n  diagnostics(): string\n  /** True when this host was adopted from the lockfile, not spawned here. */\n  readonly adopted: boolean\n  /** ADR-0009: true when this handle is backed by the v2 host-launch stack\n   * (v2 registry + heartbeat/watchdog lifecycle) rather than the legacy v1\n   * lockfile. v2 handles never arm the v1 idle-5s timer or write the lock. */\n  readonly v2Managed?: boolean\n  readonly refCount: number\n  /** +1 user (cancels a pending idle-exit). */\n  retain(): void\n  /** -1 user; at 0 arms the idle-exit timer (unless idleExitSec is 0). */\n  release(): void\n  /** SIGTERM (+SIGKILL escalation), remove the lockfile, evict the entry. */\n  dispose(): Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// Internal state.\n// ---------------------------------------------------------------------------\n\ntype HostState = 'booting' | 'ready' | 'disposing' | 'dead'\n\ninterface ManagedHost {\n  key: string\n  profile: string\n  dshHome: string\n  pid: number\n  port: number\n  authority: string\n  cookieHeader: string\n  url: string | null\n  token: string | null\n  adopted: boolean\n  /** ADR-0009 v2-backed host: no v1 lockfile writes, no v1 idle timer. */\n  v2Managed?: boolean\n  child: HostChildProcess | null\n  refCount: number\n  idleTimer: ReturnType<typeof setTimeout> | null\n  idleExitSec: number\n  maxAgeMs?: number\n  state: HostState\n  /** The lockfile currently describes this host. */\n  lockOwned: boolean\n  outputTail: string\n  exitInfo: { code: number | null; signal: string | null } | null\n  resolveExit: () => void\n  exitPromise: Promise<void>\n  termination: Promise<void> | null\n  handle: HostHandle | null\n  mintCookie?: MintOwnerCookie\n}\n\ninterface LockFile {\n  pid: number\n  port: number\n  authority: string\n  startedAt: string\n  profile: string\n  /** True on the O_EXCL placeholder a booter holds between spawn and\n   * readiness+mint; absent (false) on the real post-boot lock. */\n  booting?: boolean\n}\n\n/** Live managed hosts, keyed by `<dshHome>\\u0000<profile>`. */\nconst registry = new Map<string, ManagedHost>()\n/** In-flight boots, same keys — concurrent ensureHosts join them. */\nconst pendingBoots = new Map<string, Promise<ManagedHost>>()\n/** Spawn-attempt timestamps per key, for the rapid-respawn cap. */\nconst respawnHistory = new Map<string, number[]>()\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\nfunction registryKey(dshHome: string, profile: string): string {\n  return `${dshHome}\\u0000${profile}`\n}\n\nexport function defaultDshHome(): string {\n  return process.env.DSH_HOME || join(homedir(), '.dsh')\n}\n\nfunction lockPathFor(dshHome: string, profile: string): string {\n  return join(dshHome, `opentui-host.${profile}.json`)\n}\n\n// ---------------------------------------------------------------------------\n// Primitives: pid / listener / port / lockfile.\n// ---------------------------------------------------------------------------\n\nexport function pidAlive(pid: number): boolean {\n  return defaultPidAlive(pid)\n}\n\nexport function isListening(port: number): Promise<boolean> {\n  return new Promise((resolve) => {\n    let settled = false\n    const socket = netConnect({ host: '127.0.0.1', port })\n    const finish = (value: boolean) => {\n      if (settled) return\n      settled = true\n      socket.destroy()\n      resolve(value)\n    }\n    socket.setTimeout(LISTEN_PROBE_TIMEOUT_MS)\n    socket.once('connect', () => finish(true))\n    socket.once('error', () => finish(false))\n    socket.once('timeout', () => finish(false))\n  })\n}\n\n/** Stronger than a bare TCP accept: the port answers HTTP. A host binds its\n * socket before the HTTP/WS stack is mounted, so a TCP-only readiness signal\n * hands the carrier an authority whose first mux upgrade is rejected — the\n * `[connection] connection lost, retry #n` burst this check prevents. Any\n * status counts (401/404 prove the HTTP stack is serving). */\nasync function httpResponds(port: number): Promise<boolean> {\n  try {\n    const response = await fetch(`http://127.0.0.1:${port}/`, {\n      signal: AbortSignal.timeout(LISTEN_PROBE_TIMEOUT_MS),\n      redirect: 'manual',\n    })\n    try {\n      await response.body?.cancel()\n    } catch {\n      /* already drained */\n    }\n    return true\n  } catch {\n    return false\n  }\n}\n\n/** Bind-probe a free loopback port to hand to `dsh --port` (macOS has no\n * `timeout` command — all waiting here is JS timers). */\nfunction getFreePort(): Promise<number> {\n  return new Promise((resolve, reject) => {\n    const server = new Server((socket) => socket.destroy())\n    server.once('error', reject)\n    server.listen(0, '127.0.0.1', () => {\n      const { port } = server.address() as AddressInfo\n      server.close(() => resolve(port))\n    })\n  })\n}\n\n/** ADR-0009 v2 guard: the registry file at `<dshHome>/opentui-host.<profile>.json`\n * is shared by the v1 lockfile and the v2 registry. A record carrying\n * `version: 2` belongs to the host-launch stack and is NEVER a valid v1 lock.\n * v1 code must treat it as absent (read-only) — never downgrade it to v1. */\nfunction isV2Registry(dshHome: string, profile: string): boolean {\n  try {\n    const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as { version?: unknown } | null\n    return raw !== null && typeof raw === 'object' && raw.version === 2\n  } catch {\n    return false\n  }\n}\n\nfunction readLock(dshHome: string, profile: string): LockFile | null {\n  try {\n    const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as Partial<LockFile>\n    // v2 records are not v1 locks: refuse to read them as such (P0-1).\n    if ((raw as { version?: unknown }).version === 2) return null\n    if (typeof raw.pid !== 'number' || typeof raw.port !== 'number') return null\n    return {\n      pid: raw.pid,\n      port: raw.port,\n      authority: typeof raw.authority === 'string' ? raw.authority : `127.0.0.1:${raw.port}`,\n      startedAt: typeof raw.startedAt === 'string' ? raw.startedAt : '',\n      profile: typeof raw.profile === 'string' ? raw.profile : profile,\n      booting: raw.booting === true,\n    }\n  } catch {\n    return null // missing or corrupt → stale\n  }\n}\n\nfunction writeLock(dshHome: string, profile: string, host: ManagedHost): void {\n  // P0-1: never overwrite a v2 registry with a v1 payload. The v2 stack owns\n  // this file once written; an adopted client is strictly read-only here.\n  if (isV2Registry(dshHome, profile)) return\n  mkdirSync(dshHome, { recursive: true })\n  const path = lockPathFor(dshHome, profile)\n  const payload: LockFile = {\n    pid: host.pid,\n    port: host.port,\n    authority: host.authority,\n    startedAt: new Date().toISOString(),\n    profile,\n  }\n  const tmp = `${path}.tmp`\n  writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\\n')\n  renameSync(tmp, path) // near-atomic single-instance lock write\n}\n\n/** Remove the lockfile only if it still describes THIS host (never clobber a\n * newer host's lock). */\nfunction clearOurLock(host: ManagedHost): void {\n  if (!host.lockOwned) return\n  const lock = readLock(host.dshHome, host.profile)\n  if (lock && lock.pid === host.pid && lock.port === host.port) {\n    rmSync(lockPathFor(host.dshHome, host.profile), { force: true })\n  }\n}\n\n// -- Cold-boot mutual exclusion (the `booting` placeholder) -----------------\n\n/** Atomically claim the lockfile as a booting placeholder (create-if-absent\n * via link(2) on a fully-written tmp file — the winner's content is complete\n * at creation, so readers never see a partial claim). Exactly one cold boot\n * per profile wins across processes. Returns the claim's startedAt token, or\n * null when a rival (booting placeholder or real lock) already holds the\n * file. The placeholder's pid is the BOOTER's pid — the liveness anchor until\n * the real lock (child pid) replaces it. */\nfunction claimBootLock(dshHome: string, profile: string): string | null {\n  // P0-1: a v2 registry is a live single-instance claim — a v1 booter must\n  // never clobber it with a booting placeholder (that would orphan the v2 host).\n  if (isV2Registry(dshHome, profile)) return null\n  mkdirSync(dshHome, { recursive: true })\n  const path = lockPathFor(dshHome, profile)\n  const payload: LockFile = {\n    pid: process.pid,\n    port: 0, // unknown until the bind probe; waiters never probe it\n    authority: '127.0.0.1:0',\n    startedAt: new Date().toISOString(),\n    profile,\n    booting: true,\n  }\n  const tmp = `${path}.claim-${process.pid}-${Date.now()}`\n  writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\\n')\n  try {\n    linkSync(tmp, path) // EEXIST when a rival holds the file\n    return payload.startedAt\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'EEXIST') return null\n    throw err\n  } finally {\n    rmSync(tmp, { force: true })\n  }\n}\n\n/** Remove a booting placeholder only if it still describes THIS claim (pid,\n * optionally the startedAt token) — never a completed boot's real lock or a\n * rival's newer claim. */\nfunction removeBootClaim(\n  dshHome: string,\n  profile: string,\n  claim: { pid: number; startedAt?: string },\n): boolean {\n  const path = lockPathFor(dshHome, profile)\n  try {\n    const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<LockFile>\n    if (raw.booting !== true || raw.pid !== claim.pid) return false\n    if (claim.startedAt !== undefined && raw.startedAt !== claim.startedAt) return false\n  } catch {\n    return false // gone or corrupt — nothing of ours to remove\n  }\n  rmSync(path, { force: true })\n  return true\n}\n\n/** Remove a stale REAL lock only if it still describes the lock we judged\n * stale (never clobber a fresher write, never touch a placeholder). */\nfunction removeStaleLock(dshHome: string, profile: string, stale: LockFile): boolean {\n  const path = lockPathFor(dshHome, profile)\n  try {\n    const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<LockFile>\n    if (raw.booting === true || raw.pid !== stale.pid || raw.port !== stale.port) return false\n  } catch {\n    return false\n  }\n  rmSync(path, { force: true })\n  return true\n}\n\n/** True while the lockfile still holds OUR booting claim. */\nfunction bootClaimIntact(dshHome: string, profile: string, startedAt: string): boolean {\n  try {\n    const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as Partial<LockFile>\n    return raw.booting === true && raw.pid === process.pid && raw.startedAt === startedAt\n  } catch {\n    return false\n  }\n}\n\n/** Wait out a foreign booting placeholder (cross-process cold-boot mutual\n * exclusion): poll until the claim either flips into a real lock (the boot\n * completed — bootHost re-evaluates and adopts it) or becomes takeable\n * (booting pid dead / join budget lapsed — bootHost re-evaluates, finds no\n * lock and claims the boot itself). Never signals the booting pid. */\nasync function waitOutBootingLock(first: LockFile, o: ResolvedOptions): Promise<void> {\n  // A booting claim naming OUR pid is a leftover from a previous incarnation\n  // of this pid (crash + pid reuse): take it over immediately.\n  if (first.pid === process.pid) {\n    removeBootClaim(o.dshHome, o.profile, { pid: first.pid })\n    return\n  }\n  const budget = o.bootJoinTimeoutMs ?? o.readinessTimeoutMs + BOOT_JOIN_MARGIN_MS\n  const deadline = Date.now() + budget\n  const claim = { pid: first.pid, startedAt: first.startedAt }\n  while (Date.now() < deadline) {\n    await sleep(BOOT_JOIN_POLL_MS)\n    if (!pidAlive(claim.pid)) {\n      // the booter died mid-boot: its claim is abandoned — take it over\n      removeBootClaim(o.dshHome, o.profile, claim)\n      return\n    }\n    const current = readLock(o.dshHome, o.profile)\n    if (!current || !current.booting) return // boot completed (or claim gone) — re-evaluate\n  }\n  // Join budget lapsed: force the takeover if the claim is unchanged.\n  removeBootClaim(o.dshHome, o.profile, claim)\n}\n\n// ---------------------------------------------------------------------------\n// Cookie mint resolution (real module owned by the transport/cookie agent).\n// ---------------------------------------------------------------------------\n\nlet realMintPromise: Promise<MintOwnerCookie | null> | null = null\n\n/** Resolves `mintOwnerCookie` from ./cookie-mint.ts at runtime. The specifier\n * is built dynamically on purpose: the module is owned by the parallel\n * transport/cookie agent and may not exist yet — a literal import would fail\n * to typecheck until it lands, and flipping ts-ignore/expect-error would\n * break whichever side lands last. */\nfunction loadRealMint(): Promise<MintOwnerCookie | null> {\n  realMintPromise ??= (async () => {\n    const dynamicImport = (specifier: string): Promise<unknown> => import(specifier)\n    for (const specifier of ['./cookie-mint.js', './cookie-mint.ts']) {\n      try {\n        const mod: unknown = await dynamicImport(specifier)\n        const mint = (mod as { mintOwnerCookie?: unknown }).mintOwnerCookie\n        if (typeof mint === 'function') return mint as MintOwnerCookie\n      } catch {\n        // try next specifier / fall through to null\n      }\n    }\n    return null\n  })()\n  return realMintPromise\n}\n\nasync function mintCookieFor(host: ManagedHost): Promise<string> {\n  const mint = host.mintCookie ?? (await loadRealMint())\n  if (!mint) throw new MintUnavailableError()\n  return mint({\n    home: host.dshHome,\n    authority: host.authority,\n    ...(host.maxAgeMs !== undefined ? { maxAgeMs: host.maxAgeMs } : {}),\n  })\n}\n\n/** Mint errors that mean \"the host has not written its grant yet\" (first-boot\n * race — the Host persists `client-connection/browser-session` during\n * connection activation, which can lag the readiness line on a cold boot).\n * cookie-mint.ts already retries these for 2s internally; a cold scratch\n * home needs more, so the manager retries them here too. Permanent mint\n * failures (insecure file, invalid grant shape) surface immediately. */\nconst RETRYABLE_MINT_ERRORS = new Set(['CredentialsFileMissingError', 'CredentialsGrantMissingError'])\nconst MINT_RETRY_BUDGET_MS = 15_000\nconst MINT_RETRY_INTERVAL_MS = 250\n\nasync function mintCookieWithRetry(host: ManagedHost): Promise<string> {\n  const deadline = Date.now() + MINT_RETRY_BUDGET_MS\n  for (;;) {\n    try {\n      return await mintCookieFor(host)\n    } catch (err) {\n      const retryable = err instanceof Error && RETRYABLE_MINT_ERRORS.has(err.name)\n      if (!retryable || Date.now() >= deadline) throw err\n      await sleep(MINT_RETRY_INTERVAL_MS)\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Child plumbing.\n// ---------------------------------------------------------------------------\n\nfunction defaultSpawnDsh(argv: string[], options: { cwd: string; env: NodeJS.ProcessEnv }): HostChildProcess {\n  const env = { ...options.env }\n  // npm_config_* leaks from `npm run` wrappers confuse the dsh boot; strip.\n  for (const key of Object.keys(env)) {\n    if (key.startsWith('npm_config_')) delete env[key]\n  }\n  const child = spawn('dsh', argv, {\n    cwd: options.cwd,\n    env,\n    detached: true, // resident host must survive this client process\n    stdio: ['ignore', 'pipe', 'pipe'],\n  })\n  child.unref()\n  // piped stdio keeps the manager's event loop alive; unref the pipes too\n  // (bun's stream types omit unref, hence the structural cast)\n  for (const pipe of [child.stdout, child.stderr]) {\n    ;(pipe as unknown as { unref?: () => void }).unref?.()\n  }\n  return child as unknown as HostChildProcess\n}\n\n/** OpenTUI's native layer (host-entry-v2) needs node's `--experimental-ffi`;\n * a bare `dsh --profile <profile>` does not carry it (only the dsh-opentui\n * launcher injects it, and client mode never runs through that launcher).\n * Without the flag the mounted v2 shell re-execs the whole dsh command line\n * to add it (reExecWithFfi) — a second host instance then races the booting\n * listener (EADDRINUSE) and the client's TUI renders blank. Merge the flag\n * into NODE_OPTIONS here, once, deduped as a space-delimited token (the same\n * rule as the dsh-opentui launcher's `--plugin` branch) so an inherited\n * NODE_OPTIONS that already carries the flag is passed through untouched. */\nconst FFI_FLAG = '--experimental-ffi'\n\nfunction withFfiFlag(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n  const existing = env.NODE_OPTIONS ?? ''\n  if (existing.split(/\\s+/).includes(FFI_FLAG)) return env\n  return { ...env, NODE_OPTIONS: `${existing} ${FFI_FLAG}`.trim() }\n}\n\nfunction childEnv(dshHome: string): NodeJS.ProcessEnv {\n  return withFfiFlag({ ...process.env, DSH_HOME: dshHome })\n}\n\nfunction attachChildWatchers(host: ManagedHost, child: HostChildProcess): void {\n  const push = (chunk: unknown) => {\n    host.outputTail = (host.outputTail + String(chunk)).slice(-OUTPUT_TAIL_CAP)\n  }\n  child.stdout.on('data', push)\n  child.stderr.on('data', push)\n  child.on('error', () => {\n    // post-boot spawn errors (rare; boot-time ones are surfaced by the\n    // readiness waiter's own 'error' listener)\n  })\n  child.on('exit', (code, signal) => {\n    host.exitInfo = { code, signal }\n    host.resolveExit()\n    if (host.state === 'ready') {\n      // unexpected death: clear the lock, evict; the next ensureHost respawns\n      if (host.idleTimer) {\n        clearTimeout(host.idleTimer)\n        host.idleTimer = null\n      }\n      clearOurLock(host)\n      host.state = 'dead'\n      registry.delete(host.key)\n    }\n    // 'booting' → the readiness waiter rejects; 'disposing' → our own kill.\n  })\n}\n\ninterface ReadyResult {\n  url: string | null\n  token: string | null\n  port: number\n  authority: string\n  /** Which signal resolved readiness. `url` is the host's post-loader line\n   * (the full plugin tree and the connection service are mounted); `listener`\n   * is the weaker HTTP fallback and must be followed by a mux probe. */\n  via: 'url' | 'listener'\n}\n\nfunction readyFromUrl(urlText: string): ReadyResult {\n  const url = new URL(urlText)\n  const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80)\n  return {\n    url: urlText,\n    token: url.searchParams.get('token'),\n    port,\n    authority: `${url.hostname}:${port}`,\n    via: 'url',\n  }\n}\n\nfunction waitForReadiness(\n  child: HostChildProcess,\n  expectedPort: number,\n  budgetMs: number,\n  getTail: () => string,\n): Promise<ReadyResult> {\n  return new Promise<ReadyResult>((resolve, reject) => {\n    let settled = false\n    const done = (ok: boolean, value: ReadyResult | HostLifecycleError) => {\n      if (settled) return\n      settled = true\n      clearTimeout(timer)\n      clearInterval(poll)\n      if (ok) resolve(value as ReadyResult)\n      else reject(value)\n    }\n    const timer = setTimeout(() => {\n      child.kill('SIGTERM')\n      done(false, new HostBootTimeoutError(budgetMs, getTail()))\n    }, budgetMs)\n    child.on('exit', (code, signal) =>\n      done(false, new HostDiedError(code, signal, getTail())),\n    )\n    child.on('error', (err) => done(false, new HostSpawnError(err)))\n    child.stdout.on('data', (chunk) => {\n      const match = URL_LINE.exec(String(chunk))\n      if (match) done(true, readyFromUrl(match[1]!))\n    })\n    // Fallback: wait for the HTTP stack, not just the bound socket (in case\n    // the stdout contract changes). TCP-bind readiness is too early — the\n    // carrier's first mux upgrade would be rejected.\n    const poll = setInterval(() => {\n      void httpResponds(expectedPort).then((up) => {\n        if (up) {\n          done(true, {\n            url: null,\n            token: null,\n            port: expectedPort,\n            authority: `127.0.0.1:${expectedPort}`,\n            via: 'listener',\n          })\n        }\n      })\n    }, LISTEN_POLL_MS)\n  })\n}\n\n// ---------------------------------------------------------------------------\n// Boot / adopt / terminate.\n// ---------------------------------------------------------------------------\n\nfunction makeHandle(host: ManagedHost): HostHandle {\n  host.handle ??= {\n    get profile() {\n      return host.profile\n    },\n    get dshHome() {\n      return host.dshHome\n    },\n    get pid() {\n      return host.pid\n    },\n    get port() {\n      return host.port\n    },\n    get authority() {\n      return host.authority\n    },\n    get cookieHeader() {\n      return host.cookieHeader\n    },\n    get url() {\n      return host.url\n    },\n    get token() {\n      return host.token\n    },\n    diagnostics() {\n      return errorTail(host.outputTail).replace(/^\\n/, '')\n    },\n    get adopted() {\n      return host.adopted\n    },\n    get v2Managed() {\n      return host.v2Managed === true\n    },\n    get refCount() {\n      return host.refCount\n    },\n    retain() {\n      attachHost(host)\n    },\n    release() {\n      releaseHost(host)\n    },\n    dispose() {\n      return terminateHost(host)\n    },\n  }\n  return host.handle!\n}\n\nfunction adoptHost(lock: LockFile, o: ResolvedOptions): ManagedHost {\n  const host: ManagedHost = {\n    key: o.key,\n    profile: o.profile,\n    dshHome: o.dshHome,\n    pid: lock.pid,\n    port: lock.port,\n    authority: lock.authority,\n    cookieHeader: '',\n    url: null,\n    token: null,\n    adopted: true,\n    child: null,\n    refCount: 0,\n    idleTimer: null,\n    idleExitSec: o.idleExitSec,\n    maxAgeMs: o.maxAgeMs,\n    state: 'ready',\n    lockOwned: true, // the existing lockfile already describes this host\n    outputTail: '',\n    exitInfo: null,\n    resolveExit: () => {},\n    exitPromise: Promise.resolve(),\n    termination: null,\n    handle: null,\n    mintCookie: o.mintCookie,\n  }\n  registry.set(o.key, host)\n  // Adoption bump: refresh startedAt/mtime so the detached idle reaper sees\n  // recent liveness — the adopted client can spend up to MINT_RETRY_BUDGET_MS\n  // minting its cookie before its first ESTABLISHED connection, past a\n  // grace-edge adoption.\n  writeLock(o.dshHome, o.profile, host)\n  return host\n}\n\ninterface ResolvedOptions {\n  profile: string\n  dshHome: string\n  idleExitSec: number\n  readinessTimeoutMs: number\n  serveProbeBudgetMs: number\n  bootJoinTimeoutMs?: number\n  staleProbeMs: number\n  maxAgeMs?: number\n  spawnDsh: SpawnDsh\n  mintCookie?: MintOwnerCookie\n  key: string\n}\n\nfunction resolveOptions(opts: EnsureHostOptions): ResolvedOptions {\n  const profile = opts.profile ?? DEFAULT_PROFILE\n  const dshHome = opts.dshHome ?? defaultDshHome()\n  const idleExitSec = resolveIdleExitSec(opts.idleExitSec)\n  return {\n    profile,\n    dshHome,\n    idleExitSec,\n    readinessTimeoutMs: resolveBootTimeoutMs(opts.readinessTimeoutMs),\n    serveProbeBudgetMs: resolveMuxTimeoutMs(opts.serveProbeBudgetMs),\n    ...(opts.bootJoinTimeoutMs !== undefined ? { bootJoinTimeoutMs: opts.bootJoinTimeoutMs } : {}),\n    staleProbeMs: opts.staleProbeMs ?? DEFAULT_STALE_PROBE_MS,\n    ...(opts.maxAgeMs !== undefined ? { maxAgeMs: opts.maxAgeMs } : {}),\n    spawnDsh: opts.spawnDsh ?? defaultSpawnDsh,\n    ...(opts.mintCookie !== undefined ? { mintCookie: opts.mintCookie } : {}),\n    key: registryKey(dshHome, profile),\n  }\n}\n\nasync function bootHost(o: ResolvedOptions): Promise<ManagedHost> {\n  // Respawn cap: no infinite loops. Spawn attempts inside the rolling window\n  // count; a successful boot resets the history.\n  const now = Date.now()\n  const history = (respawnHistory.get(o.key) ?? []).filter((t) => now - t < RESPAWN_WINDOW_MS)\n  if (history.length >= MAX_RAPID_RESPAWNS) {\n    throw new HostRespawnLoopError(MAX_RAPID_RESPAWNS, RESPAWN_WINDOW_MS)\n  }\n  respawnHistory.set(o.key, [...history, now])\n\n  // Phase 1 — resolve the single-instance lock. Loops until this process\n  // either adopts a live host or holds the O_EXCL booting claim.\n  let claimStartedAt = ''\n  for (;;) {\n    const lock = readLock(o.dshHome, o.profile)\n    if (lock?.booting) {\n      // Another process holds the cold-boot claim: wait it out (join on\n      // success, takeover on booter death / join-budget lapse), then\n      // re-evaluate — a completed boot is adopted below.\n      await waitOutBootingLock(lock, o)\n      continue\n    }\n    if (lock && (await lockIsFresh(lock, o.staleProbeMs))) {\n      const adopted = adoptHost(lock, o) // bumps the lockfile (reaper liveness)\n      adopted.cookieHeader = await mintCookieWithRetry(adopted)\n      // A live pid + open port is not enough: the process must accept OUR\n      // cookie (same home grant) and serve the web app. A foreign/rotated\n      // host on that port answers 401/404 and would make the carrier retry\n      // forever — treat the lock as stale and boot fresh instead.\n      if (\n        await probeHostHttp({\n          authority: adopted.authority,\n          cookieHeader: adopted.cookieHeader,\n          timeoutMs: ADOPT_PROBE_TIMEOUT_MS,\n        })\n      ) {\n        respawnHistory.delete(o.key)\n        return adopted\n      }\n      // Never signal the foreign pid (it may belong to another home / user);\n      // drop only the stale lock so the fresh boot can claim it.\n      registry.delete(o.key)\n      removeStaleLock(o.dshHome, o.profile, lock)\n      continue\n    }\n    // Stale lock (or none): clear the way, verify the profile, claim the\n    // boot placeholder. A rival that claimed first leaves the file in place\n    // (EEXIST) — re-evaluate against its booting claim.\n    if (lock) removeStaleLock(o.dshHome, o.profile, lock)\n    const lockPath = lockPathFor(o.dshHome, o.profile)\n    if (!existsSync(lockPath)) {\n      const profileDir = join(o.dshHome, 'profiles', o.profile)\n      if (!existsSync(profileDir)) throw new ProfileMissingError(o.profile, profileDir)\n      const claimed = claimBootLock(o.dshHome, o.profile)\n      if (claimed !== null) {\n        claimStartedAt = claimed\n        break // we hold the claim — proceed to spawn\n      }\n    } else if (readLock(o.dshHome, o.profile) === null) {\n      // File exists but is unreadable/corrupt: pre-fix semantics treat a\n      // corrupt lock as stale — remove it and re-evaluate.\n      rmSync(lockPath, { force: true })\n    }\n    await sleep(BOOT_JOIN_POLL_MS)\n  }\n\n  // Phase 2 — boot under the claim. The claim is released by writeLock on\n  // success and removed in the failure path.\n  const profileDir = join(o.dshHome, 'profiles', o.profile)\n  // Append-system (dsh-tui-pi port): seed $DSH_HOME/APPEND_SYSTEM.md and keep\n  // the managed preset row in the profile patch BEFORE the host spawns — the\n  // host reads the patch (and evaluates the persona suffix's `!!js` read) at\n  // its own boot. Best-effort: a failure boots without the preset, and the\n  // roster gate in remote-host-session keeps `agentPreset` off the wire, so\n  // an enrichment must never fail the boot.\n  try {\n    const provision = provisionAppendSystem(o.dshHome, o.profile)\n    // Same channel as the throw path: a skipped/collision outcome boots\n    // WITHOUT the preset and must be visible in the error log, never silent.\n    if (provision.patch.status === 'collision' || provision.patch.status === 'skipped') {\n      console.error(`[lifecycle] append-system preset not provisioned (${provision.patch.status}): ${provision.patch.detail}`)\n    }\n  } catch (error) {\n    console.error('[lifecycle] append-system sync failed (booting without the preset):', error)\n  }\n  const port = await getFreePort()\n  const child = o.spawnDsh(['--profile', o.profile, '--no-open', '--port', String(port)], {\n    cwd: profileDir,\n    env: childEnv(o.dshHome),\n  })\n  const host: ManagedHost = {\n    key: o.key,\n    profile: o.profile,\n    dshHome: o.dshHome,\n    pid: child.pid,\n    port,\n    authority: `127.0.0.1:${port}`,\n    cookieHeader: '',\n    url: null,\n    token: null,\n    adopted: false,\n    child,\n    refCount: 0,\n    idleTimer: null,\n    idleExitSec: o.idleExitSec,\n    maxAgeMs: o.maxAgeMs,\n    state: 'booting',\n    lockOwned: false,\n    outputTail: '',\n    exitInfo: null,\n    resolveExit: () => {},\n    exitPromise: Promise.resolve(),\n    termination: null,\n    handle: null,\n    mintCookie: o.mintCookie,\n  }\n  {\n    let resolveExit!: () => void\n    host.exitPromise = new Promise<void>((resolve) => {\n      resolveExit = resolve\n    })\n    host.resolveExit = resolveExit\n  }\n  attachChildWatchers(host, child)\n\n  try {\n    const ready = await waitForReadiness(child, port, o.readinessTimeoutMs, () => host.outputTail)\n    host.url = ready.url\n    host.token = ready.token\n    if (ready.port !== port) {\n      host.port = ready.port\n    }\n    host.authority = ready.authority\n    host.cookieHeader = await mintCookieWithRetry(host)\n    // The listener-fallback readiness only proves the HTTP stack answers.\n    // Gate on the actual client mux ($events ready item) so the carrier's\n    // first attempt cannot land in the retry loop; the URL line already\n    // implies the loader + connection service are mounted.\n    if (ready.via === 'listener') {\n      const deadline = Date.now() + o.serveProbeBudgetMs\n      let serving = false\n      while (Date.now() < deadline) {\n        serving = await probeHostMux({\n          authority: host.authority,\n          cookieHeader: host.cookieHeader,\n          timeoutMs: 1_500,\n        })\n        if (serving) break\n        if (!pidAlive(child.pid)) break // died after binding: surface the tail now\n        await sleep(SERVE_PROBE_POLL_MS)\n      }\n      if (!serving) throw new HostNotServingError(host.outputTail, o.serveProbeBudgetMs)\n    }\n    // Claim still ours? A join-budget takeover by another client replaced the\n    // placeholder — kill our child rather than clobber the winner's lock\n    // (which would leave two live hosts and concurrent DSH_HOME writers).\n    if (!bootClaimIntact(o.dshHome, o.profile, claimStartedAt)) {\n      throw new HostBootSupersededError()\n    }\n    writeLock(o.dshHome, o.profile, host) // replaces the booting placeholder\n    host.lockOwned = true\n    host.state = 'ready'\n    respawnHistory.delete(o.key)\n    registry.set(o.key, host)\n    return host\n  } catch (err) {\n    // Boot failed (timeout / death / mint / superseded): release the claim\n    // and shut down what we started.\n    removeBootClaim(o.dshHome, o.profile, { pid: process.pid, startedAt: claimStartedAt })\n    await terminateHost(host).catch(() => {})\n    throw err\n  }\n}\n\n/** Fresh lock check: pid alive AND listener up. A pid that is alive but not\n * listening may be mid-boot, so it gets `staleProbeMs` to come up. */\nasync function lockIsFresh(lock: LockFile, staleProbeMs: number): Promise<boolean> {\n  if (!pidAlive(lock.pid)) return false\n  if (await isListening(lock.port)) return true\n  const deadline = Date.now() + staleProbeMs\n  while (Date.now() < deadline) {\n    await sleep(LISTEN_POLL_MS)\n    if (!pidAlive(lock.pid)) return false\n    if (await isListening(lock.port)) return true\n  }\n  return false\n}\n\nfunction attachHost(host: ManagedHost): void {\n  host.refCount += 1\n  if (host.idleTimer) {\n    clearTimeout(host.idleTimer)\n    host.idleTimer = null\n  }\n}\n\nfunction releaseHost(host: ManagedHost): void {\n  host.refCount = Math.max(0, host.refCount - 1)\n  // ADR-0009 decision 6: v2-backed hosts are shut down by the refcount +\n  // heartbeat + last-one grace path (client-lifecycle), never by the legacy\n  // idle-5s timer. A v2 release only drops the in-process ref; it never arms\n  // a kill timer (two lifecycles must not coexist on one host).\n  if (host.v2Managed) return\n  if (host.refCount === 0 && host.state === 'ready' && host.idleExitSec > 0) {\n    const timer = setTimeout(() => {\n      host.idleTimer = null\n      void terminateHost(host)\n    }, host.idleExitSec * 1000)\n    timer.unref?.() // a refcount-0 manager must not hang on this timer\n    host.idleTimer = timer\n  }\n}\n\nfunction signalPid(pid: number, signal: NodeJS.Signals): void {\n  try {\n    process.kill(pid, signal)\n  } catch {\n    // already gone — fine\n  }\n}\n\nasync function waitPidGone(pid: number, budgetMs: number): Promise<boolean> {\n  const deadline = Date.now() + budgetMs\n  while (pidAlive(pid)) {\n    if (Date.now() > deadline) return false\n    await sleep(LISTEN_POLL_MS)\n  }\n  return true\n}\n\nasync function terminateHost(host: ManagedHost): Promise<void> {\n  if (host.state === 'dead') {\n    clearOurLock(host)\n    registry.delete(host.key)\n    return\n  }\n  if (host.state === 'disposing' && host.termination) return host.termination\n  if (host.termination) return host.termination\n\n  host.state = 'disposing'\n  clearOurLock(host)\n  registry.delete(host.key)\n\n  host.termination = (async () => {\n    if (host.child) {\n      host.child.kill('SIGTERM')\n      await Promise.race([host.exitPromise, sleep(KILL_GRACE_MS)])\n      if (!host.exitInfo) {\n        signalPid(host.pid, 'SIGKILL')\n        await Promise.race([host.exitPromise, sleep(KILL_ESCALATE_MS)])\n      }\n    } else {\n      // Adopted host: no child object in this process; signal by pid.\n      signalPid(host.pid, 'SIGTERM')\n      if (!(await waitPidGone(host.pid, KILL_GRACE_MS))) {\n        signalPid(host.pid, 'SIGKILL')\n        await waitPidGone(host.pid, KILL_ESCALATE_MS)\n      }\n    }\n    host.state = 'dead'\n  })()\n  // The exit watcher only acts on state 'ready', so our own SIGTERM here\n  // ('disposing') and booting failures ('booting') are not re-evicted.\n  return host.termination\n}\n\n// ---------------------------------------------------------------------------\n// v2 host-launch attach (ADR-0009 — the production path).\n// ---------------------------------------------------------------------------\n\n/** The v2 registry fields the client adapter needs (host-registry.ts owns the\n * canonical type; read locally to avoid the registry→lifecycle import cycle). */\nfunction readV2Record(dshHome: string, profile: string): { pid: number; port: number; authority: string } | null {\n  try {\n    const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as {\n      version?: unknown\n      pid?: unknown\n      port?: unknown\n      authority?: unknown\n    } | null\n    if (raw === null || typeof raw !== 'object' || raw.version !== 2) return null\n    if (typeof raw.pid !== 'number' || typeof raw.port !== 'number') return null\n    return {\n      pid: raw.pid,\n      port: raw.port,\n      authority: typeof raw.authority === 'string' ? raw.authority : `127.0.0.1:${raw.port}`,\n    }\n  } catch {\n    return null\n  }\n}\n\n/** Default v2 launcher: dynamically import host-launch so this module never\n * statically depends on the registry/health/port modules that import it back\n * (their `pidAlive`/`isListening` helpers are used at call time only). */\nasync function defaultLaunchHost(deps: V2LaunchDeps): Promise<V2LaunchResult> {\n  const mod = await import('./host-launch.ts')\n  return mod.ensureHost({ home: deps.home, profile: deps.profile, cwd: deps.cwd })\n}\n\n/** Boot/adopt the host via the v2 host-launch stack and wrap it in a\n * HostHandle. This performs NO v1 lockfile write: `lockOwned` is false and a\n * v2 registry is consumed read-only. The host's real lifecycle is refcount +\n * heartbeat + last-one grace + watchdog (client-lifecycle.ts), not the v1\n * idle-5s timer. */\nasync function bootV2Host(o: ResolvedOptions, opts: EnsureHostOptions): Promise<ManagedHost> {\n  const launch = opts.launchHost ?? defaultLaunchHost\n  const result = await launch({ home: o.dshHome, profile: o.profile, cwd: opts.cwd ?? process.cwd() })\n\n  // The launcher writes the v2 registry; adopt it read-only. Fall back to the\n  // launcher result when a fake seam did not materialise a record on disk.\n  const record = readV2Record(o.dshHome, o.profile)\n  const port = record?.port ?? result.port\n  const pid = record?.pid ?? result.hostPid ?? 0\n  const authority = record?.authority ?? `127.0.0.1:${port}`\n\n  const host: ManagedHost = {\n    key: o.key,\n    profile: o.profile,\n    dshHome: o.dshHome,\n    pid,\n    port,\n    authority,\n    cookieHeader: '',\n    url: null,\n    token: null,\n    adopted: result.adopted,\n    v2Managed: true,\n    child: null,\n    refCount: 0,\n    idleTimer: null,\n    idleExitSec: 0, // no legacy idle timer: ADR-0009 decision 6\n    state: 'ready',\n    lockOwned: false, // never write/clear the v1 lockfile\n    outputTail: '',\n    exitInfo: null,\n    resolveExit: () => {},\n    exitPromise: Promise.resolve(),\n    termination: null,\n    handle: null,\n    ...(o.maxAgeMs !== undefined ? { maxAgeMs: o.maxAgeMs } : {}),\n    ...(o.mintCookie !== undefined ? { mintCookie: o.mintCookie } : {}),\n  }\n  registry.set(o.key, host)\n  host.cookieHeader = await mintCookieWithRetry(host)\n  return host\n}\n\n/** ADR-0009 production entry: ensure/adopt the singleton host through the v2\n * host-launch stack (v2 registry), producing a HostHandle with no v1 writes. */\nexport async function ensureV2Host(opts: EnsureHostOptions = {}): Promise<HostHandle> {\n  const o = resolveOptions(opts)\n\n  const live = registry.get(o.key)\n  if (live && live.state === 'ready' && live.v2Managed) {\n    attachHost(live)\n    return makeHandle(live)\n  }\n\n  const pending = pendingBoots.get(o.key)\n  if (pending) {\n    const host = await pending\n    attachHost(host)\n    return makeHandle(host)\n  }\n\n  const boot = bootV2Host(o, opts).finally(() => pendingBoots.delete(o.key))\n  pendingBoots.set(o.key, boot)\n  const host = await boot\n  attachHost(host)\n  return makeHandle(host)\n}\n\n// ---------------------------------------------------------------------------\n// Public entry point.\n// ---------------------------------------------------------------------------\n\n/** Manage one resident dsh host per profile (see file header for the full\n * contract). Idempotent: existing live hosts are joined, not re-booted.\n *\n * ADR-0009 (P0-1): when the registry is already a version-2 record, this\n * delegates to `ensureV2Host` so the legacy v1 lockfile path never touches it.\n * The legacy path remains only for pre-upgrade (v1) registries. */\nexport async function ensureHost(opts: EnsureHostOptions = {}): Promise<HostHandle> {\n  const o = resolveOptions(opts)\n  if (isV2Registry(o.dshHome, o.profile)) return ensureV2Host(opts)\n\n  const live = registry.get(o.key)\n  if (live && live.state === 'ready') {\n    attachHost(live)\n    return makeHandle(live)\n  }\n\n  const pending = pendingBoots.get(o.key)\n  if (pending) {\n    const host = await pending\n    attachHost(host)\n    return makeHandle(host)\n  }\n\n  const boot = bootHost(o).finally(() => pendingBoots.delete(o.key))\n  pendingBoots.set(o.key, boot)\n  const host = await boot\n  attachHost(host)\n  return makeHandle(host)\n}\n\n// ---------------------------------------------------------------------------\n// Test-only internals.\n// ---------------------------------------------------------------------------\n\n/** Exposed strictly for the lifecycle tests: registry eviction checks and\n * probing whether the real cookie-mint module has landed. Not a public API. */\nexport const __internals = {\n  registry,\n  pendingBoots,\n  respawnHistory,\n  loadRealMint,\n  lockPathFor,\n  registryKey,\n}\n",
    "/**\n * Singleton host registry — schema v2 (ADR-0009 decisions 4 & 8;\n * DESIGN-redesign §7).\n *\n * File: `<DSH_HOME>/opentui-host.<profile>.json`\n *\n *   {\n *     version: 2, profile, home, pid, port,\n *     phase: \"claim|booting|ready|stopping\",\n *     startedAt, updatedAt, authority,\n *     clients: [{ id, pid, lastSeen }]\n *   }\n *\n * Invariants this module enforces:\n * - writes are ATOMIC (temp file in the same directory + rename); readers\n *   never observe a half-written record;\n * - the O_EXCL claim uses `link(2)` on a fully-written temp file, so exactly\n *   one of N concurrent claimers wins and a loser gets \"occupied\", never a\n *   clobbered winner;\n * - reads are SCHEMA-VALIDATED: a v2 record is returned typed; an old record\n *   (no `version` / no `clients`) is tagged `legacy`; garbage is `invalid`;\n * - stale detection and legacy cleanup NEVER signal a process\n *   (`safeClearLegacy` only unlinks the registry FILE). Killing a host needs\n *   the three-evidence rule in ADR-0009 decision 8 and belongs to a later\n *   task — this module deliberately has no `process.kill` call.\n *\n * Reuse: the schema is a superset of the existing v1 lockfile handled by\n * `lifecycle.ts` (`{ pid, port, authority, startedAt, profile }`), which is\n * exactly the `legacy` shape detected here. The default liveness probe\n * delegates to `lifecycle.pidAlive`. No existing export or behavior in\n * lifecycle.ts is changed by this module.\n *\n * Filesystem and clock are injectable seams so concurrency / stale / legacy\n * cases are unit-testable without touching the real HOME or spawning a host.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n  existsSync,\n  linkSync,\n  mkdirSync,\n  readFileSync,\n  renameSync,\n  unlinkSync,\n  writeFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { pidAlive as defaultPidAlive } from './lifecycle.ts'\n\n/** Current registry schema version. */\nexport const REGISTRY_SCHEMA_VERSION = 2\n\n/** Lifecycle phases a v2 registry may record. */\nexport const REGISTRY_PHASES = ['claim', 'booting', 'ready', 'stopping'] as const\nexport type RegistryPhase = (typeof REGISTRY_PHASES)[number]\n\n/** One attached client recorded in the registry. */\nexport interface RegistryClient {\n  id: string\n  pid: number\n  /** ISO timestamp of the last heartbeat. */\n  lastSeen: string\n}\n\n/** A validated schema-v2 host registry record. */\nexport interface HostRegistryV2 {\n  version: 2\n  profile: string\n  home: string\n  pid: number\n  port: number\n  phase: RegistryPhase\n  startedAt: string\n  updatedAt: string\n  authority: string\n  clients: RegistryClient[]\n}\n\n/** The shape of a pre-v2 (legacy) lockfile — kept for callers that migrate. */\nexport interface LegacyRegistry {\n  pid: number\n  port: number\n  authority?: string\n  startedAt?: string\n  profile?: string\n  booting?: boolean\n}\n\n/** Tagged result of reading + validating a registry file. */\nexport type RegistryReadResult =\n  | { kind: 'v2'; value: HostRegistryV2 }\n  | { kind: 'legacy'; raw: LegacyRegistry }\n  | { kind: 'invalid'; raw: unknown; reason: string }\n  | { kind: 'missing' }\n\n// ---------------------------------------------------------------------------\n// Injectable seams.\n// ---------------------------------------------------------------------------\n\n/** The slice of `node:fs` this module needs (injectable in tests). */\nexport interface RegistryFs {\n  existsSync(path: string): boolean\n  mkdirSync(path: string, options?: { recursive?: boolean }): void\n  readFileSync(path: string, encoding: 'utf8'): string\n  writeFileSync(path: string, data: string, options?: { mode?: number }): void\n  renameSync(from: string, to: string): void\n  linkSync(from: string, to: string): void\n  unlinkSync(path: string): void\n}\n\n/** Default filesystem: the real `node:fs`. */\nexport const nodeRegistryFs: RegistryFs = {\n  existsSync: (path) => existsSync(path),\n  mkdirSync: (path, options) => {\n    mkdirSync(path, options)\n  },\n  readFileSync: (path, encoding) => readFileSync(path, encoding),\n  writeFileSync: (path, data, options) => {\n    writeFileSync(path, data, options)\n  },\n  renameSync: (from, to) => renameSync(from, to),\n  linkSync: (from, to) => linkSync(from, to),\n  unlinkSync: (path) => unlinkSync(path),\n}\n\n// ---------------------------------------------------------------------------\n// Path + construction + validation.\n// ---------------------------------------------------------------------------\n\n/** Absolute registry path for a `(home, profile)` — the v1 lockfile path. */\nexport function registryPath(home: string, profile: string): string {\n  return join(home, `opentui-host.${profile}.json`)\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isInteger(value: unknown): value is number {\n  return typeof value === 'number' && Number.isInteger(value)\n}\n\nfunction isString(value: unknown): value is string {\n  return typeof value === 'string'\n}\n\nfunction nonEmpty(value: unknown): value is string {\n  return isString(value) && value.trim() !== ''\n}\n\nfunction invalid(reason: string, raw: unknown): RegistryReadResult {\n  return { kind: 'invalid', raw, reason }\n}\n\n/**\n * Validate a parsed JSON value into a tagged {@link RegistryReadResult}.\n * A record with `version === 2` is checked field-by-field; a record with no\n * version (or version 1) that still carries `pid`/`port` is `legacy`; anything\n * else is `invalid`. Pure — no filesystem access.\n */\nexport function validateRegistry(raw: unknown): RegistryReadResult {\n  if (!isPlainObject(raw)) return invalid('registry is not an object', raw)\n\n  if (raw.version === REGISTRY_SCHEMA_VERSION) {\n    if (!nonEmpty(raw.profile)) return invalid('profile must be a non-empty string', raw)\n    if (!nonEmpty(raw.home)) return invalid('home must be a non-empty string', raw)\n    if (!isInteger(raw.pid) || raw.pid < 0) return invalid('pid must be a non-negative integer', raw)\n    if (!isInteger(raw.port) || raw.port < 0 || raw.port > 65535) return invalid('port must be an integer in [0, 65535]', raw)\n    if (!(REGISTRY_PHASES as readonly string[]).includes(raw.phase as string)) {\n      return invalid(`phase must be one of ${REGISTRY_PHASES.join('|')}`, raw)\n    }\n    if (!nonEmpty(raw.startedAt)) return invalid('startedAt must be a non-empty string', raw)\n    if (!nonEmpty(raw.updatedAt)) return invalid('updatedAt must be a non-empty string', raw)\n    if (!isString(raw.authority)) return invalid('authority must be a string', raw)\n    if (!Array.isArray(raw.clients)) return invalid('clients must be an array', raw)\n    const clients: RegistryClient[] = []\n    for (const [index, item] of raw.clients.entries()) {\n      if (!isPlainObject(item)) return invalid(`clients[${index}] must be an object`, raw)\n      if (!nonEmpty(item.id)) return invalid(`clients[${index}].id must be a non-empty string`, raw)\n      if (!isInteger(item.pid) || item.pid < 0) return invalid(`clients[${index}].pid must be a non-negative integer`, raw)\n      if (!nonEmpty(item.lastSeen)) return invalid(`clients[${index}].lastSeen must be a non-empty string`, raw)\n      clients.push({ id: item.id, pid: item.pid, lastSeen: item.lastSeen })\n    }\n    return {\n      kind: 'v2',\n      value: {\n        version: 2,\n        profile: raw.profile,\n        home: raw.home,\n        pid: raw.pid,\n        port: raw.port,\n        phase: raw.phase as RegistryPhase,\n        startedAt: raw.startedAt,\n        updatedAt: raw.updatedAt,\n        authority: raw.authority,\n        clients,\n      },\n    }\n  }\n\n  // Any other explicit version is unsupported (not \"legacy\" — legacy is the\n  // pre-version lockfile only).\n  if (raw.version !== undefined) return invalid(`unsupported registry version ${String(raw.version)}`, raw)\n  if (!isInteger(raw.pid) || !isInteger(raw.port)) {\n    return invalid('legacy registry is missing pid/port', raw)\n  }\n  return {\n    kind: 'legacy',\n    raw: {\n      pid: raw.pid,\n      port: raw.port,\n      ...(isString(raw.authority) ? { authority: raw.authority } : {}),\n      ...(isString(raw.startedAt) ? { startedAt: raw.startedAt } : {}),\n      ...(isString(raw.profile) ? { profile: raw.profile } : {}),\n      ...(raw.booting === true ? { booting: true } : {}),\n    },\n  }\n}\n\n/** Build a well-formed v2 claim record (the O_EXCL placeholder content). */\nexport function createClaimRegistry(home: string, profile: string, pid: number, nowIso: string): HostRegistryV2 {\n  return {\n    version: 2,\n    profile,\n    home,\n    pid,\n    port: 0,\n    phase: 'claim',\n    startedAt: nowIso,\n    updatedAt: nowIso,\n    authority: '',\n    clients: [],\n  }\n}\n\n/** Copy a registry with a new `phase` / `updatedAt` (no in-place mutation). */\nexport function withPhase(reg: HostRegistryV2, phase: RegistryPhase, nowIso: string): HostRegistryV2 {\n  return { ...reg, phase, updatedAt: nowIso }\n}\n\n/** Copy a registry with a new `updatedAt` (heartbeat / adoption bump). */\nexport function touchRegistry(reg: HostRegistryV2, nowIso: string): HostRegistryV2 {\n  return { ...reg, updatedAt: nowIso }\n}\n\n// ---------------------------------------------------------------------------\n// Read / atomic write.\n// ---------------------------------------------------------------------------\n\n/** Read + validate the registry file. Never throws — IO/JSON errors are tagged. */\nexport function readRegistryAt(path: string, fs: RegistryFs = nodeRegistryFs): RegistryReadResult {\n  let text: string\n  try {\n    text = fs.readFileSync(path, 'utf8')\n  } catch {\n    return { kind: 'missing' }\n  }\n  let raw: unknown\n  try {\n    raw = JSON.parse(text)\n  } catch {\n    return invalid('registry file is not valid JSON', text)\n  }\n  return validateRegistry(raw)\n}\n\n/** Read + validate `<home>/opentui-host.<profile>.json`. */\nexport function readRegistry(home: string, profile: string, fs: RegistryFs = nodeRegistryFs): RegistryReadResult {\n  return readRegistryAt(registryPath(home, profile), fs)\n}\n\nlet writeSeq = 0\n\n/**\n * Atomically write a v2 registry: serialize to a temp file in the same\n * directory, then rename over the target. On a rename error the temp file is\n * swept so no orphan accumulates. The record is validated first — callers\n * cannot persist a malformed v2 shape.\n */\nexport function writeRegistry(home: string, profile: string, record: HostRegistryV2, fs: RegistryFs = nodeRegistryFs): void {\n  const checked = validateRegistry(record)\n  if (checked.kind !== 'v2') {\n    throw new Error(`writeRegistry: refusing to write invalid v2 record (${checked.kind === 'invalid' ? checked.reason : checked.kind})`)\n  }\n  fs.mkdirSync(home, { recursive: true })\n  const path = registryPath(home, profile)\n  const tmp = `${path}.tmp-${process.pid}-${++writeSeq}`\n  fs.writeFileSync(tmp, JSON.stringify(checked.value, null, 2) + '\\n')\n  try {\n    fs.renameSync(tmp, path)\n  } catch (error) {\n    try {\n      fs.unlinkSync(tmp)\n    } catch {\n      /* nothing to sweep */\n    }\n    throw error\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Atomic claim / release (link(2) = O_EXCL).\n// ---------------------------------------------------------------------------\n\nexport interface ClaimOptions {\n  fs?: RegistryFs\n  now?: () => number\n  /** Claimer pid (default `process.pid`). Stored in the claim record. */\n  pid?: number\n}\n\nexport type ClaimResult =\n  | { ok: true; token: string; path: string; registry: HostRegistryV2 }\n  | { ok: false; reason: 'occupied'; path: string }\n\nfunction isErrno(error: unknown, code: string): boolean {\n  return error instanceof Error && (error as NodeJS.ErrnoException).code === code\n}\n\n/**\n * Atomically claim the registry as a `phase=claim` placeholder.\n *\n * The fully-written temp file is `link(2)`ed to the target: `link` fails with\n * EEXIST when the target already exists, so exactly one concurrent claimer\n * wins. Unlike `writeFileSync('wx')`-style approaches the placeholder content\n * is complete at creation — readers never see a partial claim.\n *\n * Returns `{ ok: false, reason: 'occupied' }` for a rival (a live claim OR an\n * existing v2 record); the existing file is never modified.\n */\nexport function claimRegistry(home: string, profile: string, options: ClaimOptions = {}): ClaimResult {\n  const fs = options.fs ?? nodeRegistryFs\n  const now = options.now ?? Date.now\n  const pid = options.pid ?? process.pid\n  const nowIso = new Date(now()).toISOString()\n  fs.mkdirSync(home, { recursive: true })\n  const path = registryPath(home, profile)\n  const registry = createClaimRegistry(home, profile, pid, nowIso)\n  const tmp = `${path}.claim-${process.pid}-${randomUUID()}`\n  fs.writeFileSync(tmp, JSON.stringify(registry, null, 2) + '\\n')\n  try {\n    fs.linkSync(tmp, path) // EEXIST when a rival holds the file\n    return { ok: true, token: registry.startedAt, path, registry }\n  } catch (error) {\n    if (isErrno(error, 'EEXIST')) return { ok: false, reason: 'occupied', path }\n    throw error\n  } finally {\n    try {\n      fs.unlinkSync(tmp)\n    } catch {\n      /* nothing to sweep */\n    }\n  }\n}\n\nexport interface ReleaseClaimOptions {\n  fs?: RegistryFs\n}\n\n/**\n * Remove a claim ONLY if the file still holds THIS claim (phase `claim`, same\n * claimer pid + startedAt token). Never removes a completed boot's real\n * record or a rival's newer claim. Returns whether anything was removed.\n */\nexport function releaseClaim(\n  home: string,\n  profile: string,\n  claim: { pid: number; token: string },\n  options: ReleaseClaimOptions = {},\n): boolean {\n  const fs = options.fs ?? nodeRegistryFs\n  const path = registryPath(home, profile)\n  const read = readRegistryAt(path, fs)\n  if (read.kind !== 'v2') return false\n  const value = read.value\n  if (value.phase !== 'claim' || value.pid !== claim.pid || value.startedAt !== claim.token) return false\n  fs.unlinkSync(path)\n  return true\n}\n\n// ---------------------------------------------------------------------------\n// Stale detection + safe legacy cleanup (NO process signalling).\n// ---------------------------------------------------------------------------\n\nexport interface StaleDeps {\n  now?: () => number\n  /** Pid liveness probe. Default: `lifecycle.pidAlive`. */\n  pidAlive?: (pid: number) => boolean\n  /** Optional max age of `updatedAt` before a live-pid record is stale. */\n  registryMaxAgeMs?: number\n}\n\nexport type StaleReason = 'legacy-schema' | 'invalid-schema' | 'dead-pid' | 'registry-too-old'\n\nexport interface StaleVerdict {\n  stale: boolean\n  reasons: StaleReason[]\n}\n\nfunction looksLikeV2(value: RegistryReadResult | HostRegistryV2): value is HostRegistryV2 {\n  // Narrow through an `unknown` candidate: applying isPlainObject() directly to\n  // the tagged union keeps the {kind:'v2', value:...} branch in play, which has\n  // no top-level `version` and fails the check. A raw HostRegistryV2 does.\n  const candidate: unknown = value\n  return isPlainObject(candidate) && candidate.version === REGISTRY_SCHEMA_VERSION\n}\n\n/**\n * Decide whether a registry is stale. Pure given the injected clock / pid\n * probe. Legacy and invalid records are stale by schema; a v2 record is stale\n * when its pid is dead. The optional `registryMaxAgeMs` applies ONLY to\n * `claim`/`booting` records — a `ready`/`stopping` host is steady-state and\n * nobody refreshes its `updatedAt` (heartbeats live in separate files), so an\n * age check there would falsely stale (>60s) healthy hosts (P1-1). A missing\n * registry is not stale — it is simply free to claim.\n */\nexport function isRegistryStale(input: RegistryReadResult | HostRegistryV2, deps: StaleDeps = {}): StaleVerdict {\n  const read: RegistryReadResult = looksLikeV2(input) ? { kind: 'v2', value: input } : input\n  if (read.kind === 'missing') return { stale: false, reasons: [] }\n  if (read.kind === 'legacy') return { stale: true, reasons: ['legacy-schema'] }\n  if (read.kind === 'invalid') return { stale: true, reasons: ['invalid-schema'] }\n\n  const reasons: StaleReason[] = []\n  const alive = deps.pidAlive ?? defaultPidAlive\n  if (!alive(read.value.pid)) reasons.push('dead-pid')\n  if (\n    deps.registryMaxAgeMs !== undefined &&\n    (read.value.phase === 'claim' || read.value.phase === 'booting')\n  ) {\n    const now = (deps.now ?? Date.now)()\n    const updated = Date.parse(read.value.updatedAt)\n    if (!Number.isNaN(updated) && now - updated > deps.registryMaxAgeMs) reasons.push('registry-too-old')\n  }\n  return { stale: reasons.length > 0, reasons }\n}\n\n/** Read a registry and classify staleness in one call (IO + injected seams). */\nexport function checkRegistryStale(\n  home: string,\n  profile: string,\n  fs: RegistryFs = nodeRegistryFs,\n  deps: StaleDeps = {},\n): { read: RegistryReadResult; verdict: StaleVerdict } {\n  const read = readRegistry(home, profile, fs)\n  return { read, verdict: isRegistryStale(read, deps) }\n}\n\nexport interface ClearLegacyResult {\n  removed: boolean\n  reason: 'legacy-removed' | 'not-legacy' | 'missing' | 'legacy-host-alive'\n}\n\nexport interface SafeClearOptions {\n  fs?: RegistryFs\n  /** Pre-read registry (e.g. from `checkRegistryStale`) to avoid a second read. */\n  read?: RegistryReadResult\n  /** Pid liveness probe. Default: `lifecycle.pidAlive` (EPERM counts as alive). */\n  pidAlive?: (pid: number) => boolean\n}\n\n/**\n * Remove a legacy registry FILE on first run of the new version — ONLY when\n * its pid is confirmed dead. P1-4: a legacy record can be the sole record of\n * a still-running old host; unlinking it would orphan that host and make\n * `--force` unable to locate it. When the pid is alive (or its liveness is\n * uncertain — EPERM counts as alive), the record is KEPT for `--force` /\n * manual intervention. DESIGN §7: \"if it cannot be confirmed, leave it for\n * stale cleanup\".\n *\n * Accepts either a `(home, profile)` pair (reads the file itself) or a\n * pre-read registry via `options.read`. CONTRACT: this function only ever\n * unlinks the registry file. It NEVER signals or kills the legacy pid —\n * identifying and stopping that host needs the three-evidence rule\n * (ADR-0009 decision 8). A v2 record (or a missing/unreadable file) is left\n * untouched.\n */\nexport function safeClearLegacy(home: string, profile: string, options: SafeClearOptions = {}): ClearLegacyResult {\n  const fs = options.fs ?? nodeRegistryFs\n  const path = registryPath(home, profile)\n  const read = options.read ?? readRegistryAt(path, fs)\n  if (read.kind === 'missing') return { removed: false, reason: 'missing' }\n  if (read.kind !== 'legacy') return { removed: false, reason: 'not-legacy' }\n  const alive = options.pidAlive ?? defaultPidAlive\n  if (read.raw.pid > 0 && alive(read.raw.pid)) {\n    return { removed: false, reason: 'legacy-host-alive' }\n  }\n  fs.unlinkSync(path) // file only — no process.kill anywhere in this module\n  return { removed: true, reason: 'legacy-removed' }\n}\n",
    "/**\n * Client-side refcount / heartbeat / last-one grace lifecycle (ADR-0009\n * decision 6; DESIGN-redesign §4) plus the all-crash fallback watchdog and the\n * `--force`/`--yes` guard (decisions 7–8).\n *\n * WHY ONE FILE PER CLIENT: the v2 registry's `clients` array is NOT mutated via\n * read-modify-write — N concurrent clients doing that lose updates. Instead\n * each attached client owns an independent heartbeat file\n * `<DSH_HOME>/opentui-clients/<clientId>.json` ({ id, pid, lastSeen, workspace })\n * refreshed every ~3s. \"Refcount\" is just the count of FRESH heartbeats\n * (lastSeen within a 15s TTL). Writing a heartbeat only touches that client's\n * own file, so concurrent clients never clobber one another.\n *\n * Lifecycle rules:\n *  - register on every successful attach (spawned, adopted, or self-booted);\n *  - unregister (delete own file) on normal exit;\n *  - last one out: after deleting, if no OTHER fresh heartbeat remains, wait a\n *    grace window, re-check, then SIGTERM the registry host (graceful flush)\n *    and clear the registry;\n *  - all-crash fallback: a detached watchdog polls the heartbeat dir; after\n *    TTL + grace with NO fresh client it three-evidence-stops the host, clears\n *    the registry, and exits. It self-exits when the host is already gone.\n *\n * `DSH_OPENTUI_HOST_IDLE_MS` is REINTERPRETED here as the last-one grace\n * override (default 2000ms, `0` = resident / never auto-close). It is NOT the\n * old \"5s idle → kill a live-connection client\" behaviour (ADR-0009 decision 6).\n *\n * Every I/O seam (fs, clock, sleep, pid probe, signal hooks, spawn) is\n * injectable: unit tests drive the whole state machine with fakes — no real\n * host, socket, timer or signal.\n */\n\nimport { spawn as nodeSpawn } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport {\n  existsSync as nodeExistsSync,\n  mkdirSync as nodeMkdirSync,\n  readFileSync as nodeReadFileSync,\n  readdirSync as nodeReaddirSync,\n  renameSync as nodeRenameSync,\n  unlinkSync as nodeUnlinkSync,\n  writeFileSync as nodeWriteFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n  readRegistry,\n  registryPath,\n  type HostRegistryV2,\n  type RegistryReadResult,\n} from './host-registry.ts'\nimport {\n  defaultPidAlive,\n  psKillHooks,\n  safeStopHost,\n  SERVER_ENV_NAME,\n  SERVER_ENV_VALUE,\n  type ProcessKillHooks,\n  type SafeStopResult,\n} from './safe-kill.ts'\n\n/** Default three-evidence hooks, re-exported so embedders can pass `hooks`. */\nexport { psKillHooks }\n\n// ---------------------------------------------------------------------------\n// Constants + value types.\n// ---------------------------------------------------------------------------\n\n/** Directory holding one heartbeat file per attached client. */\nexport const CLIENTS_DIR_NAME = 'opentui-clients'\n/** Heartbeat refresh cadence (~3s per the ADR). */\nexport const DEFAULT_HEARTBEAT_INTERVAL_MS = 3_000\n/** A heartbeat older than this is treated as a dead client. */\nexport const DEFAULT_CLIENT_TTL_MS = 15_000\n/** Default last-one-out grace window. */\nexport const DEFAULT_LAST_ONE_GRACE_MS = 2_000\n/** Env override for the grace window (0 = resident). */\nexport const ENV_IDLE_MS = 'DSH_OPENTUI_HOST_IDLE_MS'\n/** Watchdog poll cadence. */\nexport const DEFAULT_WATCHDOG_POLL_MS = 1_000\n/** Cap for the watchdog's failure-path backoff (`graceMs * 2 ** failStreak`). */\nexport const WATCHDOG_MAX_BACKOFF_MS = 30_000\n/** Watchdog env: home / profile / explicit \"I am the watchdog\" marker. */\nexport const ENV_WATCHDOG = 'DSH_OPENTUI_WATCHDOG'\nexport const ENV_WATCHDOG_HOME = 'DSH_OPENTUI_WATCHDOG_HOME'\nexport const ENV_WATCHDOG_PROFILE = 'DSH_OPENTUI_WATCHDOG_PROFILE'\n\n/** One attached client's heartbeat record. */\nexport interface ClientHeartbeat {\n  id: string\n  pid: number\n  /** ISO timestamp of the last heartbeat refresh. */\n  lastSeen: string\n  workspace: string\n}\n\n// ---------------------------------------------------------------------------\n// Injectable fs + clock + sleep seams.\n// ---------------------------------------------------------------------------\n\n/** The slice of `node:fs` the heartbeat / registry path needs. */\nexport interface LifecycleFs {\n  existsSync(path: string): boolean\n  mkdirSync(path: string, options?: { recursive?: boolean }): void\n  readFileSync(path: string, encoding: 'utf8'): string\n  writeFileSync(path: string, data: string, options?: { mode?: number }): void\n  unlinkSync(path: string): void\n  /** Optional on injected fakes that pre-seed files without a dir listing. */\n  readdirSync?(path: string): string[]\n  renameSync?(from: string, to: string): void\n}\n\nexport const nodeLifecycleFs: LifecycleFs = {\n  existsSync: (p) => nodeExistsSync(p),\n  mkdirSync: (p, o) => nodeMkdirSync(p, o),\n  readFileSync: (p, e) => nodeReadFileSync(p, e),\n  writeFileSync: (p, d, o) => nodeWriteFileSync(p, d, o),\n  unlinkSync: (p) => nodeUnlinkSync(p),\n  readdirSync: (p) => nodeReaddirSync(p) as unknown as string[],\n  renameSync: (from, to) => nodeRenameSync(from, to),\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\n// ---------------------------------------------------------------------------\n// Paths + validation + freshness (pure).\n// ---------------------------------------------------------------------------\n\n/** Absolute path of the heartbeat directory for a home. */\nexport function clientsDir(home: string): string {\n  return join(home, CLIENTS_DIR_NAME)\n}\n\n/** Absolute path of one client's heartbeat file. */\nexport function heartbeatPath(home: string, clientId: string): string {\n  return join(clientsDir(home), `${clientId}.json`)\n}\n\n/** Validate a parsed JSON value into a ClientHeartbeat (or null). */\nexport function validateHeartbeat(raw: unknown): ClientHeartbeat | null {\n  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null\n  const r = raw as Record<string, unknown>\n  if (typeof r.id !== 'string' || r.id.trim() === '') return null\n  if (typeof r.pid !== 'number' || !Number.isInteger(r.pid) || r.pid < 0) return null\n  if (typeof r.lastSeen !== 'string' || r.lastSeen.trim() === '') return null\n  if (Number.isNaN(Date.parse(r.lastSeen))) return null\n  if (typeof r.workspace !== 'string') return null\n  return { id: r.id, pid: r.pid, lastSeen: r.lastSeen, workspace: r.workspace }\n}\n\n/** True while a heartbeat is within the TTL of `nowMs`. */\nexport function isFresh(hb: ClientHeartbeat, nowMs: number, ttlMs: number): boolean {\n  const seen = Date.parse(hb.lastSeen)\n  if (Number.isNaN(seen)) return false\n  const age = nowMs - seen\n  return age >= 0 && age <= ttlMs\n}\n\n/**\n * Resolve the last-one grace window: explicit option > env > default. `0` is a\n * valid value meaning \"resident — never auto-close\". Negative / non-finite /\n * malformed env values fall back to the default.\n */\nexport function resolveGraceMs(explicitMs?: number, env?: NodeJS.ProcessEnv): number {\n  if (explicitMs !== undefined && Number.isFinite(explicitMs)) return Math.max(0, Math.round(explicitMs))\n  const raw = (env ?? process.env)[ENV_IDLE_MS]\n  if (raw !== undefined && /^\\d+$/.test(raw)) {\n    const parsed = Number(raw)\n    if (Number.isFinite(parsed)) return Math.round(parsed)\n  }\n  return DEFAULT_LAST_ONE_GRACE_MS\n}\n\n// ---------------------------------------------------------------------------\n// Heartbeat file I/O (register / refresh / unregister / list / purge).\n// ---------------------------------------------------------------------------\n\ninterface HeartbeatDeps {\n  fs?: LifecycleFs\n  now?: () => number\n}\n\nfunction writeHeartbeatFile(home: string, hb: ClientHeartbeat, fs: LifecycleFs): void {\n  fs.mkdirSync(clientsDir(home), { recursive: true })\n  const path = heartbeatPath(home, hb.id)\n  const payload = JSON.stringify(hb, null, 2) + '\\n'\n  // Prefer atomic write; injected fakes may omit renameSync.\n  if (fs.renameSync) {\n    const tmp = `${path}.tmp-${hb.id}`\n    fs.writeFileSync(tmp, payload)\n    fs.renameSync(tmp, path)\n  } else {\n    fs.writeFileSync(path, payload)\n  }\n}\n\n/** Generate a unique client id (used when the caller does not supply one). */\nexport function newClientId(): string {\n  return `${process.pid}-${randomUUID()}`\n}\n\nexport interface HeartbeatHandle {\n  readonly id: string\n  readonly record: ClientHeartbeat\n  /** Refresh lastSeen now (also called by the auto-refresh timer). */\n  refresh(): ClientHeartbeat\n  /** Start the ~3s auto-refresh timer (idempotent; unref'd). */\n  start(intervalMs?: number): void\n  /** Stop the auto-refresh timer. */\n  stop(): void\n  /** Delete this client's heartbeat file. Returns true if it existed. */\n  remove(): boolean\n}\n\n/**\n * Register (or re-register) a client heartbeat and return a handle that can\n * refresh / auto-refresh / remove it. Does NOT start the timer until\n * `start()` is called — callers decide when the client is fully attached.\n */\nexport function registerHeartbeat(\n  home: string,\n  info: { id?: string; pid?: number; workspace: string },\n  deps: HeartbeatDeps = {},\n): HeartbeatHandle {\n  const fs = deps.fs ?? nodeLifecycleFs\n  const now = deps.now ?? Date.now\n  const id = info.id ?? newClientId()\n  const pid = info.pid ?? process.pid\n  const started: ClientHeartbeat = {\n    id,\n    pid,\n    lastSeen: new Date(now()).toISOString(),\n    workspace: info.workspace,\n  }\n  writeHeartbeatFile(home, started, fs)\n  let record = started\n  let timer: ReturnType<typeof setInterval> | null = null\n\n  const refresh = (): ClientHeartbeat => {\n    record = { ...record, lastSeen: new Date(now()).toISOString() }\n    writeHeartbeatFile(home, record, fs)\n    return record\n  }\n  return {\n    id,\n    get record() {\n      return record\n    },\n    refresh,\n    start(intervalMs = DEFAULT_HEARTBEAT_INTERVAL_MS) {\n      if (timer) return\n      timer = setInterval(() => {\n        try {\n          refresh()\n        } catch {\n          /* a transient fs error must not crash the client */\n        }\n      }, intervalMs)\n      timer.unref?.()\n    },\n    stop() {\n      if (timer) {\n        clearInterval(timer)\n        timer = null\n      }\n    },\n    remove() {\n      try {\n        if (!fs.existsSync(heartbeatPath(home, id))) return false\n        fs.unlinkSync(heartbeatPath(home, id))\n        return true\n      } catch {\n        return false\n      }\n    },\n  }\n}\n\n/** Read + validate every heartbeat file in the directory. Never throws. */\nexport function listHeartbeats(home: string, deps: HeartbeatDeps = {}): ClientHeartbeat[] {\n  const fs = deps.fs ?? nodeLifecycleFs\n  if (!fs.readdirSync) return []\n  let names: string[]\n  try {\n    names = fs.readdirSync(clientsDir(home))\n  } catch {\n    return []\n  }\n  const out: ClientHeartbeat[] = []\n  for (const name of names) {\n    if (!name.endsWith('.json')) continue\n    try {\n      const raw = JSON.parse(fs.readFileSync(join(clientsDir(home), name), 'utf8'))\n      const hb = validateHeartbeat(raw)\n      if (hb) out.push(hb)\n    } catch {\n      /* skip a half-written / corrupt heartbeat */\n    }\n  }\n  return out\n}\n\n/** All heartbeats whose lastSeen is within the TTL of `now()`. */\nexport function freshClients(\n  home: string,\n  deps: HeartbeatDeps = {},\n  ttlMs: number = DEFAULT_CLIENT_TTL_MS,\n): ClientHeartbeat[] {\n  const now = deps.now ?? Date.now\n  const nowMs = now()\n  return listHeartbeats(home, deps).filter((hb) => isFresh(hb, nowMs, ttlMs))\n}\n\n/** Delete every heartbeat file (used by a confirmed --force reset). */\nexport function purgeAllHeartbeats(home: string, deps: HeartbeatDeps = {}): string[] {\n  const fs = deps.fs ?? nodeLifecycleFs\n  const removed: string[] = []\n  for (const hb of listHeartbeats(home, deps)) {\n    try {\n      fs.unlinkSync(heartbeatPath(home, hb.id))\n      removed.push(hb.id)\n    } catch {\n      /* already gone */\n    }\n  }\n  return removed\n}\n\n/** Delete heartbeat files that have aged past the TTL. Returns removed ids. */\nexport function purgeStaleHeartbeats(\n  home: string,\n  deps: HeartbeatDeps = {},\n  ttlMs: number = DEFAULT_CLIENT_TTL_MS,\n): string[] {\n  const fs = deps.fs ?? nodeLifecycleFs\n  const now = deps.now ?? Date.now\n  const nowMs = now()\n  const removed: string[] = []\n  for (const hb of listHeartbeats(home, deps)) {\n    if (isFresh(hb, nowMs, ttlMs)) continue\n    try {\n      fs.unlinkSync(heartbeatPath(home, hb.id))\n      removed.push(hb.id)\n    } catch {\n      /* already gone */\n    }\n  }\n  return removed\n}\n\n// ---------------------------------------------------------------------------\n// Last-one-out graceful shutdown.\n// ---------------------------------------------------------------------------\n\nexport type LastOneAction =\n  | 'resident'\n  | 'others-alive'\n  | 'no-host'\n  | 'shutdown'\n  | 'evidence-refused'\n  | 'stop-failed'\n\nexport interface LastOneResult {\n  action: LastOneAction\n  /** Fresh client count observed at the decisive re-check. */\n  freshCount: number\n  /** Signals sent to the host, when a shutdown was attempted. */\n  stop?: SafeStopResult\n}\n\nexport interface LastOneOptions extends HeartbeatDeps {\n  profile?: string\n  /** Grace override (0 = resident). */\n  graceMs?: number\n  ttlMs?: number\n  sleep?: (ms: number) => Promise<void>\n  hooks: ProcessKillHooks\n  /** Signal grace tuning (tests keep it tiny). */\n  termGraceMs?: number\n  killGraceMs?: number\n}\n\n/**\n * Run the last-one-out decision AFTER this client removed its own heartbeat:\n * if any other fresh heartbeat exists (now or after the grace window), do\n * nothing; otherwise three-evidence-stop the registry host and clear the\n * registry. A `graceMs` of 0 means \"resident\" — never auto-close.\n */\nexport async function lastOneGracefulShutdown(\n  home: string,\n  options: LastOneOptions,\n): Promise<LastOneResult> {\n  const profile = options.profile ?? 'opentui'\n  const fs = options.fs ?? nodeLifecycleFs\n  const read = readRegistry(home, profile, fs as never)\n  // No host to shut down → do not wait out a grace window at all.\n  if (read.kind !== 'v2' || read.value.pid <= 0) {\n    return { action: 'no-host', freshCount: freshClients(home, options, options.ttlMs).length }\n  }\n  const graceMs = resolveGraceMs(options.graceMs)\n  if (graceMs === 0) return { action: 'resident', freshCount: freshClients(home, options, options.ttlMs).length }\n\n  const nowCount = freshClients(home, options, options.ttlMs).length\n  if (nowCount > 0) return { action: 'others-alive', freshCount: nowCount }\n\n  const sleep = options.sleep ?? defaultSleep\n  await sleep(graceMs)\n\n  const afterCount = freshClients(home, options, options.ttlMs).length\n  if (afterCount > 0) return { action: 'others-alive', freshCount: afterCount }\n\n  // Re-read: a concurrent client may have replaced the host during the grace.\n  const still = readRegistry(home, profile, fs as never)\n  if (still.kind !== 'v2' || still.value.pid !== read.value.pid) return { action: 'no-host', freshCount: 0 }\n\n  const stop = await safeStopHost({\n    pid: read.value.pid,\n    registryPid: read.value.pid,\n    hooks: options.hooks,\n    profile,\n    termGraceMs: options.termGraceMs,\n    killGraceMs: options.killGraceMs,\n    sleep,\n    now: options.now,\n    pidAlive: options.hooks.pidAlive,\n  })\n  if (!stop.evidencesOk) return { action: 'evidence-refused', freshCount: 0, stop }\n  // Evidence matched but the pid survived SIGKILL: clearing would orphan a\n  // still-live host. Keep the record unchanged (P0-2).\n  if (!stop.stopped) return { action: 'stop-failed', freshCount: 0, stop }\n\n  clearRegistryIfPid(home, profile, still, still.value.pid, fs)\n  return { action: 'shutdown', freshCount: 0, stop }\n}\n\n/** Unlink the registry only if it still describes `pid` (never clobber a newer host). */\nfunction clearRegistryIfPid(\n  home: string,\n  profile: string,\n  read: RegistryReadResult,\n  pid: number,\n  fs: LifecycleFs,\n): void {\n  if (read.kind === 'v2' && read.value.pid === pid) {\n    try {\n      fs.unlinkSync(registryPath(home, profile))\n    } catch {\n      /* already gone */\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// `--force` guard (decision 7).\n// ---------------------------------------------------------------------------\n\n/** Thrown by `assertForceAllowed` when live clients exist but `--yes` is absent. */\nexport class ForceNeedsYesError extends Error {\n  readonly code = 'force-needs-yes'\n  constructor(readonly clientCount: number) {\n    super(`--force would disconnect ${clientCount} live client(s); re-run with --force --yes to confirm.`)\n    this.name = new.target.name\n  }\n}\n\n/**\n * Thrown when the force guard is handed an fs that cannot enumerate\n * heartbeats. A slim (registry-only) fs makes `listHeartbeats` return `[]`,\n * which would silently treat a live host as clientless and bypass `--yes`.\n */\nexport class IncompleteLifecycleFsError extends Error {\n  readonly code = 'lifecycle-fs-incomplete'\n  constructor(readonly missing: string[]) {\n    super(\n      `dsh-opentui: --force guard fs is missing required method(s): ${missing.join(', ')}; ` +\n        `refusing to read an unlistable heartbeat dir as \"no live clients\" (that would bypass --yes).`,\n    )\n    this.name = new.target.name\n  }\n}\n\n/** Fail loudly instead of silently seeing zero clients when the fs is slim. */\nfunction assertLifecycleFsComplete(fs: LifecycleFs | undefined): void {\n  const f = fs ?? nodeLifecycleFs\n  const missing = (['readdirSync', 'readFileSync'] as const).filter(\n    (method) => typeof (f as unknown as Record<string, unknown>)[method] !== 'function',\n  )\n  if (missing.length > 0) throw new IncompleteLifecycleFsError([...missing])\n}\n\n/**\n * The launcher-side `--force` gate. If any FRESH heartbeat exists and `yes` is\n * false, refuse with a typed error carrying the client count (the launcher\n * prints \"will disconnect N clients\"). With `yes`, or with no live clients,\n * force is allowed to reset the host.\n */\nexport function assertForceAllowed(\n  home: string,\n  options: HeartbeatDeps & { yes?: boolean; ttlMs?: number },\n): { liveClients: number; allowed: boolean } {\n  // REFUSE a slim fs (e.g. the registry-only `nodeRegistryFs`) instead of\n  // silently reading an empty client set and bypassing the `--yes` gate.\n  assertLifecycleFsComplete(options.fs)\n  const live = freshClients(home, options, options.ttlMs)\n  if (live.length > 0 && !options.yes) throw new ForceNeedsYesError(live.length)\n  return { liveClients: live.length, allowed: true }\n}\n\n// ---------------------------------------------------------------------------\n// All-crash fallback watchdog (pure runner + detached spawn).\n// ---------------------------------------------------------------------------\n\nexport type WatchdogStopReason = 'reclaimed' | 'host-gone' | 'max-ticks' | 'resident'\n\nexport interface WatchdogResult {\n  reclaimed: boolean\n  reason: WatchdogStopReason\n  /** Signals sent when a reclaim happened. */\n  stop?: SafeStopResult\n}\n\n/** Emitted when a reclaim was refused (keep the record, retry next tick). */\nexport interface WatchdogEvidenceRefused {\n  pid: number\n  evidencesOk: boolean\n}\n\nexport interface WatchdogOptions extends HeartbeatDeps {\n  profile?: string\n  ttlMs?: number\n  graceMs?: number\n  pollMs?: number\n  sleep?: (ms: number) => Promise<void>\n  hooks: ProcessKillHooks\n  /** Safety bound for tests / runaway loops. Undefined = run until host gone. */\n  maxTicks?: number\n  termGraceMs?: number\n  killGraceMs?: number\n  onTick?: (info: { tick: number; freshCount: number; hostPid: number }) => void\n  /** Log seam for an evidence-refused reclaim (P0-2: never orphan a live host). */\n  onEvidenceRefused?: (info: WatchdogEvidenceRefused) => void\n}\n\n/**\n * One watchdog run. Polls until the host disappears (self-exit) or until NO\n * fresh client persists across TTL + grace, at which point it\n * three-evidence-stops the host, clears the registry and exits. The watchdog\n * itself is only ever signalled through the same three-evidence hooks; if the\n * registry pid is dead it exits without touching anyone.\n *\n * `graceMs === 0` means \"resident\" — the watchdog self-exits without ever\n * signalling (P1-2). If evidence is refused (or a stop is unconfirmed), the\n * registry record is KEPT, a log is emitted, and the loop retries next tick\n * instead of orphaning a live host (P0-2).\n */\nexport async function runWatchdog(home: string, options: WatchdogOptions): Promise<WatchdogResult> {\n  const profile = options.profile ?? 'opentui'\n  const graceMs = resolveGraceMs(options.graceMs)\n  if (graceMs === 0) return { reclaimed: false, reason: 'resident' }\n  const pollMs = options.pollMs ?? DEFAULT_WATCHDOG_POLL_MS\n  const sleep = options.sleep ?? defaultSleep\n  const alive = options.hooks.pidAlive ?? defaultPidAlive\n  const fs = options.fs ?? nodeLifecycleFs\n  // Consecutive refusal streak. Only the `!stop.stopped` path sleeps with\n  // exponential backoff; any fresh client / host-gone observation clears it.\n  let failStreak = 0\n\n  for (let tick = 0; options.maxTicks === undefined || tick < options.maxTicks; tick++) {\n    const read = readRegistry(home, profile, fs as never)\n    if (read.kind !== 'v2' || read.value.pid <= 0 || !alive(read.value.pid)) {\n      failStreak = 0\n      // Host gone: self-exit (also drop a stale record naming a dead pid).\n      if (read.kind === 'v2' && !alive(read.value.pid)) {\n        try {\n          fs.unlinkSync(registryPath(home, profile))\n        } catch {\n          /* already gone */\n        }\n      }\n      return { reclaimed: false, reason: 'host-gone' }\n    }\n\n    const freshCount = freshClients(home, options, options.ttlMs).length\n    options.onTick?.({ tick, freshCount, hostPid: read.value.pid })\n    if (freshCount > 0) {\n      failStreak = 0\n      await sleep(pollMs)\n      continue\n    }\n\n    // No fresh client: wait the grace window, then re-read everything (a\n    // client may have attached, or the host may have been replaced).\n    await sleep(graceMs)\n    const again = readRegistry(home, profile, fs as never)\n    if (again.kind !== 'v2' || again.value.pid !== read.value.pid) continue\n    if (freshClients(home, options, options.ttlMs).length > 0) {\n      failStreak = 0\n      continue\n    }\n    if (!alive(again.value.pid)) continue // re-loop → host-gone self-exit\n\n    const stop = await safeStopHost({\n      pid: again.value.pid,\n      registryPid: again.value.pid,\n      hooks: options.hooks,\n      profile,\n      termGraceMs: options.termGraceMs,\n      killGraceMs: options.killGraceMs,\n      sleep,\n      now: options.now,\n      pidAlive: alive,\n    })\n    if (!stop.stopped) {\n      // P0-2: evidence was refused (or the kill was not confirmed). The host is\n      // still alive — clearing its registry record would make it a permanent\n      // untrackable orphan. Keep the record, log, and retry next tick with a\n      // capped exponential backoff (the functional graceMs window above is\n      // untouched — this only throttles repeated refusals).\n      options.onEvidenceRefused?.({ pid: again.value.pid, evidencesOk: stop.evidencesOk })\n      // Floating-point multiply: unlike `<<` (32-bit signed) this never wraps\n      // to a negative/tiny delay when graceMs is large and the streak grows.\n      // Math.min still pins the result to the 30s cap.\n      await sleep(Math.min(graceMs * 2 ** failStreak, WATCHDOG_MAX_BACKOFF_MS))\n      // Cap the exponent so we never compute a meaningless huge power (which\n      // would overflow to Infinity). The backoff is already pinned at the cap\n      // long before this — the clamp is NOT about 32-bit wrap (multiply can't).\n      failStreak = Math.min(failStreak + 1, 30)\n      continue\n    }\n    clearRegistryIfPid(home, profile, again, again.value.pid, fs)\n    return { reclaimed: stop.evidencesOk, reason: 'reclaimed', stop }\n  }\n  return { reclaimed: false, reason: 'max-ticks' }\n}\n\nexport interface SpawnWatchdogOptions {\n  /** Absolute path to the watchdog CLI bundle (dist/watchdog.mjs). */\n  scriptPath: string\n  profile?: string\n  env?: NodeJS.ProcessEnv\n  /** Injectable spawn (tests record instead of spawning). */\n  spawn?: (\n    command: string,\n    args: string[],\n    options: { env: NodeJS.ProcessEnv; detached: boolean; stdio: 'ignore' },\n  ) => { pid?: number; unref?(): void }\n  command?: string\n}\n\n/**\n * Spawn a detached watchdog for `(home, profile)`. The child is marked with\n * the SAME three evidences as the host (`--profile opentui` on its cmdline via\n * argv + `DSH_OPENTUI_SERVER=1` in env), so it is identifiable and is itself\n * subject to decision-8 identification; it self-exits when the host dies.\n */\nexport function spawnWatchdog(home: string, options: SpawnWatchdogOptions): { pid?: number } {\n  const profile = options.profile ?? 'opentui'\n  const env: NodeJS.ProcessEnv = {\n    ...(options.env ?? process.env),\n    [SERVER_ENV_NAME]: SERVER_ENV_VALUE,\n    [ENV_WATCHDOG]: '1',\n    [ENV_WATCHDOG_HOME]: home,\n    [ENV_WATCHDOG_PROFILE]: profile,\n  }\n  const command = options.command ?? process.execPath\n  const child = (options.spawn ?? defaultSpawnWatchdog)(command, [options.scriptPath, '--profile', profile], {\n    env,\n    detached: true,\n    stdio: 'ignore',\n  })\n  child.unref?.()\n  return { pid: child.pid }\n}\n\nfunction defaultSpawnWatchdog(\n  command: string,\n  args: string[],\n  options: { env: NodeJS.ProcessEnv; detached: boolean; stdio: 'ignore' },\n): { pid?: number; unref?(): void } {\n  const child = nodeSpawn(command, args, options)\n  child.unref()\n  return child\n}\n",
    "/**\n * Mint a Host API cookie from the persisted `client-connection/browser-session`\n * grant secret in `$DSH_HOME/.credentials.yaml`.\n *\n * Reproduces the Host's own cookie recipe (dsh-client-connection BrowserAuth /\n * dsh-credentials) byte-for-byte — verified against a live host by the H1\n * token spike (cookie accepted on HTTP GET, on the mux WebSocket upgrade, and\n * on unary RPC):\n *\n *   secret      = records[\"client-connection/browser-session\"].payload.secret\n *                 (43-char base64url encoding a 32-byte HMAC key)\n *   cookie name = \"dsh-auth-\" + base64url(sha256(authority))\n *   body        = base64url(JSON { version: 1, authority, issuedAt, expiresAt })\n *   value       = `v1.${body}.${base64url(HMAC-SHA256(secret, body))}`\n *\n * `authority` is the HTTP audience `host:port` (scheme omitted) exactly as the\n * Host binds it. HTTPS audiences additionally carry the `https:` scheme inside\n * the signed payload — not supported here (v1 client mode is a local HTTP\n * listener; see ADR-0005).\n *\n * Security posture:\n * - the credentials file must be owner-only (0600); anything wider refuses to\n *   mint (fail closed);\n * - neither the secret nor any cookie material ever appears in a thrown\n *   error message — errors carry only paths, record keys, and shape reasons;\n * - the record's first-boot creation is retried (the Host writes the grant\n *   during connection activation, which can race a fast client start);\n * - missing and shape-invalid grants raise distinct typed errors so the\n *   caller can decide to re-mint or surface a configuration problem.\n *\n * The file reader is a targeted subset parser for the flat schema the Host\n * writes (`version`, `records`, one grant record with `kind`/`payload`), not a\n * general YAML implementation. Sibling records are skipped by indentation\n * scoping; anything unexpected inside the target record fails closed with a\n * typed error and the strict secret pattern re-validates whatever was read.\n */\n\nimport { createHash, createHmac } from \"node:crypto\"\nimport { readFileSync, statSync } from \"node:fs\"\nimport { join } from \"node:path\"\n\n/** The credentials record that holds the browser/API session signing secret. */\nconst RECORD_KEY = \"client-connection/browser-session\"\n/** Host default `cookieMaxAgeDays`; larger lifetimes are clamped to it. */\nconst DEFAULT_MAX_AGE_MS = 30 * 86_400_000\n/** First-boot retry cadence: the Host writes the grant during activation. */\nconst RETRY_INTERVAL_MS = 100\nconst RETRY_WINDOW_MS = 2000\nconst SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/\n\nexport interface MintOwnerCookieOptions {\n\t/** Host home directory (the `$DSH_HOME` that holds `.credentials.yaml`). */\n\thome: string\n\t/** Cookie audience bound into name and payload: `host:port` (no scheme). */\n\tauthority: string\n\t/** Cookie lifetime; clamped to the Host's 30-day default window. */\n\tmaxAgeMs?: number\n}\n\n/** Base class for every mint failure; messages are always secret-free. */\nexport class OwnerCookieError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = \"OwnerCookieError\"\n\t}\n}\n\n/** `.credentials.yaml` absent (or unreadable) past the first-boot retry window. */\nexport class CredentialsFileMissingError extends OwnerCookieError {}\n/** The `client-connection/browser-session` grant record is absent past the window. */\nexport class CredentialsGrantMissingError extends OwnerCookieError {}\n/** The grant exists but its shape is wrong (rotated format, corrupt write, host upgrade). */\nexport class CredentialsGrantInvalidError extends OwnerCookieError {}\n/** The credentials file is readable by group/other; minting refuses to proceed. */\nexport class CredentialsFileInsecureError extends OwnerCookieError {}\n/** The file violates the credentials YAML subset the Host writes. */\nexport class CredentialsParseError extends OwnerCookieError {}\n\n/** Deterministic cookie name for one authority: `dsh-auth-` + base64url(sha256). */\nexport function ownerCookieName(authority: string): string {\n\treturn \"dsh-auth-\" + base64url(createHash(\"sha256\").update(authority).digest())\n}\n\n/**\n * Mint the API cookie for one authority from the host home's persisted grant.\n * @returns the full `Cookie` header value: `<name>=<value>`.\n */\nexport function mintOwnerCookie(options: MintOwnerCookieOptions): string {\n\tconst authority = options.authority\n\tif (typeof authority !== \"string\" || authority.length === 0 || /[\\r\\n/]/.test(authority)) {\n\t\tthrow new OwnerCookieError(\"authority must be a non-empty host:port without scheme or path separators\")\n\t}\n\tconst secret = readGrantSecret(options.home)\n\tconst issuedAt = Date.now()\n\tconst maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS\n\tconst expiresAt = issuedAt + Math.min(maxAgeMs, DEFAULT_MAX_AGE_MS)\n\tconst body = base64url(Buffer.from(JSON.stringify({ version: 1, authority, issuedAt, expiresAt }), \"utf8\"))\n\tconst signature = base64url(createHmac(\"sha256\", secret).update(body).digest())\n\treturn `${ownerCookieName(authority)}=v1.${body}.${signature}`\n}\n\n/** Read + validate the grant secret from `<home>/.credentials.yaml` (with first-boot retries). */\nfunction readGrantSecret(home: string): Buffer {\n\tconst path = join(home, \".credentials.yaml\")\n\tconst deadline = Date.now() + RETRY_WINDOW_MS\n\tlet sawFile = false\n\twhile (true) {\n\t\tlet file = \"\"\n\t\ttry {\n\t\t\tassertOwnerOnly(path)\n\t\t\tfile = readFileSync(path, \"utf8\")\n\t\t\tsawFile = true\n\t\t} catch (error) {\n\t\t\tif (error instanceof CredentialsFileInsecureError) throw error\n\t\t\tsawFile = false\n\t\t}\n\t\tif (sawFile) {\n\t\t\tconst secret = extractSecret(file, path)\n\t\t\tif (secret !== undefined) return decodeSecret(secret, path)\n\t\t}\n\t\tif (Date.now() >= deadline) {\n\t\t\tif (!sawFile) {\n\t\t\t\tthrow new CredentialsFileMissingError(\n\t\t\t\t\t`no credentials file at ${path} within ${RETRY_WINDOW_MS}ms (host first boot still pending?)`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow new CredentialsGrantMissingError(\n\t\t\t\t`credentials record \"${RECORD_KEY}\" absent in ${path} within ${RETRY_WINDOW_MS}ms (host first boot still pending?)`,\n\t\t\t)\n\t\t}\n\t\tsleepSync(RETRY_INTERVAL_MS)\n\t}\n}\n\n/** Refuse to read credentials that group/other can read (must be 0600 or stricter). */\nfunction assertOwnerOnly(path: string): void {\n\tlet mode: number\n\ttry {\n\t\tmode = statSync(path).mode\n\t} catch {\n\t\treturn // absent → retryable, not a permissions fault\n\t}\n\tif ((mode & 0o077) !== 0) {\n\t\tthrow new CredentialsFileInsecureError(\n\t\t\t`credentials file ${path} is group/other accessible (mode ${mode.toString(8)}); refusing to mint — chmod 600 required`,\n\t\t)\n\t}\n}\n\n/**\n * Pull `records.<RECORD_KEY>.{kind, payload.version, payload.secret}` out of\n * the credentials file. Indentation is discovered dynamically (the Host's\n * writer nests by two spaces today). Returns undefined when the record (or\n * `records`) is absent — a retryable first-boot condition. Any malformed\n * content inside the target record raises (fail closed).\n */\nfunction extractSecret(file: string, path: string): string | undefined {\n\tconst lines = file.split(\"\\n\")\n\tconst recordsLine = findBlockLine(lines, \"records\", 0)\n\tif (recordsLine === -1) return undefined\n\tconst childIndent = nextChildIndent(lines, recordsLine)\n\tif (childIndent === -1) return undefined\n\tconst recordLine = findBlockLine(lines, RECORD_KEY, childIndent, recordsLine + 1)\n\tif (recordLine === -1) return undefined\n\tconst recordIndent = nextChildIndent(lines, recordLine)\n\tif (recordIndent === -1) {\n\t\tthrow new CredentialsGrantInvalidError(`credentials record \"${RECORD_KEY}\" in ${path} has no kind field`)\n\t}\n\tconst kind = readScalarLine(lines, \"kind\", recordIndent, recordLine + 1)\n\tif (kind !== \"grant\") {\n\t\tthrow new CredentialsGrantInvalidError(\n\t\t\t`credentials record \"${RECORD_KEY}\" in ${path} has ${kind === undefined ? \"no kind field\" : `kind other than \"grant\"`}`,\n\t\t)\n\t}\n\tconst payloadLine = findBlockLine(lines, \"payload\", recordIndent, recordLine + 1)\n\tif (payloadLine === -1) {\n\t\tthrow new CredentialsGrantInvalidError(`credentials record \"${RECORD_KEY}\" in ${path} has no payload block`)\n\t}\n\tconst payloadIndent = nextChildIndent(lines, payloadLine)\n\tif (payloadIndent === -1) {\n\t\tthrow new CredentialsGrantInvalidError(`credentials record \"${RECORD_KEY}\" in ${path} has an empty payload block`)\n\t}\n\tconst payloadVersion = readScalarLine(lines, \"version\", payloadIndent, payloadLine + 1)\n\tif (payloadVersion !== \"1\") {\n\t\tthrow new CredentialsGrantInvalidError(\n\t\t\t`credentials record \"${RECORD_KEY}\" in ${path} has payload.version ${payloadVersion === undefined ? \"absent\" : \"other than 1\"} (rotated grant format)`,\n\t\t)\n\t}\n\tconst secret = readScalarLine(lines, \"secret\", payloadIndent, payloadLine + 1)\n\tif (secret === undefined) {\n\t\tthrow new CredentialsGrantInvalidError(`credentials record \"${RECORD_KEY}\" in ${path} has no payload.secret`)\n\t}\n\treturn secret\n}\n\n/** First line index of a block entry `key:` at exactly `atIndent`, scanning from `from`. */\nfunction findBlockLine(lines: string[], key: string, atIndent: number, from = 0): number {\n\tconst range = blockRange(lines, from, atIndent)\n\tfor (let i = range.start; i < range.end; i++) {\n\t\tconst entry = parseEntryLine(lines[i])\n\t\tif (entry && entry.indent === atIndent && entry.key === key && entry.value === undefined) return i\n\t}\n\treturn -1\n}\n\n/** Scalar value of `key:` at exactly `atIndent` inside the block scanned from `from`. */\nfunction readScalarLine(lines: string[], key: string, atIndent: number, from: number): string | undefined {\n\tconst range = blockRange(lines, from, atIndent)\n\tfor (let i = range.start; i < range.end; i++) {\n\t\tconst entry = parseEntryLine(lines[i])\n\t\tif (entry && entry.indent === atIndent && entry.key === key) {\n\t\t\tif (entry.value === undefined) {\n\t\t\t\tthrow new CredentialsParseError(`credentials file has a nested block where the \"${key}\" scalar is required`)\n\t\t\t}\n\t\t\treturn entry.value\n\t\t}\n\t}\n\treturn undefined\n}\n\n/**\n * Line range [start, end) of one indentation block at `atIndent`, scanning\n * from `from`: every non-empty line until the first dedent below `atIndent`\n * (a top-level block therefore spans the whole document).\n */\nfunction blockRange(lines: string[], from: number, atIndent: number): { start: number; end: number } {\n\tlet start = -1\n\tlet i = from\n\tfor (; i < lines.length; i++) {\n\t\tconst line = lines[i]\n\t\tif (!line.trim() || line.trimStart().startsWith(\"#\")) continue\n\t\tif (leadingSpaces(line) < atIndent) break\n\t\tif (start === -1) start = i\n\t}\n\treturn { start: start === -1 ? lines.length : start, end: i }\n}\n\n/** Indentation of the first content line after `entryLine`, or -1 when the block is empty. */\nfunction nextChildIndent(lines: string[], entryLine: number): number {\n\tconst parentIndent = leadingSpaces(lines[entryLine])\n\tfor (let i = entryLine + 1; i < lines.length; i++) {\n\t\tconst line = lines[i]\n\t\tif (!line.trim() || line.trimStart().startsWith(\"#\")) continue\n\t\tconst indent = leadingSpaces(line)\n\t\treturn indent > parentIndent ? indent : -1\n\t}\n\treturn -1\n}\n\nfunction leadingSpaces(line: string): number {\n\tlet n = 0\n\twhile (n < line.length && line[n] === \" \") n++\n\treturn n\n}\n\ninterface EntryLine {\n\tindent: number\n\tkey: string\n\t/** undefined when the line is `key:` (block value follows). */\n\tvalue?: string\n}\n\n/** Parse one `key: value` line; undefined for blanks, comments, and unparsable lines. */\nfunction parseEntryLine(line: string): EntryLine | undefined {\n\tconst trimmed = line.trim()\n\tif (!trimmed || trimmed.startsWith(\"#\")) return undefined\n\tif (line.includes(\"\\t\")) return undefined // tabs never appear in the Host's writer\n\tconst indent = leadingSpaces(line)\n\tconst rest = line.slice(indent)\n\tconst colon = rest.indexOf(\":\")\n\tif (colon === -1) return undefined\n\tconst key = unquote(rest.slice(0, colon).trim())\n\tif (!key) return undefined\n\tconst rawValue = rest.slice(colon + 1).trim()\n\tif (rawValue === \"\" || rawValue.startsWith(\"#\")) return { indent, key }\n\treturn { indent, key, value: unquoteScalar(rawValue) }\n}\n\nfunction unquote(text: string): string {\n\tif (text.length >= 2) {\n\t\tif (text.startsWith(\"'\") && text.endsWith(\"'\")) return text.slice(1, -1).replaceAll(\"''\", \"'\")\n\t\tif (text.startsWith('\"') && text.endsWith('\"')) return unescapeDoubleQuoted(text.slice(1, -1))\n\t}\n\treturn text\n}\n\n/** Plain scalars drop a trailing ` # comment`; quoted scalars unescape minimally. */\nfunction unquoteScalar(rawValue: string): string {\n\tif (rawValue.startsWith(\"'\") || rawValue.startsWith('\"')) return unquote(rawValue)\n\tconst comment = rawValue.indexOf(\" #\")\n\treturn (comment === -1 ? rawValue : rawValue.slice(0, comment)).trim()\n}\n\nfunction unescapeDoubleQuoted(text: string): string {\n\treturn text.replaceAll('\\\\\"', '\"').replaceAll(\"\\\\\\\\\", \"\\\\\")\n}\n\n/** Validate the 43-char base64url secret shape and decode it to the 32-byte key. */\nfunction decodeSecret(secret: string, path: string): Buffer {\n\tif (!SECRET_PATTERN.test(secret)) {\n\t\tthrow new CredentialsGrantInvalidError(\n\t\t\t`credentials record \"${RECORD_KEY}\" in ${path} has a secret that is not a 43-char base64url string (rotated grant format)`,\n\t\t)\n\t}\n\tconst key = Buffer.from(secret.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\") + \"=\", \"base64\")\n\tif (key.length !== 32) {\n\t\tthrow new CredentialsGrantInvalidError(\n\t\t\t`credentials record \"${RECORD_KEY}\" in ${path} decodes to ${String(key.length)} bytes, expected 32`,\n\t\t)\n\t}\n\treturn key\n}\n\nfunction base64url(buffer: Buffer): string {\n\treturn buffer.toString(\"base64\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/u, \"\")\n}\n\nfunction sleepSync(ms: number): void {\n\t// Atomics.wait parks the (contractually synchronous) mint without a busy\n\t// loop; the spin fallback covers runtimes that disallow Atomics.wait.\n\tconst buffer = new Int32Array(new SharedArrayBuffer(4))\n\tconst parked = (() => {\n\t\ttry {\n\t\t\treturn Atomics.wait(buffer, 0, 0, ms) === \"timed-out\"\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t})()\n\tif (!parked) {\n\t\tconst until = Date.now() + ms\n\t\twhile (Date.now() < until) {}\n\t}\n}\n",
    "/**\n * Injectable host health validation (ADR-0009 decision 5; DESIGN-redesign §3\n * step 4 — the three-signal readiness gate's TCP + HTTP legs).\n *\n * A host is \"healthy\" for attachment only when BOTH hold:\n *   1. TCP connect to `authority` succeeds (the listener is up), AND\n *   2. `GET /` carrying the owner cookie answers 2xx/3xx (it is OUR host,\n *      not a foreign home / a wedge that lost its connection service).\n *\n * The decision is a PURE function of two injectable probes:\n *   - `connectTcp(authority)`         → boolean\n *   - `requestStatus(authority, cookie)` → number | null\n * No sockets are opened unless the caller uses the default probes. Unit tests\n * inject fakes and assert the 2xx/3xx boundary, the short-circuit order, and\n * that the cookie/authority are forwarded — no real host is started.\n *\n * Reuse: the default probes delegate to `lifecycle.isListening` (bounded\n * loopback connect) and `host-probe.probeHostHttpStatus` (the authenticated\n * GET / that already backs `probeHostHttp`). This module adds only the\n * composition + injectable seam, not a second HTTP implementation.\n */\n\nimport { isListening } from './lifecycle.ts'\nimport { probeHostHttpStatus } from './host-probe.ts'\n\n/** Lowest healthy HTTP status (inclusive). */\nexport const HEALTH_STATUS_MIN = 200\n/** Highest healthy HTTP status (exclusive) — 3xx redirects count. */\nexport const HEALTH_STATUS_MAX_EXCLUSIVE = 400\n\n/** The two probe seams. Inject to make health checking pure/testable. */\nexport interface HealthProbes {\n  /** `true` when a TCP connect to `authority` (`host:port`) succeeds. */\n  connectTcp: (authority: string) => Promise<boolean>\n  /** HTTP status of the owner-cookie `GET /`, or `null` on no response. */\n  requestStatus: (authority: string, cookieHeader: string) => Promise<number | null>\n}\n\nexport interface HealthTarget {\n  /** `host:port` exactly as the host binds it. */\n  authority: string\n  /** Full `Cookie` header value minted for this authority. */\n  cookieHeader: string\n}\n\nexport type HealthReason =\n  | 'ok'\n  | 'tcp-failed'\n  | 'http-no-response'\n  | 'http-unhealthy-status'\n\nexport interface HealthCheck {\n  healthy: boolean\n  /** TCP connect result (false when short-circuited by a malformed authority). */\n  tcp: boolean\n  /** HTTP status from `requestStatus`, or null when it was not called / failed. */\n  httpStatus: number | null\n  reason: HealthReason\n}\n\n/** Extract the port from a `host:port` authority. IPv6 brackets are supported. */\nexport function authorityPort(authority: string): number | null {\n  if (typeof authority !== 'string' || authority.length === 0) return null\n  let host = authority\n  if (host.startsWith('[')) {\n    const end = host.indexOf(']')\n    if (end === -1) return null\n    host = host.slice(end + 1)\n    if (!host.startsWith(':')) return null\n    host = host.slice(1)\n  } else {\n    const colon = host.lastIndexOf(':')\n    if (colon === -1) return null\n    host = host.slice(colon + 1)\n  }\n  if (!/^\\d+$/.test(host)) return null\n  const port = Number(host)\n  return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null\n}\n\n/** True for any 2xx/3xx status. */\nexport function isHealthyStatus(status: number | null): boolean {\n  return status !== null && status >= HEALTH_STATUS_MIN && status < HEALTH_STATUS_MAX_EXCLUSIVE\n}\n\n/** Default probes: bounded TCP connect + authenticated GET / status. */\nexport const defaultHealthProbes: HealthProbes = {\n  async connectTcp(authority) {\n    const port = authorityPort(authority)\n    return port === null ? false : isListening(port)\n  },\n  async requestStatus(authority, cookieHeader) {\n    return probeHostHttpStatus({ authority, cookieHeader })\n  },\n}\n\n/**\n * Decide host health from the injected probes. TCP is checked first; the\n * HTTP probe is skipped when TCP fails (an unreachable listener cannot serve\n * HTTP). Never throws — a throwing probe is treated as a failed one.\n */\nexport async function checkHostHealth(target: HealthTarget, probes: HealthProbes = defaultHealthProbes): Promise<HealthCheck> {\n  let tcp = false\n  try {\n    tcp = await probes.connectTcp(target.authority)\n  } catch {\n    tcp = false\n  }\n  if (!tcp) return { healthy: false, tcp: false, httpStatus: null, reason: 'tcp-failed' }\n\n  let status: number | null = null\n  try {\n    status = await probes.requestStatus(target.authority, target.cookieHeader)\n  } catch {\n    status = null\n  }\n  if (status === null) return { healthy: false, tcp: true, httpStatus: null, reason: 'http-no-response' }\n  if (!isHealthyStatus(status)) return { healthy: false, tcp: true, httpStatus: status, reason: 'http-unhealthy-status' }\n  return { healthy: true, tcp: true, httpStatus: status, reason: 'ok' }\n}\n",
    "/**\n * Deterministic, cross-process-stable host port derivation (ADR-0009 decision\n * 3; DESIGN-redesign §3 step 1).\n *\n *   port = base + FNV-1a(canonical(home) + \":\" + profile) % N\n *\n * The hash is a plain 32-bit FNV-1a over UTF-16 code units. It has no\n * per-process seed (unlike a JS object hash or Math.random), so two separate\n * processes derive the SAME port for the same `(home, profile)` pair — the\n * pre-condition for a shared, deterministic singleton registry.\n *\n * `canonical(home)` normalises the path text only (no filesystem access):\n * `node:path.resolve` for absolute paths / cwd-relative resolution, forward\n * slashes and lowercased drive letter on Windows. No `realpathSync` — a\n * symlink's physical path can differ between calls with a fresh mount, which\n * would break cross-process stability. Callers pass the already resolved\n * `DSH_HOME` (see `defaultDshHome` in lifecycle.ts).\n *\n * Conflict handling is the caller's job: `derivePort` gives the PREFERRED\n * port; `findFreePort` probes the `[derived, derived + N)` window and returns\n * the first free port. The caller pins that result into the registry so later\n * launches reuse it — the same window for every process keeps the choice\n * reproducible until it is actually taken.\n *\n * The TCP probe is injectable so unit tests never bind a real socket; the\n * default reuses `isListening` from lifecycle.ts (a bounded loopback connect).\n */\n\nimport { resolve } from 'node:path'\nimport { isListening } from './lifecycle.ts'\n\n/** Default base of the deterministic port window (ADR-0009: 60000). */\nexport const DEFAULT_PORT_BASE = 60_000\n/** Default size of the deterministic port window (ADR-0009: 1000). */\nexport const DEFAULT_PORT_COUNT = 1_000\n\n/** FNV-1a 32-bit offset basis. */\nconst FNV_OFFSET_BASIS = 0x811c9dc5\n/** FNV-1a 32-bit prime. */\nconst FNV_PRIME = 0x01000193\n\n/**\n * Normalise a home path into the exact string the port hash consumes.\n * Pure: no I/O, no `realpath`. Stable for the same textual path across runs.\n */\nexport function canonicalHome(home: string): string {\n  const resolved = resolve(home)\n  if (process.platform !== 'win32') return resolved\n  // Windows: normalise separators + drive-letter case so `C:\\x` and `c:/x`\n  // hash identically even across processes with a different cwd spelling.\n  return resolved\n    .replace(/\\\\/g, '/')\n    .replace(/^([A-Za-z]):/, (_match, drive: string) => drive.toLowerCase() + ':')\n}\n\n/**\n * 32-bit FNV-1a over UTF-16 code units, returned as an unsigned integer.\n * `Math.imul` keeps the multiply in 32-bit space (a plain `*` would lose\n * precision above 2^53 and become platform-dependent).\n */\nexport function fnv1a32(text: string): number {\n  let hash = FNV_OFFSET_BASIS\n  for (let i = 0; i < text.length; i++) {\n    hash ^= text.charCodeAt(i)\n    hash = Math.imul(hash, FNV_PRIME)\n  }\n  return hash >>> 0\n}\n\nexport interface PortDerivationOptions {\n  /** Window base. Default {@link DEFAULT_PORT_BASE}. */\n  base?: number\n  /** Window size. Default {@link DEFAULT_PORT_COUNT}. */\n  count?: number\n}\n\n/**\n * The preferred port for `(home, profile)`: `base + hash % count`.\n * Deterministic across calls and processes for identical inputs.\n */\nexport function derivePort(home: string, profile: string, options: PortDerivationOptions = {}): number {\n  const base = options.base ?? DEFAULT_PORT_BASE\n  const count = options.count ?? DEFAULT_PORT_COUNT\n  if (!Number.isInteger(base) || !Number.isInteger(count) || count <= 0) {\n    throw new RangeError('derivePort: base and count must be integers and count > 0')\n  }\n  const offset = fnv1a32(`${canonicalHome(home)}:${profile}`) % count\n  return base + offset\n}\n\n/** A TCP probe: `true` when the port is in use / already listening. */\nexport type PortOccupiedProbe = (port: number) => Promise<boolean>\n\nexport interface FindFreePortOptions extends PortDerivationOptions {\n  /** Injectable occupancy probe. Default: `lifecycle.isListening` (bounded TCP connect). */\n  probe?: PortOccupiedProbe\n}\n\n/** Thrown when every port in the derived window is occupied. */\nexport class NoFreePortError extends Error {\n  readonly code = 'no-free-port'\n  constructor(\n    readonly home: string,\n    readonly profile: string,\n    readonly base: number,\n    readonly count: number,\n  ) {\n    super(`no free port for ${profile} in [${base}, ${base + count}) under ${home}`)\n    this.name = 'NoFreePortError'\n  }\n}\n\n/**\n * Pick the actual port: start at the derived preference and walk the\n * `[derived, derived + count)` window, returning the first port the probe\n * reports free. The result is returned to the caller, which is responsible\n * for pinning it into the registry — this function never writes state.\n */\nexport async function findFreePort(home: string, profile: string, options: FindFreePortOptions = {}): Promise<number> {\n  const base = options.base ?? DEFAULT_PORT_BASE\n  const count = options.count ?? DEFAULT_PORT_COUNT\n  if (!Number.isInteger(base) || !Number.isInteger(count) || count <= 0) {\n    throw new RangeError('findFreePort: base and count must be integers and count > 0')\n  }\n  const derived = derivePort(home, profile, { base, count })\n  const probe = options.probe ?? isListening\n  for (let port = derived; port < derived + count; port++) {\n    if (!(await probe(port))) return port\n  }\n  throw new NoFreePortError(home, profile, derived, count)\n}\n",
    "/**\n * Launcher-side host bootstrap orchestration (ADR-0009 decisions 2–5 & 8;\n * DESIGN-redesign §3 — the launcher startup sequence).\n *\n * This module is the *launcher* half of the singleton host: it resolves the\n * `(home, profile)` scope, derives a deterministic port, reads the v2 registry,\n * attaches to a healthy host on the fast path (no progress), and otherwise\n * atomically claims the registry and spawns ONE host — rendering progress\n * (spawn → booting → ready + elapsed) before the launcher hands the TTY to the\n * bun client. It never changes the host core and adds no argv flag: the host\n * is marked by env `DSH_OPENTUI_SERVER=1` (dsh 0.18.4+ exits 2 on unknown flags).\n *\n * Concurrency: the atomic `link(2)` claim in host-registry guarantees exactly\n * one winner per `(home, profile)`. A loser never spawns; it polls the registry\n * until `phase=ready` (or timeout) and adopts. The 5-minute timeout identifies\n * and kills ONLY this spawn's pid — and only when three evidences agree\n * (registry pid + `--profile opentui` cmdline + `DSH_OPENTUI_SERVER=1` env),\n * with injectable kill hooks so tests never signal a real process.\n *\n * All I/O that reaches the process (spawn, clock, sleep, fs, TCP/HTTP probes,\n * cookie mint, process evidence/kill) is an injectable seam. Unit tests drive\n * the whole state machine with fakes — no real host, socket, or signal.\n */\n\nimport { spawn } from 'node:child_process'\nimport { homedir } from 'node:os'\nimport { connect as netConnect, Server, type AddressInfo } from 'node:net'\nimport { dirname, join } from 'node:path'\n\n// ADR-0009 decisions 6–8 — client heartbeat guard, three-evidence safe stop.\nimport {\n  assertForceAllowed,\n  nodeLifecycleFs,\n  purgeAllHeartbeats,\n  type LifecycleFs,\n} from './client-lifecycle.ts'\nimport { mintOwnerCookie } from './cookie-mint.ts'\nimport { checkHostHealth, defaultHealthProbes, type HealthCheck } from './host-health.ts'\nimport { findFreePort } from './host-port.ts'\n// ADR-0009 decision 8 — the three-evidence gate and the only sanctioned way to\n// signal a host. Re-exported below so existing callers keep their imports.\nimport {\n  defaultPidAlive,\n  psKillHooks,\n  safeStopHost,\n  SERVER_ENV_NAME,\n  SERVER_ENV_VALUE,\n  type ProcessKillHooks,\n} from './safe-kill.ts'\nimport {\n  claimRegistry,\n  isRegistryStale,\n  nodeRegistryFs,\n  readRegistry,\n  registryPath,\n  safeClearLegacy,\n  withPhase,\n  writeRegistry,\n  type HostRegistryV2,\n  type RegistryFs,\n  type RegistryReadResult,\n} from './host-registry.ts'\n\n// ---------------------------------------------------------------------------\n// Constants + public value types.\n// ---------------------------------------------------------------------------\n\n/** The one product profile (ADR-0005 decision 3). */\nexport const DEFAULT_LAUNCH_PROFILE = 'opentui'\n/** Env marker + three-evidence hooks live in `safe-kill.ts`; re-exported for\n *  the callers/tests that imported them from here in T3a. */\nexport { SERVER_ENV_NAME, SERVER_ENV_VALUE, psKillHooks } from './safe-kill.ts'\nexport type { ProcessKillHooks } from './safe-kill.ts'\n/** 5-minute budget for the whole claim→ready sequence (ADR-0009 decision 5). */\nexport const DEFAULT_LAUNCH_TIMEOUT_MS = 5 * 60_000\n/** Progress / readiness poll cadence (100–200ms per the ADR). */\nexport const DEFAULT_POLL_MS = 150\n/** Max age before a LIVE `claim`/`booting` record is stale (P1-1: never applied\n *  to steady-state `ready`/`stopping`, whose `updatedAt` is not refreshed). */\nexport const DEFAULT_REGISTRY_MAX_AGE_MS = 60_000\n/** SIGTERM → SIGKILL grace for a confirmed `--force --yes` host stop. */\nexport const FORCE_TERM_GRACE_MS = 2_000\nexport const FORCE_KILL_GRACE_MS = 1_000\n\n/** Stages rendered in the launcher terminal while WE spawn the host. */\nexport const LAUNCH_PHASES = ['spawn', 'booting', 'ready'] as const\nexport type LaunchPhase = (typeof LAUNCH_PHASES)[number]\n\n/** One progress sample emitted by the winner (`elapsedMs` from spawn). */\nexport interface LaunchProgressEvent {\n  phase: LaunchPhase\n  elapsedMs: number\n}\n\nexport interface HostLaunchResult {\n  /** The port the host listens on (pinned into the registry). */\n  port: number\n  /** Whether we started the host (spawn) or joined an existing one (adopt). */\n  mode: 'adopted' | 'spawned'\n  adopted: boolean\n  spawned: boolean\n  /** The Host service pid when known. */\n  hostPid?: number\n}\n\n/** Typed timeout error carrying the diagnostic log path (ADR-0009 decision 5). */\nexport class HostLaunchTimeoutError extends Error {\n  readonly code = 'host-launch-timeout'\n  constructor(\n    message: string,\n    readonly logPath: string,\n  ) {\n    super(`${message}\\n--- dsh host log: ${logPath} ---`)\n    this.name = new.target.name\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Injectable seams.\n// ---------------------------------------------------------------------------\n\n/** Minimal child handle the orchestrator needs (structurally a ChildProcess). */\nexport interface SpawnedHost {\n  pid: number\n  stdout?: { on(event: 'data', listener: (chunk: unknown) => void): unknown }\n  stderr?: { on(event: 'data', listener: (chunk: unknown) => void): unknown }\n  on?(event: 'exit', listener: (code: number | null, signal: string | null) => void): unknown\n  on?(event: 'error', listener: (err: Error) => void): unknown\n  kill?(signal?: string): boolean\n}\n\nexport type SpawnHost = (\n  argv: string[],\n  options: { cwd: string; env: NodeJS.ProcessEnv },\n) => SpawnedHost\n\nexport interface HostLaunchDeps {\n  home?: string\n  profile?: string\n  cwd?: string\n  /** Reset the singleton host. Live clients require `yes` too (ADR-0009 §7). */\n  force?: boolean\n  /** Confirm a force reset when live clients exist (`--force --yes`). */\n  yes?: boolean\n  /** Filesystem seam for the registry + diagnostic log. */\n  fs?: RegistryFs\n  /** Filesystem seam for the `--force` heartbeat guard. Defaults to the full\n   *  real fs (WITH `readdirSync`) — never the slim registry-only `RegistryFs`.\n   *  Keeping this separate is what stops the packaged bundle from degrading the\n   *  force guard to an fs that cannot see live clients. */\n  lifecycleFs?: LifecycleFs\n  /** Clock (`Date.now` equivalent) for timestamps, elapsed and deadlines. */\n  now?: () => number\n  /** Cancellable sleep seam. */\n  sleep?: (ms: number) => Promise<void>\n  /** Spawn seam. Default: real `dsh`, detached + unref'd. */\n  spawnHost?: SpawnHost\n  /** Pid liveness. Default: `process.kill(pid, 0)`. */\n  pidAlive?: (pid: number) => boolean\n  /** Health gate for attach + readiness. Default: `checkHostHealth` (TCP + GET /). */\n  health?: (authority: string, cookieHeader: string) => Promise<HealthCheck>\n  /** Cookie mint for the health probe. Default: `mintOwnerCookie` from this home. */\n  mintCookie?: (opts: { home: string; authority: string }) => string\n  /** Free-port selection. Default: `findFreePort` over the derived window. */\n  findPort?: (home: string, profile: string, probe: (port: number) => Promise<boolean>) => Promise<number>\n  /** Port-occupancy probe used by the default `findPort`. */\n  portProbe?: (port: number) => Promise<boolean>\n  /** Progress sink. Absent = silent (headless / attach fast path). */\n  progress?: (event: LaunchProgressEvent) => void\n  /** Process identification + kill, used only on timeout. */\n  killHooks?: ProcessKillHooks\n  /** Whole-sequence budget. Default 5 minutes. */\n  timeoutMs?: number\n  /** Poll cadence. Default 150ms. */\n  pollMs?: number\n  /** Max age of a live-pid v2 record before it is stale. */\n  registryMaxAgeMs?: number\n  /** Diagnostic log path for the spawned host's captured output. */\n  logPath?: (home: string, profile: string) => string\n  /** NODE_OPTIONS-affecting env for the spawned host (tests keep it clean). */\n  baseEnv?: NodeJS.ProcessEnv\n}\n\ninterface ResolvedDeps {\n  home: string\n  profile: string\n  cwd: string\n  force: boolean\n  yes: boolean\n  fs: RegistryFs\n  lifecycleFs: LifecycleFs\n  now: () => number\n  sleep: (ms: number) => Promise<void>\n  spawnHost: SpawnHost\n  pidAlive: (pid: number) => boolean\n  health: (authority: string, cookieHeader: string) => Promise<HealthCheck>\n  mintCookie: (opts: { home: string; authority: string }) => string\n  findPort: (home: string, profile: string, probe: (port: number) => Promise<boolean>) => Promise<number>\n  portProbe: (port: number) => Promise<boolean>\n  progress?: (event: LaunchProgressEvent) => void\n  killHooks: ProcessKillHooks\n  timeoutMs: number\n  pollMs: number\n  registryMaxAgeMs: number\n  logPath: (home: string, profile: string) => string\n  baseEnv: NodeJS.ProcessEnv\n}\n\n// ---------------------------------------------------------------------------\n// Default seam implementations.\n// ---------------------------------------------------------------------------\n\nexport function defaultDshHome(): string {\n  return process.env.DSH_HOME || join(homedir(), '.dsh')\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\nconst defaultPortProbe = (port: number): Promise<boolean> =>\n  new Promise((resolve) => {\n    let settled = false\n    const socket = netConnect({ host: '127.0.0.1', port })\n    const finish = (value: boolean) => {\n      if (settled) return\n      settled = true\n      socket.destroy()\n      resolve(value)\n    }\n    socket.setTimeout(750)\n    socket.once('connect', () => finish(true))\n    socket.once('error', () => finish(false))\n    socket.once('timeout', () => finish(false))\n  })\n\n/** OpenTUI's host core needs node's `--experimental-ffi`; mirror lifecycle.ts. */\nconst FFI_FLAG = '--experimental-ffi'\n\nfunction withFfiFlag(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n  const existing = env.NODE_OPTIONS ?? ''\n  if (existing.split(/\\s+/).includes(FFI_FLAG)) return env\n  return { ...env, NODE_OPTIONS: `${existing} ${FFI_FLAG}`.trim() }\n}\n\n/** Default spawn: detached/unref'd so the host outlives the launcher process. */\nexport const defaultSpawnHost: SpawnHost = (argv, options) => {\n  const env = { ...options.env }\n  for (const key of Object.keys(env)) {\n    if (key.startsWith('npm_config_')) delete env[key]\n  }\n  const child = spawn('dsh', argv, {\n    cwd: options.cwd,\n    env,\n    detached: true,\n    stdio: ['ignore', 'pipe', 'pipe'],\n  })\n  child.unref()\n  for (const pipe of [child.stdout, child.stderr]) {\n    ;(pipe as unknown as { unref?: () => void }).unref?.()\n  }\n  return child as unknown as SpawnedHost\n}\n\nconst defaultHealth = (authority: string, cookieHeader: string): Promise<HealthCheck> =>\n  checkHostHealth({ authority, cookieHeader }, defaultHealthProbes)\n\nfunction resolveDeps(d: HostLaunchDeps): ResolvedDeps {\n  const home = d.home ?? defaultDshHome()\n  const profile = d.profile ?? DEFAULT_LAUNCH_PROFILE\n  return {\n    home,\n    profile,\n    cwd: d.cwd ?? process.cwd(),\n    force: d.force ?? false,\n    yes: d.yes ?? false,\n    fs: d.fs ?? nodeRegistryFs,\n    lifecycleFs: d.lifecycleFs ?? nodeLifecycleFs,\n    now: d.now ?? Date.now,\n    sleep: d.sleep ?? defaultSleep,\n    spawnHost: d.spawnHost ?? defaultSpawnHost,\n    pidAlive: d.pidAlive ?? defaultPidAlive,\n    health: d.health ?? defaultHealth,\n    mintCookie: d.mintCookie ?? mintOwnerCookie,\n    findPort: d.findPort ?? ((home, profile, probe) => findFreePort(home, profile, { probe })),\n    portProbe: d.portProbe ?? defaultPortProbe,\n    ...(d.progress ? { progress: d.progress } : {}),\n    killHooks: d.killHooks ?? psKillHooks,\n    timeoutMs: d.timeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS,\n    pollMs: d.pollMs ?? DEFAULT_POLL_MS,\n    registryMaxAgeMs: d.registryMaxAgeMs ?? DEFAULT_REGISTRY_MAX_AGE_MS,\n    logPath: d.logPath ?? ((h, p) => join(h, `opentui-host.${p}.log`)),\n    baseEnv: d.baseEnv ?? process.env,\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Progress rendering (TTY overwrite vs non-TTY one line per phase).\n// ---------------------------------------------------------------------------\n\nexport interface ProgressRendererOptions {\n  isTty: boolean\n  write: (text: string) => void\n}\n\n/**\n * Build the progress sink the launcher passes as `deps.progress`.\n * - TTY: redraw one line (`\\r` + clear) on every sample, terminated by a\n *   newline at `ready` so the client's alternate screen starts on a fresh line.\n * - non-TTY: emit one line per PHASE CHANGE only (no 150ms spam).\n */\nexport function createLaunchProgress(options: ProgressRendererOptions): (event: LaunchProgressEvent) => void {\n  const { isTty, write } = options\n  let lastPhase: LaunchPhase | null = null\n  return (event) => {\n    const seconds = (event.elapsedMs / 1000).toFixed(1)\n    const line = `dsh-opentui: host ${event.phase}  ${seconds}s`\n    if (isTty) {\n      write(`\\r\\u001b[2K${line}`)\n      if (event.phase === 'ready') write('\\n')\n      return\n    }\n    if (event.phase === lastPhase) return\n    lastPhase = event.phase\n    write(`${line}\\n`)\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers: registry hygiene, evidence, log capture.\n// ---------------------------------------------------------------------------\n\n/** Remove a v2 record only if it still matches the pid/token we judged stale. */\nfunction removeStaleRecord(home: string, profile: string, stale: HostRegistryV2, o: ResolvedDeps): void {\n  const current = readRegistry(home, profile, o.fs)\n  if (current.kind === 'v2' && current.value.pid === stale.pid && current.value.startedAt === stale.startedAt) {\n    try {\n      o.fs.unlinkSync(registryPath(home, profile))\n    } catch {\n      /* already gone */\n    }\n  }\n}\n\n/** Remove an invalid file (unparseable / unsupported) so a fresh claim can start. */\nfunction removeInvalidRecord(home: string, profile: string, o: ResolvedDeps): void {\n  try {\n    o.fs.unlinkSync(registryPath(home, profile))\n  } catch {\n    /* already gone */\n  }\n}\n\n/** Attach output listeners that accumulate a bounded tail for the log/timeout. */\nfunction captureOutput(child: SpawnedHost, tail: { text: string }): void {\n  const push = (chunk: unknown) => {\n    tail.text = (tail.text + String(chunk)).slice(-8_000)\n  }\n  child.stdout?.on('data', push)\n  child.stderr?.on('data', push)\n}\n\nfunction flushLog(o: ResolvedDeps, tail: { text: string }): string {\n  const path = o.logPath(o.home, o.profile)\n  try {\n    o.fs.mkdirSync(dirname(path), { recursive: true })\n    o.fs.writeFileSync(path, `[dsh-opentui] host output tail\\n${tail.text}\\n`)\n  } catch {\n    /* logging must never mask the real timeout error */\n  }\n  return path\n}\n\n// ---------------------------------------------------------------------------\n// Public entry point.\n// ---------------------------------------------------------------------------\n\n/**\n * Ensure a single healthy host for `(home, profile)` and return the port to\n * attach to. See the file header for the state machine. Emits progress ONLY\n * when this call spawns the host; the attach fast path and the adopt-wait path\n * are silent. `force` is accepted here in T3a (skips the attach fast path);\n * its full stop/restart semantics land in T3b.\n */\nexport async function ensureHost(deps: HostLaunchDeps = {}): Promise<HostLaunchResult> {\n  const o = resolveDeps(deps)\n\n  // 0. `--force` reset (ADR-0009 decision 7). Refuse when live clients exist\n  //    without `--yes`; otherwise three-evidence-stop the registry host and\n  //    clear its registry + client heartbeats before the normal boot sequence.\n  if (o.force) {\n    // The heartbeat guard MUST see live clients. Use the dedicated full fs\n    // (with readdirSync), never the slim registry fs; assertForceAllowed now\n    // hard-errors if an incomplete fs is ever passed here again.\n    const hbDeps = { fs: o.lifecycleFs, now: o.now }\n    assertForceAllowed(o.home, { ...hbDeps, yes: o.yes })\n    const current = readRegistry(o.home, o.profile, o.fs)\n    // A live legacy record is ALSO a host that must be stopped before its sole\n    // record is removed (P1-4 hands it to --force / manual intervention).\n    const forcePid =\n      current.kind === 'v2' ? current.value.pid : current.kind === 'legacy' ? current.raw.pid : 0\n    if (forcePid > 0) {\n      const stop = await safeStopHost({\n        pid: forcePid,\n        registryPid: forcePid,\n        hooks: o.killHooks,\n        profile: o.profile,\n        termGraceMs: FORCE_TERM_GRACE_MS,\n        killGraceMs: FORCE_KILL_GRACE_MS,\n        sleep: o.sleep,\n        now: o.now,\n        pidAlive: o.pidAlive,\n      })\n      // P0-2: only unlink after the old host is CONFIRMED stopped. Otherwise\n      // clearing the record turns it into an untrackable live orphan.\n      if (!stop.stopped) {\n        throw new Error(\n          `dsh-opentui: --force could not confirm the old host pid ${forcePid} is stopped ` +\n            `(evidences ${stop.evidencesOk ? 'matched but pid survived' : 'refused'}); ` +\n            `registry left intact — retry --force or stop it manually.`,\n        )\n      }\n      try {\n        o.fs.unlinkSync(registryPath(o.home, o.profile))\n      } catch {\n        /* already gone */\n      }\n    }\n    purgeAllHeartbeats(o.home, hbDeps)\n  }\n\n  // The launch budget covers the claim → ready sequence only, not the force\n  // teardown that preceded it.\n  const startedAt = o.now()\n  const deadline = startedAt + o.timeoutMs\n  const emit = (phase: LaunchPhase) => o.progress?.({ phase, elapsedMs: o.now() - startedAt })\n\n  // 1. Read + classify the registry (attach fast path first).\n  let read = readRegistry(o.home, o.profile, o.fs)\n  if (read.kind === 'v2' && !o.force) {\n    const reg = read.value\n    const authority = reg.authority || `127.0.0.1:${reg.port}`\n    if (reg.phase === 'ready' && reg.port > 0 && o.pidAlive(reg.pid)) {\n      const cookie = o.mintCookie({ home: o.home, authority })\n      if ((await o.health(authority, cookie)).healthy) {\n        return { port: reg.port, mode: 'adopted', adopted: true, spawned: false, hostPid: reg.pid }\n      }\n      // A live pid whose cookie/port no longer answers is not attachable —\n      // fall through to the stale/claim path (never signal the foreign pid).\n    }\n  }\n\n  // 2. Cleanup stale / legacy / invalid state before claiming. A bounded loop\n  //    prevents a racing writer from spinning us forever; a leftover file just\n  //    makes the atomic claim below lose (→ adopt-wait), never double-spawn.\n  for (let attempt = 0; attempt < 4; attempt++) {\n    read = readRegistry(o.home, o.profile, o.fs)\n    if (read.kind === 'missing') break\n    if (read.kind === 'legacy') {\n      // P1-4: safeClearLegacy keeps the record when the old pid is still alive.\n      const cleared = safeClearLegacy(o.home, o.profile, { fs: o.fs, read, pidAlive: o.pidAlive })\n      if (!cleared.removed) {\n        throw new Error(\n          `dsh-opentui: legacy host pid ${read.raw.pid} is still alive; ` +\n            `its registry record is kept — stop it manually or use --force --yes.`,\n        )\n      }\n      continue\n    }\n    if (read.kind === 'invalid') {\n      removeInvalidRecord(o.home, o.profile, o)\n      continue\n    }\n    const verdict = isRegistryStale(read, {\n      now: o.now,\n      pidAlive: o.pidAlive,\n      registryMaxAgeMs: o.registryMaxAgeMs,\n    })\n    if (verdict.stale) {\n      removeStaleRecord(o.home, o.profile, read.value, o)\n      continue\n    }\n    // Fresh v2 we could not attach to: an unhealthy `ready` host is first\n    // three-evidence-STOPPED, then its record is dropped so a fresh claim can\n    // reboot it (P0-2: never just abandon the record — that leaks a live host).\n    // If the stop cannot be confirmed, keep the record and fail loudly instead\n    // of silently orphaning the old host. A `claim`/`booting` record is LEFT\n    // INTACT — another launcher owns it and our claim below must lose (adopt-wait).\n    if (read.value.phase === 'ready' && read.value.pid > 0) {\n      const stop = await safeStopHost({\n        pid: read.value.pid,\n        registryPid: read.value.pid,\n        hooks: o.killHooks,\n        profile: o.profile,\n        termGraceMs: FORCE_TERM_GRACE_MS,\n        killGraceMs: FORCE_KILL_GRACE_MS,\n        sleep: o.sleep,\n        now: o.now,\n        pidAlive: o.pidAlive,\n      })\n      if (!stop.stopped) {\n        throw new Error(\n          `dsh-opentui: unhealthy host pid ${read.value.pid} could not be stopped ` +\n            `(evidences ${stop.evidencesOk ? 'matched but pid survived' : 'refused'}); ` +\n            `registry record kept — retry or stop it manually.`,\n        )\n      }\n      removeStaleRecord(o.home, o.profile, read.value, o)\n    }\n    break\n  }\n\n  // 3. Atomic claim — exactly one winner per (home, profile).\n  const claim = claimRegistry(o.home, o.profile, { fs: o.fs, now: o.now, pid: process.pid })\n  if (!claim.ok) {\n    // 3b. Loser: poll to ready or timeout, then adopt. NEVER spawn.\n    while (o.now() < deadline) {\n      const current = readRegistry(o.home, o.profile, o.fs)\n      if (current.kind === 'v2' && current.value.phase === 'ready' && current.value.port > 0) {\n        return {\n          port: current.value.port,\n          mode: 'adopted',\n          adopted: true,\n          spawned: false,\n          hostPid: current.value.pid,\n        }\n      }\n      await o.sleep(o.pollMs)\n    }\n    throw new HostLaunchTimeoutError(\n      `timed out waiting for the host claimed by another launcher (${o.timeoutMs}ms)`,\n      o.logPath(o.home, o.profile),\n    )\n  }\n\n  // 4. Winner: choose a port, write booting, spawn the host with the env marker.\n  const port = await o.findPort(o.home, o.profile, o.portProbe)\n  const booting: HostRegistryV2 = {\n    ...claim.registry,\n    pid: 0, // replaced with the child pid the moment it spawns\n    port,\n    phase: 'booting',\n    authority: `127.0.0.1:${port}`,\n    updatedAt: new Date(o.now()).toISOString(),\n  }\n  const env: NodeJS.ProcessEnv = withFfiFlag({\n    ...o.baseEnv,\n    [SERVER_ENV_NAME]: SERVER_ENV_VALUE,\n    DSH_HOME: o.home,\n  })\n  const child = o.spawnHost(['--profile', o.profile, '--no-open', '--port', String(port)], {\n    cwd: o.cwd,\n    env,\n  })\n  writeRegistry(o.home, o.profile, { ...booting, pid: child.pid }, o.fs)\n  const bootingRecord: HostRegistryV2 = { ...booting, pid: child.pid }\n  emit('spawn')\n  const tail = { text: '' }\n  captureOutput(child, tail)\n\n  // 5. Poll readiness (registry phase stays `booting`; health = TCP + GET /)\n  //    while rendering progress. Only the winner renders.\n  const authority = `127.0.0.1:${port}`\n  const cookie = o.mintCookie({ home: o.home, authority })\n  let ready = false\n  let died = false\n  child.on?.('exit', () => {\n    died = true\n  })\n  while (o.now() < deadline) {\n    if (died || !o.pidAlive(child.pid)) break\n    if ((await o.health(authority, cookie)).healthy) {\n      ready = true\n      break\n    }\n    emit('booting')\n    await o.sleep(o.pollMs)\n  }\n\n  if (ready) {\n    writeRegistry(o.home, o.profile, withPhase(bootingRecord, 'ready', new Date(o.now()).toISOString()), o.fs)\n    emit('ready')\n    return { port, mode: 'spawned', adopted: false, spawned: true, hostPid: child.pid }\n  }\n\n  // 6. Timeout / death: verify three evidences against the registry's CURRENT\n  //    pid, then use the SAME SIGTERM → grace → SIGKILL sequence as\n  //    safeStopHost (P2-1) to give the host a chance to flush. Clear the\n  //    registry only for our own spawn and surface the log path.\n  const log = flushLog(o, tail)\n  const current = readRegistry(o.home, o.profile, o.fs)\n  const registryPid = current.kind === 'v2' ? current.value.pid : -1\n  await safeStopHost({\n    pid: child.pid,\n    registryPid,\n    hooks: o.killHooks,\n    profile: o.profile,\n    termGraceMs: FORCE_TERM_GRACE_MS,\n    killGraceMs: FORCE_KILL_GRACE_MS,\n    sleep: o.sleep,\n    now: o.now,\n    pidAlive: o.pidAlive,\n  })\n  if (current.kind === 'v2' && current.value.pid === child.pid) {\n    try {\n      o.fs.unlinkSync(registryPath(o.home, o.profile))\n    } catch {\n      /* already gone */\n    }\n  }\n  throw new HostLaunchTimeoutError(\n    `host did not become ready within ${o.timeoutMs}ms (port ${port}, pid ${child.pid})`,\n    log,\n  )\n}\n\n/** Bind-probe a free loopback port (handy for tests / callers that need one). */\nexport function bindFreePort(): Promise<number> {\n  return new Promise((resolve, reject) => {\n    const server = new Server((socket) => socket.destroy())\n    server.once('error', reject)\n    server.listen(0, '127.0.0.1', () => {\n      const { port } = server.address() as AddressInfo\n      server.close(() => resolve(port))\n    })\n  })\n}\n\n// Re-export so callers can read a validated registry without reaching into the\n// sibling module directly, plus the typed `--force` refusal the launcher gates on.\nexport { readRegistry, type HostRegistryV2, type RegistryReadResult }\nexport { ForceNeedsYesError } from './client-lifecycle.ts'\n"
  ],
  "mappings": ";;;;;;;;;;;;;;;;AA2BA;AA6BA,SAAS,cAAc,CAAC,WAA4B;AAAA,EAClD,OAAO,OAAO,cAAc,YAAY,UAAU,SAAS,KAAK,CAAC,UAAU,KAAK,SAAS;AAAA;AAUpF,eAAe,mBAAmB,CAAC,SAAmD;AAAA,EAC3F,IAAI,CAAC,eAAe,QAAQ,SAAS;AAAA,IAAG,OAAO;AAAA,EAC/C,MAAM,YAAY,QAAQ,aAAa;AAAA,EACvC,IAAI;AAAA,IACF,MAAM,WAAW,MAAM,MAAM,UAAU,QAAQ,cAAc;AAAA,MAC3D,SAAS,EAAE,QAAQ,QAAQ,aAAa;AAAA,MACxC,QAAQ,YAAY,QAAQ,SAAS;AAAA,IACvC,CAAC;AAAA,IAED,IAAI;AAAA,MACF,MAAM,SAAS,MAAM,OAAO;AAAA,MAC5B,MAAM;AAAA,IAGR,OAAO,SAAS;AAAA,IAChB,MAAM;AAAA,IACN,OAAO;AAAA;AAAA;AAAA,IApDE,gCAAgC;AAAA;AAAA,EAH7C;AAAA;;;ICIa,0BAA0B,yBAE1B;AAAA;AAAA,yBAAuB,UAAU;AAAA;;;ACV9C;AAoCA,SAAS,MAAM,CAAC,KAA4B;AAAA,EAC1C,IAAI;AAAA,IACF,MAAM,SAAS,UAAU,MAAM,CAAC,MAAM,OAAO,GAAG,GAAG,MAAM,OAAO,GAAG,EAAE,UAAU,OAAO,CAAC;AAAA,IACvF,IAAI,OAAO,SAAS,OAAO,WAAW;AAAA,MAAG,OAAO;AAAA,IAChD,QAAQ,OAAO,UAAU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